【问题标题】:How do I rename a image file with timestamp when uploaded on my server?上传到服务器时如何重命名带有时间戳的图像文件?
【发布时间】:2017-10-02 01:42:49
【问题描述】:

这是来自upload.php 的我的代码,单击“上传”按钮后将发布到该代码。我的目标是让上传的图像文件按时间戳重命名,请帮助!

<?php require_once("includes/connection.php"); ?>
<?php require_once("includes/functions.php"); ?>
<?php
//turn on php error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);

if ($_SERVER['REQUEST_METHOD'] == 'POST') {

    $name     = $_FILES['file']['name'];
    $tmpName  = $_FILES['file']['tmp_name'];
    $error    = $_FILES['file']['error'];
    $size     = $_FILES['file']['size'];
    $ext      = strtolower(pathinfo($name, PATHINFO_EXTENSION));

    switch ($error) {
        case UPLOAD_ERR_OK:
            $valid = true;
            //validate file extensions
            if ( !in_array($ext, array('jpg','jpeg','png','gif')) ) {
                $valid = false;
                $response = 'Invalid file extension.';
            }
            //validate file size
            if ( $size/1024/1024 > 2 ) {
                $valid = false;
                $response = 'File size is exceeding maximum allowed size.';
            }
            //upload file
            if ($valid) {
                $targetPath =  dirname( __FILE__ ) . DIRECTORY_SEPARATOR. 
            'uploads' . DIRECTORY_SEPARATOR. $name;
                move_uploaded_file($tmpName,$targetPath); 
                header( 'Location: CheckTooth.php' ) ;
                exit;
            }
        break;
    case UPLOAD_ERR_INI_SIZE:
        $response = 'The uploaded file exceeds the upload_max_filesize 
        directive in php.ini.';
        break;
    case UPLOAD_ERR_PARTIAL:
        $response = 'The uploaded file was only partially uploaded.';
        break;
    case UPLOAD_ERR_NO_FILE:
        $response = 'No file was uploaded.';
        break;
    case UPLOAD_ERR_NO_TMP_DIR:
        $response = 'Missing a temporary folder. Introduced in PHP 4.3.10 
        and PHP 5.0.3.';
        break;
    case UPLOAD_ERR_CANT_WRITE:
        $response = 'Failed to write file to disk. Introduced in PHP 
        5.1.0.';
        break;
    default:
        $response = 'Unknown error';
    break;
}

echo $response;
}
?>

我需要添加时间戳,以便我的 opencv 能够读取多个文件。

【问题讨论】:

    标签: php html post upload timestamp


    【解决方案1】:

    $targetPath 更新为time() 而不是$name

    //upload file
    if ($valid) {
        // UPDATED LINE
        $targetPath =  dirname( __FILE__ ) . DIRECTORY_SEPARATOR. 
          'uploads' . DIRECTORY_SEPARATOR . time();
        move_uploaded_file($tmpName,$targetPath); 
        header( 'Location: CheckTooth.php' ) ;
        exit;
    }
    

    【讨论】:

    • 我总是把它们弄混,它是time()。我更新了我的答案以反映这一点。
    • 谢谢,它正在工作,但它没有作为 jpeg 文件上传,我该怎么做?
    猜你喜欢
    • 2014-06-11
    • 1970-01-01
    • 2017-05-18
    • 1970-01-01
    • 1970-01-01
    • 2023-01-13
    • 2010-12-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多