我需要检查文件是否存在于多个域/服务器中,然后向用户显示下载链接或编写错误消息。我有这个脚本为1域工作:
<?php
$domain0='www.example.com';
$file=$_GET['file']
$resourceUrl = 'http://$domain0/$file';
$resourceExists = false;
$ch = curl_init($resourceUrl);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_exec($ch);
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
//200 = OK
if ($statusCode == '200') {
$resourceExists = true;
}
if ($resourceExists == true) {
echo "Exist! $file";
} else {
echo "$file doesnt exist!";
}
?>
现在我需要检查该文件是否存在于4个域中,我该怎么做?我不知道如何使用数组,所以如果有人告诉我怎么做,我将非常感激。
- 我将创建一个数组域
- 我将使用"foreach"循环遍历数组
-
我将调用一个函数来获得结果
function checkFileOnDomain($file,$domain) { $resourceUrl = "http://$domain/$file"; $ch = curl_init($resourceUrl); curl_setopt($ch, CURLOPT_NOBODY, true); curl_exec($ch); $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); if($statusCode == '200') return true; } $file=$_GET["file"]; // $_GET should be sanitized! $domain_list=array("www.test1.com","www.test2.com"); foreach ($domain_list as $domain) { echo "Check DOMAIN: $domain <hr/>"; if (checkFileOnDomain($file,$domain)) { echo ">> [ $file ] EXISTS"; } else { echo ">> [ $file ] DOES NOT EXIST"; } echo "<br/><br/>"; } unset($domain);
要应用您的规范,您需要在foreach之前添加一个额外的变量。
$link_to_file="";
foreach ($domain_list as $domain) {
if (checkFileOnDomain($file,$domain)) {
$link_to_file="$domain/$file";
break; // get first result and quit
}
} unset($domain);
if (!empty($link_to_file)) {
echo $link_to_file; //file is here
} else {
echo "404";
}
数组应该可以为您解决这个问题。这将创建一个您想要检查的域数组,然后运行您编写的代码逐一遍历它们。
如果你在使用数组时遇到困难,请查看这里获取更多信息
<?php
// Create an array of domains
$domains = ['www.example.com', 'www.example2.com', ...];
// Cycle through all the domains and run the code
foreach($domains as $domain) {
$domain0='www.example.com';
$file=$_GET['file']
$resourceUrl = 'http://$domain0/$file';
$resourceExists = false;
$ch = curl_init($resourceUrl);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_exec($ch);
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
//200 = OK
if($statusCode == '200') {
$resourceExists = true;
} else if($resourceExists == false) {
}
if ($resourceExists == true) {
echo "Exist! $file";
} else {
echo "$file doesnt exist!";
}
}
?>