如何使用mongodb和php上传用户特定的图像

时间:2015-12-17 05:53:03

标签: php html mongodb

我正在制作Login应用程序,因为我希望用户插入应存储在mongodb中的图像。我上传了图片,但我无法找到如何区分mongodb中的用户特定图像。请帮忙。

2 个答案:

答案 0 :(得分:0)

当用户上传图像时,只需将图像重命名为其用户名的哈希值+时间或其他内容,并将图像名称存储在数据库中。然后,当您需要显示它时,只需将图像源设为url myfolder / $ userImage

答案 1 :(得分:0)

试试这个:

HTML文件:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="file_submit.php" method="POST">
    <input type="file" name="file">
    <input name="submit" id="submit" type="submit" value="Upload" />
</form>
</body>
</html>

PHP file_submit.php文件:

<?php

session_start();

// Connecting to mongoDB server
$m = new MongoClient();

// Selecting the Database
$db = $m->db_name;
// Selecting the collection
$collection = $db->collection_name;

if(isset($_FILES["file"])){

    $id = $_SESSION['id'];  // Taking user id stored in session.

    $path = "files/"; // Directory where your file name to be stored.
    $time = time();

    $file_name= $_FILES["file"]["name"];    // Storing file name in a variable.
    $file_size= $_FILES["file"]["size"];    // Taking file size.

    $file_new_name = $id.$time; // Adding id and time to file name to make a unique file name.

    $ext_arr = explode('.', strrev($file_name));
    $ext = $ext_arr[0];     // Getting File Extension
    $file_new_name = ".".$ext;  // Setting extension to new file name

    $dir = $path.$file_new_name;

    if(count($ext_arr)>1){
        if($file_size < 33554433){  // If you want to limit the size of the file (in byte)
            if(move_uploaded_file($_FILES['file']['tmp_name'], $path.$file_name)){
                if(@rename($path.$file_name,$dir)){
                    try{
                        $collection->insert(array("file_name"=> $file_new_name, "file_size"=>$file_size, "time"=> $time));
                        echo 'Successfully Uploaded';
                    }catch (MongoException $ex){
                        echo "There was some problem. ".$ex;
                    }
                }else{
                    echo "Sorry, there was a problem. Please Try again";
                }
            }else{
                echo "Sorry, there was a problem. Please Try again";
            }
        }else{
            echo "File Size is more than 32 MB";
        }
    }else{
        echo "Invalid File Name!";
    }
}else{
    echo "Sorry, there was a problem. Please Try again";
}

我知道帖子已经过时但如果您仍在寻找解决方案,这可能有所帮助。