【问题标题】:PHP file_get_contents and others return 404 but URL is accessible via browserPHP file_get_contents 和其他返回 404 但 URL 可通过浏览器访问
【发布时间】:2018-06-29 06:09:09
【问题描述】:

我正在尝试制作一个 PHP CLI 应用程序,它会抓取一组 URL,这些 URL 是指向图像的直接链接,例如:

https://static.wixstatic.com/media/6f6e33_4e2920af05b4440f87880154b5cfcc80~mv2_d_1500_1500_s_2.png

虽然您可以看到该 URL 是可公开访问的,但似乎无论我尝试恢复它并将其添加到我的本地计算机我得到 404。我已检查以确保在我的php.ini,我尝试忽略 404,但仍然尝试返回结果(CURL、file_get_contents),欺骗了我的用户代理,我尝试了 file_get_contents()、copy()、curl 和其他几种方法并得到了相同的结果结果; 404。

这是有问题的函数的样子:

获取文件路径数组并将其提供给下载函数的函数。

     /**
     * @param array $locations
     * Downloads images at the specified locations into the directory specified in the constructor. 
     */
    public function scrapeImages($locations){
        echo "Attempting to download images from given source data. Standby... \n";
        foreach($locations as $location){
            echo "Scraping: ".$location;
            $fname = basename($location);
            //$this->downloadFile($location, $this->formatDirectory($this->dir).$fname);
            file_put_contents($this->formatDirectory($this->dir).$fname,$this->downloadFile($location));
        }
    }

实际执行下载的函数。

     /**
     * @param string $path 
     * Checks to see if a file exists and is readable then if it is, downloads it. 
     */
    public function downloadFile($path){
        if(!file_exists($path)){
            echo "File does not exist! \n";
        }
        if(!is_readable($path)){
            echo "File is not readable! \n";
        };
        return file_get_contents(trim($path));
    }

如果您需要进一步分析,可以在这里找到整个代码库—— https://github.com/ErvinSabic/SabicRipper

我在网上搜索了几个小时,最终放弃了。所以我想我会在这里发帖。有什么建议吗?

提前谢谢你们。

【问题讨论】:

  • 据我所知 file_get_contents() 方法接受相对路径。您是否提供了文件的完整路径?
  • 如果你在一个新的 php 文件中运行它(在同一台服务器上)会发生什么? <?php $image = 'https://static.wixstatic.com/media/6f6e33_4e2920af05b4440f87880154b5cfcc80~mv2_d_1500_1500_s_2.png'; $imageData = base64_encode(file_get_contents($image)); $src = 'data: image/png;base64,'.$imageData; echo '<img src="' . $src . '">'; ?> 在这里工作得很好。所以我没有理由认为服务器正在积极阻止您的请求。
  • 您能否将var_dump($path) 添加到downloadFile() 的顶部并在此处报告其值?我怀疑 url 有问题,导致 404,因为您正在访问一个实际上不存在的文件/url。
  • @Nielles - 给定的脚本按我的预期显示图像。
  • 同时转储路径会返回与我最初提供的完全相同的路径,因为我能够将其复制并粘贴到浏览器中并访问资源。

标签: php web-scraping phantomjs command-line-interface


【解决方案1】:

所以我最终做的是使用 wget,因为大多数其他方法都不起作用。下面是工作函数。

     /**
     * @param string $path 
     * Checks to see if a file exists and is readable then if it is, downloads it. 
     */
    public function downloadFile($path){
        echo "Grabbing File:" .$path."\n";
        shell_exec("wget -P".$this->getDirectory()." ".$path);
        //echo "Attempting to place ".basename($path)." in ".$this->getDirectory();
    }

我从来没有真正知道为什么它会返回 404 到可公开访问的 URL。但这就是我想出的解决方法。可以查看整个文件here.

【讨论】:

    猜你喜欢
    • 2021-10-02
    • 1970-01-01
    • 1970-01-01
    • 2016-11-30
    • 1970-01-01
    • 2016-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多