Define php var after textbox - php

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.

Related

PHP - I can't save content from input

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.

Something wrong with PHP

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).

Trying to pass variable values from PHP to a new HTML file

using PHP 5.6.27 I'm trying to generate a HTML file by combining
(1) Input from form fields
(2) HTML code (template)
Issue: The file gets created but only has the $template value but not the form field input.
Code is below. Also Live link is at http://fastlaw.in/formv2.html
Sure I'm missing something simple, but would appreciate it if anyone can help out.
formv2.html
<form action="formscriptv2.php" method="POST">
<input id="field1" type="text"/> <br />
<input id="field2" type="text" /> <br />
<input type="submit" name="submit" value="Save Data">
</form>
formscriptv2.php
<?php
$Field1 = $_POST['field1'];
$Field2 = $_POST['field2'];
$onepart = "
<div class='table table-left'>
<section>
<h2 class='table-heading'>";
$twopart = "</h2>
<table class='data'>
<caption>
<p>";
$threepart = "</p>
</caption>
";
$template = $onepart . $Field1 . $twopart . $Field2 . $threepart;
$ret = file_put_contents('tmp/mydata.txt', $template, FILE_APPEND | LOCK_EX);
if($ret === false) {
die('There was an error writing this file');
}
else {
echo "$ret bytes written to file";
}
?>
PHP $_POST array are populated via the name HTML attribute:
<input id="field1" name="field1" type="text"/> <br />
<input id="field2" name="field2" type="text" /> <br />

Passing PHP variable data onto another page after validation

While I found something similar to this question on here it didn't answer my question outright.
I have set up this php script to validate the form data, which works, after its validated I want it to then pass the info onto another script page to let the user then verify their input data and then mail the data. Its at this state that I'm having trouble. I've spent the last few days trying to find a solution to this and unfortunately coming up short.
<?php
$name_error = '';
$email_error = '';
$comments_error = '';
$error = false;
if (!empty($_POST['submitted']))
{ //if submitted, the validate.
$name = trim($_POST['name']);
if (empty($name))
{
$name_error='Name is required';
$error = true;
}
$email = trim($_POST['email']);
/* If e-mail is not valid show error message */
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email))
{
$email_error='E-mail address not valid';
$error = true;
}
$comments = trim($_POST['comments']);
if (empty($comments))
{
$comments_error='Comments are required';
$error = true;
}
if ($error == false)
{
$name_send = $name;
$email_send = $email;
$comments_send = $comments;
/* Redirect visitor to the thank you page */
header('Location: /mail.php');
exit();
}
}
The form this is attached to:
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>" method="post">
<label>Your Name</label><br />
<input type="text" name="name" style="width:95%" class="text" value='<?php echo htmlentities($name) ?>' />
<br/>
<span class='error'><?php echo $name_error ?></span>
<br />
<label>Email</label><br />
<input type="email" name="email" style="width:95%" class="text" value='<?php echo htmlentities($email) ?>' />
<br/>
<span class='error'><?php echo $email_error ?></span>
<br />
<label for="comments" style="font-size:16px;">Feedback Comments</label><br />
<textarea name="comments" style="width:95%;" rows="8" value='<?php echo htmlentities($comments) ?>'></textarea>
<br />
<span class='error'><?php echo $comments_error ?></span>
<br />
<input type="checkbox" name="allowCommentPublish" checked="checked" />
<label for="allowCommentPublish" style="font-size:10px;">Allow these comments to be used on our website</label>
<fieldset class="optional">
<h2>[ OPTIONAL ]</h2>
<label>Company Name</label><br />
<input type="text" name="companyName" style="width:95%" class="text" />
<br/>
<label>Phone</label><br />
<input type="text" name="phone" style="width:95%" class="text" /><br/>
<div style="margin:5px 0px;">
<input type="checkbox" name="incmarketing" />
<label style="font-size:10px;"> Yes, you can email me specials and promotions.</label>
<br/>
</div>
</fieldset>
<fieldset>
<input type="submit" name="submitted" value="Send" />
</fieldset>
I will point out im focusing on the main data inputs: Name E-mail and comments.
I need the info from this form to be sent onward but i dont know exactly how to do this and any help will be appreciated greatly.
For passing the values to next page you will have to use either of the three methods.
1. Set cookies with the data.
2. Use global variable session.
3.Pass the data in the url.
For cookies u can set cookies with the values like
setcookie('name',$name);
in ur next page read those cookie data
For sessions:
$_SESSION['name']= $name;
for reading data from cookies & session:
$name = $_COOKIE['name'];
$name = $_SESSION['name'];
For using sessions you must add the line
session_start();
at the start of both the pages that send or receive(use) the data
and for urls
header('Location: /mail.php?name=$name&email=$email&comment=$comments');
Read more on using session
If you need to pass values from one script to another you can use $_SESSION variables. To start a session use: (at the top of the php script)
session_start();
$_SESSION['somename'] = $somevariable;
To access or get that same variable you can use this:
session_start();
$some_other_variable = $_SESSION['somename'];
or you can use hidden input fields.
You can use hidden fields and javascript to submit the form. However as this is the same php page as the original form you will need an if statement
echo '<form name="newForm" action="newpage.php" method="POST">';
echo '<input type="hidden" name="name2" value"' . $name . '">;
echo '<input type="hidden" name="email2" value"' . $email . '">;
echo '<input type="hidden" name="comments2" value"' . $comments . '"></form>;
echo '<script> if (document.getElementById("name2").value != ""){window.onload = function(){ window.document.newForm.submit(); }} </script>';

Get variable from query string

I was trying to get variable in Query String from URL. But somehow, its just got one variable instead of getting all variables from querystring. I really don't know what goes wrong with my code. Here is the code I want to print out error from the invalidate form:
<?php
displayForm();
function displayForm(){
?>
<form action="./prod_add_action.php" method="post" name="addproductForm">
<fieldset>
<legend>Online Ordering System Setup</legend>
<label for="product_name">Product Name: </label><input type="text" name="product_name" value="" /><?php echo $_GET["name_error"]; ?>
<label for="product_date">Product Date: </label><input type="text" name="product_date" value="" /><?php echo $_GET["date_error"]; ?>
<label for="product_price">Product Price: </label><input type="text" name="product_price" value="" /><?php echo $_GET["price_error"]; ?>
<input name="add_button" type="submit" value="Add" />
<input name="reset_button" type="reset" value="Clear" />
</fieldset>
</form>
<?php
}
?>
And here is the code I created the querystring:
$query_string = "name_error=" .urlencode($name_error) ."&date_error=" .urlencode($date_error) ."&price_error=" .urlencode($price_error);
header("Location: ./prod_add.php?$query_string");
exit();
In the first code, the page only print the first $_GET['name_error'], while it should be include $_GET['date_error'] and $_GET['price_error. ']
This is the address:
http://example.com/prod_add.php?name_error=Product+name+must+be+characters+only&date_error=Product+date+must+be+input+as+this+formate+DD-MM-YYYY&price_error=Product+price+must+be+float+number+only
You should use & instead of &'s ?
$query_string = "name_error=" .urlencode($name_error) ."&date_error=" .urlencode($date_error) ."&price_error=" .urlencode($price_error);
header("Location: ./prod_add.php?$query_string");
exit();
Change & to & as:
$query_string = "name_error=" . urlencode($name_error) . "&date_error=" . urlencode($date_error) . "&price_error=" . urlencode($price_error);
header("Location: ./prod_add.php?$query_string");
exit();

Categories