Reputation: 297
I am trying to rename the file if existing, the file will be moved successfully but the new file name will be like 0. the file will be shown only if I add .png manually to the name. I am not able to let the php rename the file correctly.
I have tried many suggested ways here on stack overflow but the file won't be moved either will be renamed as 0. a
It will be appreciated to let me know what is wrong with my code, please don't reply that I have to make my research first then write here, as I did already but I had no luck to figure it out myself.
PHP
$i = 0;
$extension = pathinfo($name, PATHINFO_EXTENSION);
$actual_name = pathinfo($name,PATHINFO_FILENAME);
$original_name = $actual_name;
while(file_exists('../cutomeruploads/'.$actual_name.".".$extension))
{
$actual_name = (string)$original_name;
$actual_name = $actual_name.(string)$i;
$name = $actual_name.".".$extension;
$i++;
}
if(move_uploaded_file($_FILES['upl']['tmp_name'], '../cutomeruploads/'.$name)){
$picname = $_FILES['upl']['name'];
echo '{"status":"success"}';
exit;
}
Upvotes: 1
Views: 816
Reputation: 297
These changes renaming the file to xx1.ext xx2.ext
note:xx = $orDi
$actual_name = pathinfo($_FILES['upl']['name'], PATHINFO_FILENAME);
$extension = pathinfo($_FILES['upl']['name'], PATHINFO_EXTENSION);
while(file_exists('../cutomeruploads/'.$actual_name.".".$extension))
{
$i++;
$actual_name = (string)$orDi.(string)$i;
}
if(move_uploaded_file($_FILES['upl']['tmp_name'], '../cutomeruploads/'.$actual_name.".".$extension)){
$picname = $actual_name.".".$extension;
Upvotes: 0
Reputation: 2819
Try this one.
/*
* $dir - Directory path to check where the file is exist
* $filename - contains only name of the file
*
*/
public static function getFileName($dir, $filename) {
// If name contains any white space replace with '-'
$filename = str_replace(" ", "-", $filename);
$filePath = $dir . $filename;
$fileInfo = pathinfo($filePath);
$i = 0;
$flag = false;
while(file_exists($filePath)) {
$filePath = $dir . $fileInfo['filename'] . "_" . $i . "." . $fileInfo['extension'];
$i++;
$flag = true;
}
if($flag === TRUE)
return $fileInfo['filename'] . "_" . $i . "." . $fileInfo['extension'];
else
return $fileInfo['filename'] . "." . $fileInfo['extension'];
}
This is will return new filename
if already exist one.
For example, image.jpg
already exist, it automatically adding image_1.jpg
, image_2.jpg
and so on.
Upvotes: 0
Reputation: 528
Have u tried the rename function of the php?
rename("The existing file name", "the new name");
Upvotes: 3
Reputation: 1353
Renaming a file in php is quite easy.
rename("oldfile.ext","newname.ext");
For more info see this: https://www.php.net/rename
Upvotes: 1