Php image loading and naming error

I have a small form to add categories. My table fields are as follows:

Name Required

Description Not required

Photo Not required

It will create a category with all the information, it will even enter the name of the image into the database.

The problem I am facing is not moving the image to the uploads folder. Also it will rename the image like this: if the name of the image is avatar .jpg, it will rename it to database field 85789avatar.jpg.

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

and the last problem is that 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");      

      

+3


source to share


1 answer


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

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

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

      

To do this (to add the filename to the folder):



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

      

the last problem is that 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 boolean , the code can be updated to only insert a record if the file was uploaded successfully.

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(); 
}

      

+1


source







All Articles