简体   繁体   English

PHP问题包括

[英]PHP problem with include

<?
$dir=scandir('/home/crusty/www/crusty.bshellz.pl/htdocs/404/');

foreach($dir as $file){
        if($file!='.' && $file!='..' && $file!='index.php'){
                $choice=$dir[rand(0, count($dir) - 1)];
                include($choice);
        }
}
?>

I have a little problem with that code. 我对该代码有一点问题。 Of course it is working on some files but it is still trying to include index.php, .. and . 当然,它正在处理某些文件,但仍在尝试包含index.php,..和.。 Can sameone help me with solving it? 有人可以帮我解决吗?

You have to supply the full path, your trying to include the file from the location of the script. 您必须提供完整路径,并尝试从脚本位置包括文件。

Change this: 更改此:

include($choice);

to: 至:

include('/home/crusty/www/crusty.bshellz.pl/htdocs/404/'.$choice);

I wouldn't do it this way, but it should work. 我不会这样,但是应该可以。

Split Your code into two parts: first one to prepare array of good files; 将您的代码分为两部分:第一部分准备好文件的数组;第二部分准备好的文件。 second to include random file: 第二个包含随机文件:

$allfiles = scandir('/home/crusty/www/crusty.bshellz.pl/htdocs/404/');

$goodfiles = array();
foreach ($allfiles as $file) {
  if($file!='.' && $file!='..' && $file!='index.php'){
    $goodfiles[] = $file;
  }
}

$choicenfile = $goodfiles[rand(0, count($goodfiles) - 1)];
// As I understant You want to include only one file, not all;
include($choicenfile);

Now You can even extract this code to methods or functions 现在,您甚至可以将此代码提取到方法或函数中

I'm not shure if you want to include all files in randomized order or just one random file of the given folder, so I have included both in the solution - just delete what you don't need: 如果您要以随机顺序包括所有文件,还是只包含给定文件夹的一个随机文件,我不是很确定,因此我将这两个都包括在解决方案中-只需删除不需要的内容即可:

function filter_includes($incfile) {
    return !in_array($incfile, array(".", "..", "index.php"));
}

$dirPath = '/home/crusty/www/crusty.bshellz.pl/htdocs/404/';
$dir = array_filter(scandir($dirPath), "filter_includes");

// include all files in randomized order
shuffle($dir);
foreach($dir as $file) {
    include($dirPath . $file);
}

// include one random file
include($dirPath . $dir[rand(0, count($dir) - 1)]);

What is the point of the rand in $choice=$dir[rand(0, count($dir) - 1)]; $choice=$dir[rand(0, count($dir) - 1)];中的兰特的意义是什么? ?

Because right now it's just including a random file in your array. 因为现在它只是在您的数组中包括一个随机文件。

You should change your code to something like: 您应该将代码更改为:

$dir=scandir('/home/crusty/www/crusty.bshellz.pl/htdocs/404/');

foreach($dir as $file){
    if($file!='.' && $file!='..' && $file!='index.php'){
        include($file);
    }
}

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

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