22

I have developed a site for a client and he wants to be able to edit a small part of the main page in a backend type of solution. So as a solution, I want to add a very basic editor (domain.com/backend/editor.php) that when you visit it, it will have a textfield with the code and a save button. The code that it will edit will be set to a TXT file.

I would presume that such thing would be easy to code in PHP but google didn't assist me this time so I am hoping that there might be someone here that would point me to the right direction. Note that I have no experience in PHP programming, only HTML and basic javascript so please be thorough in any reply that you provide.

Alehandro Darie
  • 271
  • 1
  • 3
  • 7

8 Answers8

42

You create a HTML form to edit the text-file's content. In case it get's submitted, you update the text-file (and redirect to the form again to prevent F5/Refresh warnings):

<?php

// configuration
$url = 'http://example.com/backend/editor.php';
$file = '/path/to/txt/file';

// check if form has been submitted
if (isset($_POST['text']))
{
    // save the text contents
    file_put_contents($file, $_POST['text']);

    // redirect to form again
    header(sprintf('Location: %s', $url));
    printf('<a href="%s">Moved</a>.', htmlspecialchars($url));
    exit();
}

// read the textfile
$text = file_get_contents($file);

?>
<!-- HTML form -->
<form action="" method="post">
<textarea name="text"><?php echo htmlspecialchars((string)$text); ?></textarea>
<input type="submit" />
<input type="reset" />
</form>
hakre
  • 193,403
  • 52
  • 435
  • 836
  • It works, however, is there anyway to adjust it so that the content of the txt file is there as you load it up? – Alehandro Darie Nov 22 '11 at 13:00
  • The content of the file `$file` should be displayed on loading up. Just put some text into the file. – hakre Nov 22 '11 at 13:02
  • It is not, I have already tried it. As the $file path, I put 'test.txt' because it is in the same folder as the php file. Is that a problem? – Alehandro Darie Nov 22 '11 at 13:05
  • Yes that is a problem. Specify a full path in there, a fully qualified path, not only a filename. – hakre Nov 22 '11 at 13:07
  • Save file using UNIX newlines: file_put_contents($file, str_replace("\r", '', $_POST['text'])); – Sunry Aug 06 '15 at 08:37
  • @Sunny: Please see: [What character represents a new line in a text area](http://stackoverflow.com/q/14217101/367456) - I suggest you do standard newline normalization instead: [How to replace different newline styles in PHP the smartest way?](http://stackoverflow.com/q/7836632/367456) - You would replace with `\n` then. Take note that you also need to take care of the character encoding, the example in the answer is not specifically about one. – hakre Aug 06 '15 at 10:45
  • When I open the saved file in Dreamweaver / Notepad, there are duplicate New Lines. That leads to "500 Internal server error" because I'm using the code to save `.htaccesss` file from browser. However, this works file in my windows localhost server but have this problem when it is hosted. Please Help anyone. – Bhavesh G Sep 19 '15 at 18:08
  • @BhaveshGangani: What you need to deal with is newline normalization (and perhaps detection). See https://en.wikipedia.org/wiki/Newline ; http://stackoverflow.com/q/8627902/367456 and http://stackoverflow.com/q/14217101/367456 - Also please look for an existing answer on the concrete topic, this answer here is only a rough example. It does not care about the newline details (it's now the second time I think about this and it's ages old, so the problem probably does not occur that often). - Next to newline there is also character encoding of both the file and the website. Take care here, too. – hakre Sep 20 '15 at 16:20
  • @SomeGuyOnAComputer: Thanks for participating, I've just rolled your changes back because all those HTML tags are automatically part of the document but the style tag and I don't think it adds anything to the answer. Instead it's more code and thereofre more to read which is degrading the answer. Q&A is not a snippet library for copy-pasta-hell IMHO. – hakre Nov 04 '15 at 08:26
  • @hakre fair enough. I just couldn't read any of the text in the area so I thought I'd just expand it to the window and share. Thank you for your opinion. – SomeGuyOnAComputer Nov 04 '15 at 16:34
  • absolutely genius. Worked immediately. – Dan Mantyla May 20 '20 at 20:52
  • In php, the easiest way to get an absolute path relative to your script is `$filepath = __DIR__.'/test.txt';` and if it's in another folder you can use `..` to reference the parent directory. eg for `/path/to/script/index.php` to get to `/path/to/data/test.txt` you can use `__DIR__.'/../data/test.txt` – yarns Aug 16 '23 at 23:54
5

To read the file:

<?php
    $file = "pages/file.txt";
    if(isset($_POST))
    {
        $postedHTML = $_POST['html']; // You want to make this more secure!
        file_put_contents($file, $postedHTML);
    }
?>
<form action="" method="post">
    <?php
    $content = file_get_contents($file);
    echo "<textarea name='html'>" . htmlspecialchars($content) . "</textarea>";
    ?>
    <input type="submit" value="Edit page" />
</form>
Niels
  • 48,601
  • 4
  • 62
  • 81
  • Can you please give me more info on how I would add this? And how I would insert the textfield in there and make it functional? As I noted previously, I am very new to PHP. – Alehandro Darie Nov 22 '11 at 12:46
  • It works, however it does not fetch the content of the txt file when it loads up. If it is not to much to ask, can you kindly adjust the code to do that? – Alehandro Darie Nov 22 '11 at 12:57
  • 1
    I'm sorry but I do not understand what you mean by "fetch the content of the txt file when it loads up". – Niels Nov 22 '11 at 13:03
1

You're basically looking for a similar concept to that of a contact-form or alike.

Apply the same principles from a tutorial like this one and instead of emailing using mail check out the file functions from PHP.net.

James
  • 5,137
  • 5
  • 40
  • 80
0

I had a similar need so we created a client-friendly solution called stringmanager.com we use on all our projects and places where CMS is not effective.

From your side, you just need to tag string in the code, i.e. from:

echo "Text he wants to edit"; to:

echo _t("S_Texthewantstoedit");

stringmanager.com takes care about the rest. Your client can manage that particular text area in our online application and sync wherever he wants. Almost forgot to mention, it is completely free.

Brano
  • 39
  • 1
0

Can use this line of code :

    <form action="" method="post">
    <textarea id="test" name="test" style="width:100%; height:50%;"><? echo "$test"; ?></textarea>
    <input type="submit" value="submit">
    </form>
Avinash Dalvi
  • 8,551
  • 7
  • 27
  • 53
0

What did you Google on then? php write file gives me a few million hits.

As in the manual for fwrite():

<?php
$fp = fopen('data.txt', 'w');
fwrite($fp, '1');
fwrite($fp, '23');
fclose($fp);

// the content of 'data.txt' is now 123 and not 23!
?>

But to be honest, you should first pick up a PHP book and start trying. You have posted no single requirement, other than that you want to post a textfield (textarea I mean?) to a TXT file. This will do:

<?php
if ($_SERVER['REQUEST_METHOD'] == "POST")
{
    $handle = fopen("home.txt", 'w') or die("Can't open file for writing.");
    fwrite($fh, $_POST['textfield']);
    fclose($fh);
    echo "Content saved.";
}
else
{
    // Print the form
    ?>
    <form method="post">
        <textarea name="textfield"></textarea>
        <input type="submit" />
    </form>
    <?php
}

Note that this exactly matches your description. It doesn't read the file when printing the form (so every time you want to edit the text, you have to start from scratch), it does not check the input for anything (do you want the user to be able to post HTML?), it has no security check (everyone can access it and alter the file), and in no way it reads the file for display on the page you want.

CodeCaster
  • 147,647
  • 23
  • 218
  • 272
  • How does that code work? Can you please provide me with further information? I searched for "php editor" and similar but most resulted in applications for editing php files. – Alehandro Darie Nov 22 '11 at 12:45
  • @AlehandroDarie then why are you searching on "php editor" and stop when you don't find anything? What you want is to write a file, so search for that. I have updated my answer, but it is purely demonstrational code and in no way to be used in a production environment. – CodeCaster Nov 22 '11 at 12:49
0

First thing to do is capture the information, the simplest way to do this would be the use of a HTML Form with a TEXTAREA:

<form method='post' action='save.php'>
  <textarea name='myTextArea'></textarea>
  <button type='submit'>Go</button>
</form>

On 'save.php' (or wherever) you can easily see the information sent from the form:

<?php
  echo $_POST['myTextArea']
?>

To actually create a file, take a look at the fopen/fwrite commands in PHP, another simplistic example:

<?php 
  $handle = fopen("myFile.txt","w");
  fwrite($handle,$_POST['myTextArea'];
  fclose($handle);
?>

WARNING: This is an extremely simplistic answer! You will perhaps want to protect your form and your file, or do some different things.... All the above will do is write EXACTLY what was posted in the form to a file. If you want to specify different filenames, overwrite, append, check for bad content/spam etc then you'll need to do more work.

If you have an editor that is publicly accessible and publishes content to a web page then spam protection is a DEFINITE requirement or you will come to regret it!

If you aren't interested in learning PHP then you should think about getting a professional developer to take care of any coding work for you!

Codecraft
  • 8,291
  • 4
  • 28
  • 45
-1
<?php
$file = "127.0.0.1/test.html";
$test = file_get_contents('1.jpg', 'a');
if (isset($_POST['test'])) {
file_put_contents($file, $_POST["test"]);
};
?>
<form action="" method="post">
<textarea id="test" name="test" style="width:100%; height:50%;"><? echo "$test"; ?></textarea>
<input type="submit" value="submit">
</form>

Haven't had time to finish it, simplest possible, will add more if wanted.