Hongmu Notes
Home Language Notes PHP uses `curl` to download a file; if the download is successful, it returns the file path; if it fails, it returns a download link.
Language Notes PHP

PHP uses `curl` to download a file; if the download is successful, it returns the file path; if it fails, it returns a download link.

PHP uses `curl` to download a file; if the download is successful, it returns the file path; if it fails, it returns a download link.

I've written about similar features before, but I didn't take notes at the time, so I eventually forgot about them. Recently, I've started writing about this again, so I'd like to record it here!

ad1a1b7183114520

PHP code:

public function downloadFile($url, $path) {
    // 判断文件是否存在
    if (file_exists($path)) {
        // 判断文件大小是否大于10KB
        if (filesize($path) > 10240) {
            // 文件已经成功下载过
            return str_replace(dirname(dirname(__DIR__)), '', $path);
        }
    }
    // echo 123;
    // 初始化 cURL
    $ch = curl_init($url);

    // 设置保存文件路径及文件句柄
    $fp = fopen($path, 'w');
    curl_setopt($ch, CURLOPT_FILE, $fp);

    // 设置 cURL 选项
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($ch, CURLOPT_TIMEOUT, 60);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3');

    // 执行下载
    $result = curl_exec($ch);

    // 关闭文件句柄和 cURL 资源
    fclose($fp);
    curl_close($ch);

    // 根据下载结果返回对应的值
    if ($result !== false) {
        return str_replace(dirname(dirname(__DIR__)), '', $path);
    } else {
        // 处理错误
        return $url;
    }
}

Code Usage:

Add it to your class library, then simply pass the download link and the absolute storage path as arguments; please make the necessary modifications to the code and update it accordingly. The code is provided for reference only.

微信赞赏

WeChat

支付宝赞赏

Alipay

✍️ Author: Hong Mu

webmaster · Thanks for reading, stay tuned for more exciting content

Author homepage View home page →

Related articles

PHP ob function record

PHP ob function record Language Notes PHP

Usage of the following three functions ob_get_contents(); ob_end_clean(); ob_start(); You can use these functions to buffer local files and execute local script code. Use ob_start() to save the output code into the buffer, and the page will not be displayed; then use ob_get_contents to get the data in the buffer. o…
👁 143
PHP preg

PHP preg Language Notes PHP

The preg_match_all function is used to perform a global regular expression match. preg_match_all() Syntax int preg_match_all ( string $pattern , string $subject [, array &$matches [, int $flags = PREG…
👁 169
Detailed explanation of PHP ternary operator and if

Detailed explanation of PHP ternary operator and if Language Notes PHP

Ternary operator condition ? Result 1 : Result 2 Explanation: The position in front of the question mark is the condition for judgment. If the condition is met, the result is 1, and if it is not met, the result is 2. This article compares and explains the ternary operator and if...else... in detail. I hope it will be helpful to everyone. Today when I was revising my paper online, I encountered a statement that I couldn’t understand: $if_summary = $row['IF_SUMMARY']=…
👁 191
PHP cast type

PHP cast type Language Notes PHP PHP collection PHP and mysql

Get the data type 1. If you want to check the value and type of an expression, use var_dump(). 2. If you just want to get an easy-to-read type expression for debugging, use gettype(). 3. To check a certain type, do not use gettype(), but use the is_type() function. Converting Strings to Numbers When a string is evaluated as a number, the result is determined according to the following rules...
👁 232

Recommended reading

ChatGPT generates articles in Markdown format.

ChatGPT generates articles in Markdown format. Practical Collection Utility tools

In the early hours of March 2, OpenAI launched the official ChatGPT API – not the underlying GPT-3.5 large-scale model, but the core ChatGPT model itself: ChatGPT-3.5-Turbo! The ChatGPT-3.5-Turbo model is the model used by ChatGPT and represents the fastest, most cost-effective, and most flexible model in the GPT-3.5 series. It can deliver ultra-high...
👁 223
(Adaptive Mobile Version) Green PBootCMS Industry Development Association Website Template – Download Source Code: 0811

(Adaptive Mobile Version) Green PBootCMS Industry Development Association Website Template – Download Source Code: 0811 Practical Collection pbootcms Template

A PbootCMS website template designed for green industry development and association websites, compatible with both PC and WAP devices. Its professional yet natural design makes it ideal for industry associations and government industrial departments to showcase policies, events, and member services. It helps public institutions establish an online platform for information dissemination and communication. Template Preview | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin | Extraction Password: www.4s5.cn...
👁 50
Responsive infant and children's clothing website template – 0983

Responsive infant and children's clothing website template – 0983 Practical Collection Yiyou template

This EyouCMS responsive template is ideal for the infant and children's clothing industry. Its stylish and playful design is perfect for showcasing children's apparel products, infant and toddler garments, brand identity, and new product launches. It helps children's clothing brands attract parent consumers online and enhance their brand awareness. Template Display | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Questions for EyouCMS...
👁 44
(Adaptive Mobile Version) Responsive Elevator and Escalator PBootCMS Template – Download Source Code for Green Enterprise Websites for Elevator Manufacturers – 0157

(Adaptive Mobile Version) Responsive Elevator and Escalator PBootCMS Template – Download Source Code for Green Enterprise Websites for Elevator Manufacturers – 0157 Practical Collection pbootcms Template

This adaptive mobile-responsive elevator and escalator PbootCMS template features a professional, eco-friendly corporate design style, ideal for showcasing elevator products, maintenance services, and engineering projects. It helps elevator manufacturing or maintenance companies build their brand image online and expand their presence in the building and infrastructure construction markets. Template Display | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin | Extraction Password:...
👁 43
Firefighting and Security Equipment Website Template 0299

Firefighting and Security Equipment Website Template 0299 Practical Collection Yiyou template

This EyouCMS template is ideal for the fire safety, firefighting, and security products industry. Its eye-catching and professional design effectively showcases fire safety products, security equipment, security solutions, and corporate strength. It enables security and fire safety companies to showcase their products online, attracting both corporate and government procurement opportunities. Template Display | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for EyouCMS...
👁 54
Responsive branded sportswear website template – 0984

Responsive branded sportswear website template – 0984 Practical Collection Yiyou template

An eyouCMS responsive website template designed specifically for the branded sportswear industry. Its vibrant and fashionable design is ideal for showcasing sportswear products, brand identity, athletic equipment, and new product launches. This template helps sportswear brands showcase their products online and attract sports enthusiasts. Template Display | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for YouyouCMS...
👁 51