Adam Adam - 1 year ago 42
PHP Question

How to pass variable to PHP picture

Motivated by this post 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

header('Content-Type: image/jpeg');

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

Answer Source

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:

    header('Content-Type: image/jpeg');

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);?>"  >

    $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));