Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    Regular Coder
    Join Date
    Sep 2006
    Location
    Colorado
    Posts
    132
    Thanks
    7
    Thanked 1 Time in 1 Post

    Renaming an uploaded file before you move it

    I have this:
    PHP Code:
    $uploadpath "uploads/"
    $filename $_FILES['externalfile']['name'];
    $uploadfile $uploadpath.$filename;
        echo 
    'uploading your ' $filename '... 'flush();
        if (
    move_uploaded_file($_FILES['externalfile']['tmp_name'], $uploadfile))
        {
        
            echo 
    '<font color=green>Done!</font><br />';
        
        }
        else
        {

            die(
    '<font color=red>Error:</font> could not move file.');

        }
        
    flush(); 
    Is a block of code from my upload script. I want when I move the file to change the name to have a random number at the end, rand(1,9999)... To prevent duplicates. I tried this:
    PHP Code:
    $uploadfile $uploadpath.$filename.rand(1,9999); 
    But it didnt work, any help?
    -bubbles

  • #2
    Regular Coder
    Join Date
    Nov 2006
    Posts
    246
    Thanks
    13
    Thanked 26 Times in 24 Posts
    I don't think you can rename it before actually moving it from the temp location, but you can right after the move:

    PHP Code:
    $uploadpath "uploads/"
    $filename $_FILES['externalfile']['name'];
    $uploadfile $uploadpath.$filename;

    echo 
    'uploading your ' $filename '... 'flush();
    if (
    move_uploaded_file($_FILES['externalfile']['tmp_name'], $uploadfile))
    {
            
    $uploadnewpath $uploadpath.$filename.rand(1,9999); 
            
    rename($uploadfile$uploadnewpath) or die();
            echo 
    '<font color=green>Done!</font><br />';
    }
    else
    {
            die(
    '<font color=red>Error:</font> could not move file.');
    }
    flush(); 
    Last edited by Majoracle; 01-07-2007 at 10:35 PM.

  • #3
    Regular Coder
    Join Date
    Sep 2006
    Location
    Colorado
    Posts
    132
    Thanks
    7
    Thanked 1 Time in 1 Post
    I changed it to this:
    PHP Code:
    $uploadfile $uploadpath.$filename;
        
    $uploadnewpath $uploadpath.$filename.rand(1,9999); 
        
    rename($uploadfile$uploadnewpath);
        if (
    move_uploaded_file($_FILES['externalfile']['tmp_name'], $uploadnewpath))
        {
        
            echo 
    '<font color=green>Done!</font><br />';
        
        } 
    Since I cant rename it after I move it if there is already a file with that name in the folder. So Im trying to rename it before I move it, but its not working and I dont know why.
    -bubbles


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •