PHP,检查URL和文件是否存在?

Mer*_*kos 2 php filesystems wordpress

我为WordPress创建了一个插件,它需要存在两个文件才能正常运行.

第一个文件定义为文件系统路径,第二个文件定义为URL.

假设第一个文件是:

/home/my_site/public_html/some_folder/required_file.php
Run Code Online (Sandbox Code Playgroud)

第二个文件是:

http://www.my_site.com/some_folder/required_url_file.php
Run Code Online (Sandbox Code Playgroud)

请注意,这两个文件与文件系统中的文件不同.required_file.php具有除required_url_file.php之外的其他内容,并且它们的行为绝对不同

有关如何验证两个文件的存在的任何想法?

hak*_*kre 6

你可以检查两个:

$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;
}
Run Code Online (Sandbox Code Playgroud)

  • @CharlestonSoftwareAssociates:嗯,是谁写的,它是*Wordpress的一部分?如果从答案中复制代码,请不要忘记复制函数定义.;) (2认同)

Lan*_*and 5

基于Maor H.代码示例,这是我在插件中使用的函数:

/**
 * 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;
}
Run Code Online (Sandbox Code Playgroud)

我已经在辅助类中创建了一个方法,但是将它放在主题的functions.php文件中应该使它在任何地方都可以访问.但是,您应始终在类中编写并实例化它们.隔离插件和主题功能要好得多.

有了这个,你可以简单地使用:

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

大多数情况下,您将使用WordPress调用通过相对或完全限定的URL访问所有项目.如果你有/uploads/2012/12/myimage.png之类的相对引用,你可以通过简单地添加get_site_url()将它们转换为完全限定的URL v.一个WordPress相对URL.调用webItemExists函数时的$ string.