简体   繁体   中英

PHP - How to check if Curl actually post/send request?

I basically created a script using Curl and PHP that sends data to the website eg host, port and time. Then it submits the data. How would I know if the Curl/PHP actually sent those data to the web pages?

$fullcurl = "?host=".$host."&time=".$time.";

Any ways to see if they actually sent the data to those URLs on My MYSQL?

You can use curl_getinfo() to get the status code of the response like so:

// set up curl to point to your requested URL
$ch = curl_init($fullcurl);
// tell curl to return the result content instead of outputting it
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

// execute the request, I'm assuming you don't care about the result content
curl_exec($ch);

if (curl_errno($ch)) {
    // this would be your first hint that something went wrong
    die('Couldn\'t send request: ' . curl_error($ch));
} else {
    // check the HTTP status code of the request
    $resultStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    if ($resultStatus == 200) {
        // everything went better than expected
    } else {
        // the request did not complete as expected. common errors are 4xx
        // (not found, bad request, etc.) and 5xx (usually concerning
        // errors/exceptions in the remote script execution)

        die('Request failed: HTTP status code: ' . $resultStatus);
    }
}

curl_close($ch);

For reference: http://en.wikipedia.org/wiki/List_of_HTTP_status_codes

Or, if you are making requests to some sort of API that returns information on the result of the request, you would need to actually get that result and parse it. This is very specific to the API, but here's an example:

// set up curl to point to your requested URL
$ch = curl_init($fullcurl);
// tell curl to return the result content instead of outputting it
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

// execute the request, but this time we care about the result
$result = curl_exec($ch);

if (curl_errno($ch)) {
    // this would be your first hint that something went wrong
    die('Couldn\'t send request: ' . curl_error($ch));
} else {
    // check the HTTP status code of the request
    $resultStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    if ($resultStatus != 200) {
        die('Request failed: HTTP status code: ' . $resultStatus);
    }
}

curl_close($ch);

// let's pretend this is the behaviour of the target server
if ($result == 'ok') {
    // everything went better than expected
} else {
    die('Request failed: Error: ' . $result);
}

in order to be sure that curl sends something, you will need a packet sniffer. You can try wireshark for example.

I hope this will help you,

Jerome Wagner

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