Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTTP code 302 error when requesting URL vie PHP Curl

Tags:

html

php

libcurl

I got 302 error message when requesting a url via PHP curl_exec, but got code 200 when do it manually. What could possibly be the difference that makes the result different?

Suppose I have the following code in the server:

$url = "http://localhost/circle/my_request/susan?confirm_key=c429d674e36ffe1a4f87fd5a17a0200dcfff0884e8bb3801d2a7d559dcc8d8cd1416295160";
$ch = @curl_init($url);
@curl_setopt($ch, CURLOPT_HEADER, true);
@curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
@curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (compatible; Circle)");
@curl_setopt($ch, CURLOPT_TIMEOUT,60);
$s = @curl_exec($ch);
$curl_info = @curl_getinfo($ch);
$http_code = $curl_info['http_code'];

In this case, $http_code == 302, or the requested URL is redirected. But when I put the URL manually to the browser, it didn't do the redirection, and took me to the correct place.

Do I miss anything? How come those 2 requests result differently?

Thanks in advance

-----------additional info----

Hi I rerun the script with CURLOPT_FOLLOWLOCATION option set to true, and I got the following output:

HTTP/1.1 302 Found Date: Tue, 18 Nov 2014 14:36:37 
GMT Server: Apache/2.4.4 (Win64) 
PHP/5.4.12 X-Powered-By: PHP/5.4.12 
Set-Cookie: PHPSESSID=92t2db5qalq4ajie0ols03hik6; 
path=/; HttpOnly Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate,
post-check=0, pre-check=0 Pragma: no-cache X-Account-Management-Status: none 

Location: http://somehost.com/circle Content-Length: 0 

Content-Type: text/html HTTP/1.1 

301 Moved Permanently Date: Tue, 18 Nov 2014 14:36:37 
GMT Server: Apache/2.4.4 (Win64) 

PHP/5.4.12 Location: http://somehost.com/circle/ 

Content-Length: 232 Content-Type: text/html; 
charset=iso-8859-1 HTTP/1.1 200 OK Date: Tue,
18 Nov 2014 14:36:37 GMT Server: Apache/2.4.4 (Win64)
PHP/5.4.12 X-Powered-By: PHP/5.4.12
Set-Cookie: PHPSESSID=hk02sg1327eq78khbka0sf6pk6; 
path=/; HttpOnly Expires: Thu, 19 Nov 1981 08:52:00 
GMT Cache-Control: no-store, no-cache, must-revalidate, 
post-check=0, pre-check=0 Pragma: no-cache X-Account-Management-Status: none 
Transfer-Encoding: chunked Content-Type: text/html; charset=utf-8

I'm not sure what it says, but I'm guessing it got redirected to http://somehost.com/circle then to http://somehost.com/circle. Is this correct?

like image 499
ethereal1m Avatar asked Mar 01 '26 10:03

ethereal1m


1 Answers

May be script use redirect for check cookies or may be for other features.

  1. You can see redirect URL in $s output. Just insert echo $s; to end of your script.

  2. Also you can set CURLOPT_FOLLOWLOCATION and then curl will fllow by redirect in automatic mode.

like image 97
newman Avatar answered Mar 02 '26 23:03

newman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!