PHP, Check if URL and a file exists ?

2019-05-22 13:18发布

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 ?

10条回答
ゆ 、 Hurt°
2楼-- · 2019-05-22 13:56

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.

查看更多
乱世女痞
3楼-- · 2019-05-22 14:03

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.

查看更多
姐就是有狂的资本
4楼-- · 2019-05-22 14:05

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;
}
查看更多
▲ chillily
5楼-- · 2019-05-22 14:10

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.
查看更多
登录 后发表回答