Reputation: 326
I'm using the following code to upload a txt file to my server..
<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.";
}
}
?>
And I would like to keep only the first 4 lines of text, so trim off (delete) all lines of text (after the 4th line) before it gets uploaded.
So
line 1 text
line 2 text
line 3 text
line 4 text
line 5 text
line 6 text
line 7 text
<!--And so on-->
Becomes
line 1 text
line 2 text
line 3 text
line 4 text
How do I go about doing this? I have tried a few suggstions looking at answers to other (similar) questions but being a so novice at php I'm really not getting anywhere with this.
Upvotes: 0
Views: 181
Reputation: 28529
You can just read the first four line, then overwrite the file.
$fp = fopen($file_path);
$num = 4;
while($num-- > 0 && $line = fgets($fp)){
$lines [] = $line;
}
fclose($file_path);
file_put_contents($file_path,join("",$lines));
Upvotes: 1