dongwuwu6104 2013-12-27 14:37
浏览 26
已采纳

在上传PHP时重命名文件

I am trying to build a script to upload and rename an image to a folder and store the path in my sql db.

Here is where I am at: The file get uploaded both to the folder and the pathname to the db but I cannot figure out how to rename the filename. Ideally I would like to make the filename unique so I don't duplicates.

<?php   
//preparing the patch to copy the uploaded file
$target_path = "upload/";

//adding the name of the file, finishing the path
$target_path = $target_path . basename( $_FILES['picture']['name']); 

//moving the file to the folder
if(move_uploaded_file($_FILES['picture']['tmp_name'], $target_path)) {
   echo "The file ".  basename( $_FILES['picture']['name']). 
   " has been uploaded";
} else{
  echo "There was an error uploading the file, please try again!";
}

//getting input from the form
$name = $_POST['name'];
$description = $_POST['description'];

//preparing the query to insert the values
$query = "INSERT INTO complete_table (name, description, picture) VALUES ('$name', '$description', '". $target_path ."')";

//opening connection to db
$link = mysql_connect('localhost', 'root', 'password');
if (!$link) {
   die('Could not connect: ' . mysql_error());
}

 //selecting a db
mysql_select_db("wcs_venues", $link) or die(mysql_error());

//running the query
$result = mysql_query($query) or die (mysql_error());

//closing the connection
mysql_close($link);

?>

I am new with all this and I am really trying but after looking at many tutorial and answered questions on Stack-overflow, I realized I needed help. Thank you in advance for helping this newbie.

  • 写回答

3条回答 默认 最新

  • dovt85093 2013-12-27 14:43
    关注

    Well, this is where you set the name of the file being saved:

    $target_path = "upload/";
    $target_path = $target_path . basename( $_FILES['picture']['name']);
    

    In this case, you're building the file name in the variable $target_path. Just change that to something else. What you change it to is up to you. For example, if you don't care about the name of the file and just want it to always be unique, you could create a GUID or a Unique ID and use that as the file name. Something like:

    $target_path = "upload/";
    $target_path = $target_path . uniqid();
    

    Note that this would essentially throw away the existing name of the file and replace it entirely. If you want to keep the original name, such as for display purposes on the web page, you can store that in the database as well.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口