validation - 我们如何使用 Javascript 或 PHP 检查 URL 是否处于活动状态?
问题描述
我正在尝试使用 Javascript 和 PHP 检查 URL 是否处于活动状态(给出状态代码 200)。这是我正在尝试使用的代码。
使用 Javascript
var myRequest = new Request('https://www.google.com');
fetch(myRequest).then(function(response) {
console.log(response.status); // returns 200
});
使用 PHP:
<?php
function isValidUrl($url){
$res = getHttpResponseCode_using_curl($url);
//$res = getHttpResponseCode_using_getheaders($url);
print_r($res);
echo "<br>";
if($res != 200){
return false;
}
return true;
}
function getHttpResponseCode_using_curl($url){
if(! $url || ! is_string($url)){
return false;
}
$ch = @curl_init($url);
print_r($ch);
echo "<br>";
if($ch === false){
return false;
}
@curl_setopt($ch, CURLOPT_HEADER ,true); // we want headers
@curl_setopt($ch, CURLOPT_NOBODY ,true); // dont need body
@curl_setopt($ch, CURLOPT_RETURNTRANSFER ,true); // catch output (do NOT print!)
@curl_exec($ch);
if(@curl_errno($ch)){ // should be 0
@curl_close($ch);
return false;
}
$code = @curl_getinfo($ch, CURLINFO_HTTP_CODE);
print_r($code);
echo "<br>";
@curl_close($ch);
return $code;
}
function getHttpResponseCode_using_getheaders($url){
if(! $url || ! is_string($url)){
return false;
}
$headers = @get_headers($url);
print_r($headers);
echo "<br>";
if($headers && is_array($headers)){
foreach($headers as $hline){
if(preg_match('/^HTTP\/\S+\s+([1-9][0-9][0-9])\s+.*/', $hline, $matches) ){
$code = $matches[1];
return $code;
}
}
return false;
}
return false;
}
if(isValidUrl("https://www.google.com")){
print_r("Running");
}else{
print_r("Down");
}
?>
我尝试过 Ajax 调用以及尝试使用 @get_headers 方法来获取任何网站或 url 的状态代码!但是这些方法都没有给出任何网站的状态码。请帮忙。
解决方案
推荐阅读
- php - 当 WooCommerce 购物车和结帐页面上购物车中的特定产品时更改“总计”文本
- python - Django图像压缩和调整大小不起作用
- c++ - 如何强制 C++ 只读取以 # 结尾的输入
- postgresql - “订单”处或附近的语法错误(带有 Quill、Doobie 和 PostgreSQL 的 Scala)
- c++ - 我的类“Smart_pointer”和可变参数模板的问题
- javascript - 当数据表记录空的角度js时按钮禁用
- leaflet - 有没有更好的方法来获取传单中“popupopen”事件的源标记?
- azure-ad-b2c - Azure B2C - IDX10501:签名验证失败。无法匹配键:
- c# - SendGrid Put 请求在应用程序代码中返回 400 响应
- javascript - 在javascript中使用post方法时Json文件没有得到更新?