Subscribe to our feed

Symfony Experts

Symfony Experts
If you have an urgent question for a symfony-related issue, this is the place to ask.


Stack Overflow

The old fashioned way


January 13, 2011 – 6:43pm Using CURL through a SOCKS proxy to post XML data

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
  • -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 man page.

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
  // is your local IP, and 8080 is the port number we used for our tunnel
  curl_setopt($ch, CURLOPT_PROXY, ''); 
  // perform the curl session
  $result = curl_exec($ch);
Posted by in  Web Development   |  

One Response to Using CURL through a SOCKS proxy to post XML data

  1. kishore says:

    hi, i want like this program only but i am new to this socks, i am searching for a code “get data of url through socks and use it by API” i.e i want to curl one url using socks, can you show it here how it is….