【问题标题】:Check whether a HTML page exists检查是否存在 HTML 页面
【发布时间】:2011-10-15 00:05:07
【问题描述】:

我想检查一个 HTML 页面是否存在于另一个站点上。更准确地说,我的用户需要将.html 页面上传到他们自己的网站,然后他们需要在我的网站上按“立即验证”。然后,我的网站需要确认 html 页面存在于他们的网站上。

我找到了这段代码:

$url = 'http://domain.tld/my_page.html';
$handle = @fopen($url,'r');
if($handle !== false){
   echo 'Page Exists';
}  else {
   echo 'Page Not Found';
}

但如果my_page.html 不存在,则此代码仅返回“页面存在”。

【问题讨论】:

    标签: php fopen


    【解决方案1】:

    编辑 1: 抱歉编辑...不要先回答问题。

    您需要了解服务器会以任何方式回答。您只需要检查然后响应的代码,而不是响应文本。或解析文本。

    在您的情况下,服务器回答如下:

    Object not found!
    
     The requested URL was not found on this server. If you entered the URL manually please check your spelling and try again. 
    
     If you think this is a server error, please contact the webmaster. 
    Error 404
    work.local
    Thu Jul 28 13:22:49 2011
     Apache/2.2.15 (Linux/SUSE)
    

    编辑 2 : 您可能希望更好地使用 socket_connect 而不是 fopen 来检查文件是否存在

    【讨论】:

      【解决方案2】:

      假设您的 PHP 中安装了 curl 扩展,我认为这是您目前最好的选择: Easy way to test a URL for 404 in PHP?

      【讨论】:

      • 谢谢你,我找到了答案:)
      【解决方案3】:

      如果资源不存在,网络服务器会返回 404 HTTP 状态代码。资源是您问题中的 html 文件。

      您可以向服务器发出头部请求以了解状态 - 或者只是一个获取请求。

      PHP 也为此操作内置了一个函数,称为get_headers (Demo):

      $headers = get_headers($url, 1);
      $statusLine = $headers[0];
      list(,$statusCode) = explode(' ', $statusLine, 3);
      

      【讨论】:

      • 是的,但是例如,如果在 .htaccess 站点上有“ErrorDocument 404 domain.tld”,这将不起作用。
      • 如果服务器发送正确的响应标头,它将始终有效。对于 404 自己的 ErrorDocument 设置,通常也是如此。但是,如果错误页面将响应标头更改为 200 OK,那么除了检查返回的 HTTP 正文以查找特定的错误模式之外,什么都不会起作用(包括 curl 方法)。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-01-27
      • 1970-01-01
      • 1970-01-01
      • 2015-09-10
      • 1970-01-01
      • 2012-03-17
      • 2012-03-28
      相关资源
      最近更新 更多