I wrote a controller to upload files to a Directory. and I want if a file exists already in that Directory ,before moving , file name To be changed by increment one unit from last similar existent file name like this:
test.jpg
test(1).jpg
test(2).jpg
This is body of my Controller
$fileName = $file->getClientOriginalName();
$fileExt = $file->getClientOriginalExtension();
$destinationFolder = public_path('upload/userfiles/');
$num = 1;
$newName = $fileName;
while (file_exists($destinationFolder . $newName )) {
$newName = $fileName. '(' . $num . ')';
$num ++;
}
$file->move($destinationFolder, $newName . '.' . $fileExt);
But this does not work correctly and create file name like this :
test.jpg
test(1).jpg
test(1)(2).jpg
your problem is this:
$newName = $fileName;
at first is test.jpg
then you append the ($num++) so it becomes test(1).jpg
the next time its still test(1).jpg
and you append the ($num++) then it becomes test(1)(2).jpg
Thats it
This will work:
$fileName = $file->getClientOriginalName();
$fileExt = $file->getClientOriginalExtension();
$destinationFolder = public_path('upload/userfiles/');
$num = 1;
$newName = $fileName;
$appendNum = false;
while (file_exists($destinationFolder . $newName )) {
$appendNum = true;
$num ++;
}
if ($appendNum) $newName = $fileName. '(' . $num . ')';
$file->move($destinationFolder, $newName . '.' . $fileExt);
this work for me :
$current_name = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
$only_name = explode('.', $current_name)[0];
$new_name = $current_name;
$destination = Storage::disk($link_directory)->path($folder);
$all_files = Storage::disk($link_directory)->listContents($folder);
$searchword = $only_name;
$matches = array_filter($all_files, function($var) use ($searchword) {
if(strpos($var['filename'], $searchword) !== FALSE) {
return $var;
}
});
if( is_array($matches) ){
$new_name = $only_name. '_' . count($matches).'.'.$extension;
}
$filename = Storage::disk($link_directory)->putFileAs($folder, $file, $new_name);
I have created a simple helper function that generates file name:
if (!function_exists('generateFilename')) {
/**
* Generate filename
*
* #param string $disk
* #param string $path
* #param UploadedFile $file
* #param integer $count
* #return string $filename
*/
function generateFilename(string $disk, string $path, UploadedFile $file, int $count = 0)
{
$extension = $file->getClientOriginalExtension();
$filename = pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME) . ($count == 0 ? "." . $extension : "-{$count}." . $extension);
$filePath = Str::of($path)->finish(DIRECTORY_SEPARATOR)->finish($filename)->toString();
if (Storage::disk($disk)->exists($filePath)) {
$count++;
return generateFilename($disk, $path, $file, $count);
}
return $filename;
}
}
Related
Here is my code it is working but I want the best practice
if(Input::hasFile('note_thumb')) {
$file = Input::file('note_thumb');
$fileName = substr($file->getClientOriginalName(), -4);
if ($fileName == '.jpg' || $fileName == 'jpeg' || $fileName == '.png') {
//is image
//return 'maaz';
$finalpath = "";
$file = Input::file('note_thumb');
$tmpFilePath = '/notes/thumnail/';
$tmpFileName = time() . '-' . $file->getClientOriginalName();
$tmpFileName = preg_replace('/\s+/', '', $tmpFileName);
$file = $file->move(public_path() . $tmpFilePath, $tmpFileName);
$path = $tmpFileName;
$finalpath .= $path;
/*if ($i != $count_file - 1) {
$finalpath .= ',';
}*/
$newNote->note_thumb = $finalpath;
}
Try this:
$extension = $request->note_thumb->getClientOriginalExtension();
From the documentation:
https://laravel.com/docs/5.6/requests
I am trying to update 'employee' and 'employee_details' in which I used one to one relationship. During the update, I am getting this error exactly in $employeeDetail->card_no = $request->card_no, in employeeDetail and I searched and tried to implement the possible solutions but still getting this error. Would someone help me to solve this problem, please?
EmployeeController.php
public function update(Request $request, $id)
{
$employee = Employee::find($id);
$employee->card_no = $request->card_no;
$employee->name = $request->name;
$employee->father_name = $request->father_name;
$employee->mother_name = $request->mother_name;
$employee->spouse_name = $request->spouse_name;
$employee->permanent_add = $request->permanent_add;
$employee->present_add = $request->present_add;
$employee->area = $request->area;
$employee->dob = Carbon::parse($request->dob)->format('Y-m-d');
$employee->blood_group = $request->blood_group;
$employee->nid_number = $request->nid_number;
$employee->mobile = $request->mobile;
$employee->reference_name = $request->reference_name;
$employee->reference_nid = $request->reference_nid;
$employee->reference_mobile = $request->reference_mobile;
$employee->reference_add = $request->reference_add;
if (! $request->photo == '') {
$employee->photo = $request->photo;
if ($file = $request->file('photo')) {
$extension = $file->getClientOriginalExtension() ?: 'png';
$folderName = '/uploads/employees/photo';
$destinationPath = public_path() . $folderName;
$safeName = str_random(10) . '.' . $extension;
$file->move($destinationPath, $safeName);
//delete old photo if exists
if (File::exists(public_path() . $folderName . $employee->photo)) {
File::delete(public_path() . $folderName . $employee->photo);
}
//save new file path into db
$employee->photo = $safeName;
}
}
if (! $request->nid_file == '') {
$employee->nid_file = $request->nid_file;
if ($file = $request->file('nid_file')) {
$extension = $file->getClientOriginalExtension() ?: 'png';
$folderName = '/uploads/employees/nid';
$destinationPath = public_path() . $folderName;
$safeName = str_random(10) . '.' . $extension;
$file->move($destinationPath, $safeName);
//delete old nid_file if exists
if (File::exists(public_path() . $folderName . $employee->nid_file)) {
File::delete(public_path() . $folderName . $employee->nid_file);
}
//save new file path into db
$employee->nid_file = $safeName;
}
}
if (! $request->reference_nid_file == '') {
$employee->reference_nid_file = $request->reference_nid_file;
if ($file = $request->file('reference_nid_file')) {
$extension = $file->getClientOriginalExtension() ?: 'png';
$folderName = '/uploads/employees/nid';
$destinationPath = public_path() . $folderName;
$safeName = str_random(10) . '.' . $extension;
$file->move($destinationPath, $safeName);
//delete old reference_nid_file if exists
if (File::exists(public_path() . $folderName . $employee->reference_nid_file)) {
File::delete(public_path() . $folderName . $employee->reference_nid_file);
}
//save new file path into db
$employee->reference_nid_file = $safeName;
}
}
if (! $request->character_file == '') {
$employee->character_file = $request->character_file;
if ($file = $request->file('character_file')) {
$extension = $file->getClientOriginalExtension() ?: 'png';
$folderName = '/uploads/employees/character-certificate';
$destinationPath = public_path() . $folderName;
$safeName = str_random(10) . '.' . $extension;
$file->move($destinationPath, $safeName);
//delete old character_file if exists
if (File::exists(public_path() . $folderName . $employee->character_file)) {
File::delete(public_path() . $folderName . $employee->character_file);
}
//save new file path into db
$employee->character_file = $safeName;
}
}
if ($employee->save()) {
$employeeDetail = EmployeeDetail::where(['employee_id' => $id])
->update([
$employeeDetail->card_no = $request->card_no,
$employeeDetail->section_id = $request->section_id,
$employeeDetail->designation_id = $request->designation_id,
$employeeDetail->salarygrade_id = $request->salarygrade_id,
$employeeDetail->joining_date = Carbon::parse($request->joining_date)->format('Y-m-d'),
$employeeDetail->quit_date = $request->quit_date,
]);
return back()->with('success', 'Congratiolations! You appointed a new employee.');
}
}
Change
From
$employeeDetail = EmployeeDetail::where(['employee_id' => $id])
->update([
$employeeDetail->card_no = $request->card_no,
$employeeDetail->section_id = $request->section_id,
$employeeDetail->designation_id = $request->designation_id,
$employeeDetail->salarygrade_id = $request->salarygrade_id,
$employeeDetail->joining_date = Carbon::parse($request->joining_date)->format('Y-m-d'),
$employeeDetail->quit_date = $request->quit_date,
]);
to
$employeeDetail = EmployeeDetail::where(['employee_id' => $id])
->update([
'card_no' => $request->card_no,
'section_id' => $request->section_id,
'designation_id' => $request->designation_id,
'salarygrade_id' => $request->salarygrade_id,
'joining_date' => Carbon::parse($request->joining_date)->format('Y-m-d'),
'quit_date' => $request->quit_date,
]);
I'm using following code format to change image name if it already exists on server. I want incremental image names if they already exist with the same name.
Ex: abc.png, abc_1.png, abc_2.png
function file_newname($path, $filename){
if ($pos = strrpos($filename, '.')) {
$name = substr($filename, 0, $pos);
$ext = substr($filename, $pos);
} else {
$name = $filename;
}
$newpath = $path.'/'.$filename;
$newname = $filename;
$counter = 1;
while (file_exists($newpath)) {
$newname = $name .'_'. $counter . $ext;
$newpath = $path.'/'.$newname;
$counter++;
}
return $newname;
}
Above code is working if image name is abc.png. If already an image is there on server with name abc_1.png and I run the code it generates image format as abc_1_1.png.
Expected output:
if already abc_1.png is present and I run the code $newname should return abc_2.png . How I can achieve it?
You just need to check what the string ends with, no need to use a regex for that. Take advantage of weak typing and is_numeric to find the value of any previous counter.
function file_newname($path, $filename){
if ($pos = strrpos($filename, '.')) {
$name = substr($filename, 0, $pos);
$ext = substr($filename, $pos);
} else {
$name = $filename;
}
$newpath = $path.'/'.$filename;
$newname = $filename;
// New code here:
if(file_exists($newpath)){
$counter = 1;
if($pos = strrpos($name, '_')) {
$oldcounter = substr($name, $pos + 1);
if(is_numeric($oldcounter)){
$counter = $oldcounter + 1;
$name = substr($name, 0, $pos);
}
}
$newname = $name . '_' . $counter . $ext;
$newpath = $path . '/' . $newname;
while (file_exists($newpath)) {
$newname = $name .'_'. $counter . $ext;
$newpath = $path.'/'.$newname;
$counter++;
}
}
return $newname;
}
I've simplified the functionality a bit so I could get it into a live example, but If you want to play around with the code in the replacement section that I added you can check it out here: http://ideone.com/xR1v0j Just modify the initial value of $name to see how it will react to different inputs.
I'm trying to rename the file name of an image when it's uploaded if it exists, say if my file name is test.jpg and it already exists I want to rename it as test1.jpg and then test2.jpg and so on. With the code I've written its changing my file name like so test1.jpg and then test12.jpg any advice on fixing this would be great thank!
PHP
$name = $_FILES['picture']['name'];
$actual_name = pathinfo($name,PATHINFO_FILENAME);
$extension = pathinfo($name, PATHINFO_EXTENSION);
$i = 1;
while(file_exists('tmp/'.$actual_name.".".$extension))
{
$actual_name = (string)$actual_name.$i;
$name = $actual_name.".".$extension;
$i++;
}
Here's a minor modification that I think should do what you want:
$actual_name = pathinfo($name,PATHINFO_FILENAME);
$original_name = $actual_name;
$extension = pathinfo($name, PATHINFO_EXTENSION);
$i = 1;
while(file_exists('tmp/'.$actual_name.".".$extension))
{
$actual_name = (string)$original_name.$i;
$name = $actual_name.".".$extension;
$i++;
}
Inspired from #Jason answer, i created a function which i deemed shorter and more readable filename format.
function newName($path, $filename) {
$res = "$path/$filename";
if (!file_exists($res)) return $res;
$fnameNoExt = pathinfo($filename,PATHINFO_FILENAME);
$ext = pathinfo($filename, PATHINFO_EXTENSION);
$i = 1;
while(file_exists("$path/$fnameNoExt ($i).$ext")) $i++;
return "$path/$fnameNoExt ($i).$ext";
}
Example:
$name = "foo.bar";
$path = 'C:/Users/hp/Desktop/ikreports';
for ($i=1; $i<=10; $i++) {
$newName = newName($path, $name);
file_put_contents($newName, 'asdf');
}
New version (2022):
function newName2($fullpath) {
$path = dirname($fullpath);
if (!file_exists($fullpath)) return $fullpath;
$fnameNoExt = pathinfo($fullpath,PATHINFO_FILENAME);
$ext = pathinfo($fullpath, PATHINFO_EXTENSION);
$i = 1;
while(file_exists("$path/$fnameNoExt ($i).$ext")) $i++;
return "$path/$fnameNoExt ($i).$ext";
}
Usage:
for ($i=1; $i<=10; $i++) {
$newName = newName2($fullpath);
file_put_contents($newName, 'asdf');
}
There are several ways for renaming image in PHP before uploading to the server.
appending timestamp, unique id, image dimensions plus random number etc.You can see them all here
First, Check if the image filename exists in the hosted image folder otherwise upload it. The while loop checks if the image file name exists and appends a unique id as shown below ...
function rename_appending_unique_id($source, $tempfile){
$target_path ='uploads-unique-id/'.$source;
while(file_exists($target_path)){
$fileName = uniqid().'-'.$source;
$target_path = ('uploads-unique-id/'.$fileName);
}
move_uploaded_file($tempfile, $target_path);
}
if(isset($_FILES['upload']['name'])){
$sourcefile= $_FILES['upload']['name'];
tempfile= $_FILES['upload']['tmp_name'];
rename_appending_unique_id($sourcefile, $tempfile);
}
Check more image renaming tactics
I checked SO and found a nice C# answer here, so I ported it for PHP:
['extension' => $extension] = pathinfo($filePath);
$count = 0;
while (file_exists($filePath) === true) {
if ($count === 0) {
$filePath = str_replace($extension, '[' . ++$count . ']' . ".$extension", $filePath);
} else {
$filePath = str_replace("[$count].$extension", '[' . ++$count . ']' . ".$extension", $filePath);
}
}
Given the path /books/Aaronovitch, Ben/Rivers of London/9780575097568, how could I use PHP to rename the actual folder names to remove the spaces?
You can try the following
echo renameRecrisive(__DIR__, "xx_x/yyy yyy/zz z/fff");
Output
/public_html/www/stac/xx_x/yyy_yyy/zz_z
Function
/**
*
* #param string $path Current path ending with a slash
* #param string $pathname Path you cant to rename
* #param string $sep Optional Seprator
*/
function renameRecrisive($path, $pathname, $sep = "_") {
$pathSplit = array_filter(explode("/", $pathname));
$dir = $path;
while ( $next = array_shift($pathSplit) ) {
$current = $dir . "/" . $next;
if (! is_dir($current)) {
break;
}
if (preg_match('/\s/', $next)) {
$newName = str_replace(" ", $sep, $next);
rename($current, $dir . "/" . $newName);
$dir .= "/" . $newName;
} else {
$dir .= "/" . $next;
}
}
return $dir ;
}
Php function str_replace:
$newPath = str_replace(' ', '', $path);
and then use the rename function.
rename($path, $newPath);
This will walk down each level of the hierarchy, renaming each component if it contains spaces.
$patharray = split('/', $path);
$newpatharray = str_replace(' ', '', $patharray);
$oldpath = $patharray[0];
$newpath = $newpatharray[0];
$i = 0;
while (true) {
if ($patharray[$i] != $newpatharray[$i]) {
rename($oldpath, $newpath);
}
$i++;
if ($i >= count($patharray) {
break;
}
$oldpath .= "/".$patharray[$i];
$newpath .= "/".$newpatharray[$i];
}