php在上传时只保留文本文件的前4行
我正在使用以下代码将txt文件上载到我的服务器php在上传时只保留文本文件的前4行,php,html,file-upload,upload,trim,Php,Html,File Upload,Upload,Trim,我正在使用以下代码将txt文件上载到我的服务器 <form style="margin-bottom:2px;" method="post" enctype="multipart/form-data" name="formUploadFile"> <label>Select txt file to upload:</label> <br> <input type
<form style="margin-bottom:2px;" method="post" enctype="multipart/form-data" name="formUploadFile">
<label>Select txt file to upload:</label>
<br>
<input type="file" name="files[]" /> <input type="submit" value="Upload" name="Submit"/>
<br>
</form>
<?php
if(isset($_POST["Submit"]))
{
$errors = array();
$uploadedFiles = array();
$extension = array("txt");
$bytes = 1024;
$KB = 1024;
$totalBytes = $bytes * $KB;
$UploadFolder = "tmp_txt_store";
$counter = 0;
foreach($_FILES["files"]["tmp_name"] as $key=>$tmp_name){
$temp = $_FILES["files"]["tmp_name"][$key];
$name = $_FILES["files"]["name"][$key];
if(empty($temp))
{
break;
}
$counter++;
$UploadOk = true;
if($_FILES["files"]["size"][$key] > $totalBytes)
{
$UploadOk = false;
array_push($errors, $name." file size is larger than the 1 MB.");
}
$ext = pathinfo($name, PATHINFO_EXTENSION);
if(in_array($ext, $extension) == false){
$UploadOk = false;
array_push($errors, $name." invalid file type.");
}
if(file_exists($UploadFolder."/".$name) == true){
$UploadOk = false;
array_push($errors, $name." file already exists.");
}
if($UploadOk == true){
$name = "my.txt";
move_uploaded_file($temp,$UploadFolder."/".$name);
array_push($uploadedFiles, $name);
}
}
if($counter>0){
if(count($errors)>0)
{
echo "<b>Errors:</b>";
foreach($errors as $error)
{
echo " ".$error.",";
}
echo "<br/>";
}
if(count($uploadedFiles)>0){
echo "<b>Uploaded:</b>";
echo "=";
foreach($uploadedFiles as $fileName)
{
echo " ".$fileName.",";
}
echo "<br/>";
echo "DONE!";
}
}
else{
echo "ERROR: Please press the browse button and select a txt file to upload.";
}
}
?>
我该怎么做呢?
我尝试了一些建议,看看其他(类似)问题的答案,但作为一名php新手,我真的没有任何进展。您可以阅读前四行,然后覆盖文件
$fp = fopen($file_path);
$num = 4;
while($num-- > 0 && $line = fgets($fp)){
$lines [] = $line;
}
fclose($file_path);
file_put_contents($file_path,join("",$lines));
非常感谢您的快速回答,但我不知道在我的代码中,在哪里可以正确地将其放在工作中。你能编辑你的答案并在我的代码中显示代码吗?有谁能帮助我并让我知道我在代码中的什么地方放置了这个示例代码,因为我正在努力处理这个示例代码。
line 1 text
line 2 text
line 3 text
line 4 text
$fp = fopen($file_path);
$num = 4;
while($num-- > 0 && $line = fgets($fp)){
$lines [] = $line;
}
fclose($file_path);
file_put_contents($file_path,join("",$lines));