Adam
Adam

Reputation: 29039

How to pass variable to PHP picture

Motivated by this post https://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.

Upvotes: 0

Views: 75

Answers (1)

Furqan Aziz
Furqan Aziz

Reputation: 1104

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

Upvotes: 1

Related Questions