【问题标题】:How to catch 'The request could not be satisfied.' page/ bad URL如何捕捉“无法满足请求”。页面/错误的 URL
【发布时间】:2020-01-02 21:03:17
【问题描述】:

我正在尝试检测 php 中的错误 403。当我从 URL 加载内容并且出现错误 403 时,显示其他内容。使用 404 可以,但是使用 403 则不起作用。我有 2 个网址链接: 1)404:https://images-na.ssl-images-amazon.com/images/M/MV5BMTUwODE3MDE0MV5BMl5BanBnXkFtZTgwNTk1MjI4MzE@._V1_SX300.jpg; 2)403:http://ia.media-imdb.com/images/M/MV5BMTg3Njc2ODEyN15BMl5BanBnXkFtZTcwNTAwMzc3NA@@._V1_SX300.jpg

我尝试了很多,也使用 http_response_code(403) 并没有成功... 谢谢你的帮助...

我的代码如下:

        <div class="poster">
                    <?php
                        $posterAll = $movie->posterUrl;

                        $file_headers=@get_headers($posterAll);
                        if(!$file_headers || $file_headers[0]=='HTTP/1.1 404 Not Found' || $file_headers[0]=='Not Found' || (strpos($headers[0], '403'))){
                            $exists=false;
                        }
                        else{
                            $exists=true;
                        }
                        echo $exists;

                        if ($exists) {
                            $imageData = base64_encode(file_get_contents($posterAll));
                           echo '<img height="300" width="300" src="data:image/jpeg;base64,' . $imageData . '">';
                       }

【问题讨论】:

    标签: php


    【解决方案1】:

    您使用错误的变量名来检查 403。将 (strpos($headers[0], '403') 更改为 (strpos($file_headers[0], '403')

    if(!$file_headers || $file_headers[0]=='HTTP/1.1 404 Not Found' || $file_headers[0]=='Not Found' || (strpos($file_headers[0], '403'))){
                            $exists=false;
    }
    

    【讨论】:

      【解决方案2】:

      第二个 url 返回 503 而不是 403。检查浏览器中的网络检查器。这就是为什么您的情况不会被确定为真实的原因。

      【讨论】:

        【解决方案3】:

        您确定需要这两个查询吗? get_headers 会做一个,file_get_contents 也会做一个。

        无论如何file_get_contents 将在非 200 响应时返回 false。你可以使用这个 false 值作为图像存在的标志:

        $exists = false;
        $imageData = @file_get_contents($movie->posterUrl);
        if ($imageData !== false) {
            $exists = true;
            echo '<img height="300" width="300" src="data:image/jpeg;base64,' . $imageData . '">';
        }
        

        【讨论】:

          猜你喜欢
          • 2022-08-12
          • 1970-01-01
          • 2020-12-28
          • 2021-05-12
          • 2021-11-23
          • 2023-03-30
          • 2018-03-03
          • 1970-01-01
          • 2018-04-13
          相关资源
          最近更新 更多