PHP Contact form Validation / URL issue - php

I have a php contact form with validation but I have my .htaccess set so it strips the .php from the url so the url looks cleaner (like wp urls). The form works great except that when the user commits a validation error and presses "submit", the form validates fine, but it reloads the url with the .php extension and so if they fix their errors and submit again, my "outside url" hacking php code kicks in and doesn't send the form because the url's no longer match.
How can I either perform the validation without the page "reloading" or make it validate and reload without the .php extension in the url??
PHP:
<?php
// define variables and set to empty values
$nameErr = $fromErr = $messageErr = $subjectErr = $phoneErr = $verif_boxErr = "";
$inquiries = $name = $from = $subject = $message = $verif_box = "";
$errors = 0;
if ($_SERVER["REQUEST_METHOD"] == "POST") { //check if form has been submitted
//Get the inquiries field
$inquiries =$_POST['inquiries'];
if (empty($_POST["name"])) {
$nameErr = " * Name is missing";
$errors = 1;
echo '<style type="text/css"> input#name {border: 1px solid #F00; box-shadow: 0px 0px 5pt .1pt #F00 inset;}</style>';
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/", $name)) {
$nameErr = "Only letters and white space allowed";
$errors = 1;
echo '<style type="text/css"> input#name {border: 1px solid #F00; box-shadow: 0px 0px 5pt .1pt #F00 inset;}</style>';
}
}
if (empty($_POST["from"])) {
$fromErr = " * Email is missing";
$errors = 1;
echo '<style type="text/css"> input#from {border: 1px solid #F00; box-shadow: 0px 0px 5pt .1pt #F00 inset;}</style>';
} else {
$from = test_input($_POST["from"]);
// check if e-mail address is well-formed
if (!filter_var($from, FILTER_VALIDATE_EMAIL)) {
$fromErr = "Invalid email format";
$errors = 1;
echo '<style type="text/css"> input#from {border: 1px solid #F00; box-shadow: 0px 0px 5pt .1pt #F00 inset;}</style>';
}
}
if (empty($_POST["subject"])) {
$subjectErr = " * Subject is missing";
$errors = 1;
echo '<style type="text/css"> input#subject {border: 1px solid #F00; box-shadow: 0px 0px 5pt .1pt #F00 inset;}</style>';
} else {
$subject = test_input($_POST["subject"]);
}
if (empty($_POST["message"])) {
$messageErr = " * Message is missing";
$errors = 1;
echo '<style type="text/css"> textarea#message {border: 1px solid #F00; box-shadow: 0px 0px 5pt .1pt #F00 inset;}</style>';
} else {
$message = test_input($_POST["message"]);
}
if (empty($_POST["verif_box"])) {
$verif_boxErr = " * Security code is missing";
$errors = 1;
echo '<style type="text/css"> input#verif_box {border: 1px solid #F00; box-shadow: 0px 0px 5pt .1pt #F00 inset;}</style>';
} else {
$verif_box = test_input($_POST["verif_box"]);
if (md5($verif_box) . 'a4xn' <> $_COOKIE['tntcon']) {
$verif_boxErr = " * Security code does not match";
$errors = 1;
echo '<style type="text/css"> input#verif_box {border: 1px solid #F00; box-shadow: 0px 0px 5pt .1pt #F00 inset;}</style>';
}
}
if ($errors == 0) { // all fields successfullty validated. final hack check before sending email:
// Stop the form being used from an external URL
$referer = $_SERVER['HTTP_REFERER'] . ".php"; // Get the referring URL
$this_url = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER["REQUEST_URI"]; // Get the URL of this page
// If the referring URL and the URL of this page don't match then
// display a message and don't send the email.
if ($referer != $this_url) {
echo "You do not have permission to use this script from another URL, nice hacking attempt moron.";
exit;
} else { // send the email
$message = "Subject: " . $subject . "\n\nMessage: " . $message;
$message = "Inquiry: " . $inquiries . "\n" . $message;
$message = "Name: " . $name . "\n" . $message;
$message = "From: " . $from . "\n" . $message;
mail("milkytech#gmail.com", 'ContactUs: ' . $subject, $_SERVER['REMOTE_ADDR'] . "\n\n" . $message, "From: Contact#AntiqueCafeBakery.com");
setcookie('tntcon', ''); // delete the cookie so it cannot sent again by refreshing this page
header('Location: success'); // redirect to success page
exit();
}
}
}
function test_input($data)
{
$data = trim($data); // strip unnecessary characters (extra space, tab, newline) from the user input data
$data = stripslashes($data); // remove backslashes (\) from the user input data
$data = htmlspecialchars($data); // pass all variables through PHP's htmlspecialchars() function
return $data;
}
?>
HTML:
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" id="contactform">
<div>
<label for="name"><strong>Inquries:</strong></label>
<select name="inquiries" id="inquiries">
<option value="Catering">Catering</option>
<option value="Cookie Gift Tins">Cookie Gift Tins</option>
<option value="Retail Stores">Retail Stores</option>
<option value="Employment">Employment</option>
<option value="Investment">Investment</option>
</select>
</div>
<div>
<label for="name"><strong>Name:</strong></label>
<input type="text" size="50" name="name" id="name" value="<?php echo $name;?>"/><span class="error"><?php echo $nameErr;?></span>
</div>
<div>
<label for="email"><strong>Email:</strong></label>
<input type="text" size="50" name="from" id="from" value="<?php echo $from;?>"/><span class="error"><?php echo $fromErr;?></span>
</div>
<div>
<label for="subject"><strong>Subject:</strong></label>
<input type="text" size="50" name="subject" id="subject" value="<?php echo $subject;?>" />
</div>
<div>
<label for="message"><strong>Message:</strong></label>
<textarea rows="5" cols="69" name="message" id="message"><?php echo $message;?></textarea>
</div>
<div id="verif">
<span>Captcha Code:</span>
<input name="verif_box" type="text" size="10" id="verif_box"/>
<img id="imageid" class="verifbox" src="verificationimage.php?<?php echo rand(0,9999);?>" alt="verification image, type it in the box" />
<input type="button" value="Reload Captcha" id="reload" onclick="reloadImg()" />
<span class="error"><?php echo $verif_boxErr;?></span>
</div>
<div>
<input type="submit" value="Send Message" name="submit" />
<br /><br />
</div> <!--end form-->
</form>

I figured out a solution. I went back to w3 School to see exactly what $_SERVER["PHP_SELF"] does in form validation and it says this:
What is the $_SERVER["PHP_SELF"] variable?
The $_SERVER["PHP_SELF"] is a super global variable that returns the filename of the currently executing script.
What is the htmlspecialchars() function?
The htmlspecialchars() function converts special characters to HTML entities. This means that it will replace HTML characters like < and > with < and >. This prevents attackers from exploiting the code by injecting HTML or Javascript code (Cross-site Scripting attacks) in forms.
So I thought, if the variable $_SERVER["PHP_SELF"] is returning the filename (in this case - contact.php, there lies my problem so just replace $_SERVER["PHP_SELF"] with contact without the .php extension like below:
<form method="post" action="<?php echo htmlspecialchars(contact);?>" id="contactform">
And Voilà, it worked! But I'm not sure if this workaround creates a vulnerability for hackers.

Remove action value to submit on self page.
<form method="post" action="" id="contactform">
I hope this will work

Related

Contact Form Stopped working after adding implementing SSL, it's PHP based and was working fine before https was added

Contact Form on my website stopped working after adding implementing SSL, it's PHP based and was working fine for 5 years before when it was just http.
Now when the form is filled correctly the message *"Sorry! Unfortunately, your message could not be sent. The form as you filled it out is displayed below. Make sure each field completed, and please also address any issues listed below:" keeps appearing.
It might be a simple issue but I don't know PHP and found this on a tutorial - would really help if anyone point out the issue and how to resolve it.
I can provide more details if needed.
Thanks!!
<?php
// Information to be modified
$your_email = "mail#website.com"; // email address to which the form data will be sent
$subject = "Visitor Message from Website"; // subject of the email that is sent
$thanks_page = "thankyou.htm"; // path to the thank you page following successful form submission
$contact_page = "../contact.htm"; // path to the HTML contact page where the form appears
// Nothing needs to be modified below this line
if (!isset($_POST['submit'])) {
header( "Location: $contact_page" );
}
if (isset($_POST["submit"])) {
$nam = $_POST["name"];
$ema = trim($_POST["email"]);
$com = $_POST["comments"];
$spa = $_POST["spam"];
if (get_magic_quotes_gpc()) {
$nam = stripslashes($nam);
$ema = stripslashes($ema);
$com = stripslashes($com);
}
$error_msg=array();
if (empty($nam) || !preg_match("~^[a-z\-'\s]{1,60}$~i", $nam)) {
$error_msg[] = "The name field must contain only letters, spaces, dashes ( - ) and single quotes ( ' )";
}
if (empty($ema) || !filter_var($ema, FILTER_VALIDATE_EMAIL)) {
$error_msg[] = "Your email must have a valid format, such as name#mailhost.com";
}
$limit = 1000;
if (empty($com) || !preg_match("/^[0-9A-Za-z\/-\s'\(\)!\?\.,]+$/", $com) || (strlen($com) > $limit)) {
$error_msg[] = "The Comments field must contain only letters, digits, spaces and basic punctuation ( ' - , . ), and has a limit of 1000 characters";
}
if (!empty($spa) && !($spa == "4" || $spa == "four")) {
echo "You failed the spam test!";
exit ();
}
// Assuming there's an error, refresh the page with error list and repeat the form
if ($error_msg) {
echo '<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
<style>
body {background: #f7f7f7; font: 100%/1.375 georgia, serif;padding: 20px 40px;}
form div {margin-bottom: 10px;}
.content {width: 40%; margin: 0 auto;}
h1 {margin: 0 0 20px 0; font-size: 175%; font-family: calibri, arial, sans-serif;}
label {margin-bottom: 2px;}
input[type="text"], input[type="email"], textarea {font-size: 0.75em; width: 98%; font-family: arial; border: 1px solid #ebebeb; padding: 4px; display: block;}
input[type="radio"] {margin: 0 5px 0 0;}
textarea {overflow: auto;}
.hide {display: none;}
.err {color: red; font-size: 0.875em; margin: 1em 0; padding: 0 2em;}
</style>
</head>
<body>
<div class="content">
<h1>Sorry!</h1>
<p>Unfortunately, your message could not be sent. The form as you filled it out is displayed below. Make sure each field completed, and please also address any issues listed below:</p>
<ul class="err">';
foreach ($error_msg as $err) {
echo '<li>'.$err.'</li>';
}
echo '</ul>
<form method="post" action="', $_SERVER['PHP_SELF'], '">
<div>
<label for="name">Name</label>
<input name="name" type="text" size="40" maxlength="60" id="name" value="'; if (isset($_POST["name"])) {echo $nam;}; echo '">
</div>
<div>
<label for="email">Email Address</label>
<input name="email" type="email" size="40" maxlength="60" id="email" value="'; if (isset($_POST["email"])) {echo $ema;}; echo '">
</div>
<div>
<label for="comm">Comments</label>
<textarea name="comments" rows="10" cols="50" id="comm">'; if (isset($_POST["comments"])) {echo $com;}; echo '</textarea>
</div>
<div class="hide">
<label for="spam">What is two plus two?</label>
<input name="spam" type="text" size="4" id="spam">
</div>
<div>
<input type="submit" name="submit" value="Send">
</div>
</form>
</body>
</html>';
exit();
}
$email_body =
"Name of sender: $nam\n\n" .
"Email of sender: $ema\n\n" .
"COMMENTS:\n\n" .
"$com" ;
// Assuming there's no error, send the email and redirect to Thank You page
if (isset($_REQUEST['comments']) && !$error_msg) {
mail ($your_email, $subject, $email_body, "From: $nam <$ema>" . "\r\n" . "Reply-To: $nam <$ema>");
header ("Location: $thanks_page");
exit();
}
}

Unable to store data in the database

I am creating a PHP registration form using AJAX, the below code that I have pasted isn't working properly. I am literally new to this AJAX concept
When I click the register button it won't respond and do anything, and even in the database the values are not getting stored. I have searched a lot for this AJAX concept.
But I don't seem to get the result what I want. Please, can any one help me. Where am I actually doing the wrong thing? Thanks in advance!
index.php
<!DOCTYPE HTML>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="script.js"></script>
<style>
.error {
color:red;
}
.button {
background-color: #4CAF50;
border: none;
color: white;
padding: 10px 25px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
}
.div1 {
margin-top: -19px;
margin-bottom: -25px;
margin-left: -19px;
}
.copy {
border-radius: 4px;
padding: 6px 20px;
border-style: ridge;
}
.copy1{
border-radius: 4px;
padding: 6px 28px;
border-style: ridge;
}
.copy2{
border-radius: 4px;
padding: 4px 2px;
}
</style>
</head>
<body style="background-color: #f2f2f2;">
<?php
// define variables and set to empty values
include_once 'connect.php';
$nameErr = $emailErr = $usernameErr = $passwordErr = $ageErr = "" ;
$name = $email = $username = $password = $age = "";
if (isset($_POST['submit'])) {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["username"])) {
$usernameErr = "Username is required";
} else {
$username = test_input($_POST["username"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$username)) {
$usernameErr = "Only letters";
}
}
if (empty($_POST["password"])) {
$passwordErr = "Password is required";
} else {
$password = test_input($_POST["password"]);
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
// check weather password is alphanumeric
if(!preg_match('/^(?=.*\d)(?=.*[A-Za-z])[0-9A-Za-z!##$%]{6,}$/', $password))
{
$passwordErr = "Password must be alphanumeric and atleast 6 characters long!";
}
}
if (empty($_POST["age"])) {
$ageErr = "Age is required";
}
elseif($_POST["age"]< 17 ) {
$ageErr = "Age should be above 18 years";
}
else {
$age = $_POST["age"];
}
if($nameErr == "" && $emailErr == "" && $usernameErr == "" && $passwordErr == "" && $ageErr == "")
{
$check="SELECT * FROM users WHERE username = '$_POST[username]'";
$rs = mysqli_query($mysqli,$check);
$da = mysqli_fetch_array($rs, MYSQLI_NUM);
if($da[0] > 0) {
echo "Username Already in Exists<br/>";
}
else
{
$sql = "INSERT INTO users(`userid`,`username`, `password`, `email` , `name` , `age` )
VALUES ('','".$username."', '".$hashed_password."', '".$email."' , '".$name."' , '".$age."' )";
if (mysqli_query($mysqli, $sql)) {
echo "Registered successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($mysqli);
}
mysqli_close($mysqli);
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<div style="padding-left: 250px" class="div1">
<h2 style="color:#009999">Registration Form :</h2>
<p><span class="error">All fields are required </span></p>
<form action="" method="post" enctype="multipart/form-data">
<span style="color:#0099ff">Name: </span>
<input type="text" name="name" class= "copy" style="margin-left: 52px" value ="<?php
if (isset($name))
echo $name;
?>">
<span class="error"> <?php echo $nameErr;?></span>
<br><br>
<span style="color:#0099ff"> E-mail: </span>
<input type="text" name="email" class= "copy" style="margin-left: 48px" value ="<?php
if (isset($email))
echo $email;
?>">
<span class="error"><?php echo $emailErr;?></span>
<br><br>
<span style="color:#0099ff"> Username: </span>
<input type="text" name="username" class= "copy" style="margin-left:26px" value ="<?php
if (isset($username))
echo $username;
?>">
<span class="error"> <?php echo $usernameErr;?></span>
<br><br>
<span style="color:#0099ff"> Password: </span>
<input type="password" name="password" class= "copy" style="margin-left:30px">
<span class="error"> <?php echo $passwordErr;?></span>
<br><br>
<span style="color:#0099ff"> Age : </span>
<input type="number" name="age" class= "copy" style="margin-left:62px" value ="<?php
if (isset($age))
echo $age;
?>">
<span class="error"> <?php echo $ageErr;?></span>
<br><br>
<input type="button" class="submit" name="submit" value="submit">
</form>
</div>
</body>
</html>
script.js
$(document).ready(function(){
$(".submit").click(function(){
var name = $("name").val();
var email = $("email").val();
var username = $("username").val();
var password = $("password").val();
var age = $("age").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'name='+ name + '&email='+ email + '&username='+ username + '&password='+ password + '&age='+ age;
var dataString = $("form").serialize();
if(name==''|| email==''|| username==''|| password==''|| age=='')
{
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "index.php",
data: dataString,
cache: false,
success: function(result){
alert(result);
}
});
}
return false;
});
});
connect.php
<?php
$databaseHost = 'localhost';
$databaseName = 'ajax1';
$databaseUsername = 'root';
$databasePassword = '';
$mysqli = mysqli_connect($databaseHost, $databaseUsername, $databasePassword, $databaseName);
?>
Try this... I hope it will help you..
index.php
<!DOCTYPE HTML>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="script.js"></script>
<style>
.error {
color:red;
}
.button {
background-color: #4CAF50;
border: none;
color: white;
padding: 10px 25px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
}
.div1 {
margin-top: -19px;
margin-bottom: -25px;
margin-left: -19px;
}
.copy {
border-radius: 4px;
padding: 6px 20px;
border-style: ridge;
}
.copy1{
border-radius: 4px;
padding: 6px 28px;
border-style: ridge;
}
.copy2{
border-radius: 4px;
padding: 4px 2px;
}
</style>
</head>
<body style="background-color: #f2f2f2;">
<div style="padding-left: 250px" class="div1">
<h2 style="color:#009999">Registration Form :</h2>
<p><span class="error">All fields are required </span></p>
<form action="" method="post" enctype="multipart/form-data">
<span style="color:#0099ff">Name: </span>
<input type="text" name="name" class= "name copy" style="margin-left: 52px" value ="">
<span class="namee error"> </span>
<br><br>
<span style="color:#0099ff"> E-mail: </span>
<input type="text" name="email" class= "email copy" style="margin-left: 48px" value ="">
<span class="emaile error"></span>
<br><br>
<span style="color:#0099ff"> Username: </span>
<input type="text" name="username" class= "username copy" style="margin-left:26px" value ="">
<span class="usernamee error"></span>
<br><br>
<span style="color:#0099ff"> Password: </span>
<input type="password" name="password" class= "password copy" style="margin-left:30px">
<span class="passworde error"> </span>
<br><br>
<span style="color:#0099ff"> Age : </span>
<input type="number" name="age" class= "age copy" style="margin-left:62px" value ="">
<span class="agee error"> </span>
<br><br>
<input type="button" class="submit" name="submit" value="submit">
</form>
</div>
</body>
<script>
$(document).ready(function(){
$(".submit").click(function(){
var name = $(".name").val();
var email = $(".email").val();
var username = $(".username").val();
var password = $(".password").val();
var age = $(".age").val();
if(name==''){$('.namee').text('fill value'); return false}
if(email==''){$('.emaile').text('fill value'); return false}
if(username==''){$('.usernamee').text('fill value'); return false}
if(password==''){$('.passworde').text('fill value'); return false}
if(age==''){$('.agee').text('fill value'); return false}
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'name='+ name + '&email='+ email + '&username='+ username + '&password='+ password + '&age='+ age;
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "gethint.php",
data: dataString,
cache: false,
success: function(result){
alert(result);
}
});
});
});
</script>
</html>
gethint.php
<?php
$mysqli = mysqli_connect("localhost","root","","test");
$username =$_POST["username"];
$hashed_password=$_POST["password"];
$email=$_POST["email"];
$name=$_POST["name"];
$age=$_POST["age"];
$check="SELECT * FROM users WHERE username = '$_POST[username]'";
$rs = mysqli_query($mysqli,$check);
$da = mysqli_fetch_array($rs, MYSQLI_NUM);
if($da[0] > 0) {
echo "Username Already in Exists<br/>";
}
else
{
$sql = "INSERT INTO users(`userid`,`username`, `password`, `email` , `name` , `age` )
VALUES ('','".$username."', '".$hashed_password."', '".$email."' , '".$name."' , '".$age."' )";
if (mysqli_query($mysqli, $sql)) {
echo "Registered successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($mysqli);
}
mysqli_close($mysqli);
}
?>
The problem is when you run your index.php file for the first time , the php part gets executed.So make a new file for php part.
Get extra help From w3schools.com
https://www.w3schools.com/php/php_ajax_php.asp

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 assign an error for each entry from a different column

<?php
include ('database_connection.php');
include ('navigs.php');
if (isset($_POST['formsubmitted'])) {
$error = array();//Declare An Array to store any error message
if (empty($_POST['firstname'])) {//if no name has been supplied
$error[] = 'Please enter your firstname ';//add to array "error"
} else {
$firstname = $_POST['firstname'];//else assign it a variable
}
if (empty($_POST['nickname'])) {
$error[] = 'Please enter your nickname';
} else {
$nickname = $_POST['nickname'];
}
if (empty($_POST['email'])) {
$error[] = 'Please enter your e-mail ';
} else {
if (preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*#([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/", $_POST['email'])) {
//regular expression for email validation
$email = $_POST['email'];
} else {
$error[] = 'Your email address is invalid ';
}
}
if (empty($_POST['altemail'])) {
$error[] = 'Please enter your alternative email';
} else {
if (preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*#([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/", $_POST['altemail'])) {
$altemail = $_POST['altemail'];
} else {
$error[] = 'Not a valid email ';
}
}
if (empty($_POST['password'])) {
$error[] = 'Please enter a password ';
} else {
$password = $_POST['password'];
}
if (empty($error)) //send to Database if there's no error '
{ // If everything's OK...
// Make sure the email address is available:
$query_verify_email = "SELECT * FROM users WHERE Email ='$email' OR Altemail='$altemail' OR nickname='$nickname'";
$result_verify_email = mysqli_query($dbc, $query_verify_email);
if (!$result_verify_email) {//if the Query Failed ,similar to if($result_verify_email==false)
echo ' Database Error ';
}
if (mysqli_num_rows($result_verify_email) == 0) { // IF no previous user is using this email .
// Create a unique activation code:
$activation = md5(uniqid(rand(), true));
$query_insert_user = "INSERT INTO `users` ( `firstname`, `nickname`, `email`, `activation`, `altemail`, `password` ) VALUES ( '$firstname', '$nickname', '$email', '$activation', '$altemail', ENCRYPT('$password'))";
$result_insert_user = mysqli_query($dbc, $query_insert_user);
if (!$result_insert_user) {
echo 'Erreur SQL ';
}
if (mysqli_affected_rows($dbc) == 1) { //If the Insert Query was successfull.
// Send the email:
$message = " Pour activer ton compte, click sur ce lien:\n\n";
$message .= WEBSITE_URL . 'activate.php?email=' . urlencode($email) . "&key=$activation";
mail($altemail, 'Registration Confirmation', $message, 'From: noreply#mysite.org');
// Flush the buffered output.
// Finish the page:
echo '<div class="success">An email has been sent to the following addres: '.$altemail.' Please click on the link to activate your account </div>';
} else { // If it did not run OK.
echo '<div class="errormsgbox">An error has occurred please try again later .</div>';
}
} else { // The email address is not available.
echo '<div class="errormsgbox" >Either the nickname is already taken, the email address is already taken, or the alternative email you supplied is already on our system</div>';
}
} else {//If the "error" array contains error msg , display them
echo '<div class="errormsgbox"> <ol>';
foreach ($error as $key => $values) {
echo ' <li>'.$values.'</li>';
}
echo '</ol></div>';
}
mysqli_close($dbc);//Close the DB Connection
} // End of the main Submit conditional.
?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org /TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Create you email account</title>
<style type="text/css">
body {
font-family:"Lucida Grande", "Lucida Sans Unicode", Verdana, Arial, Helvetica, sans-serif;
font-size:12px;
}
.registration_form {
margin:0 auto;
width:500px;
padding:14px;
}
label {
width: 10em;
float: left;
margin-right: 0.5em;
display: block
}
.submit {
float:right;
}
fieldset {
background:#EBF4FB none repeat scroll 0 0;
border:2px solid #B7DDF2;
width: 500px;
}
legend {
color: #fff;
background: #80D3E2;
border: 1px solid #781351;
padding: 2px 6px
}
.elements {
padding:10px;
}
p {
border-bottom:2px solid #B7DDF2;
color:#666666;
font-size:13px;
margin-bottom:20px;
padding-bottom:9px;
}
a{
color:#0099FF;
font-weight:bold;
}
/* Box Style */
.success, .warning, .errormsgbox, .validation {
border: 1px solid;
margin: 0 auto;
padding:10px 5px 10px 50px;
background-repeat: no-repeat;
background-position: 10px center;
font-weight:bold;
width:450px;
}
.success {
color: #4F8A10;
background-color: #DFF2BF;
background-image:url('images/success.png');
}
.warning {
color: #9F6000;
background-color: #FEEFB3;
background-image: url('images/warning.png');
}
.errormsgbox {
color: #D8000C;
background-color: #FFBABA;
background-image: url('images/error.png');
}
.validation {
color: #D63301;
background-color: #FFCCBA;
background-image: url('images/error.png');
}
</style>
</head>
<body>
<form action="index.php" method="post" class="registration_form">
<fieldset>
<legend>Créer Un Compte Mail </legend>
<p>Create an email account <span style="background:#EAEAEA none repeat scroll 0 0;line-height:2;margin-left:220px;;padding:7px 7px;">Tu as un compe? Login</span> </p>
<div class="elements">
<label for="firstname">Firstname / Initiale :</label>
<input type="text" id="firstname" name="firstname" size="25" />
</div>
<div class="elements">
<label for="nickname">NickName :</label>
<input type="text" id="nickname" name="nickname" size="25" />
</div>
<div class="elements">
<label for="email">E-mail :</label>
<input type="text" id="email" name="email" size="25" />
</div>
<div class="elements">
<label for="altemail">Email de verification :</label>
<input type="text" id="altemail" name="altemail" size="25" />
</div>
<div class="elements">
<label for="password">Your Password :</label>
<input type="password" id="password" name="password" size="25" />
</div>
<div class="submit">
<input type="hidden" name="formsubmitted" value="TRUE" />
<input type="submit" value="Submit" />
</div>
</fieldset>
</form>
Go Back to Account Verification on sign up
</body>
Hi all What I am trying to achieve here is this:
When a user enters a username, an email address and an alternative email, to be able to check whether these entries do not already exist in the database and return an error accordingly.
For instance if the username is already taken it will warn the user to choose another usename and so on.
At the moment it only returns one error if any of the three entries is found, how can I do it in order to return an error according to the entry that is found in the table Please.
As an update, my question initially was to check two separate fields within the table,
First this form is to allow people to create their own email account, but for doing so, they also need to provide an existing email address in order to send them a link to activate their account.
I can check the three fields successfully but the problem I am having, is how to return an error for each of the fields separately.
At the moment I am only able to return the same error for any of the fields.
First it will check the validity of the email addresses
Second it will check if the email addresses both are not already on the system, the one the user is trying to create and the one he's providing as an alternative email address
Third it will check if the nickname is already taken.
Right now it does all of the above, the only problem I am having is how to get it to return an error for each one.
So the user won't get confused, and s/he would know which field to change in order to complete his / her registration.
If you could help me with just this
} else { // The email address is not available.
echo '<div class="errormsgbox" >Either the nickname is already taken, the email address is already taken, or the alternative email you supplied is already on our system</div>';
}
Thank you all for your help it is much appreciated
Do some print_r($error) between the different calls. Or use xdebug in order to step through your code.
Anyway I would advise you about using a CMS or Framework to build upon and not mixing all up in one file.
I suggest using a framework like Kohana, will make your life easier. This will also give you the ability to make sure only the specified fields are going through to the database, and sanitized. Don't want to deal with mass assignment (I'm bender from the future)
Create a set of rules for the available fields
$rules = array(
'email' => array(
'valid_email',
'not_empty'
),
'nickname' => array(
'not_empty',
)
)
Write a method to check against the rules and the get the messages back or return it to true.
foreach ($_POST as $field)
{
if (isset($rules[$field]))
{
// Check the rules
foreach ($rules[$field] as $rule)
{
$check = call_user_func(array(Valid, $rule), $field);
if ( !$check->isValid )
{
$this->errors[] = $check->message;
}
else
{
// Insert or do whatever you need to with the data
}
}
}
}

Categories