从上传到数据库重新命名文件名

时间:2012-05-22 17:33:26

标签: php mysql database file-upload rename

我真的需要一些帮助。我需要将文件的新名称发布到数据库。目前此代码是将原始名称发布到数据库?如何将新名称发布到数据库?请参阅下面的代码。

<form action="" method="post" enctype="multipart/form-data">
<p>
    <label for="file">Name:</label>
    <input type="text" name="user_name" id="name" size="24"/> 
</p>
<p>
    <label for="file">Email Address:</label>
    <input type="text" name="email" id="email" size="24"/> 
</p>
<p>
    <label for="file">Phone Number:</label>
    <input type="text" name="phone" id="phoneNumber" size="24"/> 
</p>
<p>
    <label for="file">Comments:</label>
    <textarea cols="80" rows="6" name="comments"></textarea> 
</p>
<p>
    <label for="file">Filename:</label>
    <input type="file" name="fupload" id="fupload" size="24"/>
</p>
<br />
<input type="submit" name="submit" value="Submit" />
</form>
<br>
<br>
<?php
    require 'config.php';
    require 'functions.php';

    if(isset($_FILES['fupload'])) {
        if(preg_match('/[.](jpg)|(gif)|(png)$/',       $_FILES['fupload']['name'])) {
            $old_filename = $_FILES['fupload']['name'];
            $random_digit=rand(0000,9999);
            $filename=$random_digit . $old_filename;
            $source = $_FILES['fupload']['tmp_name'];
            $target = $path_to_image_directory . $filename;

            move_uploaded_file($source, $target);

            createThumbnail($filename);
        }
    }

    include "connect.php";
    $db_database = new mysqli($db_host, $db_user, $db_pass, $db_database);

    $user_name = stripslashes($_POST['user_name']);
    $email = stripslashes($_POST['email']);
    $phone = stripslashes($_POST['phone']);
    $comments = stripslashes($_POST['comments']);
    $filename = basename( $_FILES['fupload']['name']);

    $query = "INSERT into upload
          (user_name, email, phone, comments, fupload, date_added)
          values ('$user_name', '$email', '$phone', '$comments', '$filename', NOW())";
    $db_database->query($query);
?>

1 个答案:

答案 0 :(得分:1)

您需要调整一行:

$filename = basename( $_FILES['fupload']['name']);

在创建SQL语句之前;您应该将$filename的值设置为文件的新名称。

哦,我确信有人会在短时间内指出您的脚本对SQL注入是开放的。