Removing file extension in PHP, whilst also creating a link - php

I have this code which is taking the name of files in a directory and then creating a link to those files. However, the text in the link has the file extension on the end. I want to remove this but at the same time keep the correct link to the file i.e. the HTML link needs the extension to remain on it - like this:
File
So here is my script:
$linkdir="documents/other";
$dir=opendir("documents/other");
$files=array();
while (($file=readdir($dir)) !== false)
{
if ($file != "." and $file != ".." and $file != "index.php")
{
array_push($files, $file);
}
}
natcasesort($files);
$files=array_reverse($files);
foreach ($files as $file)
print "<li><a href='/$linkdir/$file' rel='external'>$file</a></li>";
Here is the code I need to integrate to remove the file extension:
$name = substr($file, 0, strrpos($file, '.'));
Any help with this will be greatly appreciated.

Could you mean that you want this?
foreach ($files as $file){
$name = substr($file, 0, strrpos($file, '.'));
print "<li><a href='/$linkdir/$file' rel='external'>$name</a></li>";
}
I can't find any other question in your post :)

Using pathinfo() is a more robust solution, in case some files have name with more dots (like someclass.inc.php):
$parts = pathinfo($file);
$name = $parts['basename'];

Related

How to delete file in PHP

I want to delete files in a specific directory in PHP. How can I achieve this?
I have the following code but it does not delete the files.
$files = array();
$dir = dir('files');
while ($file = $dir->read()) {
if ($file != '.' && $file != '..') {
$files[] = $file;
}
unlink($file);
}
I think your question isn't specific, this code must clear all files in the directory 'files'.
But there are some errors in that code I think, and here is the right code:
$files= array();
$dir = dir('files');
while (($file = $dir->read()) !== false) { // You must supply a condition to avoid infinite looping
if ($file != '.' && $file != '..') {
$files[] = $file; // In this array you push the valid files in the provided directory, which are not (. , ..)
}
unlink('files/'.$file); // This must remove the file in the queue
}
And finally make sure that you provided the right path to dir().
You can get all directory contents with glob and check if the value is a file with is_file() before unlinking it.
$files = glob('files/*'); // get directory contents
foreach ($files as $file) { // iterate files
// Check if file
if (is_file($file)) {
unlink($file); // delete file
}
}
If you want to remove files matching a pattern like .png or .jpg, you have to use
$files = glob('/tmp/*.{png,jpg}', GLOB_BRACE);
See manual for glob.

PHP Remove all Files From a Directory - Exclude File Extension

I am trying for the life of me to find the best way to delete all files in a single directory excluding a single file extension, ie anything that is not .zip
The current method I have used so far which successfully deletes all files is:
$files = glob('./output/*');
foreach($files as $file)
{
if(is_file($file))
unlink($file); // delete file
}
I have tried modifying this like so:
$files = glob('./output/**.{!zip}', GLOB_BRACE);
foreach($files as $file)
{
if(is_file($file))
unlink($file); // delete file
}
However, I am not hitting the desired result. I have changed the line as follows which has deleted only the zip file itself (so I can do the opposite of desired).
$files = glob('./output/*.{zip}', GLOB_BRACE);
I understand that there are other methods to read directory contents and use strpos/preg_match etc to delete accordingly. I have also seen many other methods, but these seem to be quite long winded or intended for recursive directory loops.
I am certainly not married to glob(), I would simply like to know the simplest/most efficient way to delete all files in a single directory that are not a .zip file.
Any help/advice is appreciated.
$exclude = array("zip");
$files = glob("output/*");
foreach($files as $file) {
$extension = pathinfo($file, PATHINFO_EXTENSION);
if(!in_array($extension, $exclude)) unlink($file);
}
This code works by having an array of excluded extensions, it loads up all files in a directory then checks for the extension of each file. If the extension is in the exclusion list then it doesn't get deleted. Else, it does.
This should work for you:
(I just use array_diff() to get all files which are different to *.zip and then i go through these files and unlink them)
<?php
$files = array_diff(glob("*.*"), glob("*.zip"));
foreach($files as $file) {
if(is_file($file))
unlink($file); // delete file
}
?>
How about calling to the shell? So in Linux:
$path = '/path/to/dir/';
$shell_command = escapeshellcmd('find ' . $path .' ! -name "*.zip" -exec rm -r {}');
$output = shell_exec($shell_command);
I would simply like to know the simplest/most efficient way to delete all files in a single directory that are not a .zip file.
SPL Iterators are very effective and efficient.
This is what I would use:
$folder = __DIR__;
$it = new FilesystemIterator($folder, FilesystemIterator::SKIP_DOTS);
foreach ($it as $file) {
if ($file->getExtension() !== 'zip') {
unlink($file->getFilename());
}
}
Have you tried this:
$path = "dir/";
$dir = dir($path);
while ($file = $dir->read()) {
if ($file != "." && $file != ".." && substr($file, -4) !== '.zip') {
unlink($file);
}
}

Remove string from filename for all files (image files) available in the directory without affecting its extensions

Need to remove user requested string from file name. This below is my function.
$directory = $_SERVER['DOCUMENT_ROOT'].'/path/to/files/';
$strString = $objArray['frmName']; // Name to remove which comes from an array.
function doActionOnRemoveStringFromFileName($strString, $directory) {
if ($handle = opendir($directory)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
if(!strstr($file,$strString)) {
continue;
}
$newfilename = str_replace($strString,"",$file);
rename($directory . $file,$directory . $newfilename);
}
}
closedir($handle);
}
}
It works partially good. But the mistake what in this routine is, renaming action also takes on file's extensions. What i need is, Only to rename the file and it should not to be affect its file extensions. Any suggestions please. Thanks in advance :).
I have libraries written by myself that have some of those functions. Look:
//Returns the filename but ignores its extension
function getFileNameWithOutExtension($filename) {
$exploded = explode(".", $filename);
array_pop($exploded);
//Included a DOT as parameter in implode so, in case the
//filename contains DOT
return implode(".", $exploded);
}
//Returns the extension
function getFileExtension($file) {
$exploded = explode(".", $file);
$ext = end($exploded);
return $ext;
}
So you use
$replacedname = str_replace($strString,"", getFileNameWithOutExtension($file));
$newfilename = $replacedname.".".getFileExtension($file);
Check it working here:
http://codepad.org/CAKdCAA0

Rename function not working as expected

I'm using PHP to batch rename some local photos. The script is in the same directory as the photos.
The photos are named like 872376237_Photo_1_001.jpg. The first set of numbers (before the first underscore) is different for each file, and that's what I want to remove.
The format for the new file name should be Photo_1_001.jpg. In the PHP I get the new file name by using $newfilename = substr($filename, strpos($filename, '_') + 1);. Echo'ing out $newfilename shows the correct new file name.
The problem is when I call rename($filename, $newfilename) the files are getting renamed to 1_001.jpg. The $newfilename variable definitely contains the correct new file name. If I use copy() instead of rename() it works as expected. I can't figure this out.
Here's the code:
$dir = new DirectoryIterator(dirname(__FILE__));
foreach ($dir as $fileinfo) {
if (!$fileinfo->isDot()) {
$filename = $fileinfo->getFilename();
if ($filename != basename(__FILE__)) { // skip this script
$newfilename = substr($filename, strpos($filename, '_') + 1);
rename($filename, $newfilename);
}
}
}
EDIT: DevZer0 explained why this is happening in the comments. I thought DirectoryIterator compiled a list of all the files before iterating, but it does not. It will continuously iterate as long as new files are created (or renamed).
There's probably a better way to do this, but this works:
$dir = new DirectoryIterator(dirname(__FILE__));
$filenames = [];
foreach ($dir as $fileinfo) {
if (!$fileinfo->isDot()) {
$filename = $fileinfo->getFilename();
if ($filename != basename(__FILE__)) {
$newfilename = substr($filename, strpos($filename, '_') + 1);
array_push($filenames, [$filename, $newfilename]);
}
}
}
foreach ($filenames as $file) {
rename($file[0], $file[1]);
}

Get a list of files and filenames without an extention using php

I'm trying to make a jQuery slider that automatically loads all the images in a specified folder. So I'm using a small PHP script that makes a list of all the files in that directory. For the captions of the slider I wanted to use the filename (without extension).
I'm using the following script, using PHP. It can list all the files with the extensions, but I can't find a way to also display the filename (for the captions) without the extensions.
Anyone an idea?
Thanks in advance!
<?
$path = "img";
$dir_handle = #opendir($path) or die("Unable to open $path");
while ($file = readdir($dir_handle)) {
if($file == "." || $file == ".." || $file == "index.php" )
continue;
echo "$file";
}
closedir($dir_handle);
?>
Here you have more OO way:
$iterator = new DirectoryIterator($directory);
foreach ($iterator as $fileinfo) {
if ($fileinfo->isFile()) {
$fileinfo->getBasename('.' .$fileinfo->getExtension());
}
}
You can get the filename without its extension using pathinfo():
$filename = pathinfo( $file, PATHINFO_FILENAME);

Categories