Question

So I created an image.php file with this code and put it in my public_html folder:

<?php
header('Content-Type: image/jpeg');
readfile('home/folder/my image.jpg');
?>

and then I put this code in an html page in my public_html folder:

<img src="/image.php">

which perfectly displayed the "my image.jpg" file in my browser when I loaded the page. So this tells me that I do have access to the folder above my public_html folder (this is a dedicated server) and it tells me that I have no issues rendering a jpg file with spaces in the file name.

So now I'm trying to pull random images from the same folder, but can't seem to figure it out. Here is what I am doing that is NOT working.

I've created an image.php file with this code and put in my public_html folder:

<?php

//Define Function to Select Random Image
function random_pic($dir = '/home/folder')
{
$files = glob($dir . '/*.jpg');
$file = array_rand($files);
return $files[$file];
}

//Select Random Image Path
$randPic = random_pic('/home/folder');

//Output Random Image When image.php is called from html image requests
header('Content-Type: image/jpeg');
readfile($randPic);
?>

and then I put this code in an html page in my public_html folder:

<img src="/image.php">

Now when I load this html page with this img tag, I get nothing. No error, no image, nothing but white space. I appreciate any insight anyone can provide.

Was it helpful?

Solution

Why not use an absolute path instead of:

header('Content-Type: image/jpeg');
readfile('home/folder/my image.jpg');

like this:

// notice the absolute path prefix
if(!is_file($image_path = '/home/folder/my image.jpg')){
    header('Content-Type: text/plain', 404);
    echo 'Image file not found!';
}

// We got a file, keep going...
header('Content-Type: image/jpeg');
header('Content-Length: '.filesize($image_path));
readfile($image_path);

die; // done here

Or use the path relative to current directory of .php script with __DIR__.'/path/to/image.jpg'.

OTHER TIPS

You have to put safe_mode = off or configure open_basedir to get access to the images directory.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top