文件上传个人资料头像

时间:2014-09-09 09:08:46

标签: php

我正在尝试创建一个社交网站,我一直在观看教程,用户可以上传他们的个人资料图片并更改他们的头像。但是,每当我尝试上传图片时,它都会给我一个错误“文件上传失败”我不太确定如何解决它或者究竟要做什么。我究竟需要转储用户上传的所有图片?

photo_system.php

<?php 
    if (isset($_FILES["avatar"]["name"]) && $_FILES["avatar"]["tmp_name"] != ""){
        $fileName = $_FILES["avatar"]["name"];
        $fileTmpLoc = $_FILES["avatar"]["tmp_name"];
        $fileType = $_FILES["avatar"]["type"];
        $fileSize = $_FILES["avatar"]["size"];
        $fileErrorMsg = $_FILES["avatar"]["error"];
        $kaboom = explode(".", $fileName);
        $fileExt = end($kaboom);
        list($width, $height) = getimagesize($fileTmpLoc);


        $sql = "SELECT avatar FROM users WHERE username='$log_username' LIMIT 1";
        $query = mysqli_query($db_conx, $sql);
        $row = mysqli_fetch_row($query);
        $avatar = $row[0];
        if($avatar != ""){
            $picurl = "../user/$log_username/$avatar"; 
            if (file_exists($picurl)) { unlink($picurl); }
        }
        $moveResult = move_uploaded_file($fileTmpLoc, "../user/$log_username/$db_file_name");
        if ($moveResult != true) {
            header("location: ../message.php?msg=ERROR: File upload failed");
            exit();
        }

user.php的

$profile_pic = "";
$profile_pic_btn = "";
$avatar_form = "";

// Check to see if the viewer is the account owner
$isOwner = "no";
if($u == $log_username && $user_ok == true){
    $isOwner = "yes";
    $profile_pic_btn = '<a href="#" onclick="return false;" onmousedown="toggleElement(\'avatar_form\')">Toggle Avatar Form</a>';
    $avatar_form  = '<form id="avatar_form" enctype="multipart/form-data" method="post" action="php_parsers/photo_system.php">';
    $avatar_form .=   '<h4>Change your avatar</h4>';
    $avatar_form .=   '<input type="file" name="avatar" required>';
    $avatar_form .=   '<p><input type="submit" value="Upload"></p>';
    $avatar_form .= '</form>';
}

1 个答案:

答案 0 :(得分:0)

如果不存在,首先创建目录

  if($avatar != ""){
           $picurl = "../user/$log_username/$avatar"; 
           if (file_exists($picurl)) { unlink($picurl); }
               if(!file_exists($picurl)){
                  mkdir($picurl, 0777,true);
               }
     }