For a website, the user should be able to type a title and post in a form and press a submit button to enter them. Upon pressing the submit button, the data in the forms are written to their assigned text files which are in the same folder as the webpage. The writing works fine, but as you can see below, I have attempted to make it so that if the user clicks the submit button without one of the two fields (or neither of the fields) being filled in the site will prompt them to enter text and no file writing takes place.
My issue is that when they click submit and a field isn't filled, this will actually affect the .txt files and they will also end up blank. I want the files to retain their 'old' text unless both textareas in the form contain data to be overwritten. For example, if both .txt files have text in them and I click submit on the form with no text in the form, the two .txt files will keep their text instead of being overwritten to have no text (which is what currently happens).
Here's the html and php:
<form action="AdminBlog.php" method="post">
Blog Title:<textarea type="text" name="titleInput"></textarea><br><br>
Blog Post:<textarea type="text" name="postInput"></textarea><br><br><br>
<input type="submit" value="Submit"/>
</form>
<?php
$titleFile = fopen("Title.txt","w");
$blogTitle = null;
$postFile = fopen("Post.txt","w");
$blogPost = null;
if(!empty($_POST['titleInput']) && !empty($_POST['postInput'])) {
$blogTitle = $_POST['titleInput'];
fwrite($titleFile,$blogTitle);
fclose($titleFile);
$blogPost = $_POST['postInput'];
fwrite($postFile,$blogPost);
fclose($postFile);
}
if (empty($_POST['postInput']) || empty($_POST['titleInput'])) {
echo "Please enter a title and post.";
}
?>
Changing that final if statement to elseif or else didn't seem to make a difference. The echo is outputted when it should be, but the .txt files are still overwritten with no data (when a textarea is blank and user clicks submit).
EDIT: Just wanted to add something. I'm not sure if this is relevant, but whether there is text in the files or not, I cannot read the text from another .php file. I can from this same one, but when trying to get the .txt file contents in another .php page, I cannot do so. This is also causing me a separate problem, just wanted to mention in case it was anything useful.
I think you need to try
file_put_contents($file, $person, FILE_APPEND);
for write file.
1st argument will be name & path of the file.
2nd argument will be data in string format.
3rd argument will be FILE_APPEND if you want to add content in existing file.
if you will not use 3nd argument then it will replace content of the file all time.
Source
There is a > missing in your html after <textarea type="text" name="postInput".
Try to put that on.
Related
I have 2 file upload fields in my form. Both look like this:
<input type="file" id="file1" name="file1" accept="application/pdf,application/msword">
<span id="file1_status">Currently uploaded: <?php echo $file1_fileName; ?></span>
<input type="file" id="file2" name="file2" accept="application/pdf,application/msword">
<span id="file2_status">Currently uploaded: <?php echo $file2_fileName; ?></span>
where $file1/2_fileName; is either "none" when the page is first loaded or equal to $_FILES["file1/2"]["name"] after a post event.
Toward the end of the page, I do
$(document).ready(function () {
jQuery("input#file1").change(function () {
var val = $(this).val();
_('file1_status').innerHTML = "Currently uploaded: " + val.substr(12); // removes C:/fakedir/
});
Same for file2. So, basically if someone uploads "file.pdf", there is a text under the file input that reads: "Currently uploaded: file.pdf". I do this so the user sees that the file is still there if form validation fails after form submission.
OK so far so good.
Rather than using "required" in the input file field, upon form submission, I do the following:
if (is_uploaded_file($_FILES["file1"]["tmp_name"])) {
// check mime_type, file size, etc.
} else {
// display an error below the input field that a file is missing.
}
Same for file2. Now to the actual question/problem.
Imagine the following situation. A user only uploads file1 but forgets file2 and clicks submit. This is what happens:
Firefox (latest version): Below the file1 field the status still shows "Currently uploaded: file1.pdf" and below the file2 input field an error message is displayed to remind the user to upload this file also. If the user complies and uploads file2, then clicks on submit again, the form is submitted and all is fine, i.e., both files have been attached to the form submission. This is the expected behaviour.
Chome/Edge: For the same user behavouir everything is the same except for when the user clicks on submit a second time. For some reason, both these browsers now show an error below the file1 input field (although it still shows "Currently uploaded: file.pdf" which the user uploaded in the very beginning). So for some reason, and although $_FILES["file1"]["tmp_name"] is not empty, the test
is_uploaded_file($_FILES["file1"]["tmp_name"]) fails upon the second form submission in both Chrome and Edge but not in FF.
This is very confusing. Why is this and how can this be avoided/fixed?
It seems that the Edge/Chrome behaviour is indeed to expected/normal behaviour. To my great embarrassment I have not been able to reproduce the above behaviour in FF anymore so I am not exactly sure what happened because I really did see a different behaviour while testing it for about an hour or so.
Anyway, for all practical purposes, I was able to work around the issue by moving the files that met all my criteria (re mime types, file size, etc) into a temporary upload directory on my server, store the file name in a session variable, and modify this code:
if (is_uploaded_file($_FILES["file1"]["tmp_name"])) {
// check mime_type, file size, etc.
} else {
// display an error below the input field that a file is missing.
}
to this
if (is_uploaded_file($_FILES["file1"]["tmp_name"])) {
// check mime_type, file size, and if OK move to upload directory on server and store the name of the successfully uploaded file in $_SESSION["file1"]
} elseif (!empty($_SESSION["file1"])) { //basically this gets invoked the second time round, i.e., when the user uploads the 2nd file they forgot when submitting the form for the first time
$file1_fileName = $_SESSION["file1"]; // used to display under the input file element (see above)
} else {
// display an error below the input field that a file is missing.
}
Same for file2. So while the first "if" condition fails upon the 2nd form submission, the "elseif" condition is true and no error is issued.
It may sounds not clear, but I'll try.
I'm working on my edit page where I can edit several input types as well as file.
I'm saving my files in my database with its filename.
However, since input type = file doesn't allow to keep the data / value on it, unless I re-upload the file, it will just wipe out the filename on my database.
How would I be able to keep the filename as it is in my database without re-uploading the file?
It is very simple. You just don't need to update the database field that containing the file name if the input file is empty.
Here is a demo for you.
Lest's assume your form is like this.
<form>
<input type="file" name="myfile">
</form>
So you need to check this in your backend.
if(isset($_FILES['myfile']) && !empty($_FILES['myfile']['name']))
{
// update your databse column with new file detail
}
Hope this helps.
Ok, I've got a form and i've parsed all the data and i'm ready to write it to the file. I use the following PHP code (simplified):
$file = fopen("Data.txt","a");
fwrite($file,$_GET["InputText"]);
fclose($file);
It writes just fine to the file but opens a new blank page. How do i stop it from doing that?
Thanks for the help
-Dave
EDIT: No output generated by PHP. It just writes a line of text to a file. I am using a seperate file to hold my PHP code...
< form id="fmInput" action="IM.php" onsubmit="submitText()" >
How else can i do that?
EDIT2: Heres more of my code:
<form id="fmInput" action="IM.php" onsubmit="submitText()">
<input type="text" name="fnInputText" id="iInputText">
</form>
<?php
//IM.php
$file = #fopen("IMData.txt","ab");
fwrite($file,$_GET["fnInputText"]);
fwrite($file,"<br>");
fclose($file);
?>
Now, when the user hits enter on the form, JS captures and processes (using the submitText function) then PHP writes it to a file, but then opens a blank browser...
EDIT3: I'm guessing its a blank page being loaded in the same window because it's got this in the address bar "/IM.php?fnInputText="
I dont want it to do that. I need it to write to the file without any interuption, so having PHP display anything after it runs is a deal breaker. Even if i have to have it reload the page that'd be better... It'll be marginally more time consuming as JS will have to reload the file again...
I figured out how to read from a file using JS and the XMLHttpRequest but for the life of me i cant get JS to write to the file. I'd perfer to use JS as I know very little about PHP (which is probably aparent from this post ;D)
My goal is this: page loads, JS reads in file and displays file on screen. User types in somthing, hits enter, JS adds that to screen and then [PHP or JS] writes data to file. repeat.
Perhaps you want to redirect your user to a non-blank page after you're done writing your data?
header("Location: /back-to-my-page.html");
You must be submitting the form data to another file. For example, doing an
onsubmit="write.php"
That should open a new page and write to the file
Here is the whole package!
IM.php:
<?php
// write to file if the form is submitted
if(isset($_POST['submitted'])){ # if form is submitted
$secure_input = htmlentities($_POST['input_text']); # making sure no malicious html code is submitted
file_put_contents('some_file_to_write.txt', $secure_input); #write secure_input to a file
echo '<br>completed!</br>';
}
?>
<form id="fmInput" action="IM.php" method="post">
<input type="text" name="fnInputText" id="input_text">
<input type="submit" name="submitted" value="write to file" />
</form>
if any errors comes up : you do not have permission to write! and if the file gets downloaded you do not have php installed ;)
Good Luck!
I've been trying to create some php code that would let me
take input from a user using a text box. I want to then store
that input (probably like 7 characters long) and then display it
on a page in a list format ( eg
1
2
3
)
I've been at this for hours reading tutorials and what not but everything
I find only shows me the fwrite function and when I try to append I still
end up deleting data.
I would like the newest inputs to show up on top of the list if possible.
Can someone help me?
I am really frustrated and I know almost no php.. kind of playing around
with it and can't figure this out =/
I was thinking of storing the input from users in an array, then display the array..
But that doesn't work for me either.
So you want to have a form, let the users enter text, then display all the text entered by all the users, sort of like a wall or guestbook.
I'm presuming you've managed to fetch the user's input by looking at $_POST after the form submission. To store it in a file without overwriting the existing file contents the easiest way is file_put_contents with the special FILE_APPEND flag.
Lets say your HTML form has a textbox with name="newData". Then, in the form submission target script:
//store all user input in a file called data.txt in the current directory
$filename = "./data.txt" ;
$newData = $_POST['newData'] . "\n" ;
file_put_contents($filename, $newData, FILE_APPEND);
//now fetch all data and display it
$lines = file($filename) ;
echo '<ul>' ;
foreach ($lines as $line) {
echo "<li>$line</li>" ;
}
echo '</ul>' ;
Get started like that to see the basics in action and then you can look into:
filtering user input so that you don't store and display any nasty stuff
storing the data file outside the web root so that it's not accessible via the browser
prettifying the output list
If they're submitting the data via form, it will POST to the server; meaning you can use:
<form action="target.php" method="post">
<input type="text" name="username" value="" />
<input type="submit" name="submit value="Submit" />
</form>
for the markup, and then for the PHP (on target.php):
<?php
if (isset($_POST['submit']) { //to check if the form was submitted
$username= $_POST['username'];
}
?>
At this point you can then use <?php echo $username ?> anywhere you want to echo the data entered from the previous page.
I'm no PHP expert either (I recommend the Lynda.com training videos, "PHP & MySQL Essential Training" and "PHP & MySQL Beyond The Basics" with Kevin Skoglund) but maybe this helps.
As said above, you can use $_POST to get the data, however it is worth noting that if you are actually using this in a web application, you need to sanitize for XSS. You can do this quite simply with PHP's htmlspecialchars()
try this for taking input from user in php
$variablname = fgets(STDIN);
echo $variable;
file_put_contents('/path/to/file','contents',FILE_APPEND);
I created this layout of successive text input fields,
1- Enter data into empty fields
2- Click on button which submits to a php page that updates into database
Now the problem is that i want when i return to the main page again the empty field is replaced with data just added but there are still other empty fields to enter new data.
How can i establish that?
Thanks in advance.
You haven't given a lot of detail but here goes!
You could build your inputs like this:
<input type="text" name="age" value="<?php echo $age; ?>">
When the form first loads, it won't have values for variables like $age, so the input will appear empty. Have the form submit via POST to the same PHP file, run your validation checks, and if everything passes, insert into to your database. (Is it required that you write to the database at this point, or should it wait until the second section is filled out?)
You'll need to use some kind of conditional statement to display the second part of the form. Depending on how complex this is, or whether users will be returning later, you could:
Read the data back out of the
database to check for completeness,
and then display the second part.
Set a variable to track what stage of the form you're in, and based on that, display different sections to be completed.
If you have a way of tracking what stage of the process you're in, you could do something like this:
$formStage = 2;
function isReadOnly($formStage='')
{
if ($formStage == 2) {echo 'READONLY';}
}
and then in your HTML:
<INPUT NAME="realname" VALUE="Hi There" <?php isReadOnly($formStage)?>>