PHP include random file from folder - php

I would like to use a <?php include ... command to choose one random php file from one folder.
So this is the basic idea:
<?php include 'random file: 1.php, 2.php, 3.php or 4.php';?>
I have already read articles like this or this, but they don't answer my question clearly. What is the easiest way to do that?

// Directory to use
$directory = '.';
// Filter out directories, we only want files.
$files = array_filter(scandir($directory), fn($f) => is_file($f));
// Pick a random file
$randFile = $directory . '/' . $files[array_rand($files)];
// Include it
include $randFile;

to include random files from another directory
$path = __DIR__."/folder";
foreach(new DirectoryIterator($path) as $file){
if($file->isFile()){
$arr[] = $file->getFilename();
}
}
$randFile = $path."/".$arr[array_rand($arr)];
include $randFile;

Related

Deleting files matching a specific file extension recursivly?

I would like to delete all files matching a particular extension in a specified directory and all subtree. I suppose I should be using using unlink but some help would be highly appreciated... Thank you!
you need a combination of this
Recursive File Search (PHP)
And the unlink / delete
You should be able to edit the example instead of echoing the file, to delete it
To delete specific extension files from sub directories, you can use the following function. Example:
<?php
function delete_recursively_($path,$match){
static $deleted = 0,
$dsize = 0;
$dirs = glob($path."*");
$files = glob($path.$match);
foreach($files as $file){
if(is_file($file)){
$deleted_size += filesize($file);
unlink($file);
$deleted++;
}
}
foreach($dirs as $dir){
if(is_dir($dir)){
$dir = basename($dir) . "/";
delete_recursively_($path.$dir,$match);
}
}
return "$deleted files deleted with a total size of $deleted_size bytes";
}
?>
e.g. To remove all text files you can use it as follows:
<?php echo delete_recursively_('/home/username/directory/', '.txt'); ?>

PHP Get file name starting with prefix

This is a custom function. At the moment, this function get all the file in the default directory, strip ".php" and list them.
The problem is that I want to only get files from the directory which has starting prefix "tpl-" Example : tpl-login-page.php
/* Get template name of the file */
function get_template_name (){
$files = preg_grep('~\.(php)$~', scandir(admin . "templates/default/"));
foreach($files as $file){
$file = str_replace('.php','',$file);
echo $file . "<br/>";
}
}
You need to change the regular expression in preg_grep:
$files = preg_grep('~^tpl-.*\.php$~', scandir(admin . "templates/default/"));
Explanation:
^tpl- - starting with "tpl-"
.* - any characters
\.php$ - ending with ".php"
I like another, simple way:
1. get all files in folder
$path = './images';
$files = glob($path.'/*');
2. get all files having extension .jpg
$path = './images';
$files = glob($path.'/*.jpg');
3. get all files having prefix myprefix_
$path = './images';
$files = glob($path.'/myprefix_*');
$target_file_png = glob($target_dir.'/group_'.$groupId.'*.png');
$target_file_png will return an array containing all the files in folder specified in the path $target_dir starting with '/group_'.$groupId.' and specify the file format as *.png

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 .
Can sameone help me with solving it?
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
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.
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)];?
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);
}
}

Foreach glob to include files in a subdirectory

I'm trying to learn how to include all the files in a directory using glob(), however I can't seem to get it to work. This is the code I have now:
foreach (glob("addons/*.php") as $filename) {
include $filename;
}
However a single file include seems to work just fine:
include "addons/hello.php";
This is what my file structure looks like:
Theme
-addons
--hello.php
-index.php
-options.php
So I'm not sure where the problem is. The code is inside a (theme) subdirectory itself, if that makes a difference at all. Thanks.
Use this for testing:
foreach (glob("addons/*.php", GLOB_NOCHECK) as $filename) {
PRINT $filename . "\n";
}
Should the directory not exist relatively to the current, then it will show addons/*.php as output.
This recursive function should do the trick:
function recursiveGlob($dir, $ext) {
$globFiles = glob("$dir/*.$ext");
$globDirs = glob("$dir/*", GLOB_ONLYDIR);
foreach ($globDirs as $dir) {
recursiveGlob($dir, $ext);
}
foreach ($globFiles as $file) {
include $file;
}
}
Usage: recursiveGlob('C:\Some\Dir', 'php');
If you want it to do other things to the individual file, just replace the include $file part.
Include is going to be using the search path which (while it typically includes the current working directory) isn't limited to that... using glob() with a relative directory path will always be relative to the current working directory. Before you enter your loop... ensure that your current working directory is where you think it is using echo getcwd()... you may find you're not in the Theme subdirectory after all; but that the Theme subdirectory is in the search path.
Make sure that path to file is absolute (from root of your server).
In my case this example works without problems:
$dir = getcwd();//can be replaced with your local path
foreach (glob("{$dir}/addons/*.php") as $filename) {
if(file_exists($filename))
{
//file exists, we can include it
include $filename;
}
else
{
echo 'File ' . $filename . ' not found<br />';
}
};

PHP incomplete code - scan dir, include only if name starts or end with x

I posted a question before but I am yet limited to mix the code without getting errors.. I'm rather new to php :(
( the dirs are named in series like this "id_1_1" , "id_1_2", "id_1_3" and "id_2_1" , "id_2_2", "id_2_3" etc.)
I have this code, that will scan a directory for all the files and then include a same known named file for each of the existing folders.. the problem is I want to modify a bit the code to only include certain directories which their names:
ends with "_1"
starts with "id_1_"
I want to create a page that will load only the dirs that ends with "_1" and another file that will load only dirs that starts with "id_1_"..
<?php
include_once "$root/content/common/header.php";
include_once "$root/content/common/header_bc.php";
include_once "$root/content/" . $page_file . "/content.php";
$page_path = ("$root/content/" . $page_file);
$includes = array();
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($page_path),
RecursiveIteratorIterator::SELF_FIRST);
foreach($iterator as $file) {
if($file->isDir()) {
$includes[] = strtoupper($file . '/template.php');
}
}
$includes = array_reverse($includes);
foreach($includes as $file){
include $file;
}
include_once "$root/content/common/footer.php";
?>
Many Thanks!
foreach($iterator as $file) {
if($file->isDir()) {
// getFilename() actually gives the directory name, when it's um, a directory.
$dirName = $file->->getFilename();
if (substr($dirName, 0, 5) === 'id_1_') {
$includes[] = strtoupper($file . '/template.php');
}
}
}
There's other ways to do this, but I tried to only add simple functions and logic, in hopes you will understand it.
Ends with would look like
if (substr($dirName, -2) === '_1')

Categories