search
HomeBackend DevelopmentPHP TutorialTwo ways to quickly download files from URL in PHP

In the previous article "Example demonstrates how to call a PHP function when a button is clicked", I introduced to you how to call a PHP function when a button is clicked. Friends in need can learn about it~

The topic of this article is how to download files from URL through PHP?

There are actually many ways to download files from URLs, but this article will focus on two methods:

The first method:

Use file_get_contents () Function: The file_get_contents() function is used to read files into strings. This function uses server-supported memory mapping technology, which improves performance and makes it the preferred way to read file contents.

Syntax:

file_get_contents($path, $include_path, $context, $start, $max_length)

Create a test.php sample file with the following content:

<?php
// 将文件URL初始化为变量
$url = &#39;https://img.php.cn/upload/article/000/000/020/6125a391e4e76689.png&#39;;

// 使用basename()函数获取文件名
$file_name = basename($url);

// 使用file_get_contents()函数从url获取文件,使用file_put_contents()函数保存文件
if(file_put_contents( $file_name,file_get_contents($url))) {
    echo "文件下载成功";
}
else {
    echo "文件下载失败";
}

The running results show:

文件下载成功

Now we can Check whether the "6125a391e4e76689.png" file was successfully saved in the same directory as the test.php file:

Two ways to quickly download files from URL in PHP

The file was successfully saved from the URL.

Second method: Use PHP Curl

Create a test.php sample file, the sample code is as follows:

<?php

$url = &#39;https://img.php.cn/upload/article/000/000/020/6125a391e4e76689.png&#39;;

// 初始化cURL会话
$ch = curl_init($url);

// 初始化保存文件的目录名
$dir = &#39;./&#39;;

// 函数返回文件名
$file_name = basename($url);

// 将文件保存到给定位置
$save_file_loc = $dir . $file_name;

// 打开文件
$fp = fopen($save_file_loc, &#39;wb&#39;);

// 为cURL传输设置一个选项
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);

// 执行cURL会话
curl_exec($ch);

// 关闭cURL会话并释放所有资源
curl_close($ch);

// 关闭文件
fclose($fp);

Run the test.php file Then you can view the downloaded and saved file at the specified location.

This method implements the specific steps to download files:

  • Initialize the file URL as a variable

  • Create a cURL session

  • Declare a variable and store the name of the directory where the downloaded file will be saved.

  • If the file path is provided as a parameter, use the basename() function to return the file base name.

  • Save the file to the given location.

  • Open the saved file location by writing a string

  • Set cURL transfer options

  • Execute the cURL session and close the cURL session and release all resources

  • Close the file

Finally, I recommend the latest and most comprehensive "PHP Video tutorial》~Come and learn!

The above is the detailed content of Two ways to quickly download files from URL in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How do you create and use an interface in PHP?How do you create and use an interface in PHP?Apr 30, 2025 pm 03:40 PM

The article explains how to create, implement, and use interfaces in PHP, focusing on their benefits for code organization and maintainability.

What is the difference between crypt() and password_hash()?What is the difference between crypt() and password_hash()?Apr 30, 2025 pm 03:39 PM

The article discusses the differences between crypt() and password_hash() in PHP for password hashing, focusing on their implementation, security, and suitability for modern web applications.

How can you prevent Cross-Site Scripting (XSS) in PHP?How can you prevent Cross-Site Scripting (XSS) in PHP?Apr 30, 2025 pm 03:38 PM

Article discusses preventing Cross-Site Scripting (XSS) in PHP through input validation, output encoding, and using tools like OWASP ESAPI and HTML Purifier.

What is autoloading in PHP?What is autoloading in PHP?Apr 30, 2025 pm 03:37 PM

Autoloading in PHP automatically loads class files when needed, improving performance by reducing memory use and enhancing code organization. Best practices include using PSR-4 and organizing code effectively.

What are PHP streams?What are PHP streams?Apr 30, 2025 pm 03:36 PM

PHP streams unify handling of resources like files, network sockets, and compression formats via a consistent API, abstracting complexity and enhancing code flexibility and efficiency.

What is the maximum size of a file that can be uploaded using PHP ?What is the maximum size of a file that can be uploaded using PHP ?Apr 30, 2025 pm 03:35 PM

The article discusses managing file upload sizes in PHP, focusing on the default limit of 2MB and how to increase it by modifying php.ini settings.

What is Nullable types in PHP ?What is Nullable types in PHP ?Apr 30, 2025 pm 03:34 PM

The article discusses nullable types in PHP, introduced in PHP 7.1, allowing variables or parameters to be either a specified type or null. It highlights benefits like improved readability, type safety, and explicit intent, and explains how to declar

What is the difference between the unset() and unlink() functions ?What is the difference between the unset() and unlink() functions ?Apr 30, 2025 pm 03:33 PM

The article discusses the differences between unset() and unlink() functions in programming, focusing on their purposes and use cases. Unset() removes variables from memory, while unlink() deletes files from the filesystem. Both are crucial for effec

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.