-2

再次回到另一个新手问题。我一直在编写一个文档,该文档将允许用户将他们自己的头像上传到我正在创建的博客中学习一些 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>

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

4

2 回答 2

2

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

于 2013-10-02T06:33:07.467 回答
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)) { 
于 2013-10-02T06:56:02.590 回答