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

I basically created a script using Curl and PHP that sends data to the website e.g. 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

Related

Check header response before download in single request with CURL

Is it possible to check the response headers (200=OK) and download a file in a single CURL request?
Here is my code. The problem with this is that it makes 2 requests, and hence the second request can be different and the saved file will be overwritten. This is a problem with rate limited API. I searched here on Stackoverflow but most solutions still make 2 requests.
// Check response first, we don't want to download the response error to the file
$urlCheck = checkRemoteFile($to_download);
if ($urlCheck) {
// Response is 200, continue
} else {
// Do not overwrite existing file
echo 'Download failed, response code header is not 200';
exit();
}
// File Handling
$new_file = fopen($downloaded, "w") or die("cannot open" . $downloaded);
// Setting the curl operations
$cd = curl_init();
curl_setopt($cd, CURLOPT_URL, $to_download);
curl_setopt($cd, CURLOPT_FILE, $new_file);
curl_setopt($cd, CURLOPT_TIMEOUT, 30); // timeout is 30 seconds, to download the large files you may need to increase the timeout limit.
// Running curl to download file
curl_exec($cd);
if (curl_errno($cd)) {
echo "the cURL error is : " . curl_error($cd);
} else {
$status = curl_getinfo($cd);
echo $status["http_code"] == 200 ? "File Downloaded" : "The error code is : " . $status["http_code"] ;
// the http status 200 means everything is going well. the error codes can be 401, 403 or 404.
}
// close and finalize the operations.
curl_close($cd);
fclose($new_file);
# FUNCTIONS
function checkRemoteFile($url) {
$curl = curl_init($url);
//don't fetch the actual page, you only want to check the connection is ok
curl_setopt($curl, CURLOPT_NOBODY, true);
//do request
$result = curl_exec($curl);
$ret = false;
//if request did not fail
if ($result !== false) {
//if request was ok, check response code
$statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ($statusCode == 200) {
$ret = true;
}
}
curl_close($curl);
return $ret;
}

How detect if external website working or not?

How can I detect if external website working or not? I have thinked about HTTP ERROR MESSAGE. In general something as:
if ( <<something(url)>> != 200 ) {
// website defined in url working (up)
} else {
// website defined in url not working (down)
}
200 is code that define a success querying url. Just so understood reading here: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
Try using CURL. The example is adapted from cur_getinfo()
// Create a curl handle
$ch = curl_init('http://stackoverflow.com/');
//Return only headers
curl_setopt($ch, CURLOPT_NOBODY, true);
// Execute
curl_exec($ch);
// Check if any error occurred
if(!curl_errno($ch))
$info = curl_getinfo($ch);
// Close handle
curl_close($ch);
if ( isset($info) && $info['http_code'] == 200 )
echo "Website is up!";
else
echo "Website is down.";

PHP Curl Check 404 : Always return HTTPCODE 200 OK

I am trying to fix links on a website. I have to check for 404 for all links on a page. I am using php curl to check response http code. But strangely it always return 200 OK.
Here is my code for is_404(),
$curl = curl_init($url);
//don't fetch the actual page, you only want to check the connection is ok
curl_setopt($curl, CURLOPT_NOBODY, true);
//do request
$result = curl_exec($curl);
$ret = true;
//if request did not fail
if ($result !== false) {
//if request was ok, check response code
$statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ($statusCode == 200) {
$ret = false;
}
}
curl_close($curl);
return $ret;
I always return 200 OK even on a page where there is 404 page is displaying. Server is handling all 404 with proper page.
Any help would be appreciated!
i had the same issue until i understand it was because of multiple failover ip in my network configuration
host A ( failover ip1,failover ip2 )
host B ( failover ip1,failover ip2 )
curl create false positive on host B because it resolve by default the IP, even if the failover point to host A, the call was in local
perhaps it s the same on your configuration ?
a simple workaround which fix my problem:
curl_setopt($ch, CURLOPT_INTERFACE, "eth0");

PHP CURL Error after changing only url

For some reason my CURL isnt working now, all i did was change the url (as before i was using this to call info from the need for speed world servers) and it worked flawlessly, now I am trying to use it with IMDBAPI and it gives me an error.
url i type in:
http://localhost/movie.php?title=The Green Mile
Code:
<?php
$title = $_GET['title'];
//optional comment out or delete
error_reporting(E_ALL);
// The POST URL and parameters
$request = 'http://www.imdbapi.com/?t='.$title.'&r=XML';
// Get the curl session object
$session = curl_init($request);
// Set the POST options.
curl_setopt($session, CURLOPT_HEADER, true);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
// Do the POST and then close the session
$response = curl_exec($session);
curl_close($session);
// Get HTTP Status code from the response
$status_code = array();
preg_match('/\d\d\d/', $response, $status_code);
// Check for errors
switch( $status_code[0] ) {
case 200:
// Success
break;
case 503:
die('Service unavailable. An internal problem prevented us from returning data to you.');
break;
case 403:
die('Forbidden. You do not have permission to access this resource, or are over your rate limit.');
break;
case 400:
// You may want to fall through here and read the specific XML error
die('Bad request. The parameters passed to the service did not match as expected. The exact error is returned in the XML response.');
break;
default:
die('Your call returned an unexpected HTTP status of:' . $status_code[0]);
}
// Get the XML from the response, bypassing the header
if (!($xml = strstr($response, '<?xml'))) {
$xml = null;
}
// Output the XML
$movieInfo = simplexml_load_string($xml);
$movieTitle = $movieInfo->movie['title'];
echo "Title: $movieTitle <br />";
?>
Error:
Bad request. The parameters passed to the service did not match as expected. The exact error is returned in the XML response.
I am a noob to CURL so any help is appreciated.
You should urlencode() the $title.
http://www.imdbapi.com/?t=The%20Green%20Mile&r=XML
This one works fine for me. Try to rawurlencode that title
$title = rawurlencode($title);
As Shi said,you need encode the values:
$title = rawurlencode($_GET["title"]);
You can get the http code of your request with:
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

Checking redirect in PHP before actioning

Is there a way to check if the server responds with an error code before sending a user there?
Currently, I am redirecting based on user editable input from the backend (client request, so they can print their own domain, but send people elsewhere), but I want to check if the URL will actually respond, and if not send them to our home page with a little message.
You can do this with CURL:
$ch = curl_init('http://www.example.com/');
//make a HEAD request - we don't need the response body
curl_setopt($ch, CURLOPT_NOBODY, true);
// Execute
curl_exec($ch);
// Check if any error occured
if(!curl_errno($ch))
{
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); //integer status code
}
// Close handle
curl_close($ch);
You can then check if $httpCode is OK. Generally a 2XX response code is ok.
You could try the following, but beware that this is a seperate request to the redirect, so if something goes wrong in between then a user can still get sent to an erroneous location.
$headers = get_headers($url);
if(strpos($headers[0], 200) !== FALSE) {
// redirect to $url
} else {
// redirect to homepage with error notice
}
The PHP manual for get_headers(): http://www.php.net/manual/en/function.get-headers.php
I don't understand what you mean by making sure the URL will respond. But if you want to display a message you can use a $_SESSION variable. Just remember to put session_start() on every page that will use the variable.
So when you want to redirect them back to the home page. You could do this.
// David Caunt's answer
$ch = curl_init('http://www.example.com/');
// Execute
curl_exec($ch);
// Check if any error occured
if(!curl_errno($ch))
{
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); //integer status code
// My addition
if( $httpCode >= 200 && $httpCode < 300 ) {
// All is good
}else {
// This doesn't exist
// Set the error message
$_SESSION['error_message'] = "This domain doesn't exist";
// Send the user back to the home page
header('Location: /home.php'); // url based: http://your-site.com/home.php
}
// My addition ends here
}
// Close handle
curl_close($ch);
Then on your home page, you'll something like this.
// Make sure the error_message is set
if( isset($_SESSION['error_message']) ) {
// Put the error on the page
echo '<div class="notification warning">' . $_SESSION['error_message'] . '</div>';
}

Categories