Rename a File Upload

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
SheDesigns
Forum Commoner
Posts: 42
Joined: Tue Nov 18, 2008 9:51 am
Location: Buffalo, NY

Rename a File Upload

Post 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 :)
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Re: Rename a File Upload

Post 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.
User avatar
Ziq
Forum Contributor
Posts: 194
Joined: Mon Aug 25, 2008 12:43 am
Location: Russia, Voronezh

Re: Rename a File Upload

Post 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
}
 
Post Reply