Can I “echo” a .jpg image through php without processing it?

后端 未结 3 748
星月不相逢
星月不相逢 2020-12-20 15:40

Imagine the following:


Now, in image.php:

header(\'content-type:          


        
相关标签:
3条回答
  • 2020-12-20 15:49

    What about something like http://www.php.net/manual/en/function.readfile.php

    From the example

    <?php
    $file = 'monkey.gif';
    
    if (file_exists($file)) {
        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');
        header('Content-Length: ' . filesize($file));
        ob_clean();
        flush();
        readfile($file);
        exit;
    }
    ?>
    
    0 讨论(0)
  • 2020-12-20 15:56

    Sure, using readfile. Don't forget to restrict the allowed image names. Otherwise, you'd be creating a directory traversal vulnerability.

    header('content-type: image/jpeg');
    $img = preg_replace('/[^0-9a-z\._\-]/', '_', $_GET['image']);
    readfile($img);
    
    0 讨论(0)
  • 2020-12-20 16:04

    Yes, you can. Just readfile instead of imagecreatefromXXX+imagejpeg.

    header('Content-Type: image/jpeg');
    $src = /* process $_GET['image'] to recover the path */;
    readfile($src);
    

    The /* process $_GET['images'] to recover the path */ part implies any sanitizing you need to do on the input to avoid that someone requests a forbidden file. If your script input is a file path, this may mean checking from a predefined list, stripping of possible directory separators, checking against a regex, etc. Another way would be to store paths inside a database and pass the script a simple id, and recover the file path with it. This might be a better idea, as users will see no mention of any file path on the script URL (if you just pass a path, people can actually guess where files are, and that's what you're trying to prevent).

    0 讨论(0)
提交回复
热议问题