简体   繁体   中英

how to rename uploaded image file in php

I want to rename every image file i upload. I am working for a e-commerce site, i want to upload each image with their product name and ID from database.

Product name should be like (4124-01.jpg) at the end and upload its name to the database. where 4124 is product name and 01 is ID .

I am new in PHP and stackoverflow both.

Thank you in advance.

here's a little code::::::::

if(is_uploaded_file($_FILES['image']['tmp_name'])){
    $allowed=array('image/jpg','image/jpeg','image/gif','image/x-png','image/png');
    if(in_array($_FILES['image']['type'],$allowed)){
        echo 'Allowed format. Wait a little for completion of this task.';
    }else{
        $errors[]='Invalid format of image file. Please select a jpg, jpeg or png file.';
    }  // End of if(in_array($_FILES['image']['type'],$allwed)){

    $temp='../products/'.($_FILES['image']['name']);
    if(move_uploaded_file($_FILES['image']['tmp_name'],$temp)){
        $product_name=$_FILES['image']['name'];
        echo '<p>'.$product_name .'has been uploaded';
        echo '<img src="../products/'.$product_name.'" width="300" height="300">';
    }else{
        $errors[]='The image could not be moved. Check your directories.';
    } // End of if(move_uploaded_file($_FILES['image']['tmp_name'],$temp)){

}else{
    $errors[]='You did not select a product image.';
}  // End of if(is_uploaded_file($_FILES['image']['tmp_name'])){

Any help would be appreciated.

If you already have the product's id and name, that should be the value of your $temp variable.

You can get the extension with the following code:

$extension = strtolower(substr(strrchr($_FILES['image']['name'], '.'), 1));

And concatenated with your desired name.

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM