简体   繁体   English

使用登录的用户名创建目录

[英]Create Dir with logged-in username

i want my script to check if there exists a folder named with current logged in user if he's trying to upload file. 我希望我的脚本检查是否存在以当前登录用户命名的文件夹(如果他正在尝试上传文件)。 the script will check for folder if exists then the file will be uploaded to the folder with username if its doesn't exists the it will make new one and upload the file in it. 该脚本将检查文件夹是否存在,然后将该文件上传到带有用户名的文件夹(如果不存在该文件名),它将创建一个新文件夹并在其中上传文件。 currently my code is this : 目前我的代码是这样的:

<?php
$result = mysql_query("SELECT user_name FROM upl_users");
$row = mysql_fetch_assoc($result);
echo $row['user_name'];
if (!securePage($_SERVER['PHP_SELF'])) {
    die();
}

while ( $row = mysql_fetch_array($sql_res) ) {
    $username = $row['user_name'];
    $dir = "uploads/$username/";

    if (!is_dir($dir)) {

        mkdir($dir, 0777, true);
    }

    if (isset($_FILES["FileInput"]) && $_FILES["FileInput"]["error"] == UPLOAD_ERR_OK) {
        // ########### Edit settings ##############
        $UploadDirectory = 'uploads/$username/'; // specify upload directory ends with / (slash)
                                                                   // #########################################

        /*
         * Note : You will run into errors or blank page if "memory_limit" or "upload_max_filesize" is set to low in "php.ini". Open "php.ini" file, and search for "memory_limit" or "upload_max_filesize" limit and set them adequately, also check "post_max_size".
         */

        // check if this is an ajax request
        if (!isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
            die();
        }

        // Is file size is less than allowed size.
        if ($_FILES["FileInput"]["size"] > 5242880) {
            die("File size is too big!");
        }

        // allowed file type Server side check
        switch (strtolower($_FILES['FileInput']['type'])) {
            // allowed file types
            case 'image/png':
            case 'image/gif':
            case 'image/jpeg':
            case 'image/pjpeg':
            case 'text/plain':
            case 'text/html': // html file
            case 'application/x-zip-compressed':
            case 'application/pdf':
            case 'application/msword':
            case 'application/vnd.ms-excel':
            case 'video/mp4':
                break;
            default:
                die('Unsupported File!'); // output error
        }

        $File_Name = strtolower($_FILES['FileInput']['name']);
        $File_Ext = substr($File_Name, strrpos($File_Name, '.')); // get file extention
        $Random_Number = uniqid(); // Random number to be added to name.
        $NewFileName = $Random_Number . $File_Ext; // new file name

        if (move_uploaded_file($_FILES['FileInput']['tmp_name'], $UploadDirectory . $NewFileName)) {
            die('Success! File Uploaded.');
        } else {
            die('error uploading File!');
        }
    } else {
        die('Something wrong with upload! Is "upload_max_filesize" set correctly?');
    }
}

html : html:

<div id='upload-wrapper'>
<div align='center'>
<h3>Ajax File Uploader</h3>
<form action='upload.php' method='post' enctype='multipart/form-data' id='MyUploadForm'>
<input name='FileInput' id='FileInput' type='file' />
<input type='submit'  id='submit-btn' value='Upload' />
<img src='images/ajax-loader.gif' id='loading-img' style='display:none;' alt='Please Wait'/>
</form>
<div id='progressbox' ><div id='progressbar'></div ><div id='statustxt'>0%</div></div>
<div id='output'></div>
</div>
</div>

First, you should use uniqid() instead of rand(0, 9999999999) . 首先,您应该使用uniqid()而不是rand(0, 9999999999) It is both faster and less prone to duplicate results. 它既快又不易重复结果。

Second, you should check if the directory exists before moving the uploaded file: 其次,在移动上载的文件之前,应检查目录是否存在:

if (!file_exists($UploadedDirectory)) {
    // 0777 makes sure all users can write to the directory
    // true makes sure that any parent directories will be created if they also do not exist
    mkdir('path/to/directory', 0777, true);
}

Also in your while loop, you switch to using fetch_array, instead of fetch_assoc: 同样在while循环中,您切换到使用fetch_array而不是fetch_assoc:

while($row=mysql_fetch_assoc($sql_res)) { // fetch_array returns an indexed array
    $username=$row['user_name'];

Replace: 更换:

$dir = "uploads/<?php echo $username; ?>/";

With: 带有:

$dir = "uploads/$username/";

You don't need to use PHP tags inside of PHP. 您不需要在PHP内使用PHP标记。 Remove $UploadDirectory , it is a duplicate. 删除$UploadDirectory ,它是重复项。

Also, you need to fix your directory checking. 另外,您需要修复目录检查。 Change it from this: 从此更改:

if (!is_dir($dir)) {
    mkdir($dir, 0777, true);
}

To this: 对此:

if (!file_exists($dir)) {
    mkdir($dir, 0777, true);
}
// Will only reach this conditional if $dir exists, but is not a directory.
else if (!is_dir($dir)) {
    unlink($dir);
    mkdir($dir, 0777, true);
}

In a 100% PHP file, remove the ?> tag, you lose the risk of accidentally having added whitespace included by your PHP. 在100%PHP文件中,删除?>标记,您将失去意外添加PHP包含的空格的风险。

You need to use MySQLi variables if you are opening a MySQLi connection, not mysql functions: 如果要打开MySQLi连接而不是mysql函数,则需要使用MySQLi变量:

$mysqli = new mysqli($localhost, $username, $password, $database);
$result = $mysqli->query("SELECT user_name FROM upl_users");

// This will move the internal pointer and skip the first row, we don't want that.
//$row = mysql_fetch_assoc($result);
//echo $row['user_name'];

if (!securePage($_SERVER['PHP_SELF'])) {
    die();
}

while ( $row = $result->fetch_assoc() ) {
    $username = $row['user_name'];
    $dir = "uploads/$username/";
    // ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM