php 如何使用PHP从目录中获取随机图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1761252/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get random image from directory using PHP
提问by alex
I have one directory called images/tips.
我有一个名为 images/tips 的目录。
Now in that directory I have many images which can change.
现在在那个目录中我有很多可以改变的图像。
I want the PHP script to read the directory, to find the images, and out of those images found to pick a random image.
我希望 PHP 脚本读取目录,找到图像,并从找到的图像中选择一个随机图像。
Any idea on how to do this?
关于如何做到这一点的任何想法?
回答by alex
$imagesDir = 'images/tips/';
$images = glob($imagesDir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);
$randomImage = $images[array_rand($images)]; // See comments
You can send a 2nd argument to array_rand()to get more than 1.
您可以发送第二个参数array_rand()来获得超过 1个参数。
回答by Ignas R
$images = glob('images/tips/*');
return $images[rand(0, count($images) - 1)];
However, this doesn't ensure that the same image isn't picked twice consecutively.
但是,这并不能确保不会连续两次选取相同的图像。
回答by Sajjad Hossain
Agreed with alexa. Use simple function.
同意alexa。使用简单的功能。
function RandImg($dir)
{
$images = glob($dir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);
$randomImage = $images[array_rand($images)];
return $randomImage;
}
$the_image = RandImg('images/tips/');
echo $the_image;
回答by Makarand Mane
<?php
foreach (glob("gallery/*") as $filename) {
echo '<li><a href="'.$filename.'" title=""><img src="'.$filename.'" alt="" /></a> </li>';
}
?>
Look at this code, use it definitely if useful for you. It loads all files from folder and prints them in above format. I made this code to use with lightbox.
看看这段代码,如果对你有用,一定要使用它。它从文件夹加载所有文件并以上述格式打印它们。我制作了此代码以与灯箱一起使用。
回答by aditya4447
function get_rand_img($dir)
{
$arr = array();
$list = scandir($dir);
foreach($list as $file)
{
if(!isset($img))
{
$img = '';
}
if(is_file($dir . '/' . $file))
{
$ext = end(explode('.', $file));
if($ext == 'gif' || $ext == 'jpeg' || $ext == 'jpg' || $ext == 'png' || $ext == 'GIF' || $ext == 'JPEG' || $ext == 'JPG' || $ext == 'PNG')
{
array_push($arr, $file);
$img = $file;
}
}
}
if($img != '')
{
$img = array_rand($arr);
$img = $arr[$img];
}
$img = str_replace("'", "\'", $img);
$img = str_replace(" ", "%20", $img);
return $img;
}
echo get_rand_img('images');
replace 'images' with your folder.
用您的文件夹替换“图像”。
回答by Paolo Euvrard
Simpler:
更简单:
$directory = "medias/photos/";
$img = glob($directory . "*.jpg");
shuffle($img);
回答by stalin wesley
$folder = "images";
$results_img_arr = array();
if (is_dir($folder))
{
if ($handle = opendir($folder))
{
while(($file = readdir($handle)) !== FALSE)
{
if(!in_array($file,array(".","..")))
$results_img_arr[] = $folder."/".$file;
}
closedir($handle);
}
}
$ran_img_key = array_rand($results_img_arr);
$img_path = $results_img_arr[$ran_img_key];
回答by Alessandro
I wrote a simple php script for my personal use. Now I want share it with stackoverflow's community. Usage is simple: create a folder "php"into root of your Web Server and put inside this file php rotate.php... now create two folders into your root called "pic"and "xmas"... you can adjust the folder names by editing the var $my_folder_holidayand $my_folder_default...
我写了一个简单的 php 脚本供我个人使用。现在我想与 stackoverflow 的社区分享它。用法很简单:"php"在您的 Web 服务器的根目录中创建一个文件夹并将 php 放入该文件中rotate.php...现在在您的根目录中创建两个文件夹,名为"pic"和"xmas"...您可以通过编辑 var$my_folder_holiday和$my_folder_default...来调整文件夹名称。
<?php
##########################################################
# Simple Script Random Images Rotator ? 1.4 ? 04.01.2020 #
# Alessandro Marinuzzi [alecos] ? https://www.alecos.it/ #
##########################################################
function rotate($folder) {
if ((file_exists($_SERVER['DOCUMENT_ROOT'] . "/$folder")) && (is_dir($_SERVER['DOCUMENT_ROOT'] . "/$folder"))) {
$list = scandir($_SERVER['DOCUMENT_ROOT'] . "/$folder");
$fileList = array();
$img = '';
foreach ($list as $file) {
if ((file_exists($_SERVER['DOCUMENT_ROOT'] . "/$folder/$file")) && (is_file($_SERVER['DOCUMENT_ROOT'] . "/$folder/$file"))) {
$ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
if ($ext == 'gif' || $ext == 'jpeg' || $ext == 'jpg' || $ext == 'png') {
$fileList[] = $file;
}
}
}
if (count($fileList) > 0) {
$imageNumber = time() % count($fileList);
$img = $folder . '/' . $fileList[$imageNumber];
}
return $img;
} else {
mkdir($_SERVER['DOCUMENT_ROOT'] . "/$folder", 0755, true);
}
}
$my_gallery_month = date('m');
$my_folder_default = 'pic';
$my_folder_holiday = 'xmas';
if ($my_gallery_month == 12) {
$my_gallery = rotate($my_folder_holiday);
} else {
$my_gallery = rotate($my_folder_default);
}
?>
This script was tested under PHP 7.0/7.1/7.2/7.3 and PHP 7.4 and works fine. Usage (for example in root you may have a folder "pic"and "xmas"containing your images):
该脚本在 PHP 7.0/7.1/7.2/7.3 和 PHP 7.4 下测试过,运行良好。用法(例如在 root 中,您可能有一个文件夹"pic"并"xmas"包含您的图像):
<a href="/<?php include("php/rotate.php"); echo $my_gallery; ?>"><img src="/<?php echo $my_gallery; ?>" alt="Random Gallery" width="90" height="67"></a>
Other usage using FancyBoxlibrary:
使用FancyBox库的其他用法:
<a href="/<?php include("php/rotate.php"); echo $my_gallery; ?>" data-fancybox><img src="/<?php echo $my_gallery; ?>" alt="Random Gallery" width="90" height="67"></a>
Hope this Helps.
希望这可以帮助。
回答by keithjgrant
回答by Czlowiekwidmo
Load folder with images:
加载带有图像的文件夹:
$folder = opendir(images/tips/);
Build table out of files/images from directory:
从目录中的文件/图像构建表:
$i = 0;
while(false !=($file = readdir($folder))){
if($file != "." && $file != ".."){
$images[$i]= $file;
$i++;
}
}
Pick random:
随机选择:
$random_img=rand(0,count($images)-1);
Show on page:
在页面上显示:
echo '<img src="images/tips'.$images[$random_img].'" alt="" />';
Hope it helps. Of course enclose it in <?php ?>.
希望能帮助到你。当然把它附在<?php ?>.

