如何通过ID计算URL包含的页数


How to count number of pages a URL contains via an ID?

我正在构建一个脚本,目标是检查多达100个URLS的有效性(No 404)。

URL中唯一的变量是页码,如下所示:

http://example.com/category/id/products/page/1
http://example.com/category/id/products/page/2

等等高达100,

一旦我的代码到达一个无效的URL,我希望它停止并回显它到达的号码,这是我试图无效的代码:

$url ="http://example.com/category/id/products/page/1";
if (false !== strpos($url, $id)) {
    $pageNumber = 2;
    $check = true;
do{
    $urlIterate = "http://example.com/category/id/products/page/".$pageNumber;
    if(false !== strpos($urlIterate, $id)){
        $pageNumber++;
    }
    else{
        $check = false;
    }
}
while($pageNumber <= 99);
}
else{
    $check = false;
    echo 'No pages were found at all';
}
echo "There were ". $pageNumber." pages.;
?>

我不确定这是否是你想要的,但试试这个:

<?php
    $id_to_search = "90";
    for ($i = 1; $i <= 100; $i++) {
        $url = "http://example.com/category/id/products/page/" . $i;
        $values = parse_url($url);
        $paths = explode('/', $values['path']);
        $id_from_url = $paths[5];
        if ($id_to_search === $id_from_url) {
            $headers = get_headers($url);
            if ($headers[0] == 'HTTP/1.0 404 Not Found') {
                echo "URL Found! URL is invalid(404). URLs searched = " . $i . "<br>";
            } else {
                echo "URL is valid<br>";
            }
        } else {
            echo "URL was searched but it does not match the ID we are looking for<br>";
        }
    }

为什么不使用for循环?当我们知道需要多少迭代时,情况会更好。

for($i = 1; $1<=100; $i++){
    $urlIterate = "http://example.com/category/id/products/page/".$i; //generate url
    $headers = get_headers($urlIterate, 1); //get headers
    if($headers[0] != 'HTTP/1.1 200 OK'){ //if we have an error
        if($i > 1) //if there was at least one found
            echo 'Last found number is ' . ($i-1);
        else
            echo 'No pages were found at all';
        break; //stops the 'for' loop
    }
}

您的代码正在URL中查找$id,这有什么意义?