Output an Image in PHP

前端 未结 12 1258
萌比男神i
萌比男神i 2020-11-22 14:33

I have an image $file ( eg ../image.jpg )

which has a mime type $type

How can I output it to the browser?

12条回答
  •  我在风中等你
    2020-11-22 15:06

    (Expanding on the accepted answer...)

    I needed to:

    1. log views of a jpg image and an animated gif, and,
    2. ensure that the images are never cached (so every view is logged), and,
    3. also retain the original file extensions.

    I accomplished this by creating a "secondary" .htaccess file in the sub-folder where the images are located.
    The file contains only one line:

    AddHandler application/x-httpd-lsphp .jpg .jpeg .gif
    

    In the same folder, I placed the two 'original' image files (we'll call them orig.jpg and orig.gif), as well as two variations of the [simplified] script below (saved as myimage.jpg and myimage.gif)...

    connect_error) {         //if connected then save mySQL record
       $conn->query("INSERT INTO imageclicks (image, ip) VALUES ('$url', '$ip');");
         $conn->close();  //(datetime is auto-added to table with default of 'now')
      } 
    
      //display the image
      $imgfile='orig.jpg';                             // or 'orig.gif'
      header('Content-Type: image/jpeg');              // or 'image/gif'
      header('Content-Length: '.filesize($imgfile));
      header('Cache-Control: no-cache');
      readfile($imgfile);
    ?>
    

    The images render (or animate) normally and can be called in any of the normal ways for images (like an tag), and will save a record of the visiting IP, while invisible to the user.

提交回复
热议问题