2010-10-30 89 views
1

有没有办法在发送用户之前检查服务器是否响应错误代码?在执行操作前检查PHP中的重定向

目前,我基于来自后端的用户可编辑输入(客户端请求,因此他们可以打印他们自己的域名,但将其他人发送给别人)重定向,但是我想检查URL是否会实际响应,如果不是通过一条消息将它们发送到我们的主页。

回答

1

你可以用卷曲做到这一点:

$ch = curl_init('http://www.example.com/'); 

//make a HEAD request - we don't need the response body 
curl_setopt($ch, CURLOPT_NOBODY, true); 

// Execute 
curl_exec($ch); 

// Check if any error occured 
if(!curl_errno($ch)) 
{ 
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); //integer status code 
} 

// Close handle 
curl_close($ch); 

然后,您可以检查是否$ httpCode是OK。通常一个2XX响应代码是可以的。

+1

注意:不需要做一个完整的页面请求,只有头文件是好的,get_headers()提供这个作为一个标准的PHP函数。不需要卷曲,这只是一个过于复杂。 – 2010-10-30 15:40:30

+1

好点,我已经修改了我的答案,以提出HEAD请求! get_headers是一个可能的解决方案,但cURL功能更强大,可以像重定向一样。 – 2010-10-30 16:08:51

+1

结果get_headers()使用GET请求,所以你的方法是最好的:)但记录get_headers()也遵循重定向。 – 2010-10-30 17:14:06

0

您可以尝试以下操作,但要注意,这是对重定向的单独请求,所以如果两者之间出现问题,用户仍然可能会被发送到错误的位置。

$headers = get_headers($url); 
if(strpos($headers[0], 200) !== FALSE) { 
    // redirect to $url 
} else { 
    // redirect to homepage with error notice 
} 

为get_headers()的PHP手册:http://www.php.net/manual/en/function.get-headers.php

0

我不明白你的意思,确保网址会回应。但是如果你想显示一条消息,你可以使用一个$_SESSION变量。请记住在每个将使用该变量的页面上放置session_start()

所以当你想将它们重定向回主页。你可以做到这一点。

// David Caunt's answer 
$ch = curl_init('http://www.example.com/'); 

// Execute 
curl_exec($ch); 

// Check if any error occured 
if(!curl_errno($ch)) 
{ 
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); //integer status code 

// My addition 
if($httpCode >= 200 && $httpCode < 300) { 
    // All is good 
}else { 
    // This doesn't exist 

    // Set the error message 
    $_SESSION['error_message'] = "This domain doesn't exist"; 

    // Send the user back to the home page 
    header('Location: /home.php'); // url based: http://your-site.com/home.php 
} 
// My addition ends here 

} 

// Close handle 
curl_close($ch); 

然后在你的主页上,你会看到类似的东西。

// Make sure the error_message is set 
if(isset($_SESSION['error_message'])) { 

    // Put the error on the page 
    echo '<div class="notification warning">' . $_SESSION['error_message'] . '</div>'; 
}