如何用PHP检测社交媒体URL状态?实测代码返回302状态码
PHP检测社交媒体URL状态的解决方法
可以通过PHP检测社交媒体URL的状态,但像Facebook这类平台常返回302重定向,这是反爬机制、登录状态限制或区域限制导致的,不能仅通过初始响应的200状态码判断。
原代码的问题
你的代码只检查了第一个响应头的200标识,但302是重定向响应,需要跟随跳转直到获取最终的响应状态码,才能准确判断URL是否有效。
解决方案1:修改get_headers支持重定向
通过设置HTTP上下文,让请求自动跟随重定向,并模拟浏览器UA避免被拦截:
<?php $url = "https://www.facebook.com/shahidulmh/posts/pfbid02MfSTMjTYjndf4qCsf1qfQSTX9PfCD6FukYozjSrdmiqNK38AkykVBcJ8kD1qU3pYl?"; // 创建请求上下文,配置重定向和UA $context = stream_context_create([ 'http' => [ 'follow_location' => true, 'max_redirects' => 5, 'header' => "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36" ] ]); $headers = @get_headers($url, 0, $context); $exists = false; if ($headers) { foreach ($headers as $header) { if (strpos($header, '200 OK') !== false) { $exists = true; break; } if (strpos($header, '404 Not Found') !== false) { $exists = false; break; } } } $status = $exists ? "URL Exist" : "URL Doesn't Exist"; echo $status; ?>
解决方案2:使用cURL(推荐)
cURL比get_headers更灵活,能更好处理复杂HTTP请求场景:
<?php $url = "https://www.facebook.com/shahidulmh/posts/pfbid02MfSTMjTYjndf4qCsf1qfQSTX9PfCD6FukYozjSrdmiqNK38AkykVBcJ8kD1qU3pYl?"; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_setopt($ch, CURLOPT_MAXREDIRS, 5); curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36"); curl_setopt($ch, CURLOPT_NOBODY, true); // 仅获取响应头,提升效率 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 按需关闭SSL验证 curl_exec($ch); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); $status = ($httpCode == 200) ? "URL Exist" : "URL Doesn't Exist"; echo $status; ?>
注意事项
社交媒体平台反爬机制严格,即使配置了UA和重定向,仍可能返回403等状态码。如需进一步处理,可能需要模拟登录会话或使用代理,但所有操作需遵守平台的使用协议,避免违规。
内容的提问来源于stack exchange,提问作者aysha
相关产品推荐
相关产品推荐

