I am using the following code to retrieve the URL of a random image in a remote folder that I own.
As a newbie and although this is working I would like to know if this is done properly, if it could be improved and if there is any security issue with this approach.
I am using json_encode
and json_decode
because I need to have an array as response. Also I am passing $params
to remote through cURL because I need the returned image already with it's URL.
Thank you.
if (function_exists('curl_init')){
$url = 'http://example.com/images';
$params = 'path=' . $url;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url . '/my_remote_script.php');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$images = json_decode(curl_exec($ch));
curl_close($ch);
}
my_remote_script.php
if (!$_POST['path']){
die;
}
function getImages($path){
if ($img_dir = opendir(dirname(__FILE__))){
$images = array();
while (($img_file = readdir($img_dir)) !== false){
if (preg_match('/(\.gif|\.jpg|\.jpeg|\.png|\.GIF|\.JPG|\.JPEG|\.PNG)$/', $img_file)){
$images[] = $path . '/' . $img_file;
}
}
closedir($img_dir);
return $images;
}
}
function randomImage($list){
$num = array_rand($list);
$image = $list[$num];
return $image;
}
$images = getImages($_POST['path']);
$image = randomImage($images);
print_r(json_encode($image));