Hướng dẫn how to save image from url using php? - làm thế nào để lưu hình ảnh từ url bằng php?

Không có câu trả lời nào ở đây đề cập đến thực tế là hình ảnh URL có thể được nén (GZIP) và không ai trong số chúng hoạt động trong trường hợp này.

Có hai giải pháp có thể giúp bạn xung quanh điều này:

Đầu tiên là sử dụng phương thức Curl và đặt Curl_SetOpt CURLOPT_ENCODING, '':

// ... image validation ...

// Handle compression & redirection automatically
$ch = curl_init($image_url);
$fp = fopen($dest_path, 'wb');

curl_setopt($ch, CURLOPT_FILE, $fp);
// Exclude header data
curl_setopt($ch, CURLOPT_HEADER, 0);
// Follow redirected location
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
// Auto detect decoding of the response | identity, deflate, & gzip
curl_setopt($ch, CURLOPT_ENCODING, '');

curl_exec($ch);

curl_close($ch);
fclose($fp);

Nó hoạt động, nhưng từ hàng trăm thử nghiệm các hình ảnh khác nhau (PNG, JPG, ICO, GIF, SVG), nó không phải là cách đáng tin cậy nhất.

Điều làm việc tốt nhất là phát hiện liệu URL hình ảnh có mã hóa nội dung hay không (ví dụ: GZIP):

// ... image validation ...

// Fetch all headers from URL
$data = get_headers($image_url, true);

// Check if content encoding is set
$content_encoding = isset($data['Content-Encoding']) ? $data['Content-Encoding'] : null;

// Set gzip decode flag
$gzip_decode = ($content_encoding == 'gzip') ? true : false;

if ($gzip_decode)
{
    // Get contents and use gzdecode to "unzip" data
    file_put_contents($dest_path, gzdecode(file_get_contents($image_url)));
}
else
{
    // Use copy method
    copy($image_url, $dest_path);
}

Để biết thêm thông tin về gzdecode, hãy xem chủ đề này. Cho đến nay điều này hoạt động tốt. Nếu có bất cứ điều gì có thể được thực hiện tốt hơn, hãy cho chúng tôi biết trong các ý kiến ​​dưới đây.

Đôi khi, cần tải xuống một hình ảnh từ một URL cụ thể và sử dụng nó vào dự án. Nó rất dễ đi đến trang và sử dụng nút nhấp chuột phải và lưu hình ảnh. Nhưng điều gì sẽ xảy ra nếu bạn muốn làm điều đó theo chương trình? Những lý do có thể thay đổi người, nhà phát triển cho nhà phát triển. Nếu bộ hàng trăm URL hình ảnh được cung cấp và bằng cách nào đó muốn lưu chúng vào máy hoặc cần sử dụng khái niệm này vào các dự án. Sau đó, chắc chắn sẽ không tải xuống từng một trong những tệp đó theo cách thủ công.

Có hai cách tiếp cận khác nhau để tải xuống hình ảnh từ URL được liệt kê dưới đây:

  • Sử dụng xử lý tệp cơ bản.
  • Sử dụng thư viện HTTP được gọi là Curl.

Cả hai cách tiếp cận này đều đi kèm với bộ công trạng và điểm yếu của riêng họ.

Sử dụng xử lý tệp cơ bản: Đây là cách cơ bản và dễ nhất để hoàn thành nhiệm vụ. Cũng giống như bất kỳ tệp nào khác, hãy bắt đầu với việc tạo một tệp trống và mở nó trong chế độ viết của Write. Sau đó, lấy nội dung từ URL nguồn và dán nó vào tệp này. Và nó đơn giản như nó nghe. This is the fundamental and easiest way to accomplish the task. Just like any other file, start with the creation of an empty file and open it in “write” mode. After that, fetch the content from source URL and paste it into this file. And it is as simple as it sounds.

Từ kịch bản, bạn có thể tự mình tìm ra những gì nó làm.

  • Khai báo hai biến có tên là $ url và $ img, đại diện cho URL nguồn và tệp đích tương ứng.$url and $img, representing the source URL and destination file respectively.
  • Sử dụng hàm file_put_contents () để ghi một chuỗi vào một tệp có hai đối số. Một là tên tệp (hoặc đường dẫn) và một là nội dung cho tệp đó.file_put_contents() function to write a string to a file that takes two arguments. One is the file name (or path) and the other is the content for that file.
  • Sử dụng hàm file_get_contents () để đọc một tệp vào một chuỗi.file_get_contents() function to read a file into a string.

Example:

File downloaded!

Lưu ý: Nó lưu hình ảnh vào máy chủ với tên đã cho logo.png. It save the image to the server with given name logo.png.

Bây giờ vấn đề duy nhất với phương pháp này là nó yêu cầu cấu hình allow_url_fopen phải được đặt, được đặt thành 1 theo mặc định. Nhưng đôi khi, các yêu cầu dự án don cho phép có tùy chọn này. Điều này có thể là do một số biện pháp bảo mật phòng ngừa hoặc chỉ là một nguyên tắc thiết kế. Trong những trường hợp như vậy, có một phương pháp khác để lưu hình ảnh.

Sử dụng thư viện HTTP, Curl: Nói đúng, Curl không chỉ là một thư viện HTTP. Nó cũng có một số giao thức truyền dữ liệu khác. Vì hình ảnh của chúng tôi là trên một máy chủ HTTP, chúng tôi sẽ giới hạn bản thân trong phần nhỏ của thư viện này. Strictly speaking, cURL is not just an HTTP library. It has got several other data transferring protocols as well. As our image is on an HTTP server, we will limit ourselves to this small section of this library.

Curl cho phép thực hiện các yêu cầu HTTP trong PHP. Bắt đầu bằng cách khởi tạo một thể hiện của nó và thiết lập một số tùy chọn cần thiết cho yêu cầu, bao gồm cả URL. Sau đó thực thi truy vấn này trả về nội dung của tệp. Sau đó, phần còn lại của thủ tục là như nhau. Ngay khi chúng tôi nhận được dữ liệu, hãy đặt nó vào một tệp và lưu nó.

Approach:

  • Trong tập lệnh này, chúng tôi đã xác định một hàm file_get_contents_curl để sao chép hành vi của file_get_contents từ kỹ thuật đã đề cập trước đó.file_get_contents_curl to replicate the behaviour of file_get_contents from the previously mentioned technique.
  • Bên trong chức năng này, chúng tôi đã khởi tạo một thể hiện của Curl bằng cách sử dụng hàm Curl_init để sử dụng nó để tìm nạp dữ liệu.curl_init function in order to use it for fetching the data.
  • Sau đó, một số tùy chọn cần được đặt bằng Curl_SetOpt để ví dụ cụ thể này có thể hoạt động. Hàm này có ba đối sốcurl_setopt so that this particular example can work. This function takes three arguments
    • Một ví dụ của Curl
    • Tùy chọn tương ứng cần được đặt
    • Và giá trị mà tùy chọn được đặt

    Trong ví dụ này, các tùy chọn sau được đặt:

    • Curlopt_header, đó là đảm bảo liệu bạn có cần nhận các tiêu đề hay không;
    • Curlopt_returntransfer chuyển dữ liệu dưới dạng giá trị trả về của hàm curl_exec thay vì xuất trực tiếp.curl_exec function rather than outputting it directly.
    • Có một tùy chọn khác Curlopt_url đặt URL cho yêu cầu.
  • Sau đó, chúng tôi tìm nạp dữ liệu từ curl_exec và trả lại từ chức năng cha.curl_exec and return it from the parent function.
  • Dữ liệu này sau đó được ghi vào tệp trên máy của bạn bằng File_put_contents.file_put_contents.

Example:

function file_get_contents_curl($url

// ... image validation ...

// Fetch all headers from URL
$data = get_headers($image_url, true);

// Check if content encoding is set
$content_encoding = isset($data['Content-Encoding']) ? $data['Content-Encoding'] : null;

// Set gzip decode flag
$gzip_decode = ($content_encoding == 'gzip') ? true : false;

if ($gzip_decode)
{
    // Get contents and use gzdecode to "unzip" data
    file_put_contents($dest_path, gzdecode(file_get_contents($image_url)));
}
else
{
    // Use copy method
    copy($image_url, $dest_path);
}
0____11
// ... image validation ...

// Fetch all headers from URL
$data = get_headers($image_url, true);

// Check if content encoding is set
$content_encoding = isset($data['Content-Encoding']) ? $data['Content-Encoding'] : null;

// Set gzip decode flag
$gzip_decode = ($content_encoding == 'gzip') ? true : false;

if ($gzip_decode)
{
    // Get contents and use gzdecode to "unzip" data
    file_put_contents($dest_path, gzdecode(file_get_contents($image_url)));
}
else
{
    // Use copy method
    copy($image_url, $dest_path);
}
2

// ... image validation ...

// Fetch all headers from URL
$data = get_headers($image_url, true);

// Check if content encoding is set
$content_encoding = isset($data['Content-Encoding']) ? $data['Content-Encoding'] : null;

// Set gzip decode flag
$gzip_decode = ($content_encoding == 'gzip') ? true : false;

if ($gzip_decode)
{
    // Get contents and use gzdecode to "unzip" data
    file_put_contents($dest_path, gzdecode(file_get_contents($image_url)));
}
else
{
    // Use copy method
    copy($image_url, $dest_path);
}
0
// ... image validation ...

// Fetch all headers from URL
$data = get_headers($image_url, true);

// Check if content encoding is set
$content_encoding = isset($data['Content-Encoding']) ? $data['Content-Encoding'] : null;

// Set gzip decode flag
$gzip_decode = ($content_encoding == 'gzip') ? true : false;

if ($gzip_decode)
{
    // Get contents and use gzdecode to "unzip" data
    file_put_contents($dest_path, gzdecode(file_get_contents($image_url)));
}
else
{
    // Use copy method
    copy($image_url, $dest_path);
}
4
// ... image validation ...

// Fetch all headers from URL
$data = get_headers($image_url, true);

// Check if content encoding is set
$content_encoding = isset($data['Content-Encoding']) ? $data['Content-Encoding'] : null;

// Set gzip decode flag
$gzip_decode = ($content_encoding == 'gzip') ? true : false;

if ($gzip_decode)
{
    // Get contents and use gzdecode to "unzip" data
    file_put_contents($dest_path, gzdecode(file_get_contents($image_url)));
}
else
{
    // Use copy method
    copy($image_url, $dest_path);
}
1
// ... image validation ...

// Fetch all headers from URL
$data = get_headers($image_url, true);

// Check if content encoding is set
$content_encoding = isset($data['Content-Encoding']) ? $data['Content-Encoding'] : null;

// Set gzip decode flag
$gzip_decode = ($content_encoding == 'gzip') ? true : false;

if ($gzip_decode)
{
    // Get contents and use gzdecode to "unzip" data
    file_put_contents($dest_path, gzdecode(file_get_contents($image_url)));
}
else
{
    // Use copy method
    copy($image_url, $dest_path);
}
6

// ... image validation ...

// Fetch all headers from URL
$data = get_headers($image_url, true);

// Check if content encoding is set
$content_encoding = isset($data['Content-Encoding']) ? $data['Content-Encoding'] : null;

// Set gzip decode flag
$gzip_decode = ($content_encoding == 'gzip') ? true : false;

if ($gzip_decode)
{
    // Get contents and use gzdecode to "unzip" data
    file_put_contents($dest_path, gzdecode(file_get_contents($image_url)));
}
else
{
    // Use copy method
    copy($image_url, $dest_path);
}
0
// ... image validation ...

// Fetch all headers from URL
$data = get_headers($image_url, true);

// Check if content encoding is set
$content_encoding = isset($data['Content-Encoding']) ? $data['Content-Encoding'] : null;

// Set gzip decode flag
$gzip_decode = ($content_encoding == 'gzip') ? true : false;

if ($gzip_decode)
{
    // Get contents and use gzdecode to "unzip" data
    file_put_contents($dest_path, gzdecode(file_get_contents($image_url)));
}
else
{
    // Use copy method
    copy($image_url, $dest_path);
}
4
// ... image validation ...

// Fetch all headers from URL
$data = get_headers($image_url, true);

// Check if content encoding is set
$content_encoding = isset($data['Content-Encoding']) ? $data['Content-Encoding'] : null;

// Set gzip decode flag
$gzip_decode = ($content_encoding == 'gzip') ? true : false;

if ($gzip_decode)
{
    // Get contents and use gzdecode to "unzip" data
    file_put_contents($dest_path, gzdecode(file_get_contents($image_url)));
}
else
{
    // Use copy method
    copy($image_url, $dest_path);
}
1
File downloaded!
0

// ... image validation ...

// Fetch all headers from URL
$data = get_headers($image_url, true);

// Check if content encoding is set
$content_encoding = isset($data['Content-Encoding']) ? $data['Content-Encoding'] : null;

// Set gzip decode flag
$gzip_decode = ($content_encoding == 'gzip') ? true : false;

if ($gzip_decode)
{
    // Get contents and use gzdecode to "unzip" data
    file_put_contents($dest_path, gzdecode(file_get_contents($image_url)));
}
else
{
    // Use copy method
    copy($image_url, $dest_path);
}
0
// ... image validation ...

// Fetch all headers from URL
$data = get_headers($image_url, true);

// Check if content encoding is set
$content_encoding = isset($data['Content-Encoding']) ? $data['Content-Encoding'] : null;

// Set gzip decode flag
$gzip_decode = ($content_encoding == 'gzip') ? true : false;

if ($gzip_decode)
{
    // Get contents and use gzdecode to "unzip" data
    file_put_contents($dest_path, gzdecode(file_get_contents($image_url)));
}
else
{
    // Use copy method
    copy($image_url, $dest_path);
}
4
// ... image validation ...

// Fetch all headers from URL
$data = get_headers($image_url, true);

// Check if content encoding is set
$content_encoding = isset($data['Content-Encoding']) ? $data['Content-Encoding'] : null;

// Set gzip decode flag
$gzip_decode = ($content_encoding == 'gzip') ? true : false;

if ($gzip_decode)
{
    // Get contents and use gzdecode to "unzip" data
    file_put_contents($dest_path, gzdecode(file_get_contents($image_url)));
}
else
{
    // Use copy method
    copy($image_url, $dest_path);
}
1
File downloaded!
4$url
File downloaded!
6

____10

File downloaded!
8
File downloaded!
9
// ... image validation ...

// Fetch all headers from URL
$data = get_headers($image_url, true);

// Check if content encoding is set
$content_encoding = isset($data['Content-Encoding']) ? $data['Content-Encoding'] : null;

// Set gzip decode flag
$gzip_decode = ($content_encoding == 'gzip') ? true : false;

if ($gzip_decode)
{
    // Get contents and use gzdecode to "unzip" data
    file_put_contents($dest_path, gzdecode(file_get_contents($image_url)));
}
else
{
    // Use copy method
    copy($image_url, $dest_path);
}
1
File downloaded!
6

// ... image validation ...

// Fetch all headers from URL
$data = get_headers($image_url, true);

// Check if content encoding is set
$content_encoding = isset($data['Content-Encoding']) ? $data['Content-Encoding'] : null;

// Set gzip decode flag
$gzip_decode = ($content_encoding == 'gzip') ? true : false;

if ($gzip_decode)
{
    // Get contents and use gzdecode to "unzip" data
    file_put_contents($dest_path, gzdecode(file_get_contents($image_url)));
}
else
{
    // Use copy method
    copy($image_url, $dest_path);
}
0
File downloaded!
3
// ... image validation ...

// Fetch all headers from URL
$data = get_headers($image_url, true);

// Check if content encoding is set
$content_encoding = isset($data['Content-Encoding']) ? $data['Content-Encoding'] : null;

// Set gzip decode flag
$gzip_decode = ($content_encoding == 'gzip') ? true : false;

if ($gzip_decode)
{
    // Get contents and use gzdecode to "unzip" data
    file_put_contents($dest_path, gzdecode(file_get_contents($image_url)));
}
else
{
    // Use copy method
    copy($image_url, $dest_path);
}
1
File downloaded!
6

// ... image validation ...

// Fetch all headers from URL
$data = get_headers($image_url, true);

// Check if content encoding is set
$content_encoding = isset($data['Content-Encoding']) ? $data['Content-Encoding'] : null;

// Set gzip decode flag
$gzip_decode = ($content_encoding == 'gzip') ? true : false;

if ($gzip_decode)
{
    // Get contents and use gzdecode to "unzip" data
    file_put_contents($dest_path, gzdecode(file_get_contents($image_url)));
}
else
{
    // Use copy method
    copy($image_url, $dest_path);
}
0
File downloaded!
7
File downloaded!
8
File downloaded!
9

CURLOPT_ENCODING, ''0

File downloaded!
8 CURLOPT_ENCODING, ''2

CURLOPT_ENCODING, ''3 CURLOPT_ENCODING, ''4CURLOPT_ENCODING, ''5

File downloaded!
9

CURLOPT_ENCODING, ''7CURLOPT_ENCODING, ''8CURLOPT_ENCODING, ''30

File downloaded!
8
File downloaded!
6

3 4

5

Output:

File downloaded!

Phương pháp này cung cấp một chút linh hoạt trong khi tìm nạp nội dung từ Internet. Như đã đề cập trước đó, nó không chỉ giới hạn ở HTTP mà còn có thể được sử dụng trong nhiều trường hợp khác. Nó cho phép định cấu hình chuyển nhượng theo bất cứ cách nào bạn muốn. Ví dụ: File_Get_Contents sử dụng một yêu cầu nhận đơn giản để tìm nạp dữ liệu, nhưng với Curl, cũng có thể sử dụng GET, POST, PUT và các phương thức khác.file_get_contents uses a simple GET request to fetch the data, but with cURL, can use GET, POST, PUT and other methods as well.

PHP là ngôn ngữ kịch bản phía máy chủ được thiết kế dành riêng cho phát triển web. Bạn có thể học PHP từ đầu bằng cách làm theo hướng dẫn PHP và các ví dụ PHP này.


Làm thế nào để lưu hình ảnh trong PHP?

file_put_contents ($ IMG, file_get_contents ($ url)); echo "Tải xuống tệp!" Tải xuống tệp! Lưu ý: Nó lưu hình ảnh vào máy chủ với logo tên đã cho. echo "File downloaded!" File downloaded! Note: It save the image to the server with given name logo.

Làm cách nào để lưu hình ảnh dưới dạng URL?

Mở một tab mới và dán URL vào thanh địa chỉ (Ctrl + V hoặc nhấp chuột phải vào thanh địa chỉ và nhấn Dán).Hình ảnh sẽ xuất hiện.7. Trong tab mới, nhấp chuột phải vào hình ảnh và chọn Lưu hình ảnh dưới dạng.

Làm cách nào để tải xuống URL từ PHP?

Các bước để tải xuống tệp:..
Khởi tạo URL tệp vào biến ..
Tạo phiên Curl ..
Khai báo một biến và lưu trữ tên thư mục trong đó tệp đã tải xuống sẽ lưu ..
Sử dụng hàm basename () để trả về tên tệp basename nếu đường dẫn tệp được cung cấp dưới dạng tham số ..
Lưu tệp vào vị trí đã cho ..

Làm cách nào để sao chép hình ảnh từ thư mục này sang thư mục khác trong PHP?

Hàm Copy () trong PHP được sử dụng để sao chép một tệp từ nguồn sang mục đích hoặc thư mục đích.Nó tạo một bản sao của tệp nguồn vào tệp đích và nếu tệp đích đã tồn tại, nó sẽ bị ghi đè.Hàm COPY () trả về đúng khi thành công và sai khi thất bại.. It makes a copy of the source file to the destination file and if the destination file already exists, it gets overwritten. The copy() function returns true on success and false on failure.