How do I send a server postback safely with PHP? How do I send a server postback safely with PHP? curl curl

How do I send a server postback safely with PHP?


You doesn't have a security problem in any case if you don't process the response of the server.

For example, when you use:

$url = 'http://www.example.com/testaddr';$result = file_get_contents($url);unset($result);

You have a variable with the data. But these data aren't processed yet.

With cURL, you can get the same approach with these options:

$url = 'http://www.example.com/testaddr';$curl = curl_init();                curl_setopt ($curl, CURLOPT_URL, $url);curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);$result = curl_exec($curl);//If you need to check result, use this:if (!curl_errno($curl)) {  $http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);  if ($http_code === 200) {    echo "OK";  } else {    echo 'Unexpected HTTP code: ', $http_code, "\n";  }}curl_close($curl);unset($result);

In that case it's the same, you get the response on $result var, but, you didn't use it, in that case, it isn't a security failure.

Also, in both cases, for security reasons and prevent excessive memory usage, I delete the $result variable after finish the process.

As you can see on PHP doc:

CURLOPT_RETURNTRANSFER TRUE to return the transfer as a string of the return value of curl_exec() instead of outputting it out directly.


Two different levels

I think that you have two different levels of security here that you want to address. You may want to secure the communication channel to avoid someone spoofing the http request, and you may want to sanitize the response to avoid nasty side-effects.

Securing the HTTP request

This part depends largely on the destination server and how the communication is handled. If you can enforce HTTPS, then you can be pretty safe against MITM attacks. Otherwise you're always liable to spoofing.

Sanitizing the response

When you get the response back to your server, it all depends on how you use that data. It doesn't have much to do with the function of choice, but rather with how you use the data after the call.Since you allow the users to input this way, just expect the worst. At this point, the most common best practices for sanitizing input applies: use PDO for database access, escape chars with the &#xHH; format, and so on.

I hope this could answer your concerns, otherwise feel free to comment my answer!