Hướng dẫn php return file

Download Zip file Download PDF file Download Image file Download EXE file

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.

Ở đâ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ó.





Simple Image Gallery

    .img-box{
        display: inline-block;
        text-align: center;
        margin: 0 15px;
    }



    

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.

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.

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



fuction call with 4 parameters:

[1] = the file with CSV data [url / string]
[2] = colum delimiter [e.g: ; or | or , ...]
[3] = values enclosed by [e.g: ' or " or ^ or ...]
[4] = with or without 1st row = head [true/false]



PS: also see: //php.net/manual/de/function.fgetcsv.php to read CSV data into an array
... and other file-handling methods

^

sheldon at hyperlinked dot com

3 years ago

As of PHP 5.6 the file[], file_get_contents[], and fopen[] functions will return false if you are referencing a source URL that doesn't have a valid SSL certificate. Presumably, you will run into this a lot in your development environments this will drive you crazy.

You will need to create a stream context and provide it as an argument to the various file operations to tell it to ignore invalid SSL credentials.

$args = array["ssl"=>array["verify_peer"=>false,"verify_peer_name"=>false],"http"=>array['timeout' => 60, 'user_agent' => 'Mozilla/5.0 [Windows; U; Windows NT 5.1; en-US; rv:1.8.1.9] Gecko/20071025 Firefox/3.0.0.1']];

$context = stream_context_create[$args];
$httpfile = file[$url, false, $context];

justin at visunet dot ie

19 years ago

Note: Now that file[] is binary safe it is 'much' slower than it used to be. If you are planning to read large files it may be worth your while using fgets[] instead of file[] For example:



The resulting array is $lines.

I did a test on a 200,000 line file. It took seconds with fgets[]  compared to minutes with file[].

Reversed: moc dot liamg at senroc dot werdna

15 years ago

This note applies to PHP 5.1.6 under Windows [although may apply to other versions].

It appears that the 'FILE_IGNORE_NEW_LINES' flag doesn't remove newlines properly when reading Windows-style text files, i.e. files whose lines end in '\r\n'.

Solution: Always use 'rtrim[]' in preference to 'FILE_IGNORE_NEW_LINES'.

Anonymous

8 years ago

["file[]'s problem with UTF-16" is wrong. This is updated.
The former may miss the last line of the string.]

file[] seems to have a problem in handling
UTF-16 with or without BOM.

file[] is likely to think "\n"=LF [0A] as a line-ending.
So, not only "000A" but also "010A, 020A,...,FE0A, FF0A,..."
are regarded as line-endings.

Moreover, file[] causes a serious problem in UTF-16LE.
file[] loses first "0A" [the first half of "0A00"]!
And the next line begins with "00" [the rest of "0A00"].
So lines after the first "0A" are totally different.

To avoid this phenomena,
eg. in case [php_script : UTF-8 , file : UTF-16 with line-ending "\r\n"],



instead of
$file = file[$file_path];

If line-ending is "\n",
$pattern1 = mb_convert_encoding['[^\n]*\n', $to_encoding, $from_encoding];

vbchris at gmail dot com

14 years ago

If you're getting "failed to open stream: Permission denied" when trying to use either file[] or fopen[] to access files on another server. Check your host doesn't have any firewall restrictions in-place which prevent outbound connections. This is the case with my host Aplus.net

jon+spamcheck at phpsitesolutions dot com

14 years ago

A user suggested using rtrim always, due to the line ending conflict with files that have an EOL that differs from the server EOL.

Using rtrim with it's default character replacement is a bad solution though, as it removes all whitespace in addition to the '\r' and '\n' characters.

A good solution using rtrim follows:



This removes only EOL characters, and replaces with the server's EOL character, thus making preg_* work fine when matching the EOL [$]

lanresmith

5 years ago

Using if [ file[name.txt] ] might not be enough for testing if the file was successfully opened for reading because the file could be empty in which case the array returned is empty, so test instead with !==. e.g.:

$file_array = file['test.txt']; // an empty file

echo '

';
if [ $file_array ] {
    # code...
    echo "success\n";
} else {
    # code...
    echo "failure\n"; // executed
}

if [ $file_array !== false ] {
    # code...
    echo "success\n"; // executed
} else {
    # code...
    echo "failure\n";
}
echo '

';

result:
failure
success

marco dot remy at aol dot com

8 years ago

Here's my CSV converter
supports Header and trims all fields
Note: Headers must be not empty!

Chủ Đề