- test url, URL is exist or not exist
- How to Check if a URL Exists in PHP: Best Practices and Code Examples
- Using the get_headers() Function
- Using the file_get_contents() Function
- PHP : How can I check if a URL exists via PHP?
- Checking the Status Code in the Response Header
- Checking if a File URL Exists on a Remote Server Using PHP
- Checking if a URL Exists in Laravel Using GuzzleHttp\Client
- Best Practices for URL Checking
- Additional code samples to check if a URL exists in PHP
- Conclusion
test url, URL is exist or not exist
In this post we will show you different method for test url, URL is exist or not exist(broken url or not).
This is very fast method to test your url by using filter_var($your_url, FILTER_VALIDATE_URL); function.
NOTE : FILTER_VALIDATE_URL will not validate for like url hase the protocol ssh://, ftp:// etc..
// add your url. $your_url = "http://www.onlinecode.org"; if (filter_var($your_url, FILTER_VALIDATE_URL) === FALSE) < // broken url. echo ('Not a valid URL'); >else < // Not broken url. echo ('valid URL'); >
If we have to check image, pdf, txt or other type of url at that this method will help you lost. In this method we use fopen with rad methods and check any result is available.
$url_handle = @fopen('http://www.onlinecode.org/example/www-onlinecode-org-image-test.png','r'); if(!$url_handle) < // broken url. echo ('Not a valid URL'); >else < // Not broken url. echo ('valid URL'); >
In this method we use file_get_contents and check url exist or not. In this method, It is also work for image, pdf, txt or other type of url.
function check_url_exists($your_url) < if (@file_get_contents($your_url,false,NULL,0,1)) < return true; >return false; > // add your url. $your_url = "http://www.onlinecode"; var_dump (check_url_exists($your_url));
In this method we use curl it will work for any type of url.
// add your url. $your_url = "http://www.onlinecode.org/example/www-onlinecode-org-image-test.png"; $connection = curl_init(); curl_setopt($connection, CURLOPT_URL, $your_url); // add url curl_setopt($connection, CURLOPT_RETURNTRANSFER, 1); curl_setopt($connection, CURLOPT_FOLLOWLOCATION, 1); $curl_result = curl_exec($connection); $curl_info = curl_getinfo($connection); if($curl_info['http_code'] == 404) < // broken url. echo ('Not a valid URL'); >else < // Not broken url. echo ('valid URL'); >
This Method is advance for find url exist or not with HTTP status codes. In this method, it will show you result why url is not exist with HTTP status codes, example for 404 page not found.
function check_url_exists($your_url, array $set_options = array()) < if (empty($your_url)) < throw new Exception('URL is empty'); >// list of HTTP status codes $http_status_codes = array( 100 => 'Continue', // status codes 100 101 => 'Switching Protocols', // status codes 101 102 => 'Processing', // status codes 102 200 => 'OK', // status codes 200 201 => 'Created', // status codes 201 202 => 'Accepted', // status codes 202 203 => 'Non-Authoritative Information', // status codes 203 204 => 'No Content', // status codes 204 205 => 'Reset Content', // status codes 205 206 => 'Partial Content', // status codes 206 207 => 'Multi-Status', // status codes 207 208 => 'Already Reported', // status codes 208 226 => 'IM Used', // status codes 226 300 => 'Multiple Choices', // status codes 300 301 => 'Moved Permanently', // status codes 301 302 => 'Found', // status codes 302 303 => 'See Other', // status codes 303 304 => 'Not Modified', // status codes 304 305 => 'Use Proxy', // status codes 305 306 => 'Switch Proxy', // status codes 306 307 => 'Temporary Redirect', // status codes 307 308 => 'Permanent Redirect', // status codes 308 400 => 'Bad Request', // status codes 400 401 => 'Unauthorized', // status codes 401 402 => 'Payment Required', // status codes 402 403 => 'Forbidden', // status codes 403 404 => 'Not Found', // status codes 404 405 => 'Method Not Allowed', // status codes 405 406 => 'Not Acceptable', // status codes 406 407 => 'Proxy Authentication Required', // status codes 407 408 => 'Request Timeout', // status codes 408 409 => 'Conflict', // status code 409 410 => 'Gone', // status codes 410 411 => 'Length Required', // status codes 411 412 => 'Precondition Failed', // status codes 412 413 => 'Payload Too Large', // status codes 413 414 => 'Request-URI Too Long', // status codes 414 415 => 'Unsupported Media Type', // status codes 415 416 => 'Requested Range Not Satisfiable', // status codes 416 417 => 'Expectation Failed', // status codes 417 418 => 'I\'m a teapot', // status codes 418 422 => 'Unprocessable Entity', // status codes 422 423 => 'Locked', // status codes 423 424 => 'Failed Dependency', // status codes 424 425 => 'Unordered Collection', // status codes 425 426 => 'Upgrade Required', // status codes 426 428 => 'Precondition Required', // status codes 428 429 => 'Too Many Requests', // status codes 429 431 => 'Request Header Fields Too Large', // status codes 431 449 => 'Retry With', // status codes 449 450 => 'Blocked by Windows Parental Controls', // status codes 450 500 => 'Internal Server Error', // status codes 500 501 => 'Not Implemented', // status codes 501 502 => 'Bad Gateway', // status codes 502 503 => 'Service Unavailable', // status codes 503 504 => 'Gateway Timeout', // status codes 504 505 => 'HTTP Version Not Supported', // status codes 505 506 => 'Variant Also Negotiates', // status codes 506 507 => 'Insufficient Storage', // status codes 507 508 => 'Loop Detected', // status codes 508 509 => 'Bandwidth Limit Exceeded', // status codes 509 510 => 'Not Extended', // status codes 510 511 => 'Network Authentication Required', // status codes 511 599 => 'Network Connect Timeout Error' // status codes 599 ); $result_return = ""; $connection = curl_init($your_url); curl_setopt($connection, CURLOPT_NOBODY, true); curl_setopt($connection, CURLOPT_FOLLOWLOCATION, true); if (isset($set_options['timeout'])) < $timeout = (int) $set_options['timeout']; curl_setopt($connection, CURLOPT_TIMEOUT, $timeout); >curl_exec($connection); $returned_status_code = curl_getinfo($connection, CURLINFO_HTTP_CODE); curl_close($connection); if (array_key_exists($returned_status_code, $http_status_codes)) < $result_return = " URL : '' - Error code: - Definition: "; > else < $result_return = "'' does not exist"; > return $result_return; > // add your url. $your_url = "http://www.onlinecode"; var_dump (check_url_exists($your_url));function check_url($test_url) < $ch_init = curl_init(); curl_setopt($ch_init, CURLOPT_URL, $test_url); curl_setopt($ch_init, CURLOPT_HEADER, 1); curl_setopt($ch_init , CURLOPT_RETURNTRANSFER, 1); $data = curl_exec($ch_init); $headers_result = curl_getinfo($ch_init); curl_close($ch_init); return $headers_result['http_code']; >$test_url = "http://onlinecode"; $check_url_result = check_broken_url($test_url); if ($check_url_result == '200') < echo "This is Working Link."; >else
How to Check if a URL Exists in PHP: Best Practices and Code Examples
Learn how to check if a URL exists in PHP using different methods such as get_headers(), file_get_contents(), fopen(), cURL, and str_pos(). Follow best practices for URL checking and ensure your website's security.
- Using the get_headers() Function
- Using the file_get_contents() Function
- PHP : How can I check if a URL exists via PHP?
- Checking the Status Code in the Response Header
- Checking if a File URL Exists on a Remote Server Using PHP
- Checking if a URL Exists in Laravel Using GuzzleHttp\Client
- Best Practices for URL Checking
- Additional code samples to check if a URL exists in PHP
- Conclusion
- How to check the existence of URL in PHP?
- How to get domain from URL in PHP?
- How is a URL connected to PHP?
- How check if file exists in URL?
As a developer, checking if a URL exists is a common task that is necessary for many web development projects. There are several ways to check if a URL exists in PHP, including using the get_headers() function, file_get_contents() function, fopen() , cURL, and str_pos() . In this article, we will discuss the different ways to check if a URL exists in PHP, their advantages and disadvantages, and best practices for URL checking.
Using the get_headers() Function
The get_headers() function is the best way to check if a URL exists in PHP. The function returns an array of headers sent by the server in response to an HTTP request. The first index of the array contains the HTTP response code, which can be used to check if the URL exists. An HTTP response code of 200 indicates that the URL exists, while a code of 404 indicates that the URL does not exist.
Here’s an example of how to use the get_headers() function to check if a URL exists:
$headers = get_headers('http://www.example.com'); $status = strpos($headers[0], '200') ? true : false;
Using the file_get_contents() Function
Another way to check if a URL exists in PHP is to use the file_get_contents() function. The function returns the contents of a file as a string, which can be used to check if the URL exists. If the URL does not exist, the function will return false.
Here’s an example of how to use the file_get_contents() function to check if a URL exists:
if(@file_get_contents('http://www.example.com')) < echo 'URL exists'; >else
PHP : How can I check if a URL exists via PHP?
PHP : How can I check if a URL exists via PHP? [ Beautify Your Computer : https://www.hows Duration: 1:12
Checking the Status Code in the Response Header
The existence of a URL can also be checked by checking the status code in the response header. This can be done by using the get_headers() function or by sending a HEAD request using cURL. A status code of 200 indicates that the URL exists, while a code of 404 indicates that the URL does not exist.
Here’s an example of how to check the status code using cURL:
$url = 'http://www.example.com'; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HEADER, true); curl_setopt($ch, CURLOPT_NOBODY, true); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_TIMEOUT, 10); $output = curl_exec($ch); $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); if($httpcode == 200) < echo 'URL exists'; >else
Checking if a File URL Exists on a Remote Server Using PHP
The fopen() function and cURL can be used to check if a file URL exists on a remote server using PHP. The fopen() function opens a file or URL and returns a file pointer, which can be used to check if the URL exists.
Here’s an example of how to use the fopen() function to check if a URL exists:
$url = 'http://www.example.com'; if(@fopen($url, 'r')) < echo 'URL exists'; >else
Checking if a URL Exists in Laravel Using GuzzleHttp\Client
The GuzzleHttp\Client library can be used to check if a URL exists in Laravel. The library provides a simple and efficient way to send HTTP requests and handle responses.
Here’s an example of how to use the GuzzleHttp\Client library to check if a URL exists:
$client = new GuzzleHttp\Client(); $response = $client->get('http://www.example.com'); if($response->getStatusCode() == 200) < echo 'URL exists'; >else
Best Practices for URL Checking
When checking if a URL exists in PHP, it’s important to follow best practices to ensure that your websites and applications are secure and free from errors. Here are some best practices for URL checking:
- sanitize user input to prevent xss attacks and other security vulnerabilities.
- Use SSL/TLS to encrypt the data transmitted between the server and the client.
- Use try-catch blocks to handle exceptions and errors that may occur during URL checking.
By following these guidelines, developers can ensure that their websites and applications are secure and free from errors.
Additional code samples to check if a URL exists in PHP
In Php , php check if url exists code sample
else < $status = "URL Doesn't Exist"; >// Display result echo($status); ?>
In Php case in point, php check if a url exists code sample
function urlExists($url=NULL) < if($url == NULL) return false; $ch = curl_init($url); curl_setopt($ch, CURLOPT_TIMEOUT, 5); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $data = curl_exec($ch); $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); if($httpcode>=200 && $httpcode <300)< return true; >else < return false; >>
In Php , php url exists valid code sample
function isValidUrl($url) < // first do some quick sanity checks: if(!$url || !is_string($url))< return false; >// quick check url is roughly a valid http request: ( http://blah/. ) if( ! preg_match('/^http(s)?:\/\/[a-z0-9-]+(\.[a-z0-9-]+)*(:7+)?(\/.*)?$/i', $url) ) < return false; >// the next bit could be slow: if(getHttpResponseCode_using_curl($url) != 200) < // if(getHttpResponseCode_using_getheaders($url) != 200)< // use this one if you cant use curl return false; >// all good! return true; > function getHttpResponseCode_using_curl($url, $followredirects = true) < // returns int responsecode, or false (if url does not exist or connection timeout occurs) // NOTE: could potentially take up to 0-30 seconds , blocking further code execution (more or less depending on connection, target site, and local timeout settings)) // if $followredirects == false: return the FIRST known httpcode (ignore redirects) // if $followredirects == true : return the LAST known httpcode (when redirected) if(! $url || ! is_string($url))< return false; >$ch = @curl_init($url); if($ch === false) < return false; >@curl_setopt($ch, CURLOPT_HEADER ,true); // we want headers @curl_setopt($ch, CURLOPT_NOBODY ,true); // dont need body @curl_setopt($ch, CURLOPT_RETURNTRANSFER ,true); // catch output (do NOT print!) if($followredirects)< @curl_setopt($ch, CURLOPT_FOLLOWLOCATION ,true); @curl_setopt($ch, CURLOPT_MAXREDIRS ,10); // fairly random number, but could prevent unwanted endless redirects with followlocation=true >else < @curl_setopt($ch, CURLOPT_FOLLOWLOCATION ,false); >// @curl_setopt($ch, CURLOPT_CONNECTTIMEOUT ,5); // fairly random number (seconds). but could prevent waiting forever to get a result // @curl_setopt($ch, CURLOPT_TIMEOUT ,6); // fairly random number (seconds). but could prevent waiting forever to get a result // @curl_setopt($ch, CURLOPT_USERAGENT ,"Mozilla/5.0 (Windows NT 6.0) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1"); // pretend we're a regular browser @curl_exec($ch); if(@curl_errno($ch)) < // should be 0 @curl_close($ch); return false; >$code = @curl_getinfo($ch, CURLINFO_HTTP_CODE); // note: php.net documentation shows this returns a string, but really it returns an int @curl_close($ch); return $code; > function getHttpResponseCode_using_getheaders($url, $followredirects = true) < // returns string responsecode, or false if no responsecode found in headers (or url does not exist) // NOTE: could potentially take up to 0-30 seconds , blocking further code execution (more or less depending on connection, target site, and local timeout settings)) // if $followredirects == false: return the FIRST known httpcode (ignore redirects) // if $followredirects == true : return the LAST known httpcode (when redirected) if(! $url || ! is_string($url))< return false; >$headers = @get_headers($url); if($headers && is_array($headers)) < if($followredirects)< // we want the last errorcode, reverse array so we start at the end: $headers = array_reverse($headers); >foreach($headers as $hline) < // search for things like "HTTP/1.1 200 OK" , "HTTP/1.0 200 OK" , "HTTP/1.1 301 PERMANENTLY MOVED" , "HTTP/1.1 400 Not Found" , etc. // note that the exact syntax/version/output differs, so there is some string magic involved here if(preg_match('/^HTTP\/\S+\s+(265)\s+.*/', $hline, $matches) )/ "HTTP/*** ### ***" $code = $matches[1]; return $code; >> // no HTTP/xxx found in headers: return false; > // no headers : return false; >
Conclusion
Checking if a URL exists in PHP is an important task in web development. The best way to check if a URL exists is to use the get_headers() function, but there are other methods available such as file_get_contents() , fopen() , cURL, and str_pos() . Best practices for URL checking include sanitizing user input, using SSL/TLS, and using try-catch blocks to handle exceptions and errors. By following these guidelines, developers can ensure that their websites and applications are secure and free from errors.