将上传的文件名更改为当前会话user_id +时间

时间:2014-11-11 03:22:19

标签: php file-upload upload rename

我正在构建个人资料图片上传器并提出问题。我将如何更改上传到当前会话user_id +当前日期的文件名。

我的会话变量是$ _SESSION ['user_id'];

有没有办法将他们上传的文件 smiling_cat.jpg 重命名为 2_11102014.jpg ,同时保留其扩展名?

这就是我现在所拥有的。

<?php 
if (isset($_POST['submit']))
{
$path = '/home/marketplace/public_html/imgupload/profile_pic/';
$file_exts = array("jpg", "bmp", "jpeg", "gif", "png");
$upload_exts = end(explode(".", $_FILES["file"]["name"]));
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/png")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 2000000)
&& in_array($upload_exts, $file_exts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{
// move files to the path
move_uploaded_file($_FILES["file"]["tmp_name"], $path . $_FILES["file"]["name"]);

//echo a bunch of data to use at a later time
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br><hr>";
echo "<div class='sucess'>"."Stored in: " . $path . $_FILES["file"]["name"]."</div>";
echo '<img src="profile_pic/'.$_FILES["file"]["name"].'">';
}
}
else
{
echo "<div class='error'>Invalid file</div>";
}
}
?>

1 个答案:

答案 0 :(得分:1)

你可以这样做:

$ext = explode(".", $_FILES["file"]["name"]);

move_uploaded_file($_FILES["file"]["tmp_name"], $path . "whatever".end($ext));

顺便说一句,你应该检查一下操作

if(!move_uploaded_file($_FILES["file"]["tmp_name"], $path . "whatever".end($ext))){
    //deal with error
}
else{
    //rest of your code
}