0
我想从PHP文件夹随机设置网页的背景图像。php从文件夹随机设置背景图像
我有以下代码:
<!DOCTYPE HTML>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<title>404</title>
</head>
<body id="Background404">
<p>404-Page not found. <a href="http://url.com>Home.</a></p>
<?php
$dir = '/var/www/html/Images';
$fileNames = array();
if(is_dir($dir)){
$handle = opendir($dir);
while(false !== ($file = readdir($handle))){
if(is_file($dir.'/'.$file) && is_readable($dir.'/'.$file)){
$fileNames[] = $file;
}
}
closedir($handle);
$fileNames = array_reverse($fileNames);
print_r($fileNames);
}
$totalLength = sizeof($fileNames);
$randInt = rand(0, $totalLength);
$randFile = $fileNames[$randInt];
echo '<style> #Background404{background: url($randFile);}</style>';
?>
</body>
</html>
注:文件的打印只是为了确保我达到那个点代码和看到的文件叫什么。我在这里发现了一个类似的问题:Random Background Image PHP但是当我使用那个答案时,我只得到了纯白色的背景。
这里是印刷阵列的一个副本:
Array (
[0] => GraniteBridge.png
[1] => mobileBackground.png
[2] => OtherKingdom.png
[3] => NetherBase.png
[4] => BackgroundTablet.png
[5] => Snowy.png
[6] => Village.png
[7] => background2.png
[8] => CactusFarm.png
[9] => FrontView.png
[10] => CreditsPortal.png
[11] => FrontNight.png
[12] => background4.png
[13] => XPFarmRailway.png
[14] => GoldIronFarms.png
[15] => Pyramid.png
[16] => NetherFortress.png
[17] => TheEnd.png
[18] => Library.png
[19] => Background.png
[20] => twitter.png
[21] => mobileBackground1.png
[22] => mobileBackground2.png
[23] => BirdsEyeView.png
[24] => EndPortal.png
[25] => AboveVillage.png
[26] => TowerToTheHeavens.png
[27] => TowerArmorStands.png
[28] => FullSizeBackground.png
[29] => Mansion.png
[30] => Night.png
[31] => Dojo.png
)
我刚刚编辑的职位,因为我做了misstake,没有分配兰特om值给变量供以后使用。 – Marcin
我试过这个,现在我看到一个图像元素,但它没有找到图像,当我复制图像地址时,我得到“http://96.19.31.19/var/www/html/Images/$fileNames [%3C?= $ random?%3E]“,所以它是aparanetly没有切换PHP纯文本在HTML中使用 – kalenpw