如何修改此代码以检查远程主机上是否存在文件?

时间:2013-02-03 08:49:37

标签: php

我正在尝试使用下面的代码检查单个网站上是否存在多个文件,并且遇到的问题是只测试了顶级网址,即使它是有效的网址,我仍然会得到网址不存在

如何修改代码以正确返回结果并检查文本文件中的所有给定网址。

<?php 
$site = "http://site.com"
$urls = file('urls.txt',FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

$found = false;
foreach($urls as $url)
   if($_POST['url'] == $site . $url)
      $found = true;

if($found)
   echo "URL exists";
else
   echo 'URL doesn\'t exist';

?>

3 个答案:

答案 0 :(得分:0)

一点逻辑变化 - 根据您的需求进行定制。

<?php 

$site = "http://site.com"
$urls = file('urls.txt',FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

foreach($urls as $url)

   // TEST URL EXISTENCE HERE (not sure if just looking at $_POST will tell you if its a remote url?

   if($_POST['url'] == $site . $url) {
       echo "URL exists";
   } else {
       echo 'URL doesn\'t exist';
   }

}

?>

答案 1 :(得分:0)

试试这个。请注意,您可能必须跳过行结尾,因此请使用rtim()。此外,如果您希望urls.txt针对多个输入网址进行测试,脚本也会完成此操作。

<?php 
$site = "http://site.com"
$urls = file('urls.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

foreach($urls as $url) {
  //if you want to test multiple input urls, they might be in input array, say url[]
  //we can check for the array here
  if(is_array($_POST['url'])) {
    foreach($_POST['url'] as $post_url) {
      //You may want to skip line endings, so use rtrim
      if($post_url == ($site . rtrim($url)) {
        print 'Url found - '.$post_url.'<br>';
      } else {
        print 'Url not found - '.$post_url.'<br>';
      }
    }
  } else {
    //You may want to skip line endings, so use rtrim
    if($POST['url'] == ($site . rtrim($url)) {
      print 'Url found - '.$POST['url'].'<br>';
    } else {
      print 'Url not found - '.$POST['url'].'<br>';
    }
  }  
}
?>

答案 2 :(得分:0)

将检查远程服务器上的URL列表的代码:

<?php 
$site = "http://site.com"
$urls = file('urls.txt',FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

foreach($urls as $url) {
  $headers = get_headers($site . $url, 1);
  $status_parts = explode(" ", $headers[0]);
  $status_code = $status_parts[1];
   if ($status_code == 200)
     echo "URL exists";
   else if ($status_code == 404)
     echo 'URL doesn\'t exist';
   else
     // error or something else?
}
?>

有几点需要注意:

  1. There are similar questions
  2. 您可能希望记录url int eh响应,而不仅仅是输出它是否存在。