How to Check If a Url Exists in PHP

How can I check if a URL exists via PHP?

Here:

$file = 'http://www.example.com/somefile.jpg';
$file_headers = @get_headers($file);
if(!$file_headers || $file_headers[0] == 'HTTP/1.1 404 Not Found') {
$exists = false;
}
else {
$exists = true;
}

From here and right below the above post, there's a curl solution:

function url_exists($url) {
return curl_init($url) !== false;
}

check if url exists php

I would use cURL for url verification. An example method would be as follows

    public function urlExists($url) {

$handle = curl_init($url);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, TRUE);

$response = curl_exec($handle);
$httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
curl_close($handle);

if($httpCode >= 200 && $httpCode <= 400) {
return true;
} else {
return false;
}
}

How to check a url exist or not in php

if(! @ file_get_contents('http://www.domain.com/file.txt')){
echo 'path doesn't exist';
}

This is the easiest way to do it. If you are unfamiliar with the @, that will instruct the function to return false if it would have otherwise thrown an error

PHP - Check if the final URL exists

You can tell cURL to follow all redirects, and return the result from the final redirection. Use:

curl_setopt($handle, CURLOPT_FOLLOWLOCATION, true);

What is the best way to check if a URL exists in PHP?

You can use get_headers($url)

Example 2 from Manual:

<?php
// By default get_headers uses a GET request to fetch the headers. If you
// want to send a HEAD request instead, you can do so using a stream context:
stream_context_set_default(
array(
'http' => array(
'method' => 'HEAD'
)
)
);
print_r(get_headers('http://example.com'));

// gives
Array
(
[0] => HTTP/1.1 200 OK
[Date] => Sat, 29 May 2004 12:28:14 GMT
[Server] => Apache/1.3.27 (Unix) (Red-Hat/Linux)
[Last-Modified] => Wed, 08 Jan 2003 23:11:55 GMT
[ETag] => "3f80f-1b6-3e1cb03b"
[Accept-Ranges] => bytes
[Content-Length] => 438
[Connection] => close
[Content-Type] => text/html
)

The first array element will contain the HTTP Response Status code. You have to parse that.

Note that the get_headers function in the example will issue an HTTP HEAD request, which means it will not fetch the body of the URL. This is more efficient than using a GET request which will also return the body.

Also note that by setting a default context, any subsequent calls using an http stream context, will now issue HEAD requests. So make sure to reset the default context to use GET again when done.

PHP also provides the variable $http_response_header

The $http_response_header array is similar to the get_headers() function. When using the HTTP wrapper, $http_response_header will be populated with the HTTP response headers. $http_response_header will be created in the local scope.

If you want to download the content of a remote resource, you don't want to do two requests (one to see if the resource exists and one to fetch it), but just one. In that case, use something like file_get_contents to fetch the content and then inspect the headers from the variable.

PHP - Check if url is valid or not

The below code works well but when i put urls in array & test the same functionality then it does not give proper results ?
Any thoughts why ?
Also if any body would like to update answer to make it dynamic in the sense (should check multiple url at once, when an array of url provided).

  <?php

// URL to check
$url = 'https://www.shareasale.com/m-pr.cfm?merchantID=66802&userID=1860618&productID=1186005518';

$ch = curl_init(); // Initialize a CURL session.
curl_setopt($ch, CURLOPT_URL, $url); // Grab URL and pass it to the variable.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); // Catch output (do NOT print!)
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE); // Return follow location true
$html = curl_exec($ch);
$redirectedUrl = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL); // Getinfo or redirected URL from effective URL
curl_close($ch); // Close handle

$get_final_url = get_final_url($redirectedUrl);
if($get_final_url){
echo is_url_valid($get_final_url);
}else{
echo $redirectedUrl ? is_url_valid($redirectedUrl) : is_url_valid($url);
}

function is_url_valid($url) {
$handle = curl_init($url);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($handle, CURLOPT_NOBODY, true);
curl_exec($handle);

$httpCode = intval(curl_getinfo($handle, CURLINFO_HTTP_CODE));
curl_close($handle);
echo $httpCode;
if ($httpCode == 200) {
return '<b> Valid link </b>';
}
else {
return '<b> Invalid link </b>';
}
}

function get_final_url($url) {
$ch = curl_init();
if (!$ch) {
return false;
}
$ret = curl_setopt($ch, CURLOPT_URL, $url);
$ret = curl_setopt($ch, CURLOPT_HEADER, 1);
$ret = curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$ret = curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$ret = curl_setopt($ch, CURLOPT_TIMEOUT, 30);
$ret = curl_exec($ch);

if (!empty($ret)) {
$info = curl_getinfo($ch);
curl_close($ch);
return false;
if (empty($info['http_code'])) {
return false;
} else {
preg_match('#(https:.*?)\'\)#', $ret, $match);
$final_url = stripslashes($match[1]);
return stripslashes($match[1]);
}
}
}

How to check if the an url exist in php

I found a solution that works:

<?php

namespace AdminBundle\Validator\Constraints;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

Class ContrainteUrlExistValidator extends ConstraintValidator
{
public function validate($url, Constraint $constraint)
{
//Vérifie si l'url peut être vide
if(empty($url)&&$constraint->peutEtreVide)
{
return;
}

//Pattern pour trouver les url qui commence par http:// ou https://
$pattern='/^(https?:\/\/)/';

//Valide l'url et s'assure le preg_match a trouvé un match
if(filter_var($url, FILTER_VALIDATE_URL)&&!empty(preg_match($pattern, $url, $matches)))
{
//Trouve l'host
$hostname=parse_url($url, PHP_URL_HOST);

//Tente de trouver l'adresse IP de l'host
if (gethostbyname($hostname) !== $hostname)
{
//Cherche les données de l'entête
$headers=get_headers($url);

//Tente de trouver une erreur 404
if(!strpos($headers[0], '404'))
{
return;
}
}
}

//Crée une erreur
$this->context->buildViolation($constraint->message)
->setParameter('%string%', $url)
->addViolation();
}
}

how to check if a https site exists in php

I don't know if you can use get_headers with https.

But as an alternative (if you have Curl enabled) you can use the following function:

function getheaders($url) {
$c = curl_init();
curl_setopt($c, CURLOPT_HEADER, true);
curl_setopt($c, CURLOPT_NOBODY, true);
curl_setopt($c, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($c, CURLOPT_SSL_VERIFYHOST, true);
curl_setopt($c, CURLOPT_URL, $url);
$headers = curl_exec($c);
curl_close($c);
return $headers;
}

If you just need the HTTP status code you can modify the function like this:

function getstatus($url) {
$c = curl_init();
curl_setopt($c, CURLOPT_HEADER, true);
curl_setopt($c, CURLOPT_NOBODY, true);
curl_setopt($c, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($c, CURLOPT_SSL_VERIFYHOST, true);
curl_setopt($c, CURLOPT_URL, $url);
curl_exec($c);
$status = curl_getinfo($c, CURLINFO_HTTP_CODE);
curl_close($c);
return $status;
}

If you don't have Curl you could try the following function:

<?php
function my_get_headers($url ) {
$url_info=parse_url($url);
if (isset($url_info['scheme']) && $url_info['scheme'] == 'https') {
$port = 443;
@$fp=fsockopen('ssl://'.$url_info['host'], $port, $errno, $errstr, 10);
} else {
$port = isset($url_info['port']) ? $url_info['port'] : 80;
@$fp=fsockopen($url_info['host'], $port, $errno, $errstr, 10);
}
if($fp) {
stream_set_timeout($fp, 10);
$head = "HEAD ".@$url_info['path']."?".@$url_info['query'];
$head .= " HTTP/1.0\r\nHost: ".@$url_info['host']."\r\n\r\n";
fputs($fp, $head);
while(!feof($fp)) {
if($header=trim(fgets($fp, 1024))) {
$sc_pos = strpos( $header, ':' );
if( $sc_pos === false ) {
$headers['status'] = $header;
} else {
$label = substr( $header, 0, $sc_pos );
$value = substr( $header, $sc_pos+1 );
$headers[strtolower($label)] = trim($value);
}
}
}
return $headers;
}
else {
return false;
}
}

?>

Note that for HTTPS support you should have SSL support enabled. (uncomment extension=php_openssl.dll in php.ini).

If you can't edit your php.ini and don't have SSL support it will be difficult to get the (encrypted) headers.

You can check your wrappers (openssl and httpd) with:

$w = stream_get_wrappers();
echo 'openssl: ', extension_loaded ('openssl') ? 'yes':'no', "<br>\n";
echo 'http wrapper: ', in_array('http', $w) ? 'yes':'no', "<br>\n";
echo 'https wrapper: ', in_array('https', $w) ? 'yes':'no', "<br>\n";
echo 'wrappers: <pre>', var_dump($w), "<br>";

You can check this question on SO for a similar problem.



Related Topics



Leave a reply



Submit