php - 在 Shopify 中检查 url 是否存在
问题描述
如何验证 Shopify 商店的 URL?给定一个 URL,我如何知道它是有效 URL 还是 404 页面未找到?我正在使用 PHP。我试过使用 PHP get_headers()
。
<?php
$getheadersvalidurlresponse= get_headers('https://test072519.myshopify.com/products/test-product1'); // VALID URL
print_r($getheadersvalidurlresponse);
$getheadersinvalidurlresponse= get_headers('https://test072519.myshopify.com/products/test-product1451'); // INVALID URL
print_r($getheadersinvalidurlresponse);
?>
但是对于有效和无效的 URL,我得到了相同的响应。
Array
(
[0] => HTTP/1.1 403 Forbidden
[1] => Date: Wed, 08 Jul 2020 13:27:52 GMT
[2] => Content-Type: text/html
[3] => Connection: close
..............
)
我期待有效 URL 的 200 OK 状态代码和无效 URL 的 404。
任何人都可以帮助检查给定的shopify URL是否有效使用PHP?
提前致谢。
解决方案
发生这种情况是因为 Shopify 区分了机器人请求和实际的真实请求,以避免在一定程度上拒绝服务攻击。为了克服这个问题,您必须指定user-agent
标头以模拟浏览器请求以获取适当的 HTTP 响应。
作为改进,您可以发出HEAD
请求而不是GET
请求(get_headers()
默认情况下使用 GET 请求,如 中所述examples
),因为这里我们只关心响应元数据而不关心响应正文。
片段:
<?php
$opts = array(
'http'=>array(
'method'=> "HEAD",
'header'=> "User-agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36"
)
);
$headers1 = get_headers('https://test072519.myshopify.com/products/test-product1',0,stream_context_create($opts));
$headers2 = get_headers('https://test072519.myshopify.com/products/test-product1451',0,stream_context_create($opts));
echo "<pre>";
print_r($headers1);
print_r($headers2);
推荐阅读
- ffmpeg - 在ffmpeg中覆盖带有多个文本的字幕
- php - Paypal Orders API 混合单一&订阅购买
- php - NGINX - 从上游读取时拒绝重命名权限
- python - Windows 10 IIS 服务器上的 Python Flask 托管
- r - R如何在新列中获得afinn分数
- java - 将每个字符转换为另一个一致的字符
- angular - Angular cdkOverlay 禁用关闭
- javascript - Java 脚本验证问题
- javascript - 如果 API 有参数和标头,Service Worker 将缓存 WEBAPI 数据(等待 cache.addAll(API_URLS))
- javascript - 使用 Java 脚本 (JS) 从文本 (txt) 文件中提取特定值