.php Random image served as .jpg on external site

2019-08-13 20:01发布

问题:

A forum that I post on only allows .jpg, .png and .gif images to be loaded from an external URL. I want to get around this and have a dynamic avatar chosen randomly from a directory on my server but I'm having trouble getting it to work (possibly due to extra checks being carried out on the external site, or an error in my code).

So far I've created a folder named "avatar.jpg" on my server and the code in my index.php file within that folder is as follows:-

<?php
$arr=array();
for($i=1;$i<6;$i++){
$arr[$i]=$i.".jpg";
}
$random=rand(1,6);
echo $arr[$random];
?>

I have 6 images in the avatar.jpg folder, named 1.jpg, 2.jpg etc.

When I run mydomain.com/avatar.jpg it correctly displays a random image source, eg. 5.jpg, but when I enter this URL as my avatar URL on the forum it fails to load and Firebug reports "Failed to load given URL".

Am I missing something from my code to make this work as hoped?

回答1:

It seems you are responding with the text string "$name.jpg" for a .jpg file! You have to set the correct content-type headers and serve the bits and bytes of the actual image file.

Something like:

header("Content-type: image/jpeg");
echo file_get_contents($randomFilepath);


标签: php image random