开发者

Can I do a CURL request to the same server?

开发者 https://www.devze.com 2023-02-19 03:08 出处:网络
I need 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 h

I need 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.

I've been trying to implement this using curl, and while it works perfectly when calling fi开发者_运维百科les from another server, I get absolutely nothing when making a call to the same server where the file is.

EDIT TO ADD SOME CODE: A simplified version of what I'm doing:

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!!";
?>

After calling File1.php, I get nothing, but if File2.php is in another server then I get a result. Any help?

I tried using both the server URL (http...) and the total address of the files (/home/wwww....)


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.


Because when you tried to request to the local server with the public ip, apache couldn't resolve to its local domain. So you have to check which local ip apache is using for that domain. Then you need to edit the /etc/hosts file and add the new row with local ip plus your domain. For example:

My Local ip for that domain in apache's virtual host is : 172.190.1.120 and my domain is mydomain.com So I will add:

172.190.1.120 mydomain.com

Then your curl will work properly.


You should refactor your code. In addition to what Marc B mentioned, this approach will unnecessarily slow down your script (potentially by a large margin) and cause lots of confusion. No offense, but this is just an incredibly hacky fix for bad logic.

0

精彩评论

暂无评论...
验证码 换一张
取 消