将个人资料图片上传到用户单独的文件夹

时间:2015-07-10 20:58:33

标签: php mysqli

我想知道如何将图片/文件(pdf,ppt,doc's)放入用户各自的文件夹中。就像他/她上传她的头像,我希望它上传到路径: - www.oursite.com/uploads/profile_pics/username/filename.jpg。

我的问题是如何创建用户名目录。以下是代码段: -

if (isset($_FILES['pic']['name']))
{
  $_FILES['pic']['name'] = $pic_uniq_id;//already set using uniqid()
  $img_title = $_FILES['pic']['name'];
  $target_dest = "uploads/#profile_faces/HERE USERNAME FOLDER/".$img_title;
  $move = move_uploaded_file($_FILES['pic']['tmp_name'], $target_dest);
  if(!$move) {
    $img_msg = "<p class='pic_warning' color='red'><font color='red'><b>
    Sorry! Upload failed. Try again</b></font></p>";
    include 'includes/uploadprofilepicture.inc';
     exit();
  }else {//go on...}

如何使用用户名创建该目录?

3 个答案:

答案 0 :(得分:1)

使用

创建用户名目录
<%
set conn=Server.CreateObject("ADODB.Connection")
conn.ConnectionString="Provider=Microsoft.Jet.OLEDB.4.0"
conn.open server.mappath("database.mdb")

conn.close
%> 

答案 1 :(得分:1)

你可以这样做:

$user = "Username";
$path = "uploads/#profile_faces/".$user;
mkdir($path);
$target_dest = $path."/".$img_title;

答案 2 :(得分:1)

您必须从会话中获取用户名。因此,如果您将会话变量中的用户名保存为$_SESSION['username'],那么您的代码就像:

当您创建目录时,您必须确保您具有写入权限。

if (isset($_FILES['pic']['name'])) {

      if (!file_exists("uploads/#profile_faces/" . $_SESSION['username'] . "/")) {
        mkdir("uploads/#profile_faces/" . $_SESSION['username'] . "/", 0777, true);
      }

      $_FILES['pic']['name'] = $pic_uniq_id;//already set using uniqid()
      $img_title = $_FILES['pic']['name'];
      $target_dest = "uploads/#profile_faces/" . $_SESSION['username'] . "/".$img_title;
      $move = move_uploaded_file($_FILES['pic']['tmp_name'], $target_dest);

      if(!$move) {
        $img_msg = "<p class='pic_warning' color='red'><font color='red'><b>
        Sorry! Upload failed. Try again</b></font></p>";
        include 'includes/uploadprofilepicture.inc';
         exit();
      }

} else {
    //go on...
}