Friday 17 February 2017

Can I do a CURL request to the same server?


Hi Everybody,

If you want to implement a way to make POST calls to pages located on the same server or in another server. We cannot use include because the files that we are calling usually call different databases or have functions with the same name.
For this post call we can use curl, and while it works perfectly when calling files from another server, but if you make call fron the same server it will create deadlock condition.

e.g 
File1.php

<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "www.myserver.com/File2.php");
curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_VERBOSE, true);
$result = curl_exec($ch);
curl_close($ch);
echo $result;
?>

File2.php
<?php
echo "I'M IN!!";
?>
 
In this example, after calling File1.php, you do not get any output, but if File2.php is in another server then you get a result.

Solution of this curl deadlock


Be aware that if you're issuing the CURL request to your own site, you're using the default session handler, and the page you're requesting via CURL uses the same session as the page that's generating the request, you'll run into a deadlock situation.

The default session handler locks the session file for the duration of the page request. When you try to request another page using the same session, that subsequent request will hang until the request times out or the session file becomes available. Since you're doing an internal CURL, the script running CURL will hold a lock on the session file, and the CURL request can never complete as the target page can never load the session.

You can, just make sure that the script doing the CURL request closes the session with session_write_close() immediately before the curl_exec(). You can always do a session_start() again afterwards if you need to change anything in the session



 File1.php

<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "www.myserver.com/File2.php");
curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_VERBOSE, true);
session_write_close() 
$result = curl_exec($ch);
curl_close($ch);
session_start() 
echo $result;
?>

File2.php
<?php
echo "I'M IN!!";
?>
 
Now this will work for same serve as well as different server.
 
Thanks.