TalkPHP

TalkPHP (http://www.talkphp.com/forums.php)
-   General (http://www.talkphp.com/general/)
-   -   Renaming Uploaded Files (http://www.talkphp.com/general/1313-renaming-uploaded-files.html)

CMellor 10-17-2007 08:51 PM

Renaming Uploaded Files
 
Hey,

Have made a script that basically uploads a file... nothing special. I wanted to rename each file with the user's username, so if my username is Test User the file would rename to test_user.ext.

When I echo out the username and file name, they appear correct, but when I upload the image, it renames it to Array.ext. Not sure why it's outputting as an array, when I echo it out normally, it shows.

Here's some code:

PHP Code:

<?php
// Rename file according to username
foreach(getUser($_COOKIE['userID']) as $info) {
    
$ext explode('.'$_FILES['upload_avatar']['name']);
    
$file_name str_replace($ext[0], strtolower($info['username']), $ext);
                
    
// Avatar directory
    
$directory 'images/avatar/'.$file_name.'.'.$ext[1];
    
// Move file to directory
    
move_uploaded_file($_FILES['upload_avatar']['tmp_name'], $directory);
}
?>

Can anyone see anything that I might have missed? Can't work my head around it :confused:

Thanks

Salathe 10-17-2007 10:12 PM

PHP Code:

// Old, wrong
$file_name str_replace($ext[0], strtolower($info['username']), $ext);

// New, slightly better
$file_name str_replace($ext[0], strtolower($info['username']), $_FILES['upload_avatar']['name']); 

You were trying to do a string replacement (str_replace()) on an array ($ext). If you read the PHP manual page, you'd know that if an array is used then the return value is also an array. Because of that, when you try to put together the $directory variable, PHP converts the $file_name array into a string: "Array". That's why your files were being called Array.ext.

CMellor 10-18-2007 02:12 AM

Wiked!

Thank you Salathe :)


All times are GMT. The time now is 03:30 PM.

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0