Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rename each file before uploading to server to a time-stamp

I'm using the following code to upload some files, but well, some get replaced since the names get to be alike. I just wanna know how do i change the name, i tried but i kinda find myself messing the entire code.

PHP

if (!empty($_FILES["ambum_art"])) {
    $myFile = $_FILES["ambum_art"];
    if ($myFile["error"] !== UPLOAD_ERR_OK) {
       echo "<p>An error occurred.</p>";
        exit;
    }
    $name = preg_replace("/[^A-Z0-9._-]/i", "_", $myFile["name"]);
    $i = 0;
    $parts = pathinfo($name);
    while (file_exists(UPLOAD_DIR . $name)) {
        $i++;
        $name = $parts["filename"] . "-" . $i . "." . $parts["extension"];
    }
     $success = move_uploaded_file($myFile["tmp_name"],UPLOAD_DIR . '/'.$name);
    if (!$success) { 
        echo "<p>Unable to save file.</p>";
        exit;
    } else {
        $Dir = UPLOAD_DIR .'/'. $_FILES["ambum_art"]["name"];
    }
    chmod(UPLOAD_DIR .'/'. $name, 0644);
    unset($_SESSION['video']);
    $_SESSION['album_art'] = $Dir;
    $ambum_art_result = array();
    $ambum_art_result['content'] = $Dir;
    echo json_encode($ambum_art_result);

}

I would like each file to have something from this variable generated from time.

$rand_name = microtime().microtime().time().microtime();

Thanks.

I don't want to first check if file exists as that adds to the processes, i just want to use time() and some random string. to just get a unique name.

like image 968
user3109875 Avatar asked Oct 01 '22 22:10

user3109875


2 Answers

Please see this website for a decent example of file uploading and an explanation. Also this site appears to be where you found this particular script from or if not offers a good explanation.

I have modified your code to include some comments so you and others can understand what is going on better. In theory, the code shouldn't be overwriting existing files like you say it does but I have added what you would need to change to set the name of the file to a random string.

In addition you are storing the original filename into the session and not the modified filename.

define("UPLOAD_DIR", "/path/to/uploads/");

if (!empty($_FILES["ambum_art"])) 
{
    // The file uploaded
    $myFile = $_FILES["ambum_art"];

    // Check there was no errors
    if ($myFile["error"] !== UPLOAD_ERR_OK) {
        echo "<p>An error occurred.</p>";
        exit;
    }

    // Rename the file so it only contains A-Z, 0-9 . _ -
    $name = preg_replace("/[^A-Z0-9._-]/i", "_", $myFile["name"]);

    // Split the name into useful parts
    $parts = pathinfo($name);

    // This part of the code should continue to loop until a filename has been found that does not already exist.
    $i = 0;
    while (file_exists(UPLOAD_DIR . $name)) {
        $i++;
        $name = $parts["filename"] . "-" . $i . "." . $parts["extension"];
    }

    // If you want to set a random unique name for the file then uncomment the following line and remove the above
    // $name = uniqid() . $parts["extension"];

    // Now its time to save the uploaded file in your upload directory with the new name
    $success = move_uploaded_file($myFile["tmp_name"], UPLOAD_DIR . '/'.$name);

    // If saving failed then quit execution
    if (!$success) { 
        echo "<p>Unable to save file.</p>";
        exit;
    }

    // Set file path to the $Dir variable
    $Dir = UPLOAD_DIR .'/'. $name;

    // Set the permissions on the newly uploaded file
    chmod($Dir, 0644);

    // Your application specific session stuff
    unset($_SESSION['video']);
    $_SESSION['album_art'] = $Dir; // Save the file path to the session
    $ambum_art_result = array();
    $ambum_art_result['content'] = $Dir;
    echo json_encode($ambum_art_result);

}

Read more about PHPs uniqid.

I would also strongly advise doing some filetype checking as currently it appears as though any file can be uploaded. The second link above has a section titled 'Security Considerations' that I would recommend reading through vary carefully.

like image 177
Paul Blundell Avatar answered Oct 21 '22 03:10

Paul Blundell


This code is filtering the name, then checks if file with exactly same name is already sent. If it is - name is changed with with number.

If you want to change the file name as in many sites - you may modify this line $name = preg_replace("/[^A-Z0-9._-]/i", "_", $myFile["name"]);

For example into: $name = time().'_'.preg_replace("/[^A-Z0-9._-]/i", "_", $myFile["name"]); If user sends file calle 'hello.jpg' this code will change it to _hello.jpg if file with the same name exists already the name _hello-.jpg will be used instead.

like image 30
Seti Avatar answered Oct 21 '22 02:10

Seti