原创内容,转载请注明出处:https://www.myzhenai.com.cn/post/3048.html
关键词:PHP所有图片 PHP枚举目录与子目录 PHP读取目录与子目录
前几天,本来想给我的另外一个博客弄一个图片墙 https://jiayu.mybabya.com/ 把附件目录下所有的图片枚举出来然后再选择一张或几张来显示,做到随机显示几张或一张图片的功能,但是后来一想发现这么频繁的去枚举目录可能对系统资源并不太好,所以就没有添加了。但也把代码做为一个学习PHP的方法,以便自己以后查找和使用。
代码的思路分两部份,一部份是本地枚举所有图片文件后放到数组里随机显示,另外一种是枚举后写到文本文件里远程调用来放到数组里随机显示。
<!--?php
function upgread_images_array($path)
/**
*$path参数是路径
*函数分两个部份,第一部份是从一个文本文件里读取图片路径到数组中,第二部份是从目录中枚举所有图片到数组中
*/
{
if (strripos($path, ".txt") == false || strripos($path, ".log") == false) {
/**
* 这里是枚举目录中所有图片
*/
$ad = array();
$hd = opendir($path);//读资源
if ($hd) {
while (($file = readdir($hd)) !== false) {
if ($file != '.' && $file != '..') {
if (is_dir($file)) {//判断是否为目录,递归读取文件
$dp = upgread_images_array($file);
array_push($ad, $dp);
} else {
array_push($ad, $file);
}
}
}
closedir($hd);
}
} else {
/**
* 这里是读取一个文本文件中的图片路径
*/
if (file_exists($path)) {
$fp = fopen($path, 'r');
while (!feof($fp)) {
$dp = fgets($fp);
$ad = array();
array_push($ad, $dp);
}
}
fclose($fp);
}
/**
* 这里输出指定的数组
*/
return $ad;
}
function images_array_echo($arr)
/**
* 输出随机的一张图片
*/
{
if (is_array($arr) == true) {
$x = array_rand($arr, 1);
$im = $arr[$x];
}
return $im;
}
?-->
<!--?php
function upgread_images_array($path)
/**
*$path参数是路径
*函数分两个部份,第一部份是从一个文本文件里读取图片路径到数组中,第二部份是从目录中枚举所有图片到数组中
*/
{
if (strripos($path, ".txt") == false || strripos($path, ".log") == false) {
/**
* 这里是枚举目录中所有图片
*/
$ad = array();
$hd = opendir($path);//读资源
if ($hd) {
while (($file = readdir($hd)) !== false) {
if ($file != '.' && $file != '..') {
if (is_dir($file)) {//判断是否为目录,递归读取文件
$dp = upgread_images_array($file);
array_push($ad, $dp);
} else {
array_push($ad, $file);
}
}
}
closedir($hd);
}
} else {
/**
* 这里是读取一个文本文件中的图片路径
*/
if (file_exists($path)) {
$fp = fopen($path, 'r');
while (!feof($fp)) {
$dp = fgets($fp);
$ad = array();
array_push($ad, $dp);
}
}
fclose($fp);
}
/**
* 这里输出指定的数组
*/
return $ad;
}
function images_array_echo($arr)
/**
* 输出随机的一张图片
*/
{
if (is_array($arr) == true) {
$x = array_rand($arr, 1);
$im = $arr[$x];
}
return $im;
}
?-->
sicnature ---------------------------------------------------------------------
I P 地 址: 18.189.7.216
区 域 位 置: 美国
系 统 信 息:

Original content, please indicate the source:
同福客栈论坛 | 蟒蛇科普 | 海南乡情论坛 | JiaYu Blog
sicnature ---------------------------------------------------------------------
Welcome to reprint. Please indicate the source https://myzhenai.com/post/3048.html
没有评论