Strip the extension from a file - php

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>';
}
}

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);
}
?>

Sort by date in descending order echoed file directory in PHP

Ok I have a directory with files named by date with the extension ".html".
What I am trying to do is list the contents of the directory, minus the file extension, ordered by date with newest on top.
I have been fiddling with the below code for hours.
<?php
if ($handle = opendir('update_table_cache')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != ".." ) {
$dirFiles[] = $entry ;
rsort($dirFiles);
foreach($dirFiles as $entry) {
$withoutExt = preg_replace('/\\.[^.\\s]{3,4}$/', '', $entry);
echo ''.$withoutExt.'<br>';
}
}
}
closedir($handle);
}
?>
This outputs something like this:
2016-01-18
2016-01-19
2016-01-18
There should only be one 2016-01-18 and it should be at the bottom. Why is there an extra 2016-01-18 at the top?
Edit: ok I changed it to the following:
<?php
if ($handle = opendir('update_table_cache')) {
$dirFiles[] = $entry ;
rsort($dirFiles);
foreach($dirFiles as $entry) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != ".." ) {
$withoutExt = preg_replace('/\\.[^.\\s]{3,4}$/', '', $entry);
echo ''.$withoutExt.'<br>';
}
}
}
closedir($handle);
}
?>
But this outputs:
2016-01-18
2016-01-17
2016-01-19
(I added another file "2016-01-17.html")
You're doing the output in the middle of the loop...
First you sort one element and print it, then sort two elements and print it.
Do the output after the loop.
This is what worked:
<?php
$dir = opendir('update_table_cache'); // Open the sucker
$files = array();
while ($files[] = readdir($dir));
sort($files);
closedir($dir);
foreach ($files as $file) {
//MANIPULATE FILENAME HERE, YOU HAVE $file...
if ($file != "." && $file != ".." ){
$withoutExt = preg_replace('/\\.[^.\\s]{3,4}$/', '', $file);
echo ''.$withoutExt.'<br>';
}
}
?>
Thanks to user CBroe for pointing me in the right direction!

PHP: Where to put rsort?

$count = 0;
if ($handle = opendir('./arkiv/')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$count++;
print("".basename($file, ".php")."<br />\n");
}
}
echo '<br /><br />Tilbake';
closedir($handle);
}
This is the code I'm using, and I'm trying to figure out where to but 'rsort', but this is very new to me, can anyone help me?
Possible use can be like
$count = 0;
$fileArray = array();
if ($handle = opendir('./arkiv/'))
{
while (false !== ($file = readdir($handle)))
{
if ($file != "." && $file != "..")
{
$count++;
$fileArray[] = $file;
}
}
rsort($fileArray);
foreach($fileArray as $file)
{
print("".basename($file, ".php")."<br />\n");
}
echo '<br /><br />Tilbake';
closedir($handle);
}
Give it a try ....
GOOD LUCK !!!

opendir array exclude file from results

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.

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";
}

Categories