How to replace entire file name minus extension with timestamp or unique number?

Discussion in 'PHP' started by Mitchell, Jun 20, 2010.

  1. #1
    I know str_replace() can replace spaces with _. For example

    str_replace(' ', '_', $_FILES['image']['name']);

    Is there a function or do you recommend a way to replace the entire file name but not the extension name with a unique ID like a time stamp or something?

    Thanks.
     
    Mitchell, Jun 20, 2010 IP
  2. Cozmic

    Cozmic Member

    Messages:
    146
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    48
    #2
    
     // Set "file" to whatever the file name is.
     $file = "foobar.html";
    
     // Gets the extension.
     preg_match("/([a-zA-Z0-9_-]+).([a-zA-Z0-9]+)/", $file, $extension);
    
     // Gets the current timestamp.
     $timestamp = time();
    
     // Combines the extension with the timestamp. You can remove the echo statement. Use the rename() function to rename the file. 
     $newName = $timestamp.$extension[2];
     echo $newName;
    
    PHP:
    If you want to make it absolutely 100% unique, then you can use file_exists() to figure out if the file actually exists, then if it does, adding a unique number to the end of the stamp. Unless you expect absurd traffic, it should be needed.
     
    Cozmic, Jun 20, 2010 IP
  3. Mitchell

    Mitchell Peon

    Messages:
    204
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Thanks for your response. I spent some time reviewing preg_match() in the three php books I have.

    Does the (.) period in "/([a-zA-Z0-9_-]+).([a-zA-Z0-9]+)/" represent the period in "foobar.html"?

    So it gets all the characters in "foobar.html" and stores them in $extension?

    Should this be $extension[1]?
    $newName = $timestamp.$extension[2];
     
    Mitchell, Jun 20, 2010 IP
  4. Mitchell

    Mitchell Peon

    Messages:
    204
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #4
    I think I am starting to figure it out.

    $extension[0] keeps the name and extension.
    $extension[1] keeps the name only.
    $extension[2] keeps the extension only.

    $newName = $timestamp.$extension[2]; concatenates the extension to the end of the time stamp like this.

    1277092118jpg

    Only problem is it leaves out the (.) between time stamp and jpg. Any idea how to fix this? Thanks.
     
    Mitchell, Jun 20, 2010 IP
  5. Cozmic

    Cozmic Member

    Messages:
    146
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    48
    #5
    
     // Set "file" to whatever the file name is.
     $file = "foobar.html";
    
     // Gets the extension.
     preg_match("/([a-zA-Z0-9_-]+).([a-zA-Z0-9]+)/", $file, $extension);
    
     // Gets the current timestamp.
     $timestamp = time();
    
     // Combines the extension with the timestamp. You can remove the echo statement. Use the rename() function to rename the file. 
     $newName = $timestamp.".".$extension[2];
     echo $newName;
    
    PHP:
    Updated to include the period. I forgot to include that.

    Preg_match fills the third argument with the result from the regular expression. $array[0] is the entire match and further items in the array are each parentheses you see in the expression. The expression basically says

    ([letters/numbers only]).([letters/numbers only])

    The period is the dot before the extension.
     
    Cozmic, Jun 20, 2010 IP
  6. Mitchell

    Mitchell Peon

    Messages:
    204
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #6
    Thank you it works.

    There is one last thing I noticed. If the file I am trying to upload has spaces in the name (foo bar.jpg), preg_match dose not seem to account for that.
     
    Mitchell, Jun 20, 2010 IP
  7. Cozmic

    Cozmic Member

    Messages:
    146
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    48
    #7
    
    // Set "file" to whatever the file name is.
     $file = "foobar.html";
     $file = str_replace(' ', '_', $file);
    
     // Gets the extension.
     preg_match("/([a-zA-Z0-9_-]+).([a-zA-Z0-9]+)/", $file, $extension);
    
     // Gets the current timestamp.
     $timestamp = time();
    
     // Combines the extension with the timestamp. You can remove the echo statement. Use the rename() function to rename the file. 
     $newName = $timestamp.".".$extension[2];
     echo $newName;
    
    PHP:
    Try that. I added the str_replace() to change spaces to underscores beforehand.
     
    Cozmic, Jun 20, 2010 IP
  8. Mitchell

    Mitchell Peon

    Messages:
    204
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #8
    That's perfect. Why didn't I think of that?

    I learned something today. Thanks for your help.
     
    Mitchell, Jun 20, 2010 IP
  9. henryaga

    henryaga Peon

    Messages:
    3
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #9
    hi,

    I have not a big knowledge of php and I would like find some help to add a "word" before the file name using this code:
    
     if($_SERVER['REQUEST_METHOD'] == 'POST') {
            
    		if($_FILES['image1']) {
                preg_match('/\.([A-Za-z]+?)$/', $_FILES['image1']['name'], $matches);
                $matches[1] = strtolower($matches[1]);
                if($matches[1] == 'png' && function_exists('imagecreatefrompng') || $matches[1] == 'jpg' && function_exists('imagecreatefromjpeg') || $matches[1] == 'jpeg' && function_exists('imagecreatefromjpeg') || $matches[1] == 'gif' && function_exists('imagecreatefromgif')) {
                    list($owidth, $oheight) = getimagesize($_FILES['image1']['tmp_name']);
                    if($_POST['width400'] == 'height') {
                        $nheight = ($_POST['size']>1)?$_POST['size']:600;
                        $nwidth = $nheight / $oheight * $owidth;
                        $resized = imagecreatetruecolor($nwidth, $nheight);
                    }
                    else {
                        $nwidth = ($_POST['size']>1)?$_POST['size']:800;
                        $nheight = $nwidth / $owidth * $oheight;
                        $resized = imagecreatetruecolor($nwidth, $nheight);
                    }
                    if($matches[1] == 'png')
                        $original = imagecreatefrompng($_FILES['image1']['tmp_name']);
                    if($matches[1] == 'jpg' || $matches[1] == 'jpeg')
                        $original = imagecreatefromjpeg($_FILES['image1']['tmp_name']);
                    if($matches[1] == 'gif')
                        $original = imagecreatefromgif($_FILES['image1']['tmp_name']);
    					
                    
                    imagecopyresampled($resized, $original, 0, 0, 0, 0, $nwidth, $nheight, $owidth, $oheight);
                    header('Content-Disposition: attachment; filename="'.$_FILES['image1']['name'].'"');
                    header('Content-type: image1/'.(($matches[1] == 'jpg')?'jpeg':$matches[1]));
                    if($matches[1] == 'png')
                        imagepng($resized);
                    if($matches[1] == 'jpg' || $matches[1] == 'jpeg')
                        imagejpeg($resized);
                    if($matches[1] == 'gif')
                        imagegif($resized);
                    exit();
                    
                } else
                    $error1 = 'Please use only supported file types ( JPG, JPEG, PNG or GIF )';
            } /* 
    		else
                $error1 = 'No image uploaded!';
    		*/	
        }
    
    PHP:

    something like this: "example.jpg" changed to "NEWexample.jpg" or "NEW.example.jpg" in the result file.

    THANKS A LOT!
     
    henryaga, Sep 28, 2010 IP
  10. danx10

    danx10 Peon

    Messages:
    1,179
    Likes Received:
    44
    Best Answers:
    2
    Trophy Points:
    0
    #10
    Replace the following line:

    header('Content-Disposition: attachment; filename="'.$_FILES['image1']['name'].'"');
    PHP:
    With:

    header('Content-Disposition: attachment; filename="NEW'.$_FILES['image1']['name'].'"');
    PHP:
     
    danx10, Sep 28, 2010 IP
  11. henryaga

    henryaga Peon

    Messages:
    3
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #11
    Hi Danx10,

    the code change the name, but I don't know why the resulting file (image) is damaged. Do you know why it could be happening? I already tested the code without the name change and it is working fine.

    Thanks
     
    henryaga, Sep 29, 2010 IP
  12. henryaga

    henryaga Peon

    Messages:
    3
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #12
    Hi Danx10,

    WORKS PERFECTLY! thanks.

    I got a problem when I tried it the first time, but I made a mistake when a saved the code (missing characters). I fixed that and everything is fine now.

    thanks again

    Thanks
     
    henryaga, Sep 29, 2010 IP