Home >Backend Development >PHP Tutorial >Solution to empty jpg file downloaded by php_PHP tutorial

Solution to empty jpg file downloaded by php_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:54:391215browse

Solution to empty jpg file downloaded by php tutorial

Jpg format files, click to open in the browser and displayed as a red cross

The code is as follows:

$filetype = "image/pjpeg";
header("content-type: {$filetype}");
 

header("expires: 0");
header("cache-control: must-revalidate, post-check=0,pre-check=0");
header("pragma: public");

$file_content = file_get_contents($filepath);
echo $file_content;
exit;

First check whether there is any problem with the initial file

1. echo $filepath;

2. Open the file according to the complete path of the output file, no problem

Exclude the suspicion of the original file

Then check whether there are any problems during file reading

1. $filetype = "application/jpeg";

header("content-disposition: attachment; filename="{$headername}";");

Force file download

After downloading, I found that the file size is the same as the original file, but it is still empty after opening. It can be determined that there is a problem when the file is output

Use file_put_contents("d:aaa.jpg", file_get_contents($filepath)) to save the file to the server. The saved file can be opened

At this time I suspected that there was something wrong with the encoding when the file was output to the client

After a period of trouble, the problem was finally solved. The code is as follows:

header("content-type: {$filetype}");
header("expires: 0");
header("cache-control: must-revalidate, post-check=0,pre-check=0");
header("pragma: public");
//Add encoding settings here
header('content-transfer-encoding: binary');
//The most important thing here is to clear the output bytes
ob_clean();
//This is equal to the two injected lines below, which can save code
readfile($filepath);

//$file_content = file_get_contents($filepath);
//echo $file_content;
exit;

Attached is the explanation of ob_clean():

clean (erase) the output buffer

I understand ob_clean() is equal to response.clear() in .net;

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/632310.htmlTechArticlephp tutorial download jpg file is empty solution solution jpg format file, click to open in the browser to display a red cross The code is as follows: $filetype = image/pjpeg; header(content-type: {$filetype}...
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