PHP Undefined error , trying to do email code - php

I tried to do email code, but I have error that I can't solve. Here is my code.
error:
Notice: Undefined index: action in line 5
code:
<?php
$Datacomment = 'data.txt';
$Key = '[#]';
$Key2 = '/n';
if($_POST['action'] == 'postcomment'){
$Name = str_replace(array($Key,$Key2),'',$_POST['name']);
$Comment = str_replace(array($Key,$Key2),'',$_POST['content']);
$Comment = $Name.$Key.$Comment.$Key2;
$Modwrite = 'a';
if(!file_exists($Datacomment)){
$Modwrite = 'w';
}
$File = fopen($Datacomment,$Modwrite);
fwrite($File,$Comment);
fclose($File);
header("Location: index.php"); /*replace comment.php by your homepage*/
}
/*load coment*/
if(!file_exists($Datacomment)){
$Showcomment = '<div class="showcomment">No comment</div>';
}
else{
$Cm = file_get_contents($Datacomment);
$Array = explode($Key2,$Cm);
$Total = count($Array) -1;
$Showcomment = '<h3 style="margin-left:1%;">'.$Total.' comments</h3>';
for($i = $Total-1;$i >= 0;$i--){
$Arraycm = explode($Key,$Array[$i]);
$Name = $Arraycm[0];
$Comment = $Arraycm[1];
$Showcomment .= '<div class="showcomment"><h4>'.$Name.'</h4>'.$Comment.'</div>';
}
}
?>
<style type="text/css">
.showcomment { width:96%; float:left; border:1px solid #ccc; padding:1%; margin:0 0 10px 1%; color:#333;}
.showcomment h4 { color:#03C; padding:0px; margin:0px;}
.comment {width:400px; height:100px; outline:none;}
.name { width:400px;outline:none}
</style>
<form style="margin-left:1%;" action="comment.php" method="post">
<input type="hidden" name="action" value="postcomment" />
<h3>Enter your name :</h3>
<input type="text" name="name" class="name" />
<h3>Eenter comment :</h3>
<textarea name="content" class="comment"></textarea>
<p>
<input type="submit" name="submit" value="SEND COMMENT" />
</p>
</form>
<?php echo $Showcomment;?>

the first time you enter a comment.php validate
if(isset($_POST['action']) && $_POST['action'] == 'postcomment'){
when press submit send the parameter "action"

Related

change input box value according to variable php and html

I am making a PHP project and am trying to change an input boxes value according to a PHP variable, how would I do this? So far, when I try to change the input boxes value it just changes the value to the name of the variable.
Here's the html for that section:
echo '
<html>
<title>Ramen</title>
<body>
<h1>
<p>Welcome to NoteBook!</p>
<form method="post">
<p>File Name:<input type="text" name="fname"></p>
<p>Type Here:<input type="text" name="content" id="TextBox" value="<?php echo $value; ?>"><p>
<p>Save:<input type="submit" value="Save"></p>
</form>
<form method="post">
<p>File to Open: <input type="text" name="filename"></p>
<input type="submit" value="Open">
</form>
</h1>
</body>
<style>
body{
background-color:#66b3ff;
}
p{
margin-left:30px;
}
h1{
background-color:white;
height:600px;
border-radius:1px;
font-size:18px;
font:italic;
}
#TextBox{
height:500;
width:700;
}
{
</style>
</html>```
$value doesn't appear to be being set anywhere.
I'm also a little confused as to why you have two <form>s.
As a starter, you need to parse the values coming in from the form, for example:
<?php
if (isset($_POST["filename"]) { // The $_POST variables are set using the name element of the <input> tag
$value = $_POST["filename"]
}
?>
You would likely want to do some more validation on the content of $_POST["value"] before accepting it.
Perhaps take a look at this example to get you started.
I leave you a possible example with explanation.
Besides, I have adapted the HTML structure a bit, since it has serious formatting problems. I advise you to read the manual on how to use the labels.
I added the name attribute to the submit, in order to know if the form is defined:
<input type="submit" name="save_data" value="Save">
Example:
<?php
// reset ¡important! (avoid warning <b>Warning</b>: Undefined variable etc..)
$file_name = $content = $txt_content = '';
// Recomended to check if the form is define
if (isset($_POST['save_data'])) {
// Get the inputs data
$file_name = $_POST['fname'] ?? '';
$content = $_POST['content'] ?? '';
// You can use textarea
$txt_content = $_POST['txt_content'] ?? '';
// Data is true
if ($file_name && $content && $txt_content) :
// Do somenting (ex: save it in DB)
//
//
$success = "Save correctly: $file_name";
// Data is empty (optional)
else :
$error = 'Te fields are empty.';
endif;
}
?>
<html lang="en-EN">
<head>
<title>Ramen</title>
<style>
body{
background-color:#66b3ff;
}
p {
margin-left:30px;
}
.wrapper {
background-color:white;
height:600px;
border-radius:1px;
font-size: 1rem;
font:italic;
padding: 1rem;
}
textarea {
height:200px;
width:400px;
}
.error {
color: red;
}
.success {
color: green;
}
</style>
</head>
<body>
<div class="wrapper">
<h1>Welcome to NoteBook!</h1>
<form method="post">
<lable for="fname">File Name:</lable>
<input type="text" name="fname" id="fname" value="<?php echo $file_name; ?>"></p>
<label for="content">Type Here:</label>
<input type="text" name="content" id="content" value="<?php echo $content; ?>">
<!-- for the content you could use the textarea tag -->
<textarea name="txt_content"><?php echo $txt_content; ?></textarea>
<input type="submit" name="save_data" value="Save">
<?php if (isset($error)) echo '<p class="error">' . $error . '</p>'; ?>
<?php if (isset($success)) echo '<p class="success">' . $success . '</p>'; ?>
</form>
</div>
</body>
</html>

How do i pass variables to another page in php?

I have moved over the validation to the bikeInfo.php file. Not much changes have been made to the code, but not sure why the validation is not being processed... appreciate the help!
<?php
$nameErr = $phoneErr = $emailErr = $sErr = $errorMsg = "";
$name = $phone = $email = $serial = $type = $formSubmit = $description = "";
?>
<head>
<title>Register your bikes!</title>
</head>
<style>
body {
margin-left: auto;
margin-right: auto;
text-align: center;
padding: 8px;
}
div.sellerInfo {
position: relative;
top: 50px;
}
.error {
position: absolute;
color: red;
}
</style>
<html>
<body>
<form method="post" action="bikeInfo.php">
<b style="font-size: 20px;">Bike Information</b>
</br></br>
<div class="sellerInfo">
Name:
<input type="text" name="sName" value="<?php echo $name;?>"/>
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
Phone:
<input type="text" name="sNum" value="<?php echo $phone;?>"/>
<span class="error">* <?php echo $phoneErr;?></span>
<br><br>
Email:
<input type="text" name="sEmail" value="<?php echo $email;?>"/>
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Serial:
<input type="text" placeholder="yy-nnn-cc" name="serial" value="<?php echo $serial;?>"/>
<span class="error">* <?php echo $sErr;?></span>
<br><br>
Type:
<input type="text" name="type" value="<?php echo $type;?>"/>
<span class="error">* <?php echo $errorMsg;?></span>
<br><br>
Description:
<textarea name="description" rows="5" cols="50" value="<?php echo $description;?>"></textarea>
<br><br>
<input type="submit" name="formSubmit" value="Submit"/>
</div><br><br><br>
</form>
</body>
</html>
This is my bikeInfo.php file which does validation and displaying of the submitted values. Not sure am i suppose to separate them...
<?php
//set to empty strings
$name = $phone = $email = $serial = $type = $formSubmit = $description = "";
$nameErr = $phoneErr = $emailErr = $sErr = $errorMsg = "";
if (isset($_POST["formSubmit"]))
{
if (empty($_POST["sName"]))
{
$nameErr = "Name is required";
} else {
$name = test_input($_POST['sName']);
}
//validate phone number
if (empty($_POST["sNum"]))
{
$phoneErr = "Phone number is required";
} else {
$phone = test_input($_POST['sNum']);
if (!is_numeric($phone)) //check for letters
{
$phoneErr = "No letters allowed";
}
}
//validate email
if (empty($_POST["sEmail"]))
{
$emailErr = "Email is required";
} else {
$email = test_input($_POST['sEmail']);
if (!filter_var($email, FILTER_VALIDATE_EMAIL))
{
$emailErr = "Invalid email format";
}
}
//validate serial
if (empty($_POST["serial"]))
{
$sErr = "Serial number is required";
} else {
$serial = test_input($_POST['serial']);
//determing the pattern of the serial no. yy-nnnn-cc
if (!preg_match("/[0-9][0-9]\-\d{3}\-[a-z]{2}/", $serial))
{
$sErr = "Format is yy-nnn-cc";
}
}
//validate type
if (empty($_POST["type"]))
{
$errorMsg = "Type is required";
} else {
$type = test_input($_POST["type"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<html>
<style>
.body {
text-align: center;
padding: 20px;
}
</style>
<body>
<h1 style="text-align:center; padding: 20px">Bike listings</h1>
<?php
$listings = $name . "<br>" . $phone . "<br>" . $email . "<br>" . $serial . "<br>" . $type . "<br>" . $description;
echo "<div style='text-align:center; padding: 50px'>$listings</div>";
?>
</body>
</html>
I had a little play about refactoring the code so that you could use a single page to perform both the validation and display. Perhaps it may be of use.
<?php
error_reporting( E_ALL );
$errors=array();
$nameErr = $phoneErr = $emailErr = $sErr = $errorMsg = '';
$sName = $sNum = $sEmail = $serial = $type = $description = '';
if( $_SERVER['REQUEST_METHOD']=='POST' && isset(
$_POST['sName'],
$_POST['sNum'],
$_POST['sEmail'],
$_POST['serial'],
$_POST['type']
)){
# modified to accept uppercase chars at end and limited to 2 integers at atart
$pttn='/[0-9]{2}\-\d{3}\-[a-zA-Z]{2}/';
# config to filter POST vars
$args=array(
'sName' => FILTER_SANITIZE_STRING,
'sNum' => FILTER_SANITIZE_STRING,
'sEmail' => FILTER_SANITIZE_EMAIL,
'serial' => FILTER_SANITIZE_STRING,
'type' => FILTER_SANITIZE_STRING,
'description' => FILTER_SANITIZE_STRING
);
# test for unaccounted POST fields - possibly malicious
foreach( $_POST as $field => $value ){
if( !in_array( $field, array_keys( $args ) ) ){
$errors[]=sprintf('Unknown field %s',$field);
}
}
if( empty( $errors ) ){
# rebuild the POST array with only filtered values
$_POST=filter_input_array( INPUT_POST, $args );
# extract known values from POST array into variables
extract( $_POST );
#error messages
$nameErr=empty( $sName ) ? 'Name is required' : '';
$phoneErr=empty( $sNum ) ? 'Phone number is required' : '';
$emailErr=empty( $sEmail ) ? 'Email is required' : '';
$sErr=empty( $serial ) ? 'Serial number is required' : '';
$errorMsg=empty( $type ) ? 'Type is required' : '';
# Validate particular variables
$sEmail=filter_var( $sEmail, FILTER_VALIDATE_EMAIL );
# to filter the phone number might remove leading zero and thus appear invalid
# possibly reassign error message variables
if( !preg_match( $pttn, $serial ) )$sErr='Invalid Serial. The format is: yy-nnn-cc';
if( !$sEmail )$emailErr='Invalid email format';
if( !$sNum )$phoneErr='Invalid phone number. No letters allowed!';
# save to database, email somewhere, write text etc etc
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Register your bikes!</title>
<style>
body {
margin:auto;
text-align:center;
padding:8px;
}
div.sellerInfo {
top:50px;
}
.error {
position:absolute;
color:red;
}
section{
margin:2rem auto;
width:300px;
padding:1rem;
display:block;
border:1px solid black;
}
section *{
text-align:left;
}
</style>
</head>
<body>
<form method='post'>
<b>Bike Information</b>
<div class='sellerInfo'>
<div>
Name:
<input type='text' name='sName' value='<?php echo $sName;?>' />
<span class='error'>* <?php echo $nameErr;?></span>
</div>
<div>
Phone:
<input type='text' name='sNum' value='<?php echo $sNum;?>' />
<span class='error'>* <?php echo $phoneErr;?></span>
</div>
<div>
Email:
<input type='text' name='sEmail' value='<?php echo $sEmail;?>' />
<span class='error'>* <?php echo $emailErr;?></span>
</div>
<div>
Serial:
<input type='text' placeholder='yy-nnn-cc' name='serial' value='<?php echo $serial;?>' />
<span class='error'>* <?php echo $sErr;?></span>
</div>
<div>
Type:
<input type='text' name='type' value='<?php echo $type;?>' />
<span class='error'>* <?php echo $errorMsg;?></span>
</div>
<div>
Description:
<textarea name='description' rows='5' cols='50' value='<?php echo $description;?>'></textarea>
</div>
<input type='submit' />
</div>
</form>
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' && isset(
$sName,
$sNum,
$sEmail,
$serial,
$type,
$description
)){
if( empty( $errors ) ){
printf('
<section>
<h1 style="text-align:center; padding: 20px">Bike listings</h1>
<ul>
<li>%s</li>
<li>%s</li>
<li>%s</li>
<li>%s</li>
<li>%s</li>
<li>%s</li>
</ul>
</section>',
$sName,
$sNum,
$sEmail,
$serial,
$type,
$description
);
}else{
foreach( $errors as $error )printf('<div class="error">%s</div>',$error);
}
}
?>
</body>
</html>

Posting form data of one form as nested json in a json file that has data from another file

Title of this question can be confusing. I'm clarifying it here. I've 2 forms: One for timeline and another one for events.
HTML code:
<link rel="stylesheet" type="text/css" href="jquery-ui.css">
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="jquery-ui.js"></script>
<style>
.error {color: #FF0000;}
/* The Modal (background) */
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
padding-top: 100px; /* Location of the box */
left: 0;
top: -75px;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}
/* Modal Content */
.modal-content {
position: relative;
background-color: #fefefe;
margin: auto;
padding: 0;
border: 1px solid #888;
width: 80%;
box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2),0 6px 20px 0 rgba(0,0,0,0.19);
-webkit-animation-name: animatetop;
-webkit-animation-duration: 0.4s;
animation-name: animatetop;
animation-duration: 0.4s
}
/* Add Animation */
#-webkit-keyframes animatetop {
from {top:-300px; opacity:0}
to {top:0; opacity:1}
}
#keyframes animatetop {
from {top:-300px; opacity:0}
to {top:0; opacity:1}
}
/* The Close Button */
.close {
color: white;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
.modal-header {
padding: 2px 16px;
background-color: #5cb85c;
color: white;
}
.modal-body {padding: 2px 16px;}
.modal-footer {
padding: 2px 16px;
background-color: #5cb85c;
color: white;
}
</style>
<div id="btnDiv">
<button id="btn">Click here to create a new time line!</button>
<button id="btnOne">Click here to create a new Event!</button>
</div>
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<div class="modal-header">
<span class="close">X</span>
<h2>Modal Header</h2>
</div>
<div class="modal-body">
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail: <input type="text" name="email">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Website: <input type="text" name="website">
<span class="error"><?php echo $websiteErr;?></span>
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"></textarea>
<br><br>
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
qwe: <textarea name="qwe" rows="5" cols="40"></textarea>
<br><br>
rty: <textarea name="rty" rows="5" cols="40"></textarea>
<br><br>
abc: <textarea name="abc" rows="5" cols="40"></textarea>
<br><br>
def: <textarea name="def" rows="5" cols="40"></textarea>
<br><br>
dob: <input type="text" id="dob" name="dob">
<br><br>
<input type="submit" value="Submit">
</form>
</div>
<div class="modal-footer">
<h3>Modal Footer</h3>
</div>
</div>
</div>
<div id="myModalOne" class="modal">
<!-- Modal content -->
<div class="modal-content">
<div class="modal-header">
<span class="close">X</span>
<h2>Modal Header</h2>
</div>
<div class="modal-body">
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail: <input type="text" name="email">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Website: <input type="text" name="website">
<span class="error"><?php echo $websiteErr;?></span>
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"></textarea>
<br><br>
dob: <input type="text" id="dobOne" name="dob">
<br><br>
<input type="submit" value="Submit">
</form>
</div>
<div class="modal-footer">
<h3>Modal Footer</h3>
</div>
</div>
</div>
<script>
$(function() {
$( "#dob" ).datepicker();
$( "#dobOne" ).datepicker();
});
//modal for timeline
// Get the modal
var modal = document.getElementById('myModal');
// Get the button that opens the modal
var btn = document.getElementById("btn");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks the button, open the modal
btn.onclick = function() {
modal.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
//modal for events
// Get the modal
var modalOne = document.getElementById('myModalOne');
// Get the button that opens the modal
var btn = document.getElementById("btnOne");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks the button, open the modal
btn.onclick = function() {
modalOne.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modalOne.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modalOne.style.display = "none";
}
}
function alertjson(e) {
var file = new XMLHttpRequest();
var file_path =
file.open(validation-data.json, r);
}
</script>
PHP code:
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = $qwe = $rty = $abc = $def = $dob = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
}
if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
}
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}
if (empty($_POST["qwe"])) {
$qweErr = "Gender is required";
} else {
$qwe = test_input($_POST["qwe"]);
}
if (empty($_POST["rty"])) {
$rtyErr = "Gender is required";
} else {
$rty = test_input($_POST["rty"]);
}
if (empty($_POST["abc"])) {
$abcErr = "Gender is required";
} else {
$abc = test_input($_POST["abc"]);
}
if (empty($_POST["def"])) {
$defErr = "Gender is required";
} else {
$def = test_input($_POST["def"]);
}
if (empty($_POST["dob"])) {
$dobErr = "Gender is required";
} else {
$dob = test_input($_POST["dob"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
// echo $data; //print data
}
$file = dirname(__FILE__).'/validation-data.json';
$file_content = file_put_contents($file, json_encode($_REQUEST, JSON_PRETTY_PRINT));
//echo $file_content;
//var_dump($file_content);
?>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
echo "<br>";
echo $qwe;
echo "<br>";
echo $rty;
echo "<br>";
echo $abc;
echo "<br>";
echo $def;
echo "<br>";
echo $dob;
?>
PHP code which writes form data to json is:
$file = dirname(__FILE__).'/validation-data.json';
$file_content = file_put_contents($file, json_encode($_REQUEST, JSON_PRETTY_PRINT));
Whenever I submit the data of any one form, it gets written to json file successfully. This is the example json:
{
"name": "asd",
"email": "test#attendize.website",
"website": "esdfs",
"comment": "qasdas",
"dob": "08\/03\/2016"
}
If I fill the data of another form and submit, then old values are just replaced by new values. But I want new data to written into same json file as nested values. How can I do it?
This should be a temporary solution because it's not perfect and it could be achieved in safer and more reliable way. This limits a little bit by how it works, so you should tweak this for better results. But in general it is working and some things were changed quite much.
All PHP code (except with Your Input sentence) was mode above HTML and JS.
This will solve Notice errors because right now I have enabled error_reporting to show all errors and both modals are full of these notices.
In your second modal I also put new line (just before submit line):
<input type="hidden" value="1" name="secondModal">
Finally, modified PHP code (a lot, actually).
All areas that were changed are at the end of PHP code.
if (empty($_POST["dob"])) {
$dobErr = "Gender is required";
} else {
$dob = test_input($_POST["dob"]);
}
// All those ifs above
// Add all values into array
$array = array(
'name' => $name,
'email' => $email,
'website' => $website,
'comment' => $comment,
'gender' => $gender,
'qwe' => $qwe,
'rty' => $rty,
'abc' => $abc,
'def' => $def,
'dob' => $dob
);
// Was this the second modal?
if ($_POST['secondModal'] == 1) {
// Get serialized values from temporary file
$content = file_get_contents('temp_array.txt');
$array = unserialize($content);
// Add into already existing array new values
$array['name2'] = $name;
$array['email2'] = $email;
$array['website2'] = $website;
$array['comment2'] = $comment;
$array['dob2'] = $dob;
// Add newly modified array into .json file
$file = dirname(__FILE__).'/validation-data.json';
file_put_contents($file, json_encode($array, JSON_PRETTY_PRINT));
} else {
// Serializing array for much easier reading when we use this later
$results = serialize($array);
file_put_contents('temp_array.txt', '');
file_put_contents('temp_array.txt', $results);
}
// End of PHP code
The main idea here is that store serialized $array into temporary .txt file. After we fill out second Modal, we retrieve the same array by unserializing it and adding new values. Then we store into .json file.
This will result in 1 array with values from both modals.

PHP form-calling function failing to work properly

I have my index.php form and if a valid student name and student number are entered I'd like "Student name and number are valid." to be echoed.
I have validated the student names and student numbers. However, even when entering a valid student name and student number the message echoed is "The information you have entered is not valid. Please enter your information again."
I'm calling the function validateStudent but I must be calling it in the wrong place or incorrectly. This function is called towards the end of the PHP scrip and just before the HTML starts. Thank you.
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
// Define and set variables
$student = "";
$studentname = "";
$studentnumber = "";
$studentfile = "student.txt";
$course = "";
$coursename = "";
$coursenumber = "";
$coursemax = 0;
$coursefile = "course.txt";
$in = fopen ('course.txt', 'r') or die ("course.txt cannot be opened for reading.");
// Sanitization and Validation coding will go here
if (isset($_POST['submit'])) {
$studentname = $_POST['studentname'];
$studentnumber = $_POST['studentnumber'];
}
if (isset($_POST['studentname'])) {
$studentname = strip_tags ($_POST['studentname']);
$studentname = htmlentities ($_POST['studentname']);
}
if (isset($_POST['studentnumber'])) {
$studentnumber = strip_tags ($_POST['studentnumber']);
$studentnumber = htmlentities ($_POST['studentnumber']);
}
if (isset($_POST['course'])) {
$course = strip_tags ($_POST['course']);
$course = htmlentities ($_POST['course']);
}
$studentname = trim($_POST['studentname']);
$studentnumber = trim($_POST['studentnumber']);
// Validate student name/number against text file
function validateStudent($studentName, $studentNumber)
{
$found = false;
$fh = fopen('student.txt', 'r');
while(($line = fgetcsv($fh, null, ':')) != false) {
if(count($line) > 1) {
if($line[0] == $studentName and $line[1] == $studentNumber) {
$found = true;
break;
}
}
}
return $found;
}
// Validate course name/number against text file
function validateCourse($courseName, $courseNumber, $courseMax)
{
$found = false;
$fh = fopen('course.txt', 'r');
while(($line = fgetcsv($fh, null, ':')) != false) {
if(count($line) > 1) {
if($line[0] == $courseName and $line[1] == $courseNumber and $line[2] == $courseMax) {
$found = true;
break;
}
}
}
return $found;
}
//$DB = fopen ($coursefile, 'r') or die ("$coursefile cannot be opened for reading.");
//while ($record = fgets ($DB) ) {
//$field = explode (":", htmlentities (trim ($record)));
//echo "<option value=\"$field[1]\">$field[0] $field[1] $field[2]</option>\n";
//}
//fclose ($DB);
if (isset ($_POST[$studentname], $_POST[$studentnumber])) {
validateStudent($_POST['$studentname'], $_POST['$studentnumber']);
echo 'Student name and number are valid.\n';
}
else {
echo '<p style="color: red; text-align: center; font-size: 15px; font-weight: bold;">**The information you have entered is not valid. Please enter your information again.**</p>';
}
?>
<html>
<head>
<title>Registration Form</title>
<style>
body{background-color: #ffffe6; width:610px;}
h1 {color: #29a3a3;}
.inputbox {padding: 7px; border: #FF9966 1px solid; border-radius: 4px;}
.btn {padding: 10px; background-color: #29a3a3; border: solid 1px #FF9966; border-radius: 4px; color: #FFFFFF; font-weight: bolder; cursor: pointer;}
</style>
</head>
<body>
<h1>Course Registration</h1>
<form method="post" action="index.php">
<fieldset><legend><strong>Student Information</strong></legend>
<dl>
<dt>Student Name:</dt>
<dd><input class="inputbox" name="studentname" type="text" id="studentname" value='<?php echo htmlentities($studentname) ?>' required autofocus placeholder="Please enter your first and last name" tabindex="10" size="50"></dd>
<br>
<br>
<dt>Student Number:</dt>
<dd><input class="inputbox" name="studentnumber" type="text" id="studentnumber" value='<?php echo htmlentities($studentnumber) ?>' required placeholder="Please enter using the following format: PX-03-046" tabindex="20" size="50"></dd>
</dl>
<br>
</fieldset>
<br>
<fieldset><legend><strong>Course Selection</strong></legend>
<br>
Select a Course:<select name="course" tabindex="30">\n";
<option value="-1" >Available Courses...</option>
<?php
while(($fields = fgetcsv($in, null, ':')) != false) {
if (count($fields) > 1) {
echo "
<option value=\"$fields[1]\">$fields[0] $fields[1]</option>";
}
}
?>
</select>
<br>
<br>
<br>
<br>
<br>
<br>
</fieldset>
<div>
<p>
<input name="reset" type="reset" tabindex="40" value="Clear Form" class="btn">
<input name="submit" type="submit" tabindex="50" value="Submit Form" class="btn">
</p>
</div>
</form>
</body>
</html>
Your code has a logical error:
if (isset ($_POST[$studentname], $_POST[$studentnumber])) {
validateStudent($_POST['$studentname'], $_POST['$studentnumber']);
echo 'Student name and number are valid.\n';
}
else {
echo '<p style="color: red; text-align: center; font-size: 15px; font-weight: bold;">**The information you have entered is not valid. Please enter your information again.**</p>';
}
your code should be:
if (isset ($_POST['studentname'], $_POST['studentnumber'])) {
if (validateStudent($_POST['studentname'], $_POST['studentnumber'])){
echo 'Student name and number are valid.\n';
}
else {
echo '<p style="color: red; text-align: center; font-size: 15px; font-weight: bold;">**The information you have entered is not valid. Please enter your information again.**</p>';
}
}
also you need a form to post your variables studentname and studentnumer like:
<form method="post">
<input type="text" name="studentname"/>
<input type="text" name="studentnumber"/>
<input type="submit" name="submit"/>
</form>
Your output is because your variables $_POST['studentname'] and $_POST['studentnumber'] are not set.

How to validate form with php and show the error text in html

I want to validate form using php and then make the input save in json file. I used span class to echo the error message from writer.php to html. But it's not echo the error text in html, it's refer to writer.php with blank page.
<head>
<title>Data Buku</title>
<link rel="stylesheet" type="text/css" href="style.css">
<link href='http://fonts.googleapis.com/css?family=Ribeye+Marrow' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Comfortaa' rel='stylesheet' type='text/css'>
</head>
<body>
<div class="center">
<h1>Data Buku</h1>
<p><span class="error">* required field.</span></p>
<hr>
<form action="writer.php" method="post">
<span class="error"><?php echo $error;?></span>
<h2>Informasi Pengarang</h2>
Nama: <br><input type="text" name="nama" id="nama" />
<span class="error">* <?php echo $namaErr;?></span><br>
Nomor Telepon: <br><input type="text" name="telepon" id="telepon" />
<span class="error">* <?php echo $nomorErr;?></span><br>
e-Mail: <br><input type="email" name="email" id="email" />
<span class="error">* <?php echo $emailErr;?></span><br>
<h2>Tulisan</h2>
Judul: <br><input type="text" name="judul" id="judul" />
<span class="error">* <?php echo $judulErr;?></span><br>
Konten: <br><textarea name = "konten" rows="6" cols="50" id="konten"></textarea>
<span class="error">* <?php echo $kontenErr;?></span><br>
<input type="submit" id="submit" name = submit value="Create" />
<input type="reset" id="reset" value="Reset" />
</form>
</div>
</body>
This is my php file
<?php
// Append new form data in json string saved in json file
// path and name of the file
$filetxt = 'dataInJson.json';
// error message
$namaErr = "";
$nomorErr = "";
$emailErr = "";
$judulErr = "";
$kontenErr = "";
// check if all form data are submited, else output error message
if(isset($_POST['submit'])) {
// if form fields are empty, outputs message, else, gets their data
if(empty($_POST['nama'])) {
$namaErr = "Write your name";
}
if(empty($_POST['telepon'])){
$nomorErr = "Write the phone number";
}
if(empty($_POST['email'])){
$emailErr = "Write the email";
}
if(empty($_POST['judul'])){
$judulErr = "Write the title";
}
if(empty($_POST['konten'])) {
$kontenErr = "Write the content";
}
else {
// gets and adds form data into an array
$data = array(
'nama'=> $_POST['nama'],
'telepon'=> $_POST['telepon'],
'email'=> $_POST['email'],
'judul'=> $_POST['judul'],
'konten'=> $_POST['konten'],
);
// path and name of the file
$filetxt = 'dataInJson.json';
$arr_data = array(); // to store all form data
// check if the file exists
if(file_exists($filetxt)) {
// gets json-data from file
$jsondata = file_get_contents($filetxt);
// converts json string into array
$arr_data = json_decode($jsondata, true);
}
// appends the array with new form data
$arr_data[] = $data;
// encodes the array into a string in JSON format (JSON_PRETTY_PRINT - uses whitespace in json-string, for human readable)
$jsondata = json_encode($arr_data, JSON_PRETTY_PRINT);
// saves the json string in "dataInJson.json"
// outputs error message if data cannot be saved
if(file_put_contents('dataInJson.json', $jsondata)){
echo '<script type="text/javascript">alert("Data has been submitted");</script>';
}
else{
echo 'Tidak dapat menyimpan data di "dataInJson.json"';
}
}
}
else echo 'Form fields not submited';
?>
You would need the page to submit to itself unless you did an AJAX solution so this would all have to be on one page:
<?php
error_reporting(E_ALL);
class ValidateInfo
{
public $errors;
public $message;
public $data;
public function Check($payload = array(),$type = "error",$mess = "unknown",$validate = array())
{
$trimmed = trim($payload[$type]);
if(!empty($validate)) {
// Strip out everything but numbers and letters and a couple of symbols.
if(in_array('digits',$validate) && in_array('letters',$validate)) {
$this->data[$type] = preg_replace('/[^0-9a-zA-Z\s\-\_]/','',$trimmed);
}
// Strip out all but numbers
elseif(in_array('digits',$validate)) {
$this->data[$type] = preg_replace('/[^0-9]/','',$trimmed);
}
// Strip out letters
elseif(in_array('letters',$validate)) {
$this->data[$type] = preg_replace('/[^a-zA-Z\s\-\_]/','',$trimmed);
}
// Re-assign data type to consolidate
$this->data[$type] = (!isset($this->data[$type]))? $trimmed:$this->data[$type];
// Check if data is an email
if(in_array('email',$validate)) {
$this->data[$type] = (filter_var($this->data[$type], FILTER_VALIDATE_EMAIL))? $this->data[$type]:'';
}
// Strip out html tags
if(in_array('strip',$validate)) {
$this->data[$type] = strip_tags($this->data[$type]);
}
}
if(!isset($this->data[$type]))
$this->data[$type] = $trimmed;
$this->errors[$type] = (empty($this->data[$type]))? 1:0;
$this->message[$type] = $mess;
}
}
// Creat instance of info processor
$info = new ValidateInfo();
// check if all form data are submited, else output error message
if(isset($_POST['submit'])) {
// Checks empty fields
$info->Check($_POST,'nama','Write your name',array('letters','digits'));
$info->Check($_POST,'telepon','Write the phone number',array('digits'));
$info->Check($_POST,'email','Write the email',array('email'));
$info->Check($_POST,'judul','Write the title',array('letters','digits'));
$info->Check($_POST,'konten','Write the content', array('letters','digits','strip'));
if(array_sum($info->errors) == 0) {
// path and name of the file
$filetxt = 'dataInJson.json';
// Assign stored data
$data = $info->data;
// path and name of the file
$filetxt = 'dataInJson.json';
// to store all form data
$arr_data = array();
// check if the file exists
if(file_exists($filetxt)) {
// gets json-data from file
$jsondata = file_get_contents($filetxt);
// converts json string into array
$arr_data = json_decode($jsondata, true);
// appends the array with new form data
$arr_data[] = $data;
// encodes the array into a string in JSON format (JSON_PRETTY_PRINT - uses whitespace in json-string, for human readable)
$jsondata = json_encode($arr_data, JSON_PRETTY_PRINT);
// saves the json string in "dataInJson.json"
// outputs error message if data cannot be saved
if(file_put_contents('dataInJson.json', $jsondata)) {
$info->errors['success'] = true; ?>
<script type="text/javascript">
alert("Data has been submitted");
</script>
<?php }
else {
$info->message['general']['put_file'] = 'Tidak dapat menyimpan data di "dataInJson.json"';
}
}
else {
$info->message['general']['bad_file'] = 'No file exists';
}
}
}
else
$info->message['general']['submit'] = 'Form fields not submited'; ?>
<head>
<title>Data Buku</title>
<link rel="stylesheet" type="text/css" href="style.css">
<link href='http://fonts.googleapis.com/css?family=Ribeye+Marrow' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Comfortaa' rel='stylesheet' type='text/css'>
</head>
<style>
.error { color: red; clear: left; float: left; display: inline-block; width: 100%; font-size: 12px; }
input,
textarea { float: left; clear: left; display: inline-block; font-size: 20px; color: #333; padding: 10px; }
label { font-family: Arial, Helvetica, sans-serif; font-size: 14px; color: #888; float: left; clear: left; display: inline-block; }
div.roadie { width: 500px; border-bottom: 1px solid #CCC; display: inline-block; float: left; clear: both; padding: 10px; }
</style>
<body>
<div class="center">
<h1>Data Buku</h1>
<?php if(isset($info->errors['success'])) { ?>
<h2>Thank you!</h2>
<?php } else { ?>
<p><span class="error">* required field.</span></p>
<?php } ?>
<hr>
<form action="" method="post">
<?php if(isset($info->message['general'])) {
foreach($info->message['general'] as $_error) { ?>
<span class="error">* <?php echo $_error; ?></span><br>
<?php
}
} ?>
<h2>Informasi Pengarang</h2>
<div class="roadie">
<label for="nama">Nama:</label>
<input type="text" name="nama" id="nama"<?php if(isset($info->data['nama'])) { ?> value="<?php echo strip_tags($info->data['nama']); ?>" /><?php } ?>
<?php if(isset($info->errors['nama']) && $info->errors['nama'] == 1) { ?><span class="error">* <?php echo $info->message['nama']; ?></span><?php } ?>
</div>
<div class="roadie">
<label for="telepon">Nomor Telepon:</label>
<input type="text" name="telepon" id="telepon"<?php if(isset($info->data['telepon'])) { ?> value="<?php echo strip_tags($info->data['telepon']); ?>"<?php } ?> />
<?php if(isset($info->errors['telepon']) && $info->errors['telepon'] == 1) { ?><span class="error">* <?php echo $info->message['telepon']; ?></span><?php } ?>
</div>
<div class="roadie">
<label for="email">e-Mail:</label>
<input type="email" name="email" id="email"<?php if(isset($info->data['email'])) { ?> value="<?php echo strip_tags($info->data['email']); ?>"<?php } ?> />
<?php if(isset($info->errors['email']) && $info->errors['email'] == 1) { ?><span class="error">* <?php echo $info->message['email']; ?></span><br><?php } ?>
</div>
<div class="roadie">
<h2>Tulisan</h2>
<label for="judul">Judul:</label>
<input type="text" name="judul" id="judul"<?php if(isset($info->data['judul'])) { ?> value="<?php echo strip_tags($info->data['judul']); ?>"<?php } ?> />
<?php if(isset($info->errors['judul']) && $info->errors['judul'] == 1) { ?><span class="error">* <?php echo $info->message['judul']; ?></span><?php } ?>
</div>
<div class="roadie">
<label for="konten">Konten:</label>
<textarea name = "konten" rows="6" cols="50" id="konten"><?php if(isset($info->data['konten'])) { echo strip_tags($info->data['konten']); } ?></textarea>
<?php if(isset($info->errors['konten']) && $info->errors['konten'] == 1) { ?><span class="error">* <?php echo $info->message['konten']; ?></span><br><?php } ?>
</div>
<input type="submit" id="submit" name = submit value="Create" />
<input type="reset" id="reset" value="Reset" />
</form>
</div>
</body>
Your if/else statements are wrong. Your else execute only if !empty($_POST['konten']).
I suggest you, pull errors in to one array, stored in session in redirect user (if scripts in different files) and show content of errors array. If you have trouble with logic, view this question here - PHP form validation submitting

Categories