Hướng dẫn save image in php - lưu hình ảnh trong php

None of the answers here mention the fact that a URL image can be compressed (gzip), and none of them work in this case.

There are two solutions that can get you around this:

The first is to use the cURL method and set the 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);

It works, but from hundreds of tests of different images (png, jpg, ico, gif, svg), it is not the most reliable way.

What worked out best is to detect whether an image url has content encoding (e.g. 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);
}

For more information regarding gzdecode see this thread. So far this works fine. If there's anything that can be done better, let us know in the comments below.

Hướng dẫn save image in php - lưu hình ảnh trong php

Ở bài trước chúng ta đã học về upload file, hôm nay chúng ta sẽ học về cách Download file sử dụng PHP.Download file sử dụng PHP.

Download File trong PHP

Bình thường bạn không nhất thiết phải sử dụng bất kỳ ngôn ngữ nào như PHP để tải xuống hình ảnh, tệp zip, tài liệu pdf, tệp exe, v.v …

Nếu loại tệp đó được lưu trữ trong một thư mục có thể truy cập công khai, bạn chỉ cần tạo một đường link trỏ đến tệp đó và bất cứ khi nào người dùng nhấp vào liên kết, trình duyệt sẽ tự động tải tệp đó xuống.

Ví dụ:

<a href="downloads/test.zip">Download Zip file</a>
<a href="downloads/masters.pdf">Download PDF file</a>
<a href="downloads/sample.jpg">Download Image file</a>
<a href="downloads/setup.exe">Download EXE file</a>

Click vào đường link trỏ đến tệp PDF hoặc tệp Image sẽ không tải file xuống máy tính.

Nó sẽ chỉ mở file trong trình duyệt. Sau đó bạn có thể lưu nó. Tuy nhiên, các tệp zip và exe thì được tự động tải xuống.

Chức năng Download file sử dụng PHP

Bạn có thể bắt buộc hình ảnh hoặc loại file khác tải trực tiếp xuống máy tính của người dùng bằng hàm readfile() của PHP.hàm readfile() của PHP.

Ở đây chúng ta sẽ tạo một bộ sưu tập hình ảnh đơn giản cho phép người dùng tải xuống các tệp hình ảnh từ trình duyệt chỉ bằng một cú click chuột.

Hãy tạo một tệp có tên ‘image-gallery.php’ và đặt đoạn mã sau vào trong nó.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Simple Image Gallery</title>
<style type="text/css">
    .img-box{
        display: inline-block;
        text-align: center;
        margin: 0 15px;
    }
</style>
</head>
<body>
    <?php
    // Array containing sample image file names
    $images = array("kites.jpg", "balloons.jpg");
    
    // Loop through array to create image gallery
    foreach($images as $image){
        echo '<div class="img-box">';
            echo '<img src="images/' . $image . '" width="200" alt="' .  pathinfo($image, PATHINFO_FILENAME) .'">';
            echo '<p><a href="download.php?file=' . urlencode($image) . '">Download</a></p>';
        echo '</div>';
    }
    ?>
</body>
</html>

Nếu bạn xem mã ví dụ trên một cách cẩn thận, bạn sẽ thấy liên kết tải xuống dẫn đến file ‘download.php’, URL cũng chứa tên tệp hình ảnh dưới dạng chuỗi truy vấn.‘download.php’, URL cũng chứa tên tệp hình ảnh dưới dạng chuỗi truy vấn.

Ngoài ra, chúng ta đã sử dụng hàm urlencode() của PHP để mã hóa tên tệp hình ảnh để nó có thể được truyền an toàn dưới dạng tham số URL, bởi vì tên tệp có thể chứa các ký tự không an toàn. hàm urlencode() của PHP để mã hóa tên tệp hình ảnh để nó có thể được truyền an toàn dưới dạng tham số URL, bởi vì tên tệp có thể chứa các ký tự không an toàn.

Đây là mã hoàn chỉnh của tệp ‘download.php‘ để bắt buộc tải xuống hình ảnh.download.php‘ để bắt buộc tải xuống hình ảnh.

<?php
if(isset($_REQUEST["file"])){
    // Get parameters
    $file = urldecode($_REQUEST["file"]); // Decode URL-encoded string
    $filepath = "images/" . $file;
    
    // Process download
    if(file_exists($filepath)) {
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="'.basename($filepath).'"');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($filepath));
        flush(); // Flush system output buffer
        readfile($filepath);
        exit;
    }
}
?>

Tổng kết

Như vậy, bạn đã biết sử dụng PHP để bắt buộc Download file xuống máy tính người dùng. Bạn cũng có thể buộc tải xuống các định dạng tệp khác như word doc, tệp pdf, v.v. sử dụng PHP để bắt buộc Download file xuống máy tính người dùng. Bạn cũng có thể buộc tải xuống các định dạng tệp khác như word doc, tệp pdf, v.v.