Recently we had to communicate with an API that requires we post XML from a white-listed IP address. This made it difficult to develop against since the only way we could get a response from the API service was if we were accessing it from our production machine. This is how you set up PHP’s cURL (client URL) library to post xml data through a proxy server.
First, use ssh to set up a tunnel to your server and set up the socks proxy.
ssh -D 8080 -f -C -q -N email@example.com
- -D 8080 is a switch that makes this session act as a SOCKS server. You can use any free port above 1023.
- -f “forks” this process so it runs in the background… you don’t have leave your terminal session open to keep the connection alive.
- -C is for “compression”. This actually may not help you if you have a fast connection, so you might want to try without it.
- -q is for “quiet mode” and suppresses most warning and diagnostic messages (leave this out if you are having trouble)
- -N is for “no command” and is useful when you are just forwarding ports like we are, and is necessary when you fork the process
You can get the full rundown of these switches in the
If this works, the command will just run and put you right back at your prompt. If you want check if it is running, use
ps -aux | grep ssh to see the process.
Now that your secure tunnel is configured, it’s time to update your PHP cURL code to use it.
$ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); // we want to post XML, so lets change the content type header curl_setopt ($ch, CURLOPT_HTTPHEADER, Array("Content-Type: text/xml")); // make it a POST request, rather than the default GET curl_setopt($ch, CURLOPT_POST, 1); // the POSTFIELDS option doesn't just take an array, you can also use a string! curl_setopt($ch, CURLOPT_POSTFIELDS, $xml); // without this curl will not return the server response curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // configure curl to use SOCKS5 curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5); // 127.0.0.1 is your local IP, and 8080 is the port number we used for our tunnel curl_setopt($ch, CURLOPT_PROXY, '127.0.0.1:8080'); // perform the curl session $result = curl_exec($ch);