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.

图片转代码服务由CSDN问答提供 功能建议

我正在尝试构建一个脚本来上传图像并将其重命名为文件夹并将路径存储在我的sql db中 。 </ p>

这就是我所处的位置:文件上传到文件夹和db的路径名,但我无法弄清楚如何重命名文件名。 理想情况下,我想使文件名唯一,所以我不重复。</ p>

 &lt;?php 
 //准备补丁以复制上传的文件
 $ target_path  =“upload /”; 
 
 //添加文件名,完成路径
 $ target_path = $ target_path。  basename($ _FILES ['picture'] ['name']);  
 
 //将文件移动到文件夹
if(move_uploaded_file($ _ FILES ['picture'] ['tmp_name'],$ target_path)){
 echo“文件”。  basename($ _FILES ['picture'] ['name'])。  
“已上传”; 
}其他{
 echo“上传文件时出错,请重试!”; 
} 
 
 //从表单输入
 $ name =  $ _POST ['name']; 
 $ description = $ _POST ['description']; 
 
 //准备查询以插入值
 $ query =“INSERT INTO complete_table(name,description,picture)  VALUES('$ name','$ description','“。$ target_path。”')“; 
 
 //打开与db 
 $ link = mysql_connect('localhost','root','password)的连接 '); 
if(!$ link){
 die('无法连接:'。mysql_error()); 
} 
 
 //选择db 
mysql_select_db(“wcs_venues”,$ link)或 die(mysql_error()); 
 
 //运行查询
 $ result = mysql_query($ query)或die(mysql_error()); 
 
 //关闭连接
mysql_close($ link);  
 
?&gt; 
 </ code> </ pre> 
 
 

我是新手所有这些我真的很努力但是看了很多教程并回答了关于堆栈溢出的问题,我 意识到我需要帮助。 提前感谢您帮助这位新手。</ p> </ div>

3条回答 默认 最新

相关推荐 更多相似问题