添加用户头像时无法move_uploaded_file

时间:2013-10-02 06:30:03

标签: php html forms file

再次回到另一个新手问题。我一直在研究一个文档,它允许用户将自己的头像上传到我正在创建的博客中学习一些PHP。我已经在这个文档上工作了两天了,我已经花了六个多小时的时间来搜索和尝试不同的东西来修复它但是我无法让它超越它:

if(move_uploaded_file($_FILES['avatar']['name'], $target)){ 

    //good message
    echo "Your avatar was successfully uploaded."; 
    }else{
    //bad message
    echo "Your avatar couldnt be uploaded, please contact an admin."; 
    }

在尝试不同的解决方案大约一个小时后,它确实发送了“坏消息”,但我不太清楚为什么它会给我“坏消息”,对我来说一切看起来还不错。

完整代码:

<?php
session_start();

if (isset($_SESSION['username'])){


if (isset($_POST['submit']) && isset($_FILES['avatar'])) {
        $con = mysql_connect("localhost","root","");
        if (!$con){
            die('Could not connect: ' . mysql_error());
        }

    mysql_select_db('webserver', $con);

    $username = $_SESSION['username'];

    $query = "SELECT * FROM users WHERE username = '$username'";

    $result = mysql_query($query);                   
    $row = mysql_fetch_array($result);

    $id = $row['id'];

    //Directory to save stuff
    $target = "images/useravatars"; 
    $target = $target . basename($_FILES['avatar']['tmp_name']);

    //Save the avatar
    if(move_uploaded_file($_FILES['avatar']['name'], $target)){ 

    //good message
    echo "Your avatar was successfully uploaded."; 
    }else{
    //bad message
    echo "Your avatar couldnt be uploaded, please contact an admin."; 
    }
}else{
echo "38";
}
}
?>

<form enctype="multipart/form-data" action='uploadavatar.php' method='POST'>
    <table>
        <tr>
            <td>
            Upload an avatar:
            </td>
        </tr>
            <td>
            <input type='file' name='avatar'>
            </td>
        </tr>
    </table>
    <p>
        <input enctype='multipart/form-data' type='submit' name='submit' value='Submit'>
    </p>
</form>

顺便说一句,对不起,那里可能有一堆无用的代码,我花了很多时间才把它弄得足够远,给我一个错误。

2 个答案:

答案 0 :(得分:2)

上传文件存储在磁盘上的位置是$_FILES['avatar']['tmp_name']。您想移动那个,而不是$_FILES['avatar']['name']

答案 1 :(得分:0)

问题在于,您以错误的方式使用move_uploaded_file()。 第一个参数需要一个带扩展名的文件名,没有基本路径,比如 mypic.jpg。第二个需要一个应该上传该文件的目的地。

至于你的代码,

替换它,

//Directory to save stuff
$target = "images/useravatars"; 
$target = $target . basename($_FILES['avatar']['tmp_name']);

//Save the avatar
if(move_uploaded_file($_FILES['avatar']['temp'], $target)){ 

// I'd assume that dirname(__FILE__) refers to your root

//Directory to save stuff
$destination = sprintf('%s/images/useravatars/%s', dirname(__FILE__), $_FILES['avatar']['name']); 

//Save the avatar
if (move_uploaded_file($_FILES['avatar']['tmp_name'], $destination)) {