我需要使用php重命名上传到服务器的文件,并在文件上添加时间戳。我已经编写了一个代码,并显示了该代码,例如:logicgates.docx-29-Aug-2018 19-55-36.docx
而不是:logicgates-29-Aug-2018 19-55-36.docx
,但文件名中间没有文件扩展名。
<?php
session_start();
date_default_timezone_set('Africa/Harare');
$date = date("d-M-Y H-i-s");
//$time = time("h-i-sa");
$targetfolder = "uploads/";
$allowedMimes = ['application/pdf','application/msword','text/plain','application/vnd.openxmlformats-officedocument.wordprocessingml.document',];
$targetfolder = $targetfolder . basename( $_FILES['file']['name']) ;
$type=pathinfo($targetfolder,PATHINFO_EXTENSION);
$ok=1;
$file_type=$_FILES['file']['type'];
if (in_array($_FILES['file']['type'], $allowedMimes))
{
if(move_uploaded_file($_FILES['file']['tmp_name'], $targetfolder))
{
//add date and time stamp to the uploaded file
if (file_exists($file_type))
{
$_SESSION['message']= "Sorry, file already exists. Please rename if you still want to upload it.";
header("location:lecsubmit?error") ;
}
else{
rename("uploads/".$_FILES['file']['name'],"uploads/".$_FILES['file']['name']."-".$date.".".$type);
$_SESSION['message'] ="The file ". basename( $_FILES["file"]["name"]). " submitted successfully.";
header("location:lecsubmit?done") ;
}
}
else {
$_SESSION['message']= "Sorry, your file was not uploaded.";
header("location:lecsubmit?error") ;
}
}
else {
$_SESSION['message']= "You may only upload PDFs, DOCXs, DOCs or TXT files..";
header("location:lecsubmit?error") ;
}
?>
答案 0 :(得分:0)
找到最后一个点“。”,剪掉左侧部分,添加时间戳并添加右侧部分:
$file = "uploads/" . $_FILES['file']['name'];
$lastDot = strrpos($file, '.');
$newFile = substr($file, 0, $lastDot) . "-$date." . substr($file, $lastDot + 1);
rename($file, $newFile);
编辑: 通过 strrpos @Elementary建议的方法更改了 str_replace 。
答案 1 :(得分:0)
您可以先删除该扩展名:
map