I have a website and i'm making a content management system for the website. I need to be upload a .txt file and then be able to edit that file inside the website. so far I have this:
<?php
$myFile = fopen("welcome-content.txt", 'r');
while (($buffer = fgets($myFile)) !== false) {
echo "<p>";
echo $buffer;
echo "</p>";
}
fclose($myFile);
?>
This is able to upload the file, but I have to have the file name as "welcome-content.txt", I want to be able too select a file from the File Explorer, upload it, and then be able to edit it. Am I right in thinking I need a HTML Form in order to select the file? But as far as anything else I'm not sure where to go from there.
Any tips?
Generate html form to choose file for upload:
<form enctype="multipart/form-data" method="post" action="test_php.php">
<input id="image-file" name="image-file" type="file" />
<input type="submit" value="submit" id="submit" />
</form>
Write php code to handle your upload and modify file:
<?php
if ( !isset($_FILES['image-file']['error']) || is_array($_FILES['image-file']['error']) )
{
throw new RuntimeException('Invalid parameters.');
}
// Check $_FILES['image-file']['error'] value.
switch ($_FILES['image-file']['error'])
{
case UPLOAD_ERR_OK:
break;
case UPLOAD_ERR_NO_FILE:
throw new RuntimeException('No file sent.');
case UPLOAD_ERR_INI_SIZE:
case UPLOAD_ERR_FORM_SIZE:
throw new RuntimeException('Exceeded filesize limit.');
default:
throw new RuntimeException('Unknown errors.');
}
// Check filesize here.
if ($_FILES['image-file']['size'] > 1000000)
{
throw new RuntimeException('Exceeded filesize limit.');
}
$filename = $_FILES['image-file']['name'];
echo "Filename is $filename <br>";
//Add new line
$f = fopen($filename,"a"); // Append mode
fwrite($f, "Added new line
");
fclose($f);
echo "After modify file content is: <br>";
echo file_get_contents( $filename );