my code


Rename an Uploaded Image
by amr.mekkawy

This function is used to rename uploaded images. it replaces existing spaces with dashes and adds date and time (Unix Timestamp) to the end of the name as well

Snippet options

Download: Download snippet as rename-an-uploaded-image.php.
Copy snippet: For this you need a free my code account.
Embed code : You will find the embed code for this snippet at the end of the page, if you want to embed it into a website or a blog!


# This function renames any uploaded image.
# It replaces spaces with dashes and add date and time to the end of image name as well
function rename_uploaded_image( $original_name ) {
    # if there are 3 spaces between words replace them with 1 dash
    $new_name = str_replace('   ', '-', $original_name);
    # if there are 2 spaces between words replace them with 1 dash
    $new_name = str_replace('  ', '-', $new_name);
    # if there is 1 space between words replace it with 1 dash
    $new_name = str_replace(' ', '-', $new_name);
    # get extension of the image
    # strrchr() function gets the portion of $new_name which starts at the last occurrence of "." and goes until the end of $new_name
    $extension_with_preceding_dot = strrchr( $new_name, "." );
    # get name of the image without the extension and the dot that preceding the extension
    $new_name_without_extension = substr( $new_name, 0, strlen( $new_name ) - strlen( $extension_with_preceding_dot ) );
    # add current Unix timestamp to the end of the image name to ensure that name of the uploaded image does not match anothe image name where you are going to store it
    # current Unix timestamp is number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)
    $new_name = $new_name_without_extension . '_' . time() . $extension_with_preceding_dot;
    return $new_name;


Create a free my code account now.

my code is a free service, which allows you to save and manage code snippes of any kind and programming language. We provide many advantages for your daily work with code-snippets, also for your teamwork. Give it a try!

Find out more and register now

You can customize the height of iFrame-Codes as needed! You can find more infos in our API Reference for iframe Embeds.