上传txt文件并从第一行获取新文件名的字符串

时间:2018-04-30 16:09:33

标签: php upload rename

当在服务器上上传.txt文件时我需要读取它,取第一行并从第一行使用此字符串用于新文件名(重命名文件)。

例如,我有文件test.txt,文件中有

First line - Username: DemoUser

我需要将test.txt重命名为DemoUser.txt,并将此DemoUser.txt重命名为存储在MySQL中

1 个答案:

答案 0 :(得分:0)

这是我的剧本

<?php

if (isset($_POST['submit']))
{
    $filename = $_FILES["file"]["name"];
    $file_basename = substr($filename, 0, strripos($filename, '.')); // get file extention
    $file_ext = substr($filename, strripos($filename, '.')); // get file name
    $filesize = $_FILES["file"]["size"];
    $allowed_file_types = array('.doc','.docx','.rtf','.pdf', '.txt');

    $file = fopen($_FILES["file"]["tmp_name"],"r");
    $result = fgets($file);
    $result = explode( ': ', preg_split( '(\\r\\n|\\r|\\n)', $result )[0] )[1];
    fclose($file);

    if (in_array($file_ext,$allowed_file_types) && ($filesize < 200000))
    {   
        // Rename file
        $newfilename = $result . $file_ext;
        if (file_exists("users/" . $newfilename))
        {
            // file already exists error
            echo "You have already uploaded this file.";
        }
        else
        {       
            move_uploaded_file($_FILES["file"]["tmp_name"], "users/" . $newfilename);
            echo "File uploaded successfully.";     
        }
    }
    elseif (empty($file_basename))
    {   
        // file selection error
        echo "Please select a file to upload.";
    } 
    elseif ($filesize > 200000)
    {   
        // file size error
        echo "The file you are trying to upload is too large.";
    }
    else
    {
        // file type error
        echo "Only these file typs are allowed for upload: " . implode(', ',$allowed_file_types);
        unlink($_FILES["file"]["tmp_name"]);
    }
}
?>