<?
$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);
}
}
Related
Is there a way to get all the files with a specific name from a folder with php?
For example I have in folder next files:
6546-da6sd.png
465-dasd.jpg
654-548484.jpg
654-sasaf.png
654-sakj879.jpg
776-54fsdfs.png
....
I want to get all files that start with "654-" (but not the first (6546-da6sd.png))
Thank You!
you can use glob() and strpos() like:
<?php
$dir = 'files/';
$key = '654-';//search key
foreach (glob("$dir*") as $file) {
$file = str_replace($dir,'',$file);
if (strpos($file, $key) == 0) {
echo($file."<br>");
}
}
?>
I have multiple files in a directory for pages.
All the pages are the same except the content I enter based on
rental inspections.
bedroom1.php
bedroom2.php
bedroom3.php
But to get them to use the right header I need them to see the
correct header based on their own filename.
bedroom1.php to include header1.php
bedroom2.php to include header2.php
bedroom3.php to include header3.php
.......
bedroom10.php to include header10.php
I can get the filename easy enough.
I'm trying to use preg_match(Maybe should use something else?)
but with not getting any errors in the logs so I'm not sure
what I'm missing and not knowing enough about file comparing
I'm lost.
EDIT: ADDED : Forgot to add, this code is in bedroom1.php etc...
Thanks in advance
<?php
$file = $_SERVER["SCRIPT_NAME"];
$break = Explode('/', $file);
$pfile = $break[count($break) - 1];
if (preg_match('/bedroom . $i .php/', $pfile, $i)) {
$number = $i[1];
foreach(array('header') as $base) {
include_once "$base$number.php";
}
}
?>
It should be:
if (preg_match('/bedroom(\d+)\.php/', $pfile, $i)) {
You need to use \d+ to match numeric digits, and put it inside parentheses to make it a capture group, so you can access it with $i[1].
Try this one:
$file = basename($_SERVER['SCRIPT_NAME'], '.php');
$base = 'header';
$parts = array();
if (preg_match('/bedroom(\d+)/', $file, $parts)) {
include_once $base . $parts[1] . '.php';
} else {
// the file doesn't follow the bedroom{number}.php structure
}
Good luck!
use this
basename($_SERVER['SCRIPT_NAME'])
you get the script name
$file = $_SERVER["SCRIPT_NAME"];
$baseName=basename($file);
$base="header";
preg_match_all('/\d+/', $baseName, $baseNameInt);
$basNameFile=$baseNameInt[0][0];
if(file_exists("$base$basNameFile.php")){
include_once("$base$basNameFile.php");
} else {
// ...
}
Not sure what your array contains that necessitates the foreach (if that is just example code) but why not just:
$array = array('header');
$suffix = str_replace($array, '', basename(__FILE__));
foreach($array as $base) {
if(file_exist("$base$suffix")) {
include_once("$base$suffix");
}
}
If the only thing that will be in the array is header then forgo the loop altogether.
I want to grab the first file in a directory, without touching/grabbing all the other files. The filename is unknown.
One very short way could be this, using glob:
$file = array_slice(glob('/directory/*.jpg'), 0, 1);
But if there are a lot of files in that directory, there will be some overhead.
Other ways are answers to this question - but all involve a loop and are also longer then the glob example:
PHP: How can I grab a single file from a directory without scanning entire directory?
Is there a very short and efficient way to solve this?
Probably not totally efficient, but if you only want the FIRST jpg that appears, then
$dh = opendir('directory/');
while($filename = readdir($dh)) {
if (substr($filename, -4) == '.jpg')) {
break;
}
}
Well this is not totally a one-liner, but it is a way to go I believe:
$result = null;
foreach(new FilesystemIterator('directory/') as $file)
{
if($file->isFile() && $file->getExtension() == 'jpg') {
$result = $file->getPathname();
break;
}
}
but why don't you wrap it in a function and use it like get_first_file('directory/') ? It will be a nice and short!
This function will get the first filename of any type.
function get_first_filename ($dir) {
$d = dir($dir);
while ($f = $d->read()){
if (is_file($dir . '/' . $f)) {
$d->close();
return $f;
}
}
}
Situation
I have a relatively short php code I found and tweaked that includes a random html file from my 'randomizer' folder into my page.
Here is the code
<?php
error_reporting(0);
function random_file($string){
return ((file_exists($string))&&(preg_match('#(\.html)$#i',$string))) ? true : false ;
}
define('OUTPUT_TYPE','text');
define('RANDOM_FILES_FOLDER','randomizer/');
$my_array = Array();
$my_dir = RANDOM_FILES_FOLDER ;
if ($dir = #opendir("$my_dir")) {
while (($file = readdir($dir)) !== false) {
if ($file != "." && $file != ".." && !is_dir($my_dir.$file))
{
switch(OUTPUT_TYPE):
case'text':
if(random_file($my_dir.$file)){
$my_array[] = $file;
}
break;
default:
break;
endswitch;
}
}
closedir($dir);
}
if(count($my_array)>0){
$random_number = rand(0, count($my_array)-1);
$random_file = $my_array[$random_number];
switch(OUTPUT_TYPE):
case'text':
include($my_dir.$random_file);
break;
default:
break;
endswitch;
}
?>
Question
It does what it is supposed to do (perhaps someone can trim/optimize that code for me) but I have only a few files to randomize and I don't want the same file to appear twice when I refresh or open the page a day after.
I think cookies may be the answer, but not sure how to do anything with them.
Can anyone write a piece code to add to mine to do that or provide a code that has all those attributes? keep in mind it must include files at random from a folder, I don't want the code from those files on my actual page code for CMS purposes
Keep in mind I am a PHP and Javascript beginner with VERY basic knowledge, so please dumb it down for me.
Thanks!
Very rough:
session_start();
$dir = 'randomizer/';
if (empty($_SESSION['files'])) {
$_SESSION['files'] = array_filter(scandir($dir), function ($file) use ($dir) {
return is_file($dir . $file) && preg_match('#(\.html)$#i', $file);
});
shuffle($_SESSION['files']);
}
include $dir . array_shift($_SESSION['files']);
Keep a list of all candidate files in the session, use them one by one. That way all files will be displayed once in random order before the cycle starts again. Only not recommended if the list is very long.
It's worth noting that the array_filter callback syntax requires PHP 5.3.
This is not the perfect way to do this but it will work(intentionally simple):
Include this after the line $random_file = $my_array[$random_number];
$oldFile = ''
if(!empty($_COOKIE['oldfilename']) {
$oldFile = $_COOKIE['oldfilename'];
}
while ($oldFile == $random_file) {
$random_number = rand(0, count($my_array)-1);
$random_file = $my_array[$random_number];
}
setcookie('oldfilename', $random_file);
I need to get all the folders and files from a folder recursively in alphabetical order (folders first, files after)
Is there an implemented PHP function which caters for this?
I have this function:
function dir_tree($dir) {
$path = '';
$stack[] = $dir;
while ($stack) {
$thisdir = array_pop($stack);
if ($dircont = scandir($thisdir)) {
$i=0;
while (isset($dircont[$i])) {
if ($dircont[$i] !== '.' && $dircont[$i] !== '..' && $dircont[$i] !== '.svn') {
$current_file = "{$thisdir}/{$dircont[$i]}";
if (is_file($current_file)) {
$path[] = "{$thisdir}/{$dircont[$i]}";
} elseif (is_dir($current_file)) {
$path[] = "{$thisdir}/{$dircont[$i]}";
$stack[] = $current_file;
}
}
$i++;
}
}
}
return $path;
}
I have sorted the array and printed it like so:
$filesArray = dir_tree("myDir");
natsort($filesArray);
foreach ($filesArray as $file) {
echo "$file<br/>";
}
What I need is to know when a new sub directory is found, so I can add some spaces to print it in a directory like structure instead of just a list.
Any help?
Many thanks
Look at the RecursiveDirectoryIterator.
$directory_iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir));
foreach($directory_iterator as $filename => $path_object)
{
echo $filename;
}
I'm not sure though if it returns the files in alphabetical order.
Edit:
As you say it does not, I think the only way is to sort them yourself.
I would loop through each directory and put directories and files in a seperate arrays, and then sort them, and then recurse in the directories.
I found a link which helped me a lot in what I was trying to achieve:
http://snippets.dzone.com/posts/show/1917
This might help someone else, it creates a list with folders first, files after. When you click on a subfolder, it submits and another page with the folders and files in the partent folder is generated.