无法移动上传文件进行图片上传php

时间:2014-11-11 22:11:40

标签: php file-upload

帮助,我看过这个问题的其他答案,但我似乎无法解决这个问题。

我想将图片上传到“uploaded_files /”目录。 $ USER_ID);

然而它给了我错误:

** move_uploaded_file()[function.move-uploaded-file]:copy()函数的第二个参数不能是/home/dawn01/public_html/wp-content/wordpresstheme/twentyten/new_uploads.php上的目录第27行

PHP警告:move_uploaded_file()[function.move-uploaded-file]:无法在/ home / dawn01 / public_html / wp-content / themes / wordpresstheme /中将'/ tmp / phpkh4xzn'移动到'uploaded_files / 76'第27行的new_uploads.php **

这是我的代码:

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

1 个答案:

答案 0 :(得分:1)

让我们检查一下代码

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

让我们修复代码:

$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");
}

您还应该考虑验证上传的文件确实是图像。

$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 
}