Adam Adam - 6 months ago 11
PHP Question

How to pass variable to PHP picture

Motivated by this post
http://security.stackexchange.com/questions/32852/risks-of-a-php-image-upload-form I want to display my images by

<?php $pathToPicture = "server/www/images/imagexyz1823014719102714123.png"; ?>

<img src="/resources/php/showImage.php" >


where showImage.php is simply given by

<?php
header('Content-Type: image/jpeg');
readfile($pathToPicture);
?>


But how can I pass the variable $pathToPicture to showImage.php? I do not want to hard-code $pathToPictue into showImage.php.

Answer

Pass the path of image as get parameter to showImage.php script like.

<?php $pathToPicture = "server/www/images/imagexyz1823014719102714123.png"; ?>

<img src="/resources/php/showImage.php?pathToPicture=<?php echo $pathToPicture;?>"  >

Here you can get passed variable from $_GET array:

<?php
    header('Content-Type: image/jpeg');
    readfile($_GET['pathToPicture']);
?>

I preferably suggest use of base64_encode and base64_decode for pathToPicture for this purpose. Also not expose the whole path of your images location openly like this. Have a look at below improved code

<?php $pathToPicture = "imagexyz1823014719102714123.png"; ?>

<img src="/resources/php/showImage.php?pathToPicture=<?php echo base64_encode($pathToPicture);?>"  >

<?php
    $location = "server/www/images/";
    $image = !empty($_GET['pathToPicture']) ? base64_decode($_GET['pathToPicture']) : 'default.jpg';

    // In case the image requested doesn't exist.
    if (!file_exists($location.$image)) {
        $image = 'default.jpg';
    }

    header('Content-Type: '.exif_imagetype($location.$image));
    readfile($location.$image);
?>