i have been trying to rename all the files (images) in a folder on my website but it does not work. the files are not renamed.
i have an input field for 'name' i want to use that name, add a uniqid and rename all the files.
here's the code that i am using:
<?php
if(isset($_POST['submit2'])){
$name = $_POST['name'];
$directory = glob("../basic_images/*.*");
{
if ($file != "." && $file != "..") {
$newName = uniqid().$name;
rename($directory.$file, $directory.$newName);
}}}
?>
besides, do i really need to _Post the $name variable?
P.S. i want to rename all the files and then copy them to another folder.
You don't need to POST name
glob is return you every files in folder with path // example /basic_images/test.jpg
then you just do foreach to loop over files, and update its name.
$path = "../basic_images/";
$directory = glob($path,"*.*");
foreach($directory as $file){
$ext = pathinfo($file, PATHINFO_EXTENSION);
$newName = uniqid().$ext;
rename($file, $path.$newName);
}
read more about glob : http://php.net/manual/en/function.glob.php
so, i finally solved the problem. now, instead of renaming the original files and then copying them to another folder, i just create new copies of the files with new names.
This is the code final code that works for me:
if(isset($_POST['submit'])){
$path = "../posts_images/";
$files = glob("../basic_images/*.*");
foreach($files as $file){
$ext = pathinfo($file, PATHINFO_EXTENSION);
$name = $_POST['new_name'];
$pic = uniqid().$name;
$newName = $pic.'.'.$ext;
copy($file, $path.$newName);
}}
it is important to use $pic.'.'.$ext because without it the new files don't have any extension.
Related
I have 4 csv files in "files" folder & I want to move these files with content to another folder (i.e. backups),Files are given below.
abc.csv
abc1.csv
abc2.csv
$files = scandir('files');
$destination = 'backups/';
$date = date('Y-m-d');
foreach($files as $file){
$rename_file = $file.'_'.$date;
move_uploaded_file($rename_file, "$destination");
}
Since you are not uploading any files, try rename() function instead.
$Ignore = array(".","..","Thumbs.db");
$OriginalFileRoot = "files";
$OriginalFiles = scandir($OriginalFileRoot);
$DestinationRoot = "backups";
# Check to see if "backups" exists
if(!is_dir($DestinationRoot)){
mkdir($DestinationRoot,0777,true);
}
$Date = date('Y-m-d');
foreach($OriginalFiles as $OriginalFile){
if(!in_array($OriginalFile,$Ignore)){
$FileExt = pathinfo($OriginalFileRoot."\\".$OriginalFile, PATHINFO_EXTENSION); // Get the file extension
$Filename = basename($OriginalFile, ".".$FileExt); // Get the filename
$DestinationFile = $DestinationRoot."\\".$Filename.'_'.$Date.".".$FileExt; // Create the destination filename
rename($OriginalFileRoot."\\".$OriginalFile, $DestinationFile); // rename the file
}
}
The function move_uploaded_file is relevant for uploading files, not for other things.
To move file in the filesystem you should use the rename function:
$files = scandir('files');
$destination = 'backups/';
$date = date('Y-m-d');
foreach($files as $file){
if (!is_file($file)) {
continue;
}
$rename_file = $destination.$file.'_'.$date;
rename($file, $rename_file);
}
How can I delete images in a folder that for example all have the name "john" in them. I am making a temporary image folder and I want to erase all of the users data on the temp folder after they're done.
Thanks.
Make use of PHP's built in DirectoryIterator to iterate across all the files in the images/ directory you want to modify.
$name = 'John';
$dir = new DirectoryIterator('images'); //In this case the images directory
foreach ($dir as $fileinfo) {
if (!$fileinfo->isDot()) {
//Is a valid file name
$filename = $fileinfo->getFilename();
//Now you have access to the filename make appropriate modifications. Below is a quick naive demonstration.
if (strpos($filename, $name)) {
//We have fulfilled the 'John' condition, delete the file
unlink('images/' . $filename);
}
}
}
You may need to modify the variables and directory names accordingly based on absolute or relative pathing to your situation. Make sure you have the appropriate permissions to (if relevant).
Something like this:
<?php
$NameToDelete = $_GET['name']; //ex: file.php?name=john
$Folder = "/images/"; //The folder you want to delete from
$FileType = array( //All the filetypes (in this case some image types
'jpg',
'png',
'bmp',
'jpeg'
);
foreach($FileType as $Type){//For EACH filetype as type
$Link = $_SERVER['DOCUMENT_ROOT']."$Folder".$NameToDelete."."."$Type"; //path
#unlink($Link); //DELETE - using # to not get any errors
echo "Deleted: $Link<br/>"; //Print
}
The file name is known but the file extension is unknown. The images in thier folders do have an extension but in the database their names do not.
Example:
$ImagePath = "../images/2015/03/06/"; (Folders are based on date)
$ImageName = "lake-sunset_3";
Does not work - $Ext is empty:
$Ext = (new SplFileInfo($ImagePath))->getExtension();
echo $Ext;
Does not work either - $Ext is empty:
$Ext = (new SplFileInfo($ImagePath.$ImageName))->getExtension();
echo $Ext;
Does not work either - $Ext is still empty:
$Ext = (new SplFileInfo($ImagePath,$ImageName))->getExtension();
echo $Ext;
$Ext should produce ".jpg" or ".jpeg" or ".png" etc.
So my question is simple: What am I doing wrong?
Now, this is a bit of an ugly solution but it should work. Make sure that all your files have unique names else you'll have several of the same file, which could lead to your program obtaining the wrong one.
<?php
$dir = scandir($imagePath);
$length = strlen($ImageName);
$true_filename = '';
foreach ($dir as $k => $filename) {
$path = pathinfo($filename);
if ($ImageName === $path['filename']) {
break;
}
}
$Ext = $path['extension'];
?>
Maybe this might help you (another brute and ugly solution)-
$dir = '/path/to/your/dir';
$found = array();
$filename = 'your_desired_file';
$files = scandir($dir);
if( !empty( $files ) ){
foreach( $files as $file ){
if( $file == '.' || $file == '..' || $file == '' ){
continue;
}
$info = pathinfo( $file );
if( $info['filename'] == $filename ){
$found = $info;
break;
}
}
}
// if file name is matched, $found variable will contain the path, basename, filename and the extension of the file you are looking for
EDIT
If you just want the uri of your image then you need to take care of 2 things. First directory path and directory uri are not the same thing. If you need to work with file then you must use directory path. And to serve static files such as images then you must use directory uri. That means if you need to check files exists or what then you must use /absolute/path/to/your/image and in case of image [site_uri]/path/to/your/image/filename. See the differences? The $found variable form the example above is an array-
$found = array(
'dirname' => 'path/to/your/file',
'basename' => 'yourfilename.extension',
'filename' => 'yourfilename',
'extension' => 'fileextension'
);
// to retrieve the uri from the path.. if you use a CMS then you don't need to worry about that, just get the uri of that directory.
function path2url( $file, $Protocol='http://' ) {
return $Protocol.$_SERVER['HTTP_HOST'].str_replace($_SERVER['DOCUMENT_ROOT'], '', $file);
}
$image_url = path2url( $found['dirname'] . $found['basename'] ); // you should get the correct image url at this moment.
You are calling a file named lake-sunset_3. It has no extension.
SplFileInfo::getExtension() is not designed to do what you are requesting it to do.
From the php site:
Returns a string containing the file extension, or an empty string if the file has no extension.
http://php.net/manual/en/splfileinfo.getextension.php
Instead you can do something like this:
$path = $_FILES['image']['name'];
$ext = pathinfo($path, PATHINFO_EXTENSION);
getExtension() only returns the extension from the given path, which in your case of course doesn't have one.
In general, this is not possible. What if there is a file lake-sunset_3.jpg and a file lake-sunset_3.png?
The only thing you can do is scan the directory and look for a file with that name but any extension.
You're trying to call an incomplete path. You could try Digit's hack of looking through the directory for for a file that matches the name, or you could try looking for the file by adding the extensions to it, ie:
$basePath = $ImagePath . $ImageName;
if(file_exists($basePath . '.jpg'))
$Ext = '.jpg';
else if(file_exists($basePath . '.gif'))
$Ext = '.gif';
else if(file_exists($basePath . 'png'))
$Ext = '.png';
else
$Ext = false;
Ugly hacks aside, the question begging to be asked is why are you storing them without the extensions? It would be easier to strip off the extension if you need to than it is try and find the file without the 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);
}
}
I guys, i'm writting code to upload file, zip them and delete tmp file.
But when i use unlink function, it do not remove all file, someone can explain to me why ?
Concerned php code :
$zip = new ZipArchive();
$target_path = 'img/products/';
$zip->open($target_path.$id_insert.'.zip', ZIPARCHIVE::CREATE);
$img_count = $_POST['count_file'];
for ($i = 1; $i <= $img_count; $i++){
$temp = 'img'.$i;
$file = $i.'-'.$id_insert.'-'.$_FILES[$temp]['name'];
$path = $target_path.basename($file);
if(move_uploaded_file($_FILES[$temp]['tmp_name'], $path)) {
$zip->addFile($path, basename($file));
$files_to_delete[] = $path;
}
}
$zip->close();
foreach($files_to_delete AS $file){
//unlink(dirname(__FILE__).'/'.$path);
}
foreach($files_to_delete AS $file){
//unlink(dirname(__FILE__).'/'.$path);
}
In this block you should replace $path with $file since that's what you're foreaching them as. You get the error because after you unlink $path the first time, the file at $path is unlinked, but every other iteration of it tries to delete the same file (which is the last one assigned to the $path variable).