How to increment the filename if file already exists in PHP?

Today, We want to share with you How to increment the filename if file already exists in PHP?.In this post we will show you php check if file exists at url, hear for PHP upload file and rename if already exist we will give you demo and example for implement.In this post, we will learn about Check if a file exists and rename another file if the file exists with an example.

Free Live Chat for Any Issue

How to increment the filename if file already exists in PHP?

There are the Following The simple About php – upload and increment filename Full Information With Example and source code.

Also Read This ๐Ÿ‘‰   PHP Laravel 6 Flash Message Notification

As I will cover this Post with live Working example to develop how to rename the file if already exists in php, so the some major files and Directory structures for this example is following below.

Check if File Exists / Append Number to Name

If the your file name exists, then returns new fresh file name with uniq _number appended so you donโ€™t overwrite it.

index.php

function file_newname($path, $your_filename){
    if ($pos = strrpos($your_filename, '.')) {
           $name = substr($your_filename, 0, $pos);
           $ext = substr($your_filename, $pos);
    } else {
           $name = $your_filename;
    }

    $newpath = $path.'/'.$your_filename;
    $tmp_name = $your_filename;
    $uniq_no = 0;
    while (file_exists($newpath)) {
           $tmp_name = $name .'_'. $uniq_no . $ext;
           $newpath = $path.'/'.$tmp_name;
           $uniq_no++;
     }

    return $tmp_name;
}

Example returns:

pakainfo.jpg
pakainfo_0.jpg
pakainfo_1.jpg

Web Programming Tutorials Example with Demo

Read :

Also Read This ๐Ÿ‘‰   Social Integration with Facebook Twitter and Google using PHP

Summary

You can also read about AngularJS, ASP.NET, VueJs, PHP.

I hope you get an idea about rename file if already exists php.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, donโ€™t forget to share.

PHP Laravel is a web application framework with expressive, elegant syntax.The PHP Framework for Web Artisans,freeing you to create without sweating the small things. CRUD Operation With Server Side.

Rate this post