首页 > 解决方案 > 在 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?

提前致谢。

标签: phpshopifyurl-validation

解决方案


发生这种情况是因为 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);

推荐阅读