문제

I am Using PHP curl, my target url gives 200 or 500 depending on request parameter. But how ever it throw 500 or 200 i am getting 200 using curl_getinfo($ch, CURLINFO_HTTP_CODE). Here is the code

/**
 * use for get any file form a remote uri
 *
 * @param String $url
 * @return String
 */
public function getFileUsingCurl($url)
{
    //set all option
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);

    $file = curl_exec($ch);

    if (200 == curl_getinfo($ch, CURLINFO_HTTP_CODE)) {
        curl_close($ch);
        return $file;
    } else {
        curl_close($ch);
        return false;
    }
}

How i can get the right HTTP code form my target url ?

도움이 되었습니까?

해결책

Try this:

public function getFileUsingCurl($url)
{
    //set all option
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
    $file = curl_exec($ch);
    $curlinfo = curl_getinfo($ch);
    curl_close($ch);
    $httpcode = $curlinfo['http_code'];
    if($httpcode == "200"){
    return $file;
    }else{
    return false;
    }

}

Note:
Make sure you're not being redirected (code 301 or 302)

다른 팁

Could you try curl'ing the url on your terminal to check its status code with: curl -I www.site.com

(I know this a question rather than answer, but i dont have enough stackoverflow rep to comment yet haha, so i'll edit this to an answer when i have more info)

you should use curl_setopt($c, CURLOPT_HEADER, true); to include headers in output.

http://www.php.net/manual/en/function.curl-setopt.php

Then use var_dump($file) to see whether it is really 200 or not...

Using below code for checking status should work

$infoArray = curl_getinfo($ch);
$httpStatus = $infoArray['http_code'];
if($httpStatus == "200"){
    // do stuff here
}
curl_setopt($c, CURLOPT_HEADER, true); // you need this to get the headers
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

Use guzzle to interact with CURL in a sane manner. Then your script becomes something like:

<?php
use Guzzle\Http\Client;

// Create a client and provide a base URL
$client = new Client('http://www.example.com');

$response = $client->get('/');
$code = $response->getStatusCode();
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top