简体   繁体   中英

Downloading Images via PHP

I have a PHP file called generate.php which generates a PNG email based on some parameters I set. The image can be displayed for example by using which will return an image of "myString" text.

I would then like to add a link which allows the user to download the image:

I created a file download.php with the following code:

header('Content-disposition: attachment; filename=string.png');
header('Content-type: image/png');
readfile('generatePicture.php?string=' . $_REQUEST["string"]);

But, while I download a png file, I cannot seem to download. Any suggestions?

When you readfile() a PHP file, its source is displayed. Below I'll show you my way to solve this problem.

Assuming generatePicture.php looks like:

<?php
$im = imagecreatetruecolor($w, $h);
// work with the picture
header('Content-type: image/png');
imagepng($im);
?>

... it could be integrated with download.php this way:

<?php
$im = imagecreatetruecolor($w, $h);
// work with the picture

if(isset($_GET['download']))
    header('Content-disposition: attachment; filename=string.png');

header('Content-type: image/png');
imagepng($im);
?>

Now instead of linking to download.php?string=loremipsum , link to generatePicture.php?string=loremipsum&download=1

Hope it helps.

I've been using this with moderate success for multiple file types. The main thing you need extracted from the file information is the file type, file name, and file size.

  header("Content-Description: PHP Generated Data");
  header("Content-type:".$type);
  header("Content-Disposition: Attachment; Filename=".$name);
  header("Content-length:".$size);
  echo $data;

That might give you something different to try.

Session locking. If you have two scripts that use session_start() the first script opens and locks the session's cache, and the second script must wait for the first to complete before it can open the cache.

If you have a long-running script that you don't want to monopolize a user's session, then either do not call session_start() for that script, or call session_write_close() after you've finished with the session data, but before you begin the long-running operation.

Either that, or use two different browsers to open two separate sessions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM