I have a fileupload module in my app. I can upload files in img/upload/{container_id}/file_name_here.
The {container_id} will depend on what folder the user will use.
The problem I encountered is when they try to edit a record to another folder. The file that they uploaded remains in the old folder.
I want to move the file also to the new folder the user defines.
I have here my code, I'm stuck in moving the file.
$attachments = Attachment::where('document_id',$id)->select('filename')->get();
$document = Document::findOrFail($id);
foreach($attachments as $attachment)
{
$attachment->filename = base_path().'/public/img/upload/'.$document->container_id."/".$attachment->filename;
}
Document::findOrFail($id)->update($request->all());
$document = Document::findOrFail($id);
$x = Attachment::where('document_id','=',$id)->count();
foreach($attachments as $file)
{
HOW_DO_I_MOVE_THE_FILE????
$x++;
}
return redirect('documents');
Update:
In your case, you should use rename():
rename ('current/path/to/foo', 'new/path/to/foo');
With rename() you can not only rename, but also move! Simply, if the path of the second param differs. So you can use in your loop the attachment path as first param, and a destination path as second.
Documentation: http://php.net/rename
Below the Laravel approach for moving after upload.
From the documentation:
$request->file('photo')->move($destinationPath);
$request->file('photo')->move($destinationPath, $fileName);
photo is the name of your file upload input element.
Note, you can use the array notation, if you've multi upload, such as:
foreach ($request->file('photo') as $photo)
{
$photo->move($destinationPath, $chooseYourFileName);
}
Related
I've got a web form which has a unique upload folder for each user (using their PHP session_id() as the folder name) which works well. When the form is submitted (after error checking) PHPMailer is used to send the email and the attachments. This is also working well. However, after the email is sent, I would like to remove the uploads from the folder and then the folder itself (sort of a self-cleanup!) The files are removed as expected but the folder remains (albeit empty). I wonder if the folder is somehow "still in use" so doesn't get deleted or something similar? This is the code:
// Empty the contents of the upload folder
if (is_dir($dir)) { // Target directory ($dir) is set above in photos POST section
// Check for any files inside the directory
$files = glob($dir.'/*'); // Get all file names
foreach($files as $file) { // Iterate through the files
if(is_file($file)) { // Check its a file
unlink($file); // Delete the file
}
}
// Remove the upload folder
rmdir($dir); //NOT WORKING? NEEDS SOME TROUBLESHOOTING...
}
Any other ideas on why this folder is remaining?
Ben
I would guess that your folders might contain hidden files (starting with .) which the default glob pattern won't match, so try this:
$files = glob($dir . '/{,.}*'); // Get all file names including hidden ones
foreach($files as $file) { // Iterate through the files
if(is_file($file)) { // Check its a file
unlink($file); // Delete the file
}
}
Also check the return value on both unlink and rmdir so you can see exactly where it's failing.
Turns out after much testing that the problem was not actually with rmdir at all! My web form uses a Dropzone for photo uploads to a unique folder for each user using their php session_id() and this folder is supposed to be created when they add a photo to Dropzone (if it doesn’t already exist). Problem was I’d put the folder creation code outside of the actual upload script so the folder was in fact being deleted but them instantly created again when the form submitted and the page reloads! Sorry about that but thanks for all your help. :)
I would like to rename a collection of uploaded files, but when I use addAllMediaFromRequest() I can't retrieve information from the files.
In this example; I need to know the file extension in order to rename the file.
$files = $post->addAllMediaFromRequest();
$files->each(function (FileAdder $file) {
$file->usingFileName(Str::random(16) . '.jpg') // What if it's a png?
->toMediaCollection();
});
To get a file extension within laravel:
$request->file('photo')->extension()
To create new file name:
$newFileName = Str::random(20) .'.'.$request->file('photo')->extension();
don't forget to import Str class.
then you could rename the uploaded file before storing it easily
$item->addMedia($request->photo)->usingFileName($newFileName)->toMediaCollection('photo');
code tested Laravel v9
I want to delete a folder after deleting all the files inside it, in my codeigniter project. Lets say my folder name is upload, which is located near the application folder in my ci project.
The upload folder contains Peniyal as a sub-folder and it contains 4 images inside it. I need that 4 images to be deleted, next the sub-folder has to be deleted.upload folder should not be deleted. I am hanging my mind to do it.
So far I have tried the following:-
$files = glob('./upload/Peniyal');//to get all file names
//am not sure whether the path is correctly given..
foreach($files as $file){ // iterate files one by one
if(is_file($file))
unlink($file); // delete file
}
$path = './upload/Peniyal';
rmdir($path);
Any help will be appreciated. Thx!
The glob() function matches a pattern, but you are not providing one. So if you use the pattern *.* the glob will find all files in that folder.
// match any file
$files = glob('./upload/Peniyal/*.*');
foreach($files as $file){
if(is_file($file))
unlink($file);
}
$path = './upload/Peniyal';
rmdir($path);
With CodeIgnitor 4:
delete_files('./path/to/directory/', true);
rmdir('./path/to/directory/');
I have an update controller function in a laravel resource controller thats pretty basic. Updates the title, body etc. in the DB as normal (no issues with data updates).
The issue is with images. My image directory for each project follows a slug like naming convention based on the title of the project. I built the update function so that the directory and images would be renamed if the title was changed. This was working fine as soon as I built it, but it's suddenly stopped. The directory renames, but the files do not. Here is the relevant snippet from the controller:
$count = 0;
$slug = Input::get('title');
$prefix = Str::slug($slug);
$oldPrefix = $project->imagesprefix;
$path = public_path().'/img/projects/';
$directory = $path . $prefix;
rename($path.$oldPrefix, $directory);
//dumped directory here and it's definitely set
$files = preg_grep('~\.(jpg)$~', scandir($directory));
//dumped $files here and the array is definitely set
foreach($files as $file){
rename($directory.'/'.$file, $directory.'/'.$prefix.'-'.$count.'.jpg');
++$count;
}
rename($directory.'/thumbnails/'.$oldprefix.'-thumb.jpg', $directory.'/thumbnails/'.prefix.'-thumb.jpg');
All of this was working fine when tested this afternoon. Now it updates the DB, renames the directory folder but fails to rename the files. I've dumped the both $files and $directory before the loop and they are both set.
If file rename fails then this is quite often related to permissions.
I have audio files in var/
This is the file name
2-3109999999-3246758493-1271129518-1271129505.6.wav
Format
2=campaign id
3109999999=caller id
3246758493=number called
1271129518=timestamp call ended
1271129505=timestamp call started
6=call id
If I were to pass just the number called which was 3246758493, how can I find all the files without defining all the other variables(such as timestamp, etc) and just the files that have that number in the filename?
You would need to loop though the folder: http://php.net/manual/en/function.readdir.php
Then for each of the files in the folder, try and match it to the file that was requested using regex I guess?
http://www.txt2re.com/index-php.php3?s=2-3109999999-3246758493-1271129518-1271129505.6.wav&8
You could also use a DirectoryIterator to scan the folder and a RegexIterator to filter the files based on a pattern.
$id = '3246758493';
$files = new RegexIterator(new DirectoryIterator('var/'),
"#^\d-\d{10}-$id-\d{10}-\d{10}\.\d\.wav$#D");
foreach ($files as $fileinfo) {
echo $fileinfo . PHP_EOL;
}