Reputation: 15
Help, Ive looked at other answers to this problem, but I can't seem to solve this.
I want to upload an image to the directory "uploaded_files/" . $user_id);
However its giving me the error:
**move_uploaded_file() [function.move-uploaded-file]: The second argument to copy() function cannot be a directory in /home/dawn01/public_html/wp-content/wordpresstheme/twentyten/new_uploads.php on line 27
PHP Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move '/tmp/phpkh4xzn' to 'uploaded_files/76' in /home/dawn01/public_html/wp-content/themes/wordpresstheme/new_uploads.php on line 27**
Here is my code:
session_start();
$_SESSION['user_no'];
$startuplistingno = $_POST['startup_listing_no'];
//creating directory within uploaded files called user id
$dir = 'uploaded_files/'. $_SESSION['user_no'];
if ( !file_exists($dir) ) {
mkdir ($dir, 0744);
$temp = explode(".",$_FILES["file"]["name"]);
$newfilename = $_SESSION['user_no'];
move_uploaded_file($_FILES["file"]["tmp_name"],
"uploaded_files/" . $newfilename);
}
Upvotes: 1
Views: 1899
Reputation: 16516
Lets examine the code
$dir = 'uploaded_files/'. $_SESSION['user_no'];
// create a directory like uploaded_files/12345
if ( !file_exists($dir) ) {
// read permissions on a directory without execute permissions
// are kinda useless 700 or 755 makes more sense.
mkdir ($dir, 0744);
$newfilename = $_SESSION['user_no'];
// now here we are attempting to create a new file called
// uploaded_files/12345
// But this is an already existing directory (we just created it)
move_uploaded_file($_FILES["file"]["tmp_name"],
"uploaded_files/" . $newfilename);
}
Lets fix the code:
$dir = 'uploaded_files/'. $_SESSION['user_no'];
if (!file_exists($dir)) {
if (!mkdir($dir, 0700)) {
http_send_status(500);
die("Could not upload file");
}
}
$tmp_name = $_FILES["file"]["tmp_name"];
// create a path with file name like:
// uploaded_files/12345/730e109bd7a8a32b1cb9d9a09aa2325d2430587ddbc0c38bad911525.ext
$newfilename = $dir . '/' . hash_file('sha256', $tmp_name) . 'ext';
$success = move_uploaded_file(tmp_name, $newfilename);
if (!$success) {
http_send_status(500);
die("Could not upload file");
}
You should also look into verifying that the uploaded file is indeed an image.
$info = getimagesize($_FILES['image']['tmp_name']);
// image/jpeg does not have to be just jpeg but a list of
// mime types you will accept
if (is_array($info) && isset($info['mime']) && $info['mime'] === 'image/jpeg') {
// then move the file to permanent storage
}
Upvotes: 1