Home > Enterprise >  Response 302; Need a result like calling curl
Response 302; Need a result like calling curl

Time:02-21

I need the same result as when calling curl from terminal/consol, even if the answer is 302. Unfortunately I didn't get any data during my attempts.

$ curl bretten.work
<a href="https://www.bretten.work">Moved Permanently</a>.

CodePudding user response:

Your server seems to block requests if no user agent is set. Try this:

<?php

$ch = curl_init('http://bretten.work/');
curl_setopt($ch, CURLOPT_USERAGENT, 'curl/7.68.0');
curl_exec($ch);

To diagnose further problems try to compare curl -vvv https://example.com/ with this:

<?php

$ch = curl_init('http://example.com/');

#curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);

$cv = curl_version();
$useragent = 'curl';
if (isset($cv['version'])) {
    $useragent .= '/' . $cv['version'];
}
curl_setopt($ch, CURLOPT_USERAGENT, $useragent);

curl_setopt($ch, CURLOPT_VERBOSE, true);
$streamVerboseHandle = fopen('php://temp', 'w ');
curl_setopt($ch, CURLOPT_STDERR, $streamVerboseHandle);
$result = curl_exec($ch);
if ($result === false) {
    printf("cUrl error (#%d): %s<br>\n",
           curl_errno($ch),
           htmlspecialchars(curl_error($ch)))
           ;
}
rewind($streamVerboseHandle);
$verboseLog = stream_get_contents($streamVerboseHandle);

echo "cUrl verbose information:\n", 
     "<pre>", htmlspecialchars($verboseLog), "</pre>\n";

CodePudding user response:

To make php curl follow redirects, the FOLLOWLOCATION setting is needed, as such:

<?php
$curl = curl_init('http://bretten.work/');
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_exec($curl);

See https://evertpot.com/curl-redirect-requestbody/ for more options.

  •  Tags:  
  • php
  • Related