简体   繁体   中英

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 :

<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) . 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($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. Remove $UploadDirectory , it is a duplicate.

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.

You need to use MySQLi variables if you are opening a MySQLi connection, not mysql functions:

$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/";
    // ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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