使用php在文件名中添加时间戳

问题描述 投票:0回答:2

我需要使用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") ;
}
?>
php
2个回答
0
投票

找到最后一个点“。”,剪切左侧部分,添加时间戳并添加正确的部分:

$file = "uploads/" . $_FILES['file']['name'];
$lastDot = strrpos($file, '.');
$newFile = substr($file, 0, $lastDot) . "-$date." . substr($file, $lastDot + 1);

rename($file, $newFile);

编辑:通过@Elementary建议的strpos方法更改了str_replace。


0
投票

你可以先删除扩展名:

 rename("uploads/".$_FILES['file']['name'],"uploads/".substr($_FILES['file']['name'],0,strrpos($_FILES['file']['name'],'.'))."-".$date.".".$type);
© www.soinside.com 2019 - 2024. All rights reserved.