Hướng dẫn force download an image in php - buộc tải xuống một hình ảnh trong php

Tôi đang cố gắng tải xuống tệp hình ảnh trong CI nhưng gặp lỗi khi mở tệp hình ảnh tải xuống. Cần giúp đỡ :(

$file_name = $_GET['file_name'];
            $file_path =  "./ups_printimages/".$file_name;
            if(file_exists($file_path))
            {
                $this->load->helper('download');
                $data = file_get_contents($file_path); // Read the file's contents
                $name = 'ups_label.png';
                force_download($name, $data);
            }
            else
            {
                echo "file does not exist";
            }

Hỏi ngày 18 tháng 8 năm 2014 lúc 13:21Aug 18, 2014 at 13:21

Hướng dẫn force download an image in php - buộc tải xuống một hình ảnh trong php

3

CHÚA TRỜI. Tìm ra giải pháp :)

if(!file)
    {
         File doesn't exist, output error
         die('file not found');
    }
    else
    {
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename='.basename($file));
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: public');
        ob_clean();
        flush();
        readfile($file);
        exit;
     }

Đã trả lời ngày 19 tháng 8 năm 2014 lúc 12:49Aug 19, 2014 at 12:49

0

Sử dụng tiêu đề để buộc tải xuống. Sử dụng mã bên dưới

 $file_name = $_GET['file_name'];
                $file_path =  "./ups_printimages/".$file_name;
                if(file_exists($file_path))
                {
                 header('Content-Type: image/jpeg');
    header("Content-Transfer-Encoding: Binary"); 
    header("Content-disposition: attachment; filename=\"" . basename($file_name) . "\""); 
    readfile($file_path); 
                }
                else
                {
                    echo "file does not exist";
                }

Hy vọng điều này sẽ giúp bạn

Đã trả lời ngày 18 tháng 8 năm 2014 lúc 13:27Aug 18, 2014 at 13:27

Utkarsh Dixitutkarsh DixitUtkarsh Dixit

4.1973 Huy hiệu vàng14 Huy hiệu bạc36 Huy hiệu đồng3 gold badges14 silver badges36 bronze badges

2

Trong hướng dẫn này, bạn sẽ tìm hiểu cách buộc tải xuống một tệp bằng PHP.

Tải xuống các tệp với PHP

Thông thường, bạn không nhất thiết cần phải sử dụng bất kỳ ngôn ngữ tập lệnh phía máy chủ 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 thư mục có thể truy cập công khai, bạn có thể tạo Hyperlink 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 xuống tệp đó.

<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>

Nhấp vào liên kết trỏ đến PDF hoặc tệp hình ảnh sẽ không khiến nó trực tiếp tải xuống ổ cứng của bạn. Nó sẽ chỉ mở tệp trong trình duyệt của bạn. Hơn nữa bạn có thể lưu nó vào ổ cứng của bạn. Tuy nhiên, các tệp ZIP và EXE được tải xuống tự động vào ổ cứng theo mặc định.


Buộc tải xuống bằng PHP

Bạn có thể buộc hình ảnh hoặc loại tệp khác để tải xuống trực tiếp vào ổ cứng của người dùng bằng cách sử dụng chức năng PHP readfile(). Ở đây, chúng tôi 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ú nhấp chuột.

Hãy tạo một tệp có tên "Image-gallery.php" và đặt mã sau bên 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 thấy mã ví dụ ở trên một cách cẩn thận, bạn sẽ tìm thấy liên kết tải xuống các pint vào tệp "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 tôi đã sử dụng chức năng PHP urlencode() để mã hóa tên tệp hình ảnh để có thể được truyền an toàn dưới dạng tham số URL, vì tên tệp có thể chứa các ký tự không an toàn URL.

Dưới đây là mã hoàn chỉnh của tệp "download.php", buộc tải xuống hình ảnh.

<?php
if(isset($_REQUEST["file"])){
    // Get parameters
    $file = urldecode($_REQUEST["file"]); // Decode URL-encoded string

    /* Test whether the file name contains illegal characters
    such as "../" using the regular expression */
    if(preg_match('/^[^.][-a-z0-9_.]+[a-z]$/i', $file)){
        $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);
            die();
        } else {
            http_response_code(404);
	        die();
        }
    } else {
        die("Invalid file name!");
    }
}
?>

Tương tự, bạn có thể buộc tải xuống các định dạng các tệp khác như Word Doc, PDF Tệp, v.v.

Biểu thức chính quy trong ví dụ trên (dòng số 8) sẽ không cho phép các tệp đó có tên bắt đầu hoặc kết thúc bằng ký tự dấu chấm (.), nó cho phép các tên tệp như kites.jpg hoặc

if(!file)
    {
         File doesn't exist, output error
         die('file not found');
    }
    else
    {
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename='.basename($file));
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: public');
        ob_clean();
        flush();
        readfile($file);
        exit;
     }
0,
if(!file)
    {
         File doesn't exist, output error
         die('file not found');
    }
    else
    {
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename='.basename($file));
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: public');
        ob_clean();
        flush();
        readfile($file);
        exit;
     }
1 nhưng không Cho phép
if(!file)
    {
         File doesn't exist, output error
         die('file not found');
    }
    else
    {
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename='.basename($file));
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: public');
        ob_clean();
        flush();
        readfile($file);
        exit;
     }
2 hoặc
if(!file)
    {
         File doesn't exist, output error
         die('file not found');
    }
    else
    {
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename='.basename($file));
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: public');
        ob_clean();
        flush();
        readfile($file);
        exit;
     }
3.

Vui lòng kiểm tra hướng dẫn về các biểu thức thông thường để tìm hiểu các biểu thức thông thường chi tiết.

Làm cách nào để tải hình ảnh từ PHP?

file_put_contents ($ img, file_get_contents ($ url)); Echo "Tệp tải xuống!" Tải xuống tập tin! echo "File downloaded!" File downloaded!

Làm cách nào để làm cho tệp PHP của tôi có thể tải xuống?

PHP cho phép bạn tải xuống tệp dễ dàng bằng hàm readfile () tích hợp.Hàm readfile () đọc một tệp và ghi nó vào bộ đệm đầu ra ...
Tiêu đề ('Loại nội dung: Ứng dụng/Dòng octet') ;.
Tiêu đề ("Mã hóa chuyển đổi nội dung: UTF-8") ;.

Làm cách nào để tải xuống tệp PHP mà không cần thực hiện?

Một tệp PHP được thực thi phía máy chủ và không thể làm bất cứ điều gì với trình duyệt web của bạn.....
Nếu bạn đang tìm cách tránh tải xuống trình duyệt web của mình và thực hiện mã phía máy khách có khả năng độc hại thì bạn có thể sử dụng WGET để tải xuống đầu ra vào một tệp mà sau đó bạn có thể mở bằng Notepad.....
@Zaibis bạn chủ yếu chính xác ..

Làm cách nào để đặt PHP để tải xuống một thư mục cụ thể?

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 ..