PHP not writing to file even though there are no errors - php

I have the following script that is supposed to take the input from two forms and then rewrite two different files with the input from the forms. When I put in text into the forms and run it I get no errors but neither of the files were changed at all. I have all the proper permissions set and correct file paths. I changed the paths in the code below so as not to show sensitive information to my server. I'm really scratching my head at this one since php is a fairly new language to me so any help is greatly appreciated.
HTML Code
<form name="editfront" action="save.php" method="post">
<div class="editareasmall">
<textarea rows="1" cols="150" id="title" name="title"></textarea>
<script>$('#title').load('../content/front/Title');</script>
</div>
<div class="contentheader">Content</div>
<div class="editareabig">
<textarea rows="30" cols="150" id="content" name="content"></textarea>
<script>$('#content').load('../content/front/Content');</script>
</div>
<input type="submit" value=" Save " class="save">
</form>
PHP Code
<?php
error_reporting(E_ALL);
ini_set('display_errors', true);
$title = $_POST['title'];
$content = $_POST['content'];
$filenametitle = "../content/front/Title";
$filenamecontent = "../content/front/Content";
echo 'Form data has been saved';
$filetitle = fopen($filenametitle, "w") or die("can't open file");
$filecontent = fopen($filenamecontent, "w") or die("can't open file");
fwrite($filetitle,$title);
fwrite($filecontent,$content);
fclose($filetitle);
fclose($filecontent);
?>

When you submit the form, do you get your output message?
"Form data has been saved"

Are you sure that in php multi file opening is available?
Change your error reporting to -1. You will be informed about notice error.

Related

Empty POST method

I am totally new in PHP and i have problem with posting data. I try to post data and write it in txt file. I already increase my post max size in php.ini. I use XAMPP
<form action="forms/save_news.php" method="post" role="form">
<div class="form-group">
<input type="text" name="date" class="form-control" id="date" placeholder="Дата" data-rule="minlen:10" data-msg="Моля въведете дата" />
<div class="validate"></div>
</div>
<div class="form-group">
<input type="text" class="form-control" name="title" id="title" placeholder="Заглавние"/>
<div class="validate"></div>
</div>
<div class="form-group">
<textarea class="form-control" name="data" rows="5" data-rule="required" data-msg="Моля въведете съдържание" placeholder="Новина"></textarea>
<div class="validate"></div>
</div>
<div class="text-center"><button type="submit">Запиши</button></div>
</form>
And my PHP code is:
<?php
if(isset($_POST['date'])) {
$date = $_POST['date'];
$fp = fopen('data.txt', 'a');
fwrite($fp, $date);
fclose($fp);
}
?>
My first guess would be a permission issue. What I would do to troubleshoot this is to turn on error reporting in your PHP script. Try the following code:
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
if (isset($_POST('date')) {
$date = filter_var($$_POST['date'], FILTER_SANITIZE_STRING);
$fp = fopen('data.txt', 'a');
fwrite($fp, $date);
fclose($fp);
}
?>
Post another request from your form and see what appears in the browser. The errors that are reported should tell you where the problem is, but if you aren't positive how to fix the errors.
Now, all that said, be sure to never trust data sent from a web form. For simply testing purposes, you can do what you are doing, but I would not recommend getting into the habit since it can breed complacency. Note the change I made to the line that assigns the value of the form field to the $date variable. It uses a filter_var function to sanitize the string. There are plenty of combinations, and it is best to understand exactly how you are going to use the data, eventually to choose the correct filter(s).
You may consider an extra check. For example, if $_POST['date'] contained an empty string, it would pass isset() and would still append this to the Text file.
PHP Version is also a consideration here.
Try:
<?php
if(isset($_POST['date']) && !empty($_POST['date'])) {
$date = $_POST['date'];
if (is_writable('date.txt'){
$fp = fopen('date.txt', 'a');
if(fwrite($fp, $date) === FALSE){
echo "Cannot write to file";
exit;
}
fclose($fp);
} else {
echo "The file is not writable.";
}
}
?>
Also, this script assumes that date.txt and save_news.php reside in the same folder path. Is date.txt in forms folder? If it is not you will want to ensure that the script can reach the file and there are proper permissions for XAMPP and PHP to Read, Write to this file.
If date.txt is elsewhere, maybe in the parent, use:
$fp = fopen('../date.txt', 'a');
If PHP has decided that filename specifies a local file, then it will try to open a stream on that file. The file must be accessible to PHP, so you need to ensure that the file access permissions allow this access. If you have enabled open_basedir further restrictions may apply.
https://www.php.net/manual/en/function.fopen.php

CKeditor displaying HTML tags in browser

I have been searching for a possible cause of this issue but I couldn't find it.
I already saw this topic here but it didn't help me.
I am building a very simple CMS using exactly this technology, plus CKeditor. Everything works just fine until I decide to add some styling on my RTE, like for instance, Bold text. When I press the Submit button, the rendered html has the [b] tags.
After some investigation I went to CKeditor's config file and wrote this: config.htmlEncodeOutput = false, which didn't help either.
What might the problem might be? To not leave any questions about my code, I leave you the code below:
A PHP file with all the editable fields that the back end picks up:
$text13 = "innehall/text13.txt";
if (isset($_POST['body13'])) {
$newData = nl2br(htmlspecialchars ($_POST['body13']));
$handle = fopen($text13, "w");
fwrite($handle, $newData);
fclose($handle);
}
if (file_exists($text13)) {
$myData13 = file_get_contents($text13);
$myData13 = $myData13;
}
The back end file:
<form id="form" name="form" method="post">
<label>Beskrivning:</label>
<textarea class="ckeditor" name="body13" id="body13">
<?php echo str_replace("<br />","",$myData13); ?>
</textarea><br>
<input id="submit" name="myBtn" type="submit" value="Uppdatera fältet" />
</form>
A php file with all the sources that the index will pick up:
$text13 = "administration/innehall/text13.txt";
if (file_exists($text13)) {
$myData13 = file_get_contents($text13);
}
The index.php
<div class="six columns">
<p><?php echo $myData13 ?></p>
</div>
Can you post the contents of the text file you are saving to - I think you will find that the tags are being escaped but want to check that first.
If the tags are being escaped when you save then you need to unescape them when you show the output not just echo.
Also I guess $myData15 is meant to be $myData13???

Write data from text box to a text file

I have developed a text box and I am trying to write this data to a text file.
The PHP code is generating the file but the data is not being written.
below is my code:
<html>
<body>
<form name="form" method="post">
<input type="text" name="text_box" size="50"/>
<input type="submit" id="search-submit" value="submit" />
<?
$a=#$_POST["text_box"];
$myFile = "t.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
fwrite($fh,$a);
fclose($fh);
?>
the biggest issue i see with your code is the fact that you aren't opening php tags. you do
<?
but it should be
<?php
then, the way you call $_POST and write file and stuff means it will be executed when you first load the form into the browser as well. the php engine makes no distinction between first run and consecutive run. this means that even if the user don't submit anything, there will still be an empty file, created from the run of the script where the form was displayed. it's a side effect. i've modified your code just a little. here's my take on this:
<html>
<body>
<form name="form" method="post">
<input type="text" name="text_box" size="50"/>
<input type="submit" id="search-submit" value="submit" />
</form>
</body>
</html>
<?php
if(isset($_POST['text_box'])) { //only do file operations when appropriate
$a = $_POST['text_box'];
$myFile = "t.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
fwrite($fh, $a);
fclose($fh);
}
?>
The form's submit action is "get", but in your PHP code, you get the variable by $_POST. Try by $_GET instead.
The form is sending a GET request, but you are trying to access $_POST["text_box"]. Try changing that to $_GET['text_box'], or using a form method POST instead.
You can replace your PHP code with just:
if ($_REQUEST) {
file_put_contents("t.txt", $_REQUEST["text_box"]);
}
That will ensure that file only gets overwritten when the form is actually submitted, not also when the form is displayed.
Does $a have data? Try echo'ing it out. Or, try print_r'ing your $_POST.
EDIT: Your form's method is get, but you're trying to use $_POST. Use $_GET, or, $_REQUEST.

Simple PHP editor of text files

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.
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('Moved.', htmlspecialchars($url));
exit();
}
// read the textfile
$text = file_get_contents($file);
?>
<!-- HTML form -->
<form action="" method="post">
<textarea name="text"><?php echo htmlspecialchars($text); ?></textarea>
<input type="submit" />
<input type="reset" />
</form>
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>
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.
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.
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!
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.
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>
<?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.

HTML Form to post on php page

Thank you for reading. I'm trying to create a HTML form so that my friend can type text into it and thereafter, updates his web site with whatever is typed into the form. I'm trying to create a HTML form (on a php page) which posts whatever is entered within it's textarea to the home.php file. However, rather than simply do a "one-off" post, I'm trying to make it so that whatever is entered within the textarea saves the data into the home.php file. The home.php file is blank, and the form which I have created is as below:
<form method="post" action="home.php">
<textarea id="element" name="element" rows="15" cols="80" style="width: 80%">
</textarea>
<input type="submit" name="save" value="Save" />
<input type="reset" name="reset" value="Reset" />
</form>
For example, if the words "example" was typed into the form then submitted, the home.php file should have the words "example" written on it.
If you require more details, then please reply. Thank you. :)
<?php
$Input = $_POST['element'];
$FileToUpdate = "home.php";
$fh = fopen($FileToUpdate , 'w') or die("can't open file");
fwrite($fh, $Input);
fclose($fh);
?>
The code above will do what you wish, but will overwrite the page (to append see this reference). But really I think you need to start from basics with a good PHP Tutorial.
This should do what you want:
<?php
$filename = "/path/to/home.php";
$file = fopen( $filename, "w" );
if( $file == false ) {
echo ( "Error in opening new file" );
exit();
}
fwrite( $file, $_POST['element'] );
fclose( $file );
?>
You can read more about file I/O here.
You can use the php $_POST var to fetch the data from a form post.
For example if you want to fetch the field named "element" you can use $_POST['element']
Try the code below to display the text which was typed into the textarea. The code goes into home.php
<?php
echo $_POST['element'];
?>
Likewise you can fetch all required data. Hope this helps. Please go through http://www.w3schools.com/php/php_post.asp for more information.

Categories