php - 上传文件到用户文件夹

标签 php mysql

我正在尝试在上传文件夹中创建一个新文件夹,以便用户可以将文件上传到自己的文件夹。 我可以使用 PHP 执行此操作还是需要在 MYSQL 中添加“LONGBLOB”列? 我读到将图像存储在数据库中不是好的做法

<?php
header('Content-Type: application/json');

$succeeded = [];
$failed =[];
$uploaded = [];
$allowed = ['png', 'gif', 'jpg'];

if(!empty($_FILES["file"])) {

    foreach ($_FILES['file']['name'] as $key => $name) {
        if ($_FILES['file']['error'][$key] === 0) {

            $temp = $_FILES['file']['tmp_name'][$key];

            $ext = explode('.', $name);

            $ext = strtolower(end($ext));

            $file = md5_file($temp) . time() . '.' . $ext;

            if (in_array($ext, $allowed) === true && move_uploaded_file($temp, "uploads/{$file}") === true) {
                $succeeded[] = array(
                                'name' => $name,
                                'file' => $file
                                );

            }else{
                $failed[] = array(
                    'name' => $name);
            }
        }
    }


}

if (!empty($_POST['ajax'])) {
    echo json_encode(array(
        'succeeded' => $succeeded,
        'failed' => $failed ));
}



?>

最佳答案

假设您在 session 变量中有用户的用户名或 ID,则可以将其用作他/她将上传文件的新文件夹的基础。 显然,当他们希望下载文件时,必须使用相同的用户名和 ID。通过存储散列和文件路径,您可以生成不显示文件名、文件夹路径、所有者等的链接,因为数据库可以检查散列并在需要时返回文件和路径。

以下是生成用户自己的文件夹并在上传过程中使用的未经测试的示例 - 希望它能给您一些想法/指导。

<?php


    $succeeded = [];
    $failed =[];
    $uploaded = [];
    $allowed = ['png', 'gif', 'jpg'];


    /*
        generate a suitable name for the new folder, 
        remove characters which might be troublesome
    */
    $userdir = str_replace( 
        array("'",'"','-'),
        array('','','_'),
        $_SESSION['username']
    );



    /* 
        new path into which the files are saved
        It might be better to have the files 
        stored outside of the document root.
    */
    $savepath = 'uploads/' . $userdir;



    /* create the folder if it does not exist */
    if( !file_exists( $savepath ) ) {
        mkdir( $savepath );
        chown( $savepath, $username );
        chmod( $savepath, 0644 );
    }



    if( !empty( $_FILES["file"] ) ) {

        foreach( $_FILES['file']['name'] as $key => $name ) {
            if( $_FILES['file']['error'][$key] === 0 ) {

                $temp = $_FILES['file']['tmp_name'][$key];

                /*
                    is there anything to be gained by hashing the filename?
                    the hash would be the same for filenames with the same 
                    name anyway.

                    If the file is large, calculating the hash of the file could
                    take some time...
                */
                $ext = explode('.', $name);
                $ext = strtolower( end( $ext ) );
                $file = md5_file( $temp ) . time() . '.' . $ext;


                /* generate a random hash to use in downloads */
                $hash=uniqid( md5( date(DATE_COOKIE) ) ); 


                /* here probably - store reference in db? Assign permissions based upon owner etc */
                $sql='insert into `table` (`filename`,`username`,`uid`,`datetime`,`hash`) values (?,?,?,?,?);';             

                /* bind params and execute - not shown */



                if ( in_array( $ext, $allowed ) === true && move_uploaded_file( $temp, "{$savepath}/{$file}") === true ) {
                    $succeeded[] = array( 'name' => $name, 'file' => $file );
                }else{
                    $failed[] = array( 'name' => $name );
                }
            }
        }
    }

    if (!empty($_POST['ajax'])) {

        header('Content-Type: application/json');
        echo json_encode(array(
            'succeeded' => $succeeded,
            'failed' => $failed ));
    } else {

        header( 'HTTP/1.1 404 Not Found', true, 404 );
    }
?>

关于php - 上传文件到用户文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38550374/

相关文章:

php - 为什么我的SELECT查询失败

php - 如何忽略 Laravel 的 ConvertEmptyStringsToNull 中的特定属性?

javascript - 将值从 javascript 插入数据库

php - 在 PHP 和 MySQL 中处理时区?

php将字符串匹配到多个关键字数组

php - MySQL:查询另一个查询结果并返回两个结果?

php - 显示特定ID的数据

java - 我使用逐步构建的 sql 请求不断收到 SQLError

php - 我如何将此类转换为与 mssql 一起使用

php - (2/2) ErrorException stdClass 类的对象无法在 laravel 5 中转换为 int