opendir array exclude file from results - php

The code below will select all of my php files from the named folder and then shuffle them and echo 10 results on my page, the folder contains an index.php file which i would like to be excluded from the results.
<?php
if ($handle = opendir('../folder/')) {
$fileTab = array();
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$fileTab[] = $file;
}
}
closedir($handle);
shuffle($fileTab);
foreach(array_slice($fileTab, 0, 10) as $file) {
$title = str_replace('-', ' ', pathinfo($file, PATHINFO_FILENAME));
$thelist .= '<p>'.$title.'</p>';
}
}
?>
<?=$thelist?>
I have found a code to exclude index.php but I'm not sure how to incorporate it into my code above.
<?php
$random = array_values( preg_grep( '/^((?!index.php).)*$/', glob("../folder/*.php") ) );
$answer = $random[mt_rand(0, count($random) -1)];
include ($answer);
?>

Why not just modify the line
if ($file != "." && $file != "..") {
to
if ($file != "." && $file != ".." && $file != 'index.php') {

An approach based on glob() instead of readdir():
<?php
$files = glob('../folder/*.php');
shuffle($files);
$selection = array_slice($files, 0, 11);
foreach ($selection as $file) {
$file = basename($file);
if ($file == 'index.php') continue;
$title = str_replace('-', ' ', pathinfo($file, PATHINFO_FILENAME));
// ...
}

You can use
$it = new FilesystemIterator(__DIR__, FilesystemIterator::SKIP_DOTS);
$it = new RegexIterator($it, '/.php$/i', RegexIterator::MATCH);
$exclude = array("index.php");
foreach ( $it as $splFileInfo ) {
if (in_array($splFileInfo->getBasename(), $exclude))
continue;
// Do other stuff
}
Or Simply
$files = array_filter(glob(__DIR__ . "/*.php"), function ($v) {
return false === strpos($v, 'index.php');
});

You can exclude it while you reading directory content (like you do with '.' and '..'):
if ($handle = opendir('../folder/')) {
$fileTab = array();
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != ".." && $file != "index.php") {
$fileTab[] = $file;
}
}
closedir($handle);
shuffle($fileTab);
foreach(array_slice($fileTab, 0, 10) as $file) {
$title = str_replace('-', ' ', pathinfo($file, PATHINFO_FILENAME));
$thelist .= '<p>'.$title.'</p>';
}
}
?>

while (false !== ($file = readdir($handle)))
{
if ($file != "." && $file != ".." && $file != 'index.php')
$fileTab[] = $file;
}

you could just change this line if ($file != "." && $file != "..") { to if ($file != "." && $file != ".." && $file != 'index.php') {

The code you found replaces your cumbersome directory reading loop.
And it should be just:
$files = preg_grep('~/index\.php$~', glob("../folder/*.php"), PREG_GREP_INVERT);
Get 10 elements as before:
$files = array_slice($files, 0, 10);
Then output those.

Related

php rename error: The system cannot find the file specified. (code: 2)

<?php
$dir = opendir('C:\Users\Prometheus\Desktop\milkmaid');
$i = 1;
// loop through all the files in the directory
while (false !== ($file = readdir($dir)))
{
if ($file != "." && $file != "..") {
$newName = $i.'.mp4';
$oldname = $file;
rename($oldname, $newName);
$i++;
}
}
?>
when i run above script, i am getting following error:
The system cannot find the file specified. (code: 2)
$dir is not a string. You can't concatenate $file with it. You will need to put the directory in a separate variable, and not forget to put a / in between directory and filename.
Adding $dir in the rename() works for me
<?php
$dir = opendir('C:\Users\Prometheus\Desktop\milkmaid');
$i = 1;
// loop through all the files in the directory
while (false !== ($file = readdir($dir)))
{
if ($file != "." && $file != "..") {
$newName = $i.'.mp4';
$oldname = $file;
rename($dir.$oldname, $dir.$newName);
$i++;
}
}
?>
Use it like this :-
$directory = '/public_html/testfolder/';
$i=1;
if ($handle = opendir($directory)) {
while (false !== ($fileName = readdir($handle))) {
$newName = $i.'.mp4';
rename($directory . $fileName, $directory . $newName);
$i++:
}
closedir($handle);
}
This worked for me
<?php
$counter = 1;
$dir = 'D:\files'; //path of folder
if ($handle = opendir($dir))
{
while (false !== ($fileName = readdir($handle)))
{
if($fileName != '.' && $fileName != '..')
{
$newName = $counter . " - " . $fileName;
rename($dir."/".$fileName, $dir."/".$newName);
$counter++;
}
}
closedir($handle);
}
?>

Strip the extension from a file

I have a code that is working as i want it to apart from 1 problem.
You can see the result here http://test.whatanswered.com/health/what-can-a-first-aider-do.php on the right below "Related Articles" showing dead links.
The following is the HTML that should be displayed.
<p>Name of the page</p>
I would like to strip the dashes and php as above "Name of the page" but it also strips the dashes and php from the url.
The code is:
<?php
if ($handle = opendir('health')) {
$fileTab = array();
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$fileTab[$file] = strtr(pathinfo($file, PATHINFO_FILENAME), '-', ' ');
}
}
closedir($handle);
shuffle($fileTab);
foreach(array_slice($fileTab, 0, 10) as $file => $health) {
$thelist .= '<p>'.$health.'</p>';
}
}
?>
<?=$thelist?>
I've refactored your code a little - the $fileTab array now just stores filenames and converting this to a title happens at the point of display:
if ($handle = opendir('health')) {
$fileTab = array();
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$fileTab[] = $file;
}
}
closedir($handle);
shuffle($fileTab);
foreach(array_slice($fileTab, 0, 10) as $file) {
$title = str_replace('-', ' ', pathinfo($file, PATHINFO_FILENAME));
$thelist .= '<p>'.$title.'</p>';
}
}

PHP Sort directories by contents

I am trying to sort a list of directories according to the contents of a text file within each directory.
So far, I am displaying the list of directories:
$user = $_GET['user'];
$task_list = $_GET['list'];
if ($handle = opendir("../users/$user/tasks/$task_list/"))
{
$files = array();
while (false !== ($file = readdir($handle)))
{
if ($file != "." && $file != ".." && $file != ".htaccess")
{
array_push($files, $file);
}
}
closedir($handle);
}
//Display tasks
sort($files);
foreach ($files as $file)
{
echo "$file";
}
Each directory has a text file within it called due.txt, I would like to sort the list of directories according to the contents of this file due.txt.
So far, I have tried:
$user = $_GET['user'];
$task_list = $_GET['list'];
if ($handle = opendir("../users/$user/tasks/$task_list/"))
{
$files = array();
$tasksSort = array();
while (false !== ($file = readdir($handle)))
{
if ($file != "." && $file != ".." && $file != ".htaccess")
{
$taskSort = file_get_contents("../users/$user/tasks/$task_list/$file/due.txt");
array_push($files, $file);
array_push($tasksSort, $taskSort);
}
closedir($handle);
}
//Sort tasks and display
sort($tasksSort);
foreach ($files as $file)
{
echo "$file";
}
}
But the $tasksSort array doesn't seem to have any content to sort...?
sort($tasksSort);
foreach ($tasksSort as $file)
{
echo "$file";
}

Sort opendir In Alphabetical Order

Is it possible to sort opendir into althabetical order?
$user = $fgmembersite->UserFullName();
$handle = opendir("users/$user/");
while (false!==($file = readdir($handle))) {
if ($file != "." && $file != ".."){
echo 'some code here';
}
}
Thanks in advance!
I would use scandir() instead:
$user = $fgmembersite->UserFullName();
$files = scandir('users/' . $user . '/');
foreach ($files as $file) {
if ($file != '.' && $file != '..') {
// Do stuff here
}
}
As Blauesocke pointed out, it is already sorted.

How to exclude certain file types with PHP readdir?

I am using a php scan directory script that will scan the contents of a directory and then populate the page with links to the directory contents.
<?php
$count = 0;
if ($handle = opendir('.')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {$count++;
print("".$file."<br />\n");
}
}
echo '<br /><br />Return';
closedir($handle);
}
?
I am wondering how I can exclude certain files or file types like test.xml, durka.xslt or .html from showing up on the populated page. I have some code but not sure how to integrate it. Any help would be very appreciated...
?php
if ($handle = opendir(‘.’)) {
while (false !== ($file = readdir($handle)))
{
if ($file != “.” && $file != “..”
&& $file != “NOT-TO-BE-IN-1.php”
&& $file != “NOT-TO-BE-IN-2.html”
&& $file != “NOT-TO-BE-IN-3.jpg”
&& $file != “”
&& $file != “”
&& $file != “”
&& $file != “”
&& $file != “”
)
<?php
// These files will be ignored
$excludedFiles = array (
'excludeMe.file',
'excludeMeAs.well'
);
// These file extensions will be ignored
$excludedExtensions = array (
'html',
'htm',
'php'
);
// Make sure we ignore . and ..
$excludedFiles = array_merge($excludedFiles,array('.','..'));
// Convert to lower case so we are not case-sensitive
for ($i = 0; isset($excludedFiles[$i]); $i++) $excludedFiles[$i] = strtolower(ltrim($excludedFiles[$i],'.'));
for ($i = 0; isset($excludedExtensions[$i]); $i++) $excludedExtensions[$i] = strtolower($excludedExtensions[$i]);
// Loop through directory
$count = 0;
if ($handle = opendir('.')) {
while (false !== ($file = readdir($handle))) {
$extn = explode('.',$file);
$extn = array_pop($extn);
// Only echo links for files that don't match our rules
if (!in_array(strtolower($file),$excludedFiles) && !in_array(strtolower($extn),$excludedExtensions)) {
$count++;
print("".$file."<br />\n");
}
}
echo '<br /><br />Return';
closedir($handle);
}
?>
<?php
$count = 0;
if ($handle = opendir('.')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != ".."
&& $file != "NOT-TO-BE-IN-1.php"
&& $file != "NOT-TO-BE-IN-2.html"
&& $file != "NOT-TO-BE-IN-3.jpg"
&& substr($file,-strlen(".html")) != ".html" //if you don't want to include .html files, for instance
&& substr($file,-strlen(".js")) != ".js" //if you don't want to include .js files, for instance
&& $file != ""
) {$count++;
print("".$file."<br />\n");
}
}
echo '<br /><br />Return';
closedir($handle);
}
?>
Other way:
$excludeExtensions = array(
'php',
'html',
'jpg'
);
if ($file != "." && $file != ".." && !in_array(pathinfo($file, PATHINFO_EXTENSION), $excludeExtensions))
EDIT: again I was too late:)
you can also just use glob:
foreach (glob("*.{php|html|jpg}",GLOB_BRACE) as $file) {
echo file_get_contents($file);
}
see http://php.net/manual/en/function.glob.php for more info
<?php
if ($handle = opendir('.')) {
while (false !== ($file = readdir($handle)))
{
if ($file != "." && $file != ".."
&& $file != "NOT-TO-BE-IN-1.php"
&& $file != "NOT-TO-BE-IN-2.html"
&& $file != "NOT-TO-BE-IN-3.jpg"
&& $file != ""
&& $file != ""
&& $file != ""
&& $file != ""
&& $file != ""
)
echo file_get_contents($file);
will show contents of all pages which haven't name
NOT-TO-BE-IN-1.php
NOT-TO-BE-IN-2.html
NOT-TO-BE-IN-3.jpg
you can restrict certain filepath with
if (!preg_match('/(php|html|jpg)/', $file))
Try something like:
$excluded_files = array('test.xslt');
$excluded_ext = array('html');
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != ".." &&
!in_array($file, $excluded_files) &&
!in_array(pathinfo($file, PATHINFO_EXTENSION), $excluded_ext))
{
// do stuff
}
}

Categories