简体   繁体   中英

PHP cURL request fails, but works with Postman/curl from Bash

I encountered a very strange situation. Making a request in Postman to a web service works correctly (x-www-form-urlencoded) with a few parameters.

However when I make this request using PHP cURL the request fails with a response similar to this:

Failed to Connect, fopen(http://10.0.0.8:8080/posts?foo=bar&bar=baz): failed to open stream: HTTP request failed! 

The web service appears to be written using PHP, the endpoint is such as http://foo.com/service.php .

Postman will work 100% of the time, a cURL request made from Bash works 100% of the time.

For me it is extremely strange that it is trying to resolve an internal IP address and that it only fails when using the php cURL library.

Hopefully someone can shed some light on this or has experienced this before. I have tried pretty much every curl option imaginable to get this to work, but no luck. Any help would be appreciated.

Code:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, self::SERVICE_ENDPOINT);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $paramString);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_FAILONERROR, false);

var_dump(curl_exec($ch));
die;

Verbose output:

HTTP/1.1 200 OK
Date: Tue, 06 Jan 2015 09:27:20 GMT
Server: Apache
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Last-Modified: Tue, 06 Jan 2015 09:27:20 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Vary: Accept-Encoding
Content-Length: 324
Content-Type: text/html

Failed to Connect, fopen(http://10.0.0.8:8080/posts?foo=bar&bar=baz): failed to open stream: HTTP request failed!

The curl command is OK, but the code on the remote server tries to download some file using fopen . That fails and the error message is returned as part of the response to your calling code. It looks like the remote code tries to open a URL based on some input that it receives from the client; that input from your curl command differs from the input from Postman. To find out exactly what element in the HTTP headers or POST content is the culprit you need to take a peek in to the remote server code ( service.php ) or do trial-and-error by comparing the exact contents of the Postman request with that of the CURL request.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM