【问题标题】:How to create a folder with an image inside of it PHP如何创建一个包含图像的文件夹 PHP
【发布时间】:2023-11-30 20:40:01
【问题描述】:

当用户注册到我的网站时,我想创建一个文件夹,其中包含他们的用户名和默认的个人资料图片。我知道如何制作文件夹,但是如何制作包含文件的文件夹。

文件夹应如下所示:

/users/pcoulson/

(pcoulson 将是用户的用户名)

../pcoulson/ 应该有默认的个人资料图片,如下所示:

/users/pcoulson/default-profile_pic.png

我将如何使用 PHP

做到这一点

【问题讨论】:

  • default-profile_pic.png 来自哪里?你只是问如何复制文件..?

标签: php file-upload mkdir


【解决方案1】:
$dir='users/'.$username;
mkdir($dir);
copy('default-profile_pic.png',$dir.'/default-profile_pic.png'

【讨论】:

    【解决方案2】:
    if(isset($_POST['add-user-submit']) && isset($_FILES['image']['name']))
    {
        #label the form inputs
        $username = $_POST['username'];
        $image = $_FILES["image"]["name"]; // The file name
        $fileTmpLoc = $_FILES["image"]["tmp_name"]; // File in the PHP tmp folder
        $fileType = $_FILES["image"]["type"]; // The type of file it is
        $fileSize = $_FILES["image"]["size"]; // File size in bytes
        $fileErrorMsg = $_FILES["image"]["error"]; // 0 = false | 1 = true
        $kaboom = explode(".", $eventFlyer); // Split file name into an array using the dot
        $fileExt = end($kaboom); // Now target the last array element to get the file extension
    
        if(!$fileTmpLoc)
        {
            $error =  "Please insert ALL fields";
        }
        elseif($fileSize > 2097152 )
        {
            $error =  "ERROR: Your file was larger than 2 Megabytes in size.";
            unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
        }
        elseif(!preg_match("/.(gif|jpg|png)$/i", $image))
        {
            $error =  "ERROR: Your image was not .gif, .jpg, or .png.";
            unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
        }
        else if ($fileErrorMsg == 1)
        {
            $error =  "ERROR: An error occured while processing the file. Try  again.";
        }
        else
        {
    
            # move the file to a folder
            $moveResult = move_uploaded_file($fileTmpLoc,  "you file directory ex(../img/users/$username)");
    
            if($moveResult != true) // there was an error uploading the file to the folder
            {
                $error =  "ERROR: File not uploaded. Try again.";
                unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
            }
    

    【讨论】:

    • @user3112869 谢谢我刚刚写了一个类似的脚本,所以我想到了它
    【解决方案3】:

    我建议将图像保存在后备存储中,即您的数据库中。

    这样做,图像与用户“密切相关”。一旦用户名更改,它不会变得无关紧要。

    【讨论】:

    • @Muhammet 绝对!使用 mySQL,您可能希望使用 MEDIUMBLOB 或 MEDIUMBTEXT 类型。
    • 但是 db 中的文件路径绝对是要走的路
    • @Muhammet 不,实际上,在数据库中存储图像并没有性能损失。
    【解决方案4】:
    1. 您首先必须创建文件夹
    2. 将图片复制到新生成的文件夹中。

    假设您将用户数据退休到$userdata 变量。你可以制作这样的文件夹 我假设您的default_picusers 位于同一目录中。

     $new_directory = 'users/'.$userdata['username'];
     mkdir($new_directory,0777);
     copy('default-profile_pic.png',$new_directory.'/default-profile_pic.png');
    

    【讨论】: