如何在php上传到数据库之前更改图像文件名

时间:2015-06-23 13:39:32

标签: php html mysql

如何在插入数据库之前重命名图像文件?

  • 数据库名称:项目
  • 表名:image
  • ields:id(int),文件(varchar)[此处存储的图片网址],名称(varchar)[图片说明]

HTML代码在这里

<form method="POST" action="signup_process.php" enctype="multipart/form-data">
 Image:  <input type="file" name="user_image">
<input tyoe="submit" value="submit">
 </form>

signup_process.php

 <?php
    include 'dbcon.php';
    $filename = $_FILES[user_image][name];
    $source = $_FILES[customer_photo][tmp_name];
    $destination = "photos/$filename";
    move_uploaded_file($source, $destination);

//sql statement bla bla below to upload file in image table

    ?>

此脚本将文件上传到我的服务器的照片目录中,但我想要的是我想将该名称更改为我的图像表的相应ID。 例如sunshine.jpg - &gt; 5.jpg

2 个答案:

答案 0 :(得分:1)

Please Check below code ,is working for me.

$source = $_FILES[customer_photo][tmp_name];
$temp = explode(".",$_FILES["user_image"]["name"]);
$newfilename = rand(1,99999) . '.' .end($temp); //you can change here random id replace the your id
$destination = "photos/$newfilename";    
move_uploaded_file($source, $destination);

答案 1 :(得分:1)

如果您想在将文件名移至其最终位置之前更改文件名,只需更改此行:

$destination = "photos/$filename";

到此:

$path_parts = pathinfo($_FILES["user_image"]["name"]);
$extension = $path_parts['extension'];
$destination = "photos/<the name you want>." . $extension;