Case
Case

Reputation: 281

Php image upload and naming failure

I have a small form to add categories. My table fields are the following:

Name Required

Description Not Required

Photo Not Required

It will create a category with all the information, it will even insert the image name in the database.

The problem I am having is it will not move the image to the uploads folder. Also it will rename the image as follows: If image name is avatar.jpg it will rename it 85789avatar.jpg in the database field.

I need it to rename the image as follows O1CCJDSXBOM2.jpg.

and the last issue is the image is not required and if you leave it blank it still puts 89439 numbers in the database field.

if (isset($_POST['submit'])) {

         $Name = $_POST['name'];
         $Description = $_POST['description']; 

         if (empty($Name)) {
             $errors[] = "Name Required.";
         }
         if (!empty($errors)) {
             echo validation_errors($errors[0]);

         } else {

         $file = rand(1000, 100000). $_FILES['photo']['name'];
         $file_loc = $_FILES['photo']['tmp_name'];
         $file_size = $_FILES['photo']['size'];
         $folder = "uploads/";

         if (($file_size > 2097152)) {         

             echo validation_errors("Your avatar exceeds file size");        

         } else {

        move_uploaded_file($file_loc, $folder, $file);

        $db = dbconnect();
        $stmt = $db->prepare("INSERT INTO discussion_categories(Name, Description, Photo) VALUES (?,?,?)");
        $stmt->bind_param('sss', $Name, $Description, $file);
        $stmt->execute();        
        $stmt->close(); 

        header("Location: managecategories.php");      

Upvotes: 3

Views: 50

Answers (1)

Sᴀᴍ Onᴇᴌᴀ
Sᴀᴍ Onᴇᴌᴀ

Reputation: 8297

it will not move the image to the uploads folder also it will rename the image as follows. if image name is avatar.jpg ti will rename it 85789avatar.jpg in the database field

move_uploaded_file() takes two arguments, not three. Update this line:

move_uploaded_file($file_loc, $folder, $file);

To this (to append the filename to the folder):

move_uploaded_file($file_loc, $folder . $file);

the last issue is the image is not required and if you leave it blank it still puts 89439 numbers in the database field.

Because move_uploaded_file() returns a boolean, the code could be updated to only insert a record if the file was successfully uploaded.

if (move_uploaded_file($file_loc, $folder . $file)) {
    $db = dbconnect();
    $stmt = $db->prepare("INSERT INTO discussion_categories(Name, Description, Photo) VALUES (?,?,?)");
    $stmt->bind_param('sss', $Name, $Description, $file);
    $stmt->execute();        
    $stmt->close(); 
}

Upvotes: 1

Related Questions