0

我正在尝试使用下面的代码检查单个网站上是否存在多个文件,但遇到了一个问题,即仅测试顶部 URL,即使它是有效的 URL,我仍然得到URL 不存在

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

<?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';

?>
4

3 回答 3

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';
   }

}

?>
于 2013-02-03T08:59:26.443 回答
0

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

<?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>';
    }
  }  
}
?>
于 2013-02-03T09:01:11.883 回答
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. 有类似的问题
  2. 您可能想要记录 url int eh 响应,而不是仅仅输出它是否存在。
于 2013-02-03T09:17:01.127 回答