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 />
Related
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>';
I am beginner in PHP and I want to check whether user has filled the input named "jmeno". Name of the corresponding variable is the same. If the input is not entered, then the variable "chybi" should be expanded by text "Zadej jméno!" and that text should appear above the form.
I am getting no errors. If the input is filled, then the form proceeds. If not, then the form doesn't proceed - that works how it's supposed to. But the error message in variable "chybi" doesn't display for some unknown reason in case that the variable "jmeno" is empty (second if).
I have tried many things. It's strange that such a simple script doesn't work. Any ideas? Thank you.
<?php
$chybi = '';
$zacatek = '
<p>some long text</p>
<form action="index.php" method="post" class="akce">
<p>' .$chybi.
'<input type="text" name="jmeno" placeholder="Zadej své jméno," /></p>
<p>
vyber pohlaví<br />
<input type="radio" name="pohlavi" value="žena" /> žena<br />
<input type="radio" name="pohlavi" value="muž" /> muž
</p>
<p>a pokud se nebojíš, <input type="submit" value="vstup!" /></p>
</form>
';
if ( isset($_POST['jmeno']) && isset($_POST['pohlavi']) ) {
$jmeno = $_POST['jmeno'];
$pohlavi = $_POST['pohlavi'];
if ( empty($jmeno) ) {
$chybi .= 'Zadej jméno!<br />';
echo $zacatek;
}
else {
echo "Jmenuješ se $jmeno a jsi $pohlavi.";
}
}
else {
echo $zacatek;
}
?>
As #jylipaa pointed out you're echoing $chybi before setting it's value. Move your logic above the $zacatek varaible.
<?php
$chybi = '';
if ( isset($_POST['jmeno']) && isset($_POST['pohlavi']) ) {
$jmeno = $_POST['jmeno'];
$pohlavi = $_POST['pohlavi'];
if ( empty($jmeno) ) {
$chybi .= 'Zadej jméno!<br />';
}
else {
echo "Jmenuješ se $jmeno a jsi $pohlavi.";
}
}
$zacatek = '
<p>some long text</p>
<form action="index.php" method="post" class="akce">
<p>' .$chybi.
'<input type="text" name="jmeno" placeholder="Zadej své jméno," /></p>
<p>
vyber pohlaví<br />
<input type="radio" name="pohlavi" value="žena" /> žena<br />
<input type="radio" name="pohlavi" value="muž" /> muž
</p>
<p>a pokud se nebojíš, <input type="submit" value="vstup!" /></p>
</form>
';
echo $zacatek;
?>
you are setting $zacatek in the start of code where $chybi is still empty. It is then handled as a string and setting the value of $chybi later on will not change the content of a string afterwards.
I have following form in html
<form method="post" enctype="multipart/form-data" />
<fieldset>
<legend>Activate Scheme</legend>
<p>Date Of Draw</p>
<p><input type="text" name="dateOfDraw" class="textBox" style="width:150px" /></p>
<p>Time Of Draw</p>
<p><input type="text" class="textBox" name="timeOfDraw" style="width:150px" /></p>
<p>Enter scheme name</p>
<p><input type="text" class="textBox" name="schemeName" style="width:150px" />
</p>
<p>Upload Image</p>
<p><input type="file" name="image" id="image" /></p>
<p><input name="scheme_button" type="submit" class="button1" value="Submit"></p>
</fieldset>
</form>
Problem is that their is no error when I execute the following query
<?php
if(isset($_POST['submit_button']) && count($_POST)>0) {
print_r($_POST);
$dateOfDraw = $_POST['dateOfDraw'];
$timeOfDraw = $_POST['timeOfDraw'];
$schemeName = $_POST['schemeName'];
$imageName = $_FILES['image']['name'];
$destination = '../images/'.$imageName;
$source = $_FILES['image']['tmp_name'];
if(move_uploaded_file($source, $destination)) {
echo 'file uploaded';
} else {
echo ' file not uploaded';
}
$sSQL = "INSERT INTO landing_page(dateOfDraw, timeOfDraw, schemeName, image) VALUES('$dateOfDraw','$timeOfDraw','$schemeName','$imageName')";
echo $sSQL;
if(!$sSQL){
die(mysqli_query($con));
}
mysqli_query($con,$sSQL);
//header("location: list_products.php");
}
?>
but when I check my data in a mysql database the rows are still empty. Please check it am I missing something or the php code is wrong.
Note: I am using php version 5.5.16
The name of your submit button is scheme_button and that's exactly the thing that you need to $_POST.
if(isset($_POST['scheme_button']) && count($_POST) > 0)
You form doesn't have an action and it doesn't know where to go. So add one.
<form method="post" action="index.php" enctype="multipart/form-data" />
firstly you have to name of submit button
if(isset($_POST['scheme_button']) && count($_POST) > 0)
secondly if insert code in same page then
if insert code in another page then
action = "filename"
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.
I'm designing a fairly simple reporting system. Right now using php(and later some Jquery) to let user log in and calculate totals and post to a database. My problems began of course when I tested the page in IE8. It has major problems with the echo <<<_END statement at line 75. Anyone know an alternate to coding the nested HTML in the PHP besides this. any help is appreciated.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<HTML>
<HEAD>
<link rel="stylesheet" type="text/css" href="OPSstyle.css" />
</HEAD>
<BODY>
<div id="wrapper">
<div id="bodyContent">
<div id="header">
<img id="logo" src="OPS_logo.gif" alt="OPS Logo"/>
<p>OPS ASSESSMENT</p>
</div>
<div id="leftNav">
<p>To begin please login</p>
Test Login<br/>
Form Test<br/>
</div>
<div id="content">
<?php
//Connects to database
require_once 'login.php';
$db_server = mysql_connect($db_hostname, $db_username, $db_password);
if(!$db_server) die("Unable to connect to MySQL: " .mysql_error());
mysql_select_db($db_database)
or die ("unable to select database: " .mysql_error());
//deletes record
if(isset($_POST['delete']) && isset($_POST['AssessmentID']))
{
$AssessmentID = get_post('AssessmentID');
$query2 = "DELETE FROM assessmentscores WHERE AssessmentID='$AssessmentID'";
if(!mysql_query($query2, $db_server))
echo "Delete Failed: $query(br />" .
mysql_error() . "<br /><br />";
}
//Inserts record
if (isset ($_POST['AssessmentID'])&&
isset($_POST['Date']) &&
isset($_POST['Inspector']) &&
isset($_POST['PlantAssist']) &&
isset($_POST['Safety_Total'])
)
{
$AssessmentID = get_post('AssessmentID');
$Date = get_post('Date');
$Inspector = get_post('Inspector');
$PlantAssist =get_post('PlantAssist');
$Safety_Total = get_post('Safety_Total');
;
$query = "INSERT INTO opsassessment.assessmentscores(AssessmentID, Date, Inspector, PlantAssist, `Safety_Total`) VALUES" .
"('$AssessmentID', '$Date', '$Inspector', '$PlantAssist', '$Safety_Total')";
if (!mysql_query($query, $db_server))
echo "INSERT failed: $query<br />" .
mysql_error() . "<br /><br />";
}
echo <<<_END
<form action = "sqltest.php" method="post"><pre>
AssessmentID <input type="text" name="AssessmentID" /><br>
Date <input type="text" name="Date" /><br>
Inspector <input type="text" name="Inspector" /><br>
PlantAssist <input type="text" name="PlantAssist" /><br>
Safety_Total <input type="text" name="Safety_Total" /><br>
<input type="submit" value="ADD RECORD" /><br>
</pre></form>
_END;
$query = "SELECT * FROM assessmentscores";
$result = mysql_query($query);
if (!$result) die("Database access failed: " .mysql_error());
$rows = mysql_num_rows($result);
for($j = 0; $j < $rows; ++$j)
{
$row= mysql_fetch_row($result);
echo <<<_END
<pre>
AssessmentID: $row[0]
Date: $row[1]
Inspector: $row[2]
PlantAssist: $row[3]
Safety_Total: $row[4]
</pre>
<form action="sqltest.php" method="post">
<input type ="hidden" name="delete" value ="yes" />
<input type = "hidden" name="AssessmentID" value = "$row[0]" />
<input type ="submit" value="DELETE RECORD" /></form>
_END;
}
mysql_close($db_server);
function get_post($var)
{
return mysql_real_escape_string($_POST[$var]);
}
?>
</div>
Login Form<br><br>
OPS Assessment
</div>
</body>
</html>
The Heredoc identifier must on a line of itself and must be the only thing on this line (including indentation and such). Remove the leading whitespace and make sure the newline is direct after _END;.
However, in your case I suggest you to just leave the PHP-mode to output the plain html
For example instead of
echo <<<_END
<form action = "sqltest.php" method="post"><pre>
AssessmentID <input type="text" name="AssessmentID" /><br>
Date <input type="text" name="Date" /><br>
Inspector <input type="text" name="Inspector" /><br>
PlantAssist <input type="text" name="PlantAssist" /><br>
Safety_Total <input type="text" name="Safety_Total" /><br>
<input type="submit" value="ADD RECORD" /><br>
</pre></form>
_END;
this
?>
<form action = "sqltest.php" method="post"><pre>
AssessmentID <input type="text" name="AssessmentID" /><br>
Date <input type="text" name="Date" /><br>
Inspector <input type="text" name="Inspector" /><br>
PlantAssist <input type="text" name="PlantAssist" /><br>
Safety_Total <input type="text" name="Safety_Total" /><br>
<input type="submit" value="ADD RECORD" /><br>
</pre></form>
<?php
Its usually more readable and many IDEs are capable to recognize it and highlight the "other stuff" as html.
As the commenter says, the HEREDOC (the <<< and _END;) bits are server side PHP related, the browser should know nothing of them.
One major, easily forgettable golden rule of HEREDOC tags is that the closing tag CAN NOT BE INDENTED, EVER! Or it will break.
Heres a read about them:
http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc
If its really breaking things, and its really this thats doing it (though, no reason why it should be) - remember its just a block of output, so you could replace it at a stroke with:
$out = "blah blah";
$out .= "more blah blah";
$out .= "more blah blah";
$out .= "more blah blah";
$out .= "more blah blah";
echo $out;