I'm trying to make a forum-like section for my website. It's not posting, and I don't know why. Here's my PHP and html
<?php
if ($_POST) {
$title = $_POST['title'];
$name = $_POST['name'];
$content = $_POST['commentContent'];
$handle = fopen("comments.html", "a");
fwrite($handle, "<h2 class='Roboto-Slab'>$title</h2>", "<br>", "<h3
class='Roboto-Slab'>By $name</h3>", "<p class='Roboto-Slab'>$content</p>");
fclose($handle);
}
?>
<form action="" method="POST">
<textarea class="comment-boxmain" rows="20" cols="40" name="commentContent"
placeholder="Start Typing...."></textarea><br>
<input class="comment-boxname" placeholder="Title" type="text"
name="title">
<input class="comment-boxname" placeholder="Your Name" type="text"
name="name">
<input class="comment-btn" type="submit" value="post"><br>
</form>
<?php include "comments.html"; ?>
Please check out the answer at cvmblog.com/forum.php if that will help.
String concatenation is done with dots (.), and not commas (,).
Replace:
fwrite($handle, "<h2 class='Roboto-Slab'>$title</h2>", "<br>", "<h3
class='Roboto-Slab'>By $name</h3>", "<p class='Roboto-Slab'>$content</p>");
With:
fwrite($handle, "<h2 class='Roboto-Slab'>$title</h2>". "<br>". "<h3
class='Roboto-Slab'>By $name</h3>". "<p class='Roboto-Slab'>$content</p>");
And it will work. However, this concatenation is useless. You can do simply:
fwrite($handle, "<h2 class='Roboto-Slab'>$title</h2><br><h3 class='Roboto-Slab'>By $name</h3><p class='Roboto-Slab'>$content</p>");
Also check if comments.html file has CHMOD 777. Furthermore, enable error_reporting on your php.ini file, as the PHP error thrown on this case could guide you to the error line easily.
Here's an implementation of your code secured against stored XSS (the vulnerability that allows people to insert HTML and Javascript code on your page) as well as RCE (remote code execution):
<?php
if ($_SERVER['REQUEST_METHOD']=='POST') {
$title = strip_tags($_POST['title']);
$name = strip_tags($_POST['name']);
$content = nl2br(htmlspecialchars($_POST['commentContent']));
$handle = fopen("comments.html", "a");
fwrite($handle, "<h2 class='Roboto-Slab'>$title</h2><br><h3
class='Roboto-Slab'>By $name</h3><p class='Roboto-Slab'>$content</p>");
fclose($handle);
}
?>
<form action="" method="POST">
<textarea class="comment-boxmain" rows="20" cols="40" name="commentContent"
placeholder="Start Typing...."></textarea><br>
<input class="comment-boxname" placeholder="Title" type="text"
name="title">
<input class="comment-boxname" placeholder="Your Name" type="text"
name="name">
<input class="comment-btn" type="submit" value="post"><br>
</form>
<?php echo file_get_contents("comments.html"); ?>
Also, do some searching about database engines (if you want to still using files, take a look on implementation of flat-files databases, as it's called).
Related
I cannot make my post system work because posts in comment section duplicate if I refresh the page
I am using only HTML and PHP. It's a forum for me and my friends.
There is also code above this but it is unimportant
<form action="" method="POST">
<label> Topic:
<input type="text" name="Topic" class="Input" style="width: 300px" required>
</label>
<br><br>
<label> Name:
<input type="text" name="Name" class="Input" style="width: 225px" required>
</label>
<br><br>
<label> Comment: <br>
<textarea name="Comment" class="Input" style="width: 300px" required></textarea>
</label>
<br><br>
<input type="Submit" name="Submit" value="Submit" class="Submit">
<!--idk-->
</form>
</center>
<hr>
<br>
</body>
<!--posts-->
</html>
<html>
<center>
</html>
<?php
if($_POST['Submit']){
print "<h1>Your comment has been submitted!</h1>";
}
?>
<html>
</center>
</html>
<?php
$Topic = $_POST['Topic'];
$Name = $_POST['Name'];
$Comment = $_POST['Comment'];
#Get old comments
$old = fopen("comments.txt", "r+t");
$old_comments = fread($old, 1024);
#Delete everything, write down new and old comments
$write = fopen("comments.txt", "w+");
$string = "<b>".$Topic."</b><br>".$Name."</b><br>".$Comment."</br>\n".$old_comments;
fwrite($write, $string);
fclose($write);
fclose($old);
#Read comments
$read = fopen("comments.txt", "r+t");
echo "<br><br>Comments<hr>".fread($read, 1024);
fclose($read);
?>
The problem you are facing is due to the way you are appending the comments to the "comments.txt" text file. The problem is that every time a comment is sent, all old and new comments are written to a text file. So when you refresh the page, the same comment is repeated.
Hope the following code helps
<?php
$Topic = $_POST['Topic'];
$Name = $_POST['Name'];
$Comment = $_POST['Comment'];
# Write the new comment to the top of the file
$write = fopen("comments.txt", "a+");
$string = "<b>".$Topic."</b><br>".$Name."</b><br>".$Comment."</br>\n";
fwrite($write, $string);
fclose($write);
# Read comments from the file
$read = fopen("comments.txt", "r");
echo "<br><br>Comments<hr>";
while(!feof($read)){
$line = fgets($read);
echo $line."<br>";
}
fclose($read);
?>
I have an HTML file that contains the following form:
<form action="" class="contact-form">
<div class="input-group tm-mb-30">
<input name="username" type="text" class="form-control rounded-0 border-top-0 border-end-0 border-start-0" placeholder="Name">
</div>
<div class="input-group tm-mb-30">
<input name="email" type="text" class="form-control rounded-0 border-top-0 border-end-0 border-start-0" placeholder="Email">
</div>
<div class="input-group tm-mb-30">
<textarea rows="5" name="message" class="textarea form-control rounded-0 border-top-0 border-end-0 border-start-0" placeholder="Message"></textarea>
</div>
<div class="input-group justify-content-end">
<input type="submit" class="btn btn-primary tm-btn-pad-2" value="Save">
</div>
</form>
It seems fine to me. I also have a php script:
> <?php
extract($_REQUEST);
> $file=fopen("form.txt.", "a");
fwrite($file, "----");
fwrite($file," name :");
fwrite($file, $username ."\n");
fwrite($file," email :");
fwrite($file, $email ."\n");
frwite($file," message .:");
fwrite($file, $message ."\n");
fclose($file);
> ?>
Both are in the same file, the form in between html tags, the php script after the /html tag.
If will not execute. No matter what I do, form.txt remains empty. form.txt is in the same directory and has 777.
Since I cannot find any problem with the script (there are no error messages in the apache log file), I am wondering if there is something wrong with the php on this server (there are also no entries in syslog). phpinfo page displays fine, and php --version tells me 8.2.1 is running.
I then changed action in form to "form.php" and added method=POST to test with separate script. form.php was simply:
<?php
echo "NAME:";
echo $username;
echo "EMAIL:";
echo $email;
echo "MESSAGE:";
echo $message;
echo "POSTNAME:";
echo $_POST['username'];
echo "POSTEMAIL:";
echo $_POST['email'];
echo "POSTMESSAGE:";
echo $_POST['message'];
?>
I did not get any output for the first three entries. But I got output for the last three entries. I expected to get output for all - since the form, by sending the inputs, should automatically create/define those variables. Am I wrong?
I then added this to form.php (in front of the code mentioned above) in order to define the variables:
if(isset($_POST['submit']))
{
//fetch form data
$username = $_POST['username'];
$email = $_POST['email'];
$message = $_POST['message'];
}
because I thought defining them would solve the problem. It did not. When executing form.php (by sending the form in the html), apache.log now tells me that $username, $email and $message are not defined. But I just defined them.... ärx
Remove the last dot (.) from filename form.txt.
WRONG FILE NAME form.txt.
$file=fopen("form.txt.", "a");
CORRECT FILE NAME
$file=fopen("form.txt", "a");
Now all entries will go to form.txt file.
Full Code is shared here:
Add form method as POST and add name='submit' to submit button
<form action="" class="contact-form" method="post">
<div class="input-group tm-mb-30">
<input name="username" type="text" class="form-control rounded-0 border-top-0 border-end-0 border-start-0" placeholder="Name">
</div>
<div class="input-group tm-mb-30">
<input name="email" type="text" class="form-control rounded-0 border-top-0 border-end-0 border-start-0" placeholder="Email">
</div>
<div class="input-group tm-mb-30">
<textarea rows="5" name="message" class="textarea form-control rounded-0 border-top-0 border-end-0 border-start-0" placeholder="Message"></textarea>
</div>
<div class="input-group justify-content-end">
<input type="submit" class="btn btn-primary tm-btn-pad-2" value="Save" name="submit">
</div>
</form>
If form is submitted then write to file. Also you have typo mistake in frwite which is corrected too here.
if(isset($_POST['submit'])){
extract($_REQUEST);
$file=fopen("form.txt", "a");
fwrite($file, "----");
fwrite($file," name :");
fwrite($file, $username ."\n");
fwrite($file," email :");
fwrite($file, $email ."\n");
fwrite($file," message .:");
fwrite($file, $message ."\n");
fclose($file);
}
So this solved it for me:
I added "name=submit" to the submit input in HTML. The form posts to form.php, which now looks like this:
<html>
<body>
<?php
// turn on error reporting
ini_set('error_reporting', 'on');
error_reporting(E_ALL);
// Remove all illegal characters from email
// $email_address = filter_var($email_address, FILTER_SANITIZE_EMAIL);
// check if form has been submitted
if(isset($_POST['submit']))
{
//fetch form data
$username = $_POST['username'];
$email = $_POST['email'];
$message = $_POST['message'];
//write form data
$fp = fopen('form.txt', 'a');
fwrite($fp, "---");
fwrite($fp,"name :");
fwrite($fp, $username ."\n");
fwrite($fp," email :");
fwrite($fp, $email ."\n");
fwrite($fp," message :");
fwrite($fp, $message ."\n");
fclose ($fp);
}
//show submitted data
echo "NAME:";
echo $username;
echo "<br>";
echo "EMAIL:";
echo $email;
echo "<br>";
echo "MESSAGE:";
echo $message;
echo "<br>";
echo "POSTNAME:";
echo $_POST['username'];
echo "<br>";
echo "POSTEMAIL:";
echo $_POST['email'];
echo "<br>";
echo "POSTMESSAGE:";
echo $_POST['message'];
echo "<br>";
// extract($_REQUEST); might need to be added
?>
The data has been submitted - thanks
</body>
</html>
For some reason, the extract command seems unnecessary; it works fine without it, but I am not sure why. Anyhow, the data is now processed into the file. I got it. Thanks so much, everyone!
I am struggling with the problem on my website. I should create an form to fill which will display new information/news. I have code like this:
<?php
include "0begin.php";
$title=$_POST["title"];
isset($title) or $title=$_GET["title"];
$msg=$_POST["msg"];
isset($msg) or $msg=$_GET["msg"];
?>
<h1>News</h1>
<form method="POST">
Title<br><input type=text input name="title" value=<?=$title?> ><br>
News<br>
<textarea input name="msg" cols=40 rows=5> </textarea><br>
<input type="submit">
<br><br>
</form>
<?php
$dateposted=date("YmdHis");
if (!empty($title) and !empty($msg)) {
$fp=fopen("/home/aqueen/public_html/news/".$dateposted."txt", "w");
fwrite($fp,$title,$msg);
fwirte($fp,$msg);
fclose($fp);
include "/home/aqueen/public_html/news/".$dateposted."txt"; }
?>
My questions:
1) How can I fix that code? It generates new file but without content inside.
2) It doesn't show the new file on the website /probably doesn't include it properly/
3) When it starts working- how I can let someone delete news from website without opening the code? /online/
Thank you in advance :)
Try this code:
<?php
//include "0begin.php";
$title = $_POST["title"];
$msg = $_POST["msg"];
?>
<h1>News</h1>
<form method="POST">
Title<br>
<input type="text" name="title"><br>
News<br>
<textarea name="msg" cols="40" rows="5"></textarea><br>
<input type="submit">
<br><br>
</form>
<?php
$dateposted=date("YmdHis");
if (!empty($title) and !empty($msg)) {
if (!file_exists('news/')) {
mkdir("news/", 0755);
}
if(file_exists($_SERVER['DOCUMENT_ROOT'] . "/news/")){
$pathGenerated = $_SERVER['DOCUMENT_ROOT'] . "/news/";
}
if(file_exists( "news/")){
$pathGenerated = "news/";
}
$pathGenerated = str_replace('//', '', $pathGenerated);
$fp=fopen($pathGenerated."".$dateposted.".txt", "w");
$textInsert = "Titolo: ".$title." \nMessaggio: ".$msg;
fwrite($fp,$textInsert);
fclose($fp);
include $pathGenerated."".$dateposted.".txt";
}
?>
Auto create folder /news/ if not exist.
I have a code of a form that writes the "email" of user into a .txt file in my server.
Here are some things I want to do: Make the form have more than one variable (Like, one line to "name" and another one to "email"), put the form writing in .txt prefixes before the "input" texts, and make the output .txt file have line breaks between the contents of each variable.
Here is my code currently
<?php
if(isset($_POST['submit']))
{
$email = $_POST['email'];
$file = fopen("emaillist.txt","a+");
fwrite($file,$email);
fclose($file);
print_r(error_get_last());
}
?>
<form action= "" method="post" name="form">
Email:
<input type="email" name="email">
<br>
<br>
<input type="submit" name="submit" value="submit">
<br>
</form>
Can you help me? Thank you all.
You can add another input to your form. In your code, you have <input type="email" name="email"> for the email address. Just add a <input type="text" name="name"> for the name. The field's name (name="xxx") is the key that you can use in PHP in $_POST['xxx'] to get the information for another line.
Did I understand your question "How can I put the form writting in .txt prefixes before the "input" texts?" correct that you want to have an output in your file like "Email: x#x.x"?
To add a line break, you can write "\n" (if you use a Windows System, use "\r\n") in your strings.
Instead of fopen(), fwrite() and fclose() you can use file_put_contents() which makes your code a bit easier to read.
You can try this code:
<?php
if(isset($_POST['submit']))
{
$name = $_POST['name'];
$email = $_POST['email'];
$new_content = "\r\nName: " . $name;
$new_content .= "\r\nEmail: " . $email;
file_put_contents('emaillist.txt', $new_content, FILE_APPEND);
print_r(error_get_last());
}
?>
<form action="" method="post" name="form">
Name:
<input type="text" name="name"><br>
Email:
<input type="email" name="email">
<br>
<br>
<input type="submit" name="submit" value="submit"><br>
</form>
Please try with following code .
<?php
if(isset($_POST['submit']))
{
$email = $_POST['email'];
$name=$_POST['name'];
$variable = $name ." ". $email. PHP_EOL;
$file = fopen("emaillist.txt","a+");
fwrite($file,$variable);
fclose($file);
print_r(error_get_last());
}
?>
<form action= "" method="post" name="form">
Email:
<input type="email" name="email">
<br>
Name:
<input type="name" name="name">
<br>
<br>
<input type="submit" name="submit" value="submit"><br>
</form>
So I have a variable well defined in a php page and I'm using it in an HTML page using include.
I am currently building a page where I can change the Var ( because it's a long text, more than one actually, and to change them it will be nice to have a page with a layout just for that) so I'm using a textbox and a submit button just like this:
<?php
$titre= 'Bienvenido a PARIS EXPERT LIMOUSINE ! ' ;
?>
<form method="post">
Titre: <input name="titre" type="text" id="titre" value="<?php echo htmlspecialchars($titre); ?>" size="50" maxlength="50">
<input type="submit" name="submit">
</form>
<?php
if (isset($_POST['submit']))
{
$titre = $_POST['titre'];
echo($titre);
}
?>
The problem is that in the echo it shows the new text but if I do a refresh it will show the old one...
any ideas how can I do this?
EDIT: Added extra fields and data handler. See extra code below original answer.
Here is some code I came up with to write content to a file.
Note: To add to the file with content written one under the other, use the a or a+ switch.
To create and write content to file and overwrite previous content, use the w switch.
This method uses the fwrite() function.
(tested)
Added to OP's code: action="write.php"
FORM
<?php
$titre= 'Bienvenido a PARIS EXPERT LIMOUSINE ! ' ;
?>
<form method="post" action="write.php">
Titre: <input name="titre" type="text" id="titre" value="<?php if(isset($_POST['titre'])){echo htmlspecialchars($_POST['titre']); }
else echo htmlspecialchars($titre); ?>" size="50" maxlength="50">
<input type="submit" name="submit">
</form>
PHP write to file handler (write.php)
This example uses the w switch.
<?php
if (isset($_POST['submit']))
{
$titre = $_POST['titre'];
echo($titre);
}
?>
<?php
$filename = "output.txt"; #Must CHMOD to 666 or 644
$text = $_POST['titre']; # Form must use POST. if it uses GET, use the line below:
// $text = $_GET['titre']; #POST is the preferred method
$fp = fopen ($filename, "w" ); # w = write to the file only, create file if it does not exist, discard existing contents
if ($fp) {
fwrite ($fp, $text. "\n");
fclose ($fp);
echo ("File written");
}
else {
echo ("File was not written");
}
?>
EDIT: Added extra fields and data handler.
Extra fields can be added, and must be followed in the same fashion in the file handler.
NEW FORM with extra fields
File data example: test | email#example.com | 123-456-7890
<?php
$titre= 'Bienvenido a PARIS EXPERT LIMOUSINE ! ' ;
?>
<form method="post" action="write.php">
Titre: <input name="titre" type="text" id="titre" value="<?php if(isset($_POST['titre'])){echo htmlspecialchars($_POST['titre']); }
else echo htmlspecialchars($titre); ?>" size="50" maxlength="50">
<br>
Email: <input name="email" size="50" maxlength="50">
<br>
Telephone: <input name="telephone" size="50" maxlength="50">
<input type="submit" name="submit">
</form>
<?php
if (isset($_POST['submit']))
{
$titre = $_POST['titre'];
echo($titre);
}
?>
PHP write to file handler
<?php
$titre = $_POST['titre'];
$email = $_POST['email'];
$telephone = $_POST['telephone'];
$data = "$titre | $email | $telephone";
$fp = fopen("data.txt", "a"); // a-add append or w-write overwrite
if ($fp) {
fwrite ($fp, $data. "\n");
fclose ($fp);
echo ("File written successfully.");
}
else{
echo "FAILED";
}
?>
<?php
if(!($titre = file_get_contents("filename.txt"))){
$titre= 'Bienvenido a PARIS EXPERT LIMOUSINE ! ' ;
}
?>
<form method="post">
Titre: <input name="titre" type="text" id="titre" value="<?php echo htmlspecialchars($titre); ?>" size="50" maxlength="50">
<input type="submit" name="submit">
</form>
<?php
if (isset($_POST['submit'])) {
$titre = $_POST['titre'];
if(#file_put_contents("filename.txt", $titre))){
echo 'Success - var stored.';
} else { echo 'Some error.'; }
echo($titre);
}
?>
Try this :
Titre: <input name="titre" type="text" id="titre" value="<?php if(isset($_POST['titre'])){echo htmlspecialchars($_POST['titre']); }
else echo htmlspecialchars($titre); ?>" size="50" maxlength="50">
If you need to keep your value for ever, you should store it in a database or save it in a file (could be .txt).
[EDIT]
Here is the code for .txt solution (you first create a file.txt in the same folder):
<?php
$file = 'file.txt';
$lines = file("file.txt");
if (!isset($lines[0])) {$titre='Bienvenido a PARIS EXPERT LIMOUSINE ! ';}
else {$titre=$lines[0];}
?>
<form method="post">
Titre: <input name="titre" type="text" id="titre" value="<?php if(isset($_POST['titre'])){echo htmlspecialchars($_POST['titre']); }
else echo htmlspecialchars($titre); ?>" size="50" maxlength="50">
<input type="submit" name="submit">
</form>
<?php
if (isset($_POST['submit']))
{
echo($_POST['titre']);
$titre = $_POST['titre']."\n".$titre;
file_put_contents($file, $titre);
}
?>
Hope it helps :)
this is normal because you're showing the new content upon form submission. When you refresh the page, unless you tell it to send the POST data again with the refresh (which the browser asks you for confirmation), your form (and hence the input field) will have nothing in.