Page 1 of 1

Rename a File Upload

Posted: Wed Feb 11, 2009 10:02 pm
by SheDesigns
I need a quick & easy way to add an order number before the existing filename.

Code: Select all

 
$target_path = "uploads/";
$target_path = $target_path . basename( $_FILES['image']['name']); 
 
if(move_uploaded_file($_FILES['image']['tmp_name'], $target_path)) {
    echo "Your file upload was successful.";
} else{
    echo "<b>ATTENTION:</b> There was an error uploading your file.";
}
 
It uploads fine, I just don't want too much code. I need it to take a file like, "MyDocument.jpg" and change it to "010809_MyDocument.jpg", when the order number is 010809, etc.

Please help :)

Re: Rename a File Upload

Posted: Wed Feb 11, 2009 10:12 pm
by John Cartwright

Code: Select all

 
$orderno = '010809';
$target_path = "uploads/". $orderno .'_'. basename( $_FILES['image']['name']); 
 
It is a simple matter of prepending the order name to your $target_path. You didn't specify where the order number comes from, so for the sake of this example I've hardcoded it.

Re: Rename a File Upload

Posted: Wed Feb 11, 2009 10:40 pm
by Ziq
I would be more cautious. This situation can totaly destroy a project if someone load *.php file. He/She get full control of your site. I recomend to check file extension before uploading or create special .htaccess file to prevent this type of attack.

Code: Select all

 
$allowedExt = array('.jpg', '.gif', '.png' /* , ...*/);
if (in_array(strrchr($_FILES['image']['name']), $allowedExt)) {
    //  Upload image
} else {
    //  Print an error message
}