我正在尝试查找文件是否存在。我的服务器不报告404,而是直接重定向到自定义404页面并返回302(重定向)或类似内容。我的情况是尝试第一个URL,如果文件不存在或无效,则显示备用URL。我的脚本如下:
$filename= 'http://35.164.39.39/quote1.pdf';
$handle = curl_init($filename);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, TRUE);
/* Get the HTML or whatever is linked in $url. */
$response = curl_exec($handle);
/* Check for 404 (file not found). */
$httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
curl_close($handle);
/* If the document has loaded successfully without any redirection or error */
if ($httpCode >= 200 && $httpCode < 300) {
$new_url = 'http://34.219.140.48/quote1.pdf';
} else {
$new_url = 'http://35.164.39.39/quote1.pdf';
}
然后我将呼叫new_url:
<a target="_blank" href="<?php echo $new_url; ?>">Quote</a>
我可以在上面的代码中看到它始终将$ filename条件设为true并加载此URL。谁能建议我该如何处理。预先谢谢你。
答案 0 :(得分:0)
也许:
$proto = "http://";
$uri = "/quote1.pdf";
$success = $proto."34.219.140.48".$uri;
$failed = $proto."35.164.39.39".$uri;
$handle = curl_init($success);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, TRUE);
/* Get the HTML or whatever is linked in $url. */
$response = curl_exec($handle);
/* Check for 404 (file not found). */
$httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
curl_close($handle);
/* If the document has NOT loaded successfully without any redirection or error */
if ($httpCode !== 200) {
echo "<a target=\"_blank\" href=\"<?php echo $failed; ?>\">Quote</a>";
}else{
echo "<a target=\"_blank\" href=\"<?php echo $success; ?>\">Quote</a>"
}
答案 1 :(得分:0)
$url = 'http://34.219.140.48/quote1.pdf';
$url1 = 'http://35.164.39.39/quote1.pdf';
$handle = curl_init($url);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, TRUE);
$response = curl_exec($handle);
/* Check if not 200 */
$httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
if($httpCode !== 200) {
$url = $url1;
}
curl_close($handle);
echo "<a target=\"_blank\" href=\"$url\">Quote</a>";