如何在db中散列上传的文件名?

时间:2015-03-23 13:04:20

标签: php image hash mysqli

我有一张"个人资料图片"系统中每个注册用户都可以更改其个人资料图片,以便显示图片。上传的过程是将图像上传到名为pictures的文件夹中,然后将文件名写入名为"picture"的数据库行,它可以工作,一切都很好,但我需要知道如何哈希上传的图片的名称如果2个人有不同的图片,但同一个图片的名称会上传文件,那就会出现问题...

这是我提交的表格:

<form action="" method="post" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit" name="submit">
</form>

我有这个代码用于将文件上传到文件夹和数据库行:

<?php
    if(isset($_POST['submit'])){
        move_uploaded_file($_FILES['file']['tmp_name'],"pictures/".$user_id.$_FILES['file']['name']);
        $con = mysqli_connect("host","name","pass","db");
        $q = mysqli_query($con,"UPDATE members SET picture = '".$_FILES['file']['name']."' WHERE username = '".$_SESSION['username']."'");
    }
?>

以下是在网站上显示图片的代码:

<?php   
    $con = mysqli_connect("host","name","pass","db");
    $q = mysqli_query($con,"SELECT * FROM members WHERE username = '".$_SESSION['username']."'");
    while($row = mysqli_fetch_assoc($q)){
        if($row['picture'] == ""){
            echo " <img src='pictures/public_icon.png' width='25' height='25'>"; *//This is default pic//*
        } else {
            echo " <img width='25' height='25' src='pictures/".$row['picture']."' alt='Profile Pic'>"; *//And this is pic from db row//*
        }                                    
    }
?>

我想知道如何在上传的文件夹和数据库行中散列这张图片的名称...我可以这样做吗?我用&#34; id&#34;哈希吧。和&#34;日期&#34;从db开始,但我不知道如何...:/

2 个答案:

答案 0 :(得分:0)

使用此代替上传:

<?php
    if(isset($_POST['submit'])){

      /*
      * create a unique file name with the current time and ip address of 
      * user, since it is highly unlikely to have the same file uploaded 
      *form the same ip address at the same time
      */
      $unique_file_name = time(). $_SERVER['REMOTE_ADDR']. $_FILES['file']['name']; 

         //run query only if file upload and transfer succeeded
         if( move_uploaded_file($_FILES['file']['tmp_name'],"pictures/".$user_id. $unique_file_name) ){ 
            $con = mysqli_connect("host","name","pass","db");
            $q = mysqli_query($con,"UPDATE members SET picture = '".$_FILES['file']['name']."' WHERE username = '".$_SESSION['username']."'");
        }
    }
?>

答案 1 :(得分:-1)

你可以尝试这个

<?php
    if(isset($_POST['submit'])){
            $filename = $user_id.$_FILES['file']['name'];
            move_uploaded_file($_FILES['file']['tmp_name'],"pictures/".$filename);
            $con = mysqli_connect("host","name","pass","db");
            $q = mysqli_query($con,"UPDATE members SET picture = '".$filename."' WHERE username = '".$_SESSION['username']."'");
    } ?>