如何使用PHP为计数器创建一个变量,用于显示图像


How to make a variable I made for a counter used to display an image using PHP?

我试图每次有人加载页面时显示不同的图像,我没有使用PHP的经验,但我真的需要这样做,这是代码,图像在我的服务器上的目录名为"imagenes"。

<?php
session_start();
$counter_name = "counter.txt";
// Check if a text file exists. If not create one and initialize it to zero.
if (!file_exists($counter_name)) {
$f = fopen($counter_name, "w");
fwrite($f,"0");
fclose($f);
}
// Read the current value of our counter file
$f = fopen($counter_name,"r");
$counterVal = fread($f, filesize($counter_name));
fclose($f);
// Has visitor been counted in this session?
// If not, increase counter value by one
 $_SESSION['hasVisited']="yes";
 $counterVal++;
 $f = fopen($counter_name, "w");
 fwrite($f, $counterVal);
 fclose($f); 
 include($_SERVER['DOCUMENT_ROOT']/imagenes);
 echo "You are visitor number $counterVal to this site";
$arr1=array('1.jpg','2.jpg','3.jpg','4.jpg','5.jpg','6.jpg','7.jpg','8.jpg','9.jpg','10.jpg','11.jpg','12.jpg','13.jpg','14.jpg','15.jpg','16.jpg','17.jpg','18.jpg','19.jpg','20.jpg','21.jpg','22.jpg','23.jpg','24.jpg','24.jpg','25.jpg','26.jpg','27.jpg','28.jpg','29.jpg','30.jpg');

根据您想要的方式,如果您真的想要随机显示图像,那么您可以执行;

$num = rand(1,30)//1-30之间的数字

显示图象

//

<img src="path-to-image/<?php echo $num."jpg"; ?>">

但是,如果它必须是唯一的图像,那么您需要在.txt文件中添加一个字段来记录已经显示的图像;

或者你可以在顶部做同样的事情,但是用$counterVal代替$num

<img src="cinreyesbarrandey.com/Imagenes/<?php echo $counterVal; ?>.jpg">