简体   繁体   中英

How can upload a file using php, then use it's name to create a folder and move it within that folder?

$fileDestination = "../assets/movies/posters/" . strtolower($formattedMovieName);
 if(mkdir("../assets/movies/" . strtolower(str_replace(' ', '-', $file[0])))) {
   sleep(1);
   move_uploaded_file($fileTmpName, "../assets/movies/" . strtolower(str_replace(' ', '-', 
   $file[0])));
} else {
  header("location: create.php?error=trysomethingelse");
  exit();
}                }

That's the code. The interesting thing is that I can upload to a premade folder just fine. Or I can make a folder just fine, but I can't do both. The code right now creates a folder where I want it but doesn't place the file there. I get an unable to move error. I did some googling and I thought that pausing exception of the code would help but it didn't. You're help is greatly appreciated.

Uploading an Image is pretty simple.

<input name="img" type="file" accept="image/*"> //accept just Image

// getting image
$image = $_FILES['img'];

$img_name = $image['name'];        // name of file
$img_error = $image['error'];      // check if there is any error in file
$img_tmp = $image['tmp_name'];    //name of the file stored on the web server's hard disk in the system temporary file directory

$img_ext = explode('.', $img_name);     //cut the file name at '.' to get extension name
$img_check = strtolower(end($img_ext));    // convert extension name to lowercase
$img_ext_check = array('png', 'jpg', 'jpeg');   // file extensions, you want to accept, (you can add more)

if(in_array($img_check, $img_ext_check)){     // check if extension of file is valid or not
    
    $img_first_name = explode('.', $img_name)[0];   //getting name of file without extension to create a folder of it's name
    
    mkdir('/path/.$img_first_name.');       //create folder
     
    $img_destination = '.$img_first_name./'.$img_name;
    move_uploaded_file($img_tmp, $img_destination);   // file moved into folder

  //upload file to database
  $insert_query = "INSERT INTO `your_table` (`Image`) VALUES ('$img_destination')";

  $fire_query = mysqli_query($con, $insert_query);
}

I have just written a random code and haven't tested it on server. It might have some syntax errors. So, compromise with that.

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