简体   繁体   English

PHP-从文件夹随机获取文件并回显

[英]PHP - Randomly grab a file from folder and echo

I have a folder on my server called /assets/includes/updates/ with .php files inside featuring static html content. 我的服务器上有一个名为/assets/includes/updates/的文件夹, /assets/includes/updates/具有静态html内容的.php文件。

I'd like to randomly grab a file from this folder and echo it into a div. 我想从该文件夹中随机获取一个文件,并将其echo到div中。 Here is what I have: 这是我所拥有的:

<?php
 function random_update($dir = $_SERVER['DOCUMENT_ROOT'].'/assets/includes/updates/')
{
    $files = glob($dir . '/*.*');
    $file = array_rand($files);
    return $files[$file];
}
?>

<div class="my-div">
 <?php echo random_update(); ?>
</div><!--end my-div-->

I am getting 500 errors? 我收到500个错误? Also, my intention is to only echo 1 file at a time. 另外,我的目的是一次仅echo 1个文件。 Will the provided code accomplish that? 所提供的代码能否实现?

Php does not recognize the syntax you used. PHP无法识别您使用的语法。 You have to bypass it like this: 您必须像这样绕过它:

<?php
function random_update($dir = NULL)
{
    if ($dir === NULL) {
        $dir = $_SERVER['DOCUMENT_ROOT'] . '/assets/includes/updates/';
    }

    $files = glob($dir . '/*.*');
    $file = array_rand($files);
    return $files[$file];
}

Also, you might want to enable error dumping in your development environment so you know what went wrong next time. 另外,您可能希望在开发环境中启用错误转储,以便下次知道发生了什么问题。

Aside from another answers spotted issues, for your code to do what you want, you have to replace your following code: 除了发现问题的其他答案之外,为使代码执行所需的操作,还必须替换以下代码:

<?php echo random_update(); ?>

for this one: 为此:

<?php echo file_get_contents (random_update()); ?>

because your current code will print the filename inside the div, while I think you wanted the actual content of the file to be inserted in the div. 因为您当前的代码将在div中打印文件名,而我认为您希望将文件的实际内容插入div中。

您不能将任何表达式用作“默认”函数的参数值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM