PHP Curl在下载之前检查文件是否存在 [英] PHP Curl check for file existence before downloading

查看:144
本文介绍了PHP Curl在下载之前检查文件是否存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个PHP程序,从后端下载pdf并保存到本地驱动器。现在如何在下载之前检查文件是否存在?

I am writing a PHP program that downloads a pdf from a backend and save to a local drive. Now how do I check whether the file exists before downloading?

目前我使用curl(请参阅下面的代码)检查和下载,但它仍然下载大小为1KB的文件。

Currently I am using curl (see code below) to check and download but it still downloads the file which is 1KB in size.

$url = "http://wedsite/test.pdf";
$path = "C:\\test.pdf;"
downloadAndSave($url,$path);

function downloadAndSave($urlS,$pathS)
    {
        $fp = fopen($pathS, 'w');

        $ch = curl_init($urlS);

        curl_setopt($ch, CURLOPT_FILE, $fp);
        $data = curl_exec($ch);

        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        echo $httpCode;
        //If 404 is returned, then file is not found.
        if(strcmp($httpCode,"404") == 1)
        {
            echo $httpCode;
            echo $urlS; 
        }

        fclose($fp);

    }

我想在下载前检查文件是否存在。

I want to check whether the file exists before even downloading. Any idea how to do it?

推荐答案

您可以使用单独的curl HEAD request:

You can do this with a separate curl HEAD request:

curl_setopt($ch, CURLOPT_NOBODY, true);
$data = curl_exec($ch);

$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

当你真正想下载时,可以使用set NOBODY false

When you actually want to download you can use set NOBODY to false.

这篇关于PHP Curl在下载之前检查文件是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆