How detect if external website working or not? - php

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.";

Related

Why is my get_headers not working ? - Checking to see if a url exists or not

I am trying to validate if the input of a url, actually exists or not. I have been trying the following code, however I got no success. This is the following code:
Using cURL:
<?php
$url = 'https://github.com';
$handle = curl_init($url);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, TRUE);
/* Get the HTML or whatever is linked in $url. */
$response = curl_exec($handle);
/* Check for 404 (file not found). */
$httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
if($httpCode == 404) {
echo "Url not working";
}
echo "true";
?>
Using get_headers
<?php
// Initialize an URL to the variable
$url = "https://www.geeksforgeeks.org";
// Use get_headers() function
$headers = #get_headers($url);
// Use condition to check the existence of URL
if($headers && strpos( $headers[0], '200')) {
$status = "URL Exist";
}
else {
$status = "URL Doesn't Exist";
}
// Display result
echo($status);
?>
I have searche both these answers on stackoverflow and other websites, and used these to check if the url I give actually exists. When I write down a non existing url, I would like it to output that the website does not exists, however, I always end up having the same output as an existing url, meaning that somethig might be wrong, although I cannot fully see it. By the first code, the output is always true, even if the url does not exist. By the second code, the output is always 'URL doesn't exist', even if the url actually exists. Am I doing something wrong? I am using PHP Version 7.4, is this tool still working? I apologize if the question is not clear.

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");

Curl response in php

Am using Curl to send sms using a gateway , a, getting 200 when everything is ok and 400 if its not send now , i should get other things from the gateway such as phone number and other information , so am i missing something ?
// if the Form is submited
//if (isset($_POST['PhoneNumber'])) {
if ($_SERVER['REQUEST_METHOD'] == "POST"){
// Fetch Phone Number and escape it for security
$Phone = mysql_real_escape_string($_POST['PhoneNumber']);
// Fetch Text and escape it for security
$Text = mysql_real_escape_string($_POST['Text']);
// Structure the URl
$url = "http://xxxxxxxxxxx:xxxx?PhoneNumber=".urlencode($Phone)."&Text=".urlencode($Text)."&User=xxx&Password=xxx";
// Handeling the Curl
$handle = curl_init($url);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, TRUE);
/* Get the HTML or whatever is linked in $url. */
$response = curl_exec($handle);
/* Check for 404 (file not found). */
$httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
if ($httpCode=="200"){
// if everything is okey , the gateway returns 200 which means OK
echo "Massage Was Sent , Thank you ";
} elseif ($httpCode=="400"){
// if there was an error , the form returns a 400 which means that the sms Failed
echo "Massage was not sent , Please Try Again";
}
// Cloase the Curl Connection
curl_close($handle);
Thank you Best regards,
$response should contain the response, try:
echo '<pre>';
print_r($response);
echo '</pre>';
to show its content

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 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

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