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


How do I modify this code to check for file existence on a remote host?

我正在尝试使用以下代码检查单个网站上是否存在多个文件,并且遇到仅测试顶部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';
?>

将检查远程服务器上的 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 响应,而不仅仅是输出它是否存在。

试试这个。请注意,您可能需要跳过行尾,因此请使用 rtim()。此外,如果您希望 url.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>';
    }
  }  
}
?>

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

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