Hi guys.
I am currently in the process of trying to build a simple text editor.
But I am stumped by a function which won't work the way I want it to. So the script below is incomplete.
So far I have managed to make it so a txt file is created when the user types a file name in the text field. But when the user clicks the create button (after typing a name for the file) the file contents do not display like they should.
I basically end up with a load of html/css code inside the text area (when the field should be blank).
I have typed the following inside the text area:
<?php echo htmlspecialchars(file_get_contents($filepath)) ?>
.... this code should display the contents of the file. So I don't understand why I end up with lots of html/css code instead?
below is the code in its entirety:
<?php
define("PATH_TO_FILES", "files");
if(isset($_POST["createfile"])) {
createfile();
} else {
displayfilelist();
}
function displayfilelist($message=""){
pageheader();
if($message) {
echo $message;
}
echo '<h1>Please choose from one of the following files:</h1>';
if(!file_exists(PATH_TO_FILES)) die("the path file does not exist!");
if(!($dir = dir(PATH_TO_FILES))) die("cannot open directory!");
?>
<table style="border: 1px solid black; width: 100%; background-color: #00ff00;"><tr><th>file link</th><th>file size (bytes)</th><th>Last modified</th></tr>
<?php
while($filename = $dir->read()){
$filepath = PATH_TO_FILES . "/$filename";
if($filename != ".." & $filename != "." && !is_dir($filepath) && strrchr($filename, ".") == ".txt"){
echo '<tr style="text-align: center;"><td><a href="editor.php?filename=' . urlencode($filename) . '">' . $filename . '</a></td><td>' . filesize($filepath) . '</td><td>' . filemtime($filepath) . '</td><tr>';
}
}
echo '</table>';
$dir->close();
?>
<h2>... or create a file:</h2>
<form method="post" action="editor.php">
<label>Create a file:</label>
<input type="text" name="filename">
<input type="submit" name="createfile" value="create">
</form>
</body>
</html>
<?php
}
function createfile(){
$filename = basename($_POST["filename"]);
$filepath = PATH_TO_FILES . "/$filename";
if(!$filename){
displayfilelist("Please enter a filename");
} elseif(file_exists($filepath .= ".txt")){
displayfilelist("this file exists!");
} else {
file_put_contents($filepath, "");
editform($filename);
}
}
function editform($filename=""){
pageheader();
if($filename){
$filepath = PATH_TO_FILES . "/$filename";
}
?>
<h1>Editing <?php echo $filename ?>.txt</h1>
<form method="post" action="editor.php">
<textarea name="filecontents">
<?php echo htmlspecialchars(file_get_contents($filepath)) ?>
</textarea>
</form>
</body>
</html>
<?php
}
function pageheader() {
?>
<html>
<head>
</head>
<body>
<?php
}
?>