Php curl 302 found

CURL не может запустить URL и вернуть 302

Я пытаюсь запустить URL-адрес (который имеет функции выделения) через CURL. Но он возвращает 302 http-код. Тот же URL-адрес, когда я запускаю POSTMAN (аддон Google Chrome) или POSTER (Firefox Addon), тогда он возвращает правильный результат (< "status": "success" >). Любая помощь будет принята с благодарностью. URL (JAVA APPLICATION URL): http://website.mywebsite.com:8083/VideoBook/signout.action МОЙ КОД:

 // Open log file $logfh = fopen("GeoserverPHP.log", 'w') or die("can't open log file"); // Initiate cURL session $service = "http://website.mywebsite.com:8083/VideoBook/"; $request = "signout.action"; $url = $service . $request; $ch = curl_init($url); // Optional settings for debugging curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_VERBOSE, true); curl_setopt($ch, CURLOPT_STDERR, $logfh); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_setopt($ch, CURLOPT_COOKIESESSION, true); curl_setopt($ch, CURLOPT_REFERER, true); curl_setopt($ch, CURLOPT_COOKIEJAR, true); curl_setopt($ch, CURLOPT_COOKIEFILE, true); //Required GET request settings // $passwordStr = "geosolutions:Geos"; // curl_setopt($ch, CURLOPT_USERPWD, $passwordStr); //GET data curl_setopt($ch, CURLOPT_HTTPHEADER, array("Accept: application/json")); //GET return code $successCode = 200; $buffer = curl_exec($ch); echo "CURL INFO : " ; print_r(curl_getinfo($ch)); echo "CURL OUTPUT : " ; print_r($buffer); // Check for errors and process results $info = curl_getinfo($ch); if ($info['http_code'] != $successCode) < $msgStr = "# Unsuccessful cURL request to "; $msgStr .= $url." [". $info['http_code']. "]\n"; fwrite($logfh, $msgStr); >else < $msgStr = "# Successful cURL request to ".$url."\n"; fwrite($logfh, $msgStr); >fwrite($logfh, $buffer."\n"); curl_close($ch); fclose($logfh); 
 CURL INFO : Array ( [url] => http://website.mywebsite.com:8083/VideoBook/signout.action [content_type] => [http_code] => 302 [header_size] => 254 [request_size] => 105 [filetime] => -1 [ssl_verify_result] => 0 [redirect_count] => 0 [total_time] => 0.58976 [namelookup_time] => 0.004162 [connect_time] => 0.297276 [pretransfer_time] => 0.297328 [size_upload] => 0 [size_download] => 0 [speed_download] => 0 [speed_upload] => 0 [download_content_length] => 0 [upload_content_length] => 0 [starttransfer_time] => 0.589739 [redirect_time] => 0 [redirect_url] => https://hpecp.mywebsite.com:8443/cas/login?service=http%3A%2F%2Fwebsite.mywebsite.com%3A8083%2FVideoBook%2Flogin.action [primary_ip] => 125.21.227.2 [certinfo] => Array ( ) [primary_port] => 8083 [local_ip] => 10.0.0.8 [local_port] => 50710 ) CURL OUTPUT : 
* Hostname was NOT found in DNS cache * Trying 125.21.227.2. * Connected to website.mywebsite.com (125.21.227.2) port 8083 (#0) > GET /VideoBook/signout.action HTTP/1.1 Host: website.mywebsite.com:8083 Accept: application/json < HTTP/1.1 302 Moved Temporarily * Server Apache-Coyote/1.1 is not blacklisted < Server: Apache-Coyote/1.1 < Location: https://hpecp.mywebsite.com:8443/cas/login?service=http%3A%2F%2Fwebsite.mywebsite.com%3A8083%2FVideoBook%2Flogin.action < Content-Length: 0 < Date: Tue, 20 May 2014 06:02:29 GMT < * Connection #0 to host website.mywebsite.com left intact * Issue another request to this URL: 'https://hpecp.mywebsite.com:8443/cas/login?service=http%3A%2F%2Fwebsite.mywebsite.com%3A8083%2FVideoBook%2Flogin.action' * Hostname was NOT found in DNS cache * Trying 15.126.214.121. * Connected to hpecp.mywebsite.com (15.126.214.121) port 8443 (#1) * successfully set certificate verify locations: * CAfile: none CApath: /etc/ssl/certs * Unknown SSL protocol error in connection to hpecp.mywebsite.com:8443 * Closing connection 1 # Unsuccessful cURL request to http://website.mywebsite.com:8083/VideoBook/signout.action [302] 

Источник

Читайте также:  Declare value in javascript

CURL - если сервер отдает редирект

CURL - если сервер отдает редирект

Бывает так что сервер перенаправляет на другой URL. Например Google, если перейти на https://google.com c IP из РФ он делает 302-й редирект на https://www.google.ru . Чтобы CURL сам переходил на новый URL, нужно добавить параметр:

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
function curl_redir_exec($ch) < static $curl_loops = 0; static $curl_max_loops = 20; if ($curl_loops >= $curl_max_loops) < $curl_loops = 0; return false; >curl_setopt($ch, CURLOPT_HEADER, true); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $data = curl_exec($ch); $dd = explode("\r\n\r\n", $data); // или $dd = explode("\r\n", $data); $header = $dd[0]; $data = @$dd[1]; $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); if ($http_code == 301 || $http_code == 302) < $matches = array(); preg_match('/Location:(.*?)\n/', $header, $matches); $url = @parse_url(trim(array_pop($matches))); if (!$url) < $curl_loops = 0; return $data; >$last_url = parse_url(curl_getinfo($ch, CURLINFO_EFFECTIVE_URL)); if (empty($url['scheme'])) < $url['scheme'] = $last_url['scheme']; >if (empty($url['host'])) < $url['host'] = $last_url['host']; >if (empty($url['path'])) < $url['path'] = $last_url['path']; >$new_url = $url['scheme'] . '://' . $url['host'] . $url['path'] . ($url['query'] ? '?' . $url['query'] : ''); curl_setopt($ch, CURLOPT_URL, $new_url); return curl_redir_exec($ch); > else < $curl_loops = 0; return $data; >> $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, 'https://google.com'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_HEADER, false); $html = curl_redir_exec($ch); curl_close($ch); echo $html;

Источник

Почему CURL выдает 302?

Всех приветствую.
Такая проблема отправляю POST запрос через CURL на другой сайт, но мне выдает ошибку 302.
А как я понял это редирект. А редирект на этом сайте возникает только при запросе без POST. Следовательно сервер не получает наш POST запрос. В чем может быть проблема?
Более полугода назад как то решал эту проблему, но уже забыл.
Подскажите добрые люди.

 'http://sgu.ru/schedule/teacher/search', CURLOPT_RETURNTRANSFER => true, CURLOPT_POST => true, CURLOPT_POSTFIELDS => http_build_query(array('js' => '1', 'search' => 'Ситникова' )))); $response = curl_exec($myCurl); curl_close($myCurl); echo "Ответ на Ваш запрос: ".$response; ?>
function findTeacher()< var search = jQuery(":input[name=query]").attr('value'); if(search != '') jQuery.ajax(< url: "/schedule/teacher/search", //url : "http://sgu/schedule/teacher/search", type: 'POST', data: < js : '1', search: search >, dataType: 'json', timeout: 8000, beforeSend: function()< jQuery("#results").html( "
" + " Подождите, Ваш запрос выполняется" + "
"); >, success: function(json)< var content = ""; jQuery.each(json, function()< var teacher = this['id'].split('id'); teacher = teacher[0]||teacher[1]; content += ""+this['fio']+"
"; >); jQuery("#results").html( "
"+content+"
"); if(content == '') jQuery("#results").html("
Поиск не дал результатов
"); >, error: function() < jQuery("#results").html("
Во время выполнения запроса возникла ошибка. Попробуйте повторить попытку позже
"); > >); >;

Источник

Читайте также:  Php translit to russian

Following redirects with Curl in PHP.

As a good web citizen, I try to always follow redirects. Not just in my browser, where I actually don’t have all that much control over things, but also a consumer of web services.

When doing requests with CURL, redirects are not followed by default.

 $curl = curl_init('http://example.org/someredirect'); curl_setopt($curl, CURLOPT_POSTFIELDS, "foo"); curl_setopt($curl, CURLOPT_POST, true); curl_exec($curl); ?> 

Assuming the given url actually redirects like this:

HTTP/1.1 301 Moved Permanently Location: /newendpoint 

Curl will automatically just stop. To make it follow redirects, the FOLLOWLOCATION setting is needed, as such:

 $curl = curl_init('http://example.org/someredirect'); curl_setopt($curl, CURLOPT_POSTFIELDS, "foo"); curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true); curl_setopt($curl, CURLOPT_POST, true); curl_exec($curl); ?> 

CURLOPT_FOLLOWLOCATION will follow the redirects up to 5 times (by default).

However, if you look at the second request, it actually does a GET request after the POST .

This is also the default behavior for browsers, but actually non-conforming with the HTTP standard, and also not desirable for consumers of web services.

To fix this, all you have to do is use CURLOPT_CUSTOMREQUEST instead of CURLOPT_POST :

 $curl = curl_init('http://example.org/someredirect'); curl_setopt($curl, CURLOPT_POSTFIELDS, "foo"); curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true); curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST"); curl_exec($curl); ?> 

Streams

After doing this, the secondary request will be a POST request as well. There’s one more issue though, if you were doing a POST or a PUT request you probably had a request body attached.

There’s two ways to supply a request body, as a string or as a stream. If we were uploading a file it makes much more sense to use a stream, because it unlike posting a string, a stream doesn’t have to be kept in memory.

To upload a stream with curl, you need CURLOPT_PUT and CURLOPT_INFILE . Don’t let the name CURLOPT_PUT fool you, it’s use for every request, and without CURLOPT_PUT , CURLOPT_INFILE is ignored.

For example, this is how we could upload a large file using POST.

 $curl = curl_init('http://example.org/someredirect'); curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true); curl_setopt($curl, CURLOPT_PUT, true); curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($curl, CURLOPT_INFILE, fopen('largefile.json', 'r')); curl_exec($curl); ?> 

This will work great, unless the target location redirects. If it does, curl will throw the following error:

Necessary data rewind wasn't possible (code #65) 

This seems to be related to PHP bug #47204.

Basically this means that you cannot use CURLOPT_INFILE and CURLOPT_FOLLOWLOCATION together. There’s two alternatives:

  1. Don’t use CURLOPT_INFILE , but send the request body as a string instead, with CURLOPT_POSTFIELDS .
  2. Don’t use CURLOPT_FOLLOWLOCATION , but instead manually check if the response was a 3xx redirect and manually follow each hop.

Strings

Using CURLOPT_POSTFIELDS you can supply a request body as a string. Lets try to upload our earlier failed request using that method:

 $curl = curl_init('http://example.org/someredirect'); curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true); curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($curl, CURLOPT_POSTFIELDS, file_get_contents('largefile.json')); curl_exec($curl); ?> 

This also will not work exactly as you expect. While the second request to /someredirect will still be a POST request, it will be sent with an empty request body.

To fix this, use the undocumented CURLOPT_POSTREDIR option.

 $curl = curl_init('http://example.org/someredirect'); curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true); curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($curl, CURLOPT_POSTFIELDS, file_get_contents('largefile.json')); curl_setopt($curl, CURLOPT_POSTREDIR, 3); curl_exec($curl); ?> 

According to the PHP changelog, this was added in PHP 5.3.2, and according to PHP bug #49571 there are four possible values:

0 -> do not set any behavior 1 -> follow redirect with the same type of request only for 301 redirects. 2 -> follow redirect with the same type of request only for 302 redirects. 3 -> follow redirect with the same type of request both for 301 and 302 redirects. 

Looking for a CTO or senior developer for your next project? I'm looking for contracts or full-time gigs! Check out my resume or drop me a line! -->

Web mentions

Comments

MeadSteve • Jul 23, 2013 I guess when you get a 301/308 it'd normally be worth logging something as well, for the maintainer of the code to take some action. Versus a 302/307 where you'd be happy for the code to do this silently.

Tom Binga • Mar 20, 2014 You helped solved a problem that's been holding me back for a week or so now. Thank you!

Marcos Saturno • Jun 03, 2014 Very good info! I'm still having problems when trying to write onto web HDFS (hadoop) from a PHP script. If I make a PUT request passing CREATE as a parameter, it will provide me a 307 temporary redirect, so i'd need to make a second PUT request to the new URL provided. I'm not able to follow it or at least slipt the redirect URL from the HTTP Response. Could you please help me with it? DOC:
http://hadoop.apache.org/do. I'm using something like: $options = array( // CURLOPT_PUT => true, CURLOPT_HEADER => true, CURLOPT_CUSTOMREQUEST => "PUT", CURLOPT_FOLLOWLOCATION => true ); $ch = curl_init(':/webhdfs/v1/user/USER?op=CREATE'); // Execute
curl_setopt_array($ch, $options); curl_exec($ch); //echo curl_errno($ch); if(!curl_errno($ch))
< $info = curl_getinfo($ch); echo 'Took ' . $info['total_time'] . ' seconds to send a request to ' . $info['url']; >// Close handle curl_close($ch); ?>

Evert • Jun 03, 2014 Does your request not have a body? I wonder if that messes things up. You may want to PUT an empty string instead of nothing at all, because curl may fall back to 'GET' behavior (although with a PUT method).

Marcos Saturno • Jun 03, 2014 Hmm, good tip! But actually I found some classes ready to use WEB HDFS:
https://github.com/simpleen. Tx for the help, anyways! Regards, Marcos.

Roger Qiu • Jun 08, 2014 I don't feel secure knowing my request might be redirected to some place I don't know.

Ajai • Mar 19, 2015 i am doing an request using Advanced REST Client and i find some redirects (not cached) , but i get the actual response. But when i try the same using PHP curl it doesnt work , i dont get the output , but the redirected output is displayed. Please can any one help me

Hassan Nomani Alvi • Feb 27, 2016 I am trying to post data using curl.After posting I would like to go to the url.In other words I am trying to get same functionality as we get with form method="post" and action="someurl.php" .How to do this?Thanks in advance.

Источник

Оцените статью