3

I create a plugin for WordPress that requires two files to be exists in order to operate normaly.

The first file is defined as a file system path and the second file is defined as a URL.

Let's say the first file is that:

/home/my_site/public_html/some_folder/required_file.php

and the second file is that:

http://www.my_site.com/some_folder/required_url_file.php

Note that both files are not the same file into the file system. The required_file.php has other content than the required_url_file.php and they act absolutly diferent

Any idea on how to validate the existance of both files ?

KodeFor.Me
  • 13,069
  • 27
  • 98
  • 166
  • possible duplicate of [How can one check to see if a remote file exists using PHP?](http://stackoverflow.com/questions/981954/how-can-one-check-to-see-if-a-remote-file-exists-using-php) - for files use [`is_file`](http://php.net/is_file). – hakre Oct 31 '11 at 11:23

10 Answers10

6

Based on Maor H. code sample, here is a function I am using in my plugins:

/**
 * Check if an item exists out there in the "ether".
 *
 * @param string $url - preferably a fully qualified URL
 * @return boolean - true if it is out there somewhere
 */
function webItemExists($url) {
    if (($url == '') || ($url == null)) { return false; }
    $response = wp_remote_head( $url, array( 'timeout' => 5 ) );
    $accepted_status_codes = array( 200, 301, 302 );
    if ( ! is_wp_error( $response ) && in_array( wp_remote_retrieve_response_code( $response ), $accepted_status_codes ) ) {
        return true;
    }
    return false;
}

I've made this a method in a helper class, however putting this in your theme's functions.php file should make it generally accessible everywhere. However you should always be writing in classes and instantiating them. It is much better for isolating your plugin and theme functionality.

With this in place you can simply use:

if (webItemExists('http://myurl.com/thing.png')) { 
    print 'it iexists'; 
}

Most often you will be using WordPress calls to access all items via a relative or fully qualified URL. If you have a relative reference to something such as /uploads/2012/12/myimage.png you can convert those to a fully qualified URL v. a WordPress relative URL by simply adding get_site_url(). $string when calling the webItemExists() function.

James Jones
  • 3,850
  • 5
  • 25
  • 44
Lance Cleveland
  • 3,098
  • 1
  • 33
  • 36
6

You can check both:

$file = '/home/my_site/public_html/some_folder/required_file.php';
$url = 'http://www.my_site.com/some_folder/required_url_file.php';

$fileExists = is_file($file);
$urlExists = is_200($url);

$bothExists = $fileExists && $urlExists;

function is_200($url)
{
    $options['http'] = array(
        'method' => "HEAD",
        'ignore_errors' => 1,
        'max_redirects' => 0
    );
    $body = file_get_contents($url, NULL, stream_context_create($options));
    sscanf($http_response_header[0], 'HTTP/%*d.%*d %d', $code);
    return $code === 200;
}
hakre
  • 193,403
  • 52
  • 435
  • 836
  • is_200() is not a valid WordPress function. This code fails in WordPress 3.3 on PHP 5.2. – Lance Cleveland Nov 29 '12 at 18:18
  • 3
    @CharlestonSoftwareAssociates: Well, who wrote that it is *part of* Wordpress? If you copy the code from the answer, don't forget to copy the function definition as well. ;) – hakre Nov 29 '12 at 18:24
  • ok, missed that part but the method is still not the best method for a WordPress setup. First of all, 200 is not the only valid response that a remote URL item exists. Secondly the wp_remote_head() method in WordPress has multiple fall-backs outside of file_get_contents including curl and direct socket operations. I would remove the downvote as your answer will work but is not the best solution of those provided for a WordPress project... but SO has locked it in. :/ – Lance Cleveland Nov 29 '12 at 21:06
  • The last point you write is technically right, however, as Wordpress is pay-as-you-go, what is best is not the question, only what works. This did work, so it's okay. I won't rely too much on Wordpress core functions because the function-stack is pretty whacky. Better is you create your own API so you know what you've got. The function body can be replaced with something different if it does not work. – hakre Dec 02 '12 at 12:38
4

As for validating the URL, none of these answers are considering the correct, WordPress way to carry out this task.

For this task wp_remote_head() should be used.

Here's an article I've written about How To Check Whether an External URL Exists with WordPress’ HTTP API. Check it out and figure out how it works.

Maor H.
  • 554
  • 5
  • 5
  • Excellent solution. The code presented in your article is the right setup for this type of test. I'll post my simplified version of that code in a "webItemExists()" function below. I'd do it here but comments are not well suited to code sharing. – Lance Cleveland Nov 29 '12 at 20:08
  • Thanks @CharlestonSoftwareAssociates! I'm glad you found it useful. – Maor H. Nov 30 '12 at 21:08
  • 1
    It seems the access to the article above, presently, is not public (the site is asking for login and password). – aldemarcalazans Dec 11 '20 at 22:15
3

This seems to work for me:

function url_file_exists($url) {
    $context  = stream_context_create(array('http' =>array('method'=>'HEAD')));
    $fd = @fopen($url, 'rb', false, $context);
    if ($fd!==false) {
       fclose($fd);
       return true;
    }
    return false;
}
unsynchronized
  • 4,828
  • 2
  • 31
  • 43
  • i tested your code. that is working with one condition. if you are getting 200 form URL ** (http://example.com/a1io.jpg)** then your function return **True**. so in case, you tempered URL of the file and your server in any case return 200 then you will not check that... so, in this case, your method is **not correct**. – pankaj May 12 '20 at 18:55
2
$file_exists = file_exists($path);
$url_accessable = http_get($url, array("timeout"=>10), $info); // should not be FALSE
$status_code = $info['response_code'] //should be 200
1

remote:

$file = 'http://www.my_site.com/some_folder/required_url_file.php'
if ( @fclose(@fopen($file,"r")) ) echo "File exists!";

local:

$file = '/home/my_site/public_html/some_folder/required_file.php';
if ( is_file($file) ) echo "File exists!";
Jake
  • 2,058
  • 2
  • 24
  • 33
1

To check if a file exists, use the file_exists method.

As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.

if(! (file_exists($url1) && file_exists($url2)) ) {
    die("Files don't exist - throw error here.");
}

// Continue as usual - files exist at this point.
Greg
  • 21,235
  • 17
  • 84
  • 107
  • You generally don't want to rely on file_exists as it will return positive if a directory exists and unless you are very sure what is being returned as your file url and file name, you will often end up with a positive for the directory when a filename was returned. Use is_file(). – Jake Sep 21 '12 at 21:53
1

If you have PECL http_head function available, you could check if it returns status code 200 for the remote file.

To check if you can access the local file, could use file_exists, but this does not grant that you will be able to access that file. To check if you can read that file, use is_readable.

naivists
  • 32,681
  • 5
  • 61
  • 85
0

Use function file_exists()

file_exists('http://www.my_site.com/some_folder/required_url_file.php');

will get you results as True or false.

pinaldesai
  • 1,835
  • 2
  • 13
  • 22
  • it will not work. i checked your code. not working.. if (file_exists("https://www.xxxxxxx.in/file/ue548fac6302e469.pdf")) { return "File exists!"; } else { return "File doesn't exist."; } – pankaj May 12 '20 at 18:32
  • my link was wkring. you can check any link form google. – pankaj May 12 '20 at 18:33
0

Checking if a file exists:

if (file_exists('path/to/file.txt')) {
    echo "File exists!";
} else {
    echo "File doesn't exist.";
}

Checking if a URL is valid:

$data = @file_get_contents("http://url.com/");
if (!$data) {
    echo "URL not valid.";
} else {
    echo "URL is valid.";
}

Notes:

Ideally you shouldn't try and predict the filesystem. Whilst methods such as file_exists are very helpful, they shouldn't be relied upon and instead you should attempt to write to files, read from them, etc, and then catch and handle any exceptions or errors that occur.