unable to execute the ajax code - php

im creating a php registration form using ajax, the below code that i have pasted isnt seems to be working , im literially new to this ajax concept
when i click the register button it wont respond anything, and even in the database the values are not getting stored i have seached a lot for this ajax concept
but i don seem to get the result what i want please can any one help me where im actually going wrong please help me.
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['name'])) {
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);
?>

Update the submit button with submit class
<input type="button" class="submit" name="submit" value="submit">
Update the js code with . insted of # // as # is for id
$(".submit").click(function(){
Also, use the form serialize
var dataString = $("form").serialize();
Php code change the submit to name
if(isset($_POST['name']))

Related

Password hasing in PHP login system

I´m not very expirence in programming.
I want to build a login system in PHP with some security mesures on it. I consult a video on youtube to help me and I found this one: https://www.youtube.com/watch?v=pIO0pmMTJ6Y&list=PLiJgIxJAg1VZqxDFL1Lp9VTm8PRfFeQ-o&index=18&t=5666s
The question is that don´t include any password hashing function, so i add it myself on the signup.php ant it works !!! But now, i´m not able to login to the site with a password created on th signup page. I try to chang the login.php code but don´t have success. What I have to do to resolve?
signup.php
<?php
require "../private/autoload.php";
$Error ="";
$email = "";
$username = "";
if($_SERVER["REQUEST_METHOD"]=="POST")
{
$email =$_POST["email"];
if(!preg_match("/^[\w\-]+#[\w\-]+.[\w\-]+$/",$email))
{
$Error = "Please enter a valid email";
}
$date = date ("Y-m-d H:i:s");
$url_address = get_random_string(60);
$username = trim($_POST["username"]);
if(!preg_match("/^[a-zA-Z]+$/",$username))
{
$Error = "Please enter a valid username";
}
$username = esc($username);
$password = esc($_POST["password"]);
$passwordhashed = password_hash($password,PASSWORD_DEFAULT);
$arr = false;
$arr['email']= $email;
$query = "SELECT * FROM USERS WHERE email = :email limit 1";
$stm = $connection->prepare($query);
$check = $stm->execute($arr);
if($check)
{
$data = $stm->fetchAll(PDO::FETCH_OBJ);
if(is_array($data) && count ($data) > 0)
{
$Error = "Someone is already using that email";
}
}
if($Error =="")
{
$arr['url_address'] = $url_address;
$arr['date'] = $date;
$arr['username'] = $username;
$arr['password'] = $passwordhashed;
$arr['email'] = $email;
$query = "insert into users(url_address,username,password,email,date) values(:url_address,:username,:password,:email,:date)";
$stm = $connection->prepare($query);
$stm->execute($arr);
header ("Location: login.php");
die;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>
Signup
</title>
<h1 style="text-align:center"><span style="font-family:Arial,Helvetica,sans-serif"><strong>Bem-Vindo ao Website</strong></span></h1>
<h2 style="text-align:center"><span style="color:#999999"><span style="font-family:Arial,Helvetica,sans-serif"><strong>Faz o teu signup para acederes ao site</strong></span></span></h2>
<p><span style="font-family:Arial,Helvetica,sans-serif"><strong> </strong></span></p>
<p style="text-align:center"> </p>
<p style="text-align:center"> </p>
<body style="font-family: verdana">
<style type="text/css">
form {
margin: auto;
border: solid thin #aaa;
padding: 1px;
max-width: 200px;
}
#title {
background-color: #256972;
padding: 1cm;
text-align: center;
color: white;
}
#textbox {
border: solid thin #aaa;
margin-top: 6px;
width: 98%;
}
</style>
<form method="post">
<div><?php
if(isset($Error) && $Error != "")
{
echo $Error;
}
?>
<div id="title">Signup</div>
<input id="textbox" type="text" name="username" value="<?=$username?>" placeholder="username" required><br>
<input id="textbox" type="email" name="email" value="<?=$email?>" placeholder="email" required><br>
<input id="textbox" type="password" name="password" placeholder="password" required><br><br>
<input type="submit" value="Signup">
</form>
</body>
</head>
</html>
login.php
<?php
require "../private/autoload.php";
$Error = "";
if($_SERVER["REQUEST_METHOD"]=="POST" && isset ($_SESSION ['token']) && isset ($_POST ['token']) && $_SESSION ['token'] == $_POST["token"])
{
$email =$_POST["email"];
if(!preg_match("/^[\w\-]+#[\w\-]+.[\w\-]+$/",$email))
{
$Error = "Please enter a valid email";
}
$password = ($_POST["password"]);
$passwordhashed = password_hash($password,PASSWORD_DEFAULT);
if($Error ==""){
$arr['password'] = $passwordhashed;
$arr['email'] = $email;
$query = "SELECT * FROM USERS WHERE email = :email && password = :password limit 1";
$check = $stm->execute($arr);
if($check){
$data = $stm->fetchAll(PDO::FETCH_OBJ);
if(is_array($data) && count ($data) > 0){
$data = $data[0];
$_SESSION['username'] = $data->username;
$_SESSION['url_address'] = $data->url_address;
header ("Location: index.php");
die;
}
}
}
$Error = "Wrong email or password";
}
$_SESSION ['token'] = get_random_string(60);
?>
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
<body style="font-family: verdana">
<style type="text/css">
form {
margin: auto;
border: solid thin #aaa;
padding: 1px;
max-width: 200px;
}
#title {
background-color: #256972;
padding: 1cm;
text-align: center;
color: white;
}
#textbox {
border: solid thin #aaa;
margin-top: 6px;
width: 98%;
}
</style>
<form method="post">
<div><?php
if(isset($Error) && $Error != "")
{
echo $Error;
}
?>
<div id="title">Login</div>
<input id="textbox" type="email" name="email" placeholder="email" required><br>
<input id="textbox" type="password" name="password" placeholder="password" required><br><br>
<input type="hidden" name="token" value="<?=$_SESSION ['token']?>">
<input type="submit" value="Login">
</form>
</body>
</head>
</html>
function.php
<?php
function get_random_string ($length)
{
$array = array (0,1,2,3,4,5,6,7,8,9,'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z');
$text = "";
$lenght = rand(4,$length);
for ($i=0;$i<$lenght;$i++) {
$random = rand(0,61);
$text .=$array[$random];
}
return $text;
}
function esc($word)
{
return addslashes ($word);
}
function check_login ($connection)
{
if(isset($_SESSION['url_address']))
{
$arr['url_address'] = $_SESSION['url_address'];
$query = "SELECT * FROM USERS WHERE url_address = :url_address limit 1 && password = :password limit 1";
$stm = $connection->prepare($query);
$check = $stm->execute($arr);
if($check)
{
$data = $stm->fetchAll(PDO::FETCH_OBJ);
if(is_array($data) && count ($data) > 0)
{
return $data[0];
}
}
}
header("Location: login.php");
die;
}
I won't answer directly, but here is the doc for hashing password with php:
first
// let's say you have a $passwordToHash variable
$passwordHashed = password_hash($passwordToHash, PASSWORD_DEFAULT);
then, you could verify that you passwordHashed is equal to passwordToHash (when you want to check if a password is in your db for ex)
// true or false
password_verify($passwordToHash, $passwordHashed)

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

How to limit blank space in the input field?

<!DOCTYPE HTML>
<html>
<head>
<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 {
background-color: #f2f2f2;
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>
<?php
session_start();
if (isset($_SESSION['id'])){
header('location:welcome.php');
}
?>
<?php
// define variables and set to empty values
include_once 'connect.php';
$nameErr = $emailErr = $usernameErr = $passwordErr = $DateOfBirthErr = $departmentErr = $ageErr = $fileToUploadErr = $fileToUploadErrr = $fileToUploadErrrr = $fileToUploadErrrrr = $fileToUploadErrrrrr = "" ;
$name = $email = $username = $password = $DateOfBirth = $department = $age = $fileToUpload = $filename = $file = "";
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["Date_of_birth"])) {
$DateOfBirthErr = "Date Of Birth is required";
} else {
$DateOfBirth = test_input($_POST["Date_of_birth"]);
}
if (empty($_POST["department"])) {
$departmentErr = "Department is required";
} else {
$department = test_input($_POST["department"]);
}
if (empty($_POST["age"])) {
$ageErr = "Age is required";
} else {
$age = test_input($_POST["age"]);
}
//UPLOAD FILE
$uploaddir = 'upload/';
$uploadfile = $uploaddir . basename($_FILES['fileToUpload']['name']);
$imageFileType = pathinfo($uploadfile,PATHINFO_EXTENSION);
if($_FILES['fileToUpload']['name'] != '')
{
// Check the image is actaully image or not
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check == false)
{
$fileToUploadErrrrr = "File is not an image.";
}
// Check if file already exists
if (file_exists($uploadfile)) {
$fileToUploadErrrrrr = "Sorry, file already exists.";
}
if($imageFileType != "jpg" && $imageFileType != "png" )
{
$fileToUploadErr = "Sorry, only JPG,PNG files are allowed.";
}
elseif($_FILES['fileToUpload']['size'] > 500000)
{
$fileToUploadErrrr = "Sorry, your file is too large.";
}
else
{
/* if($filename != '')
{
$target = "upload/".$filename;
unlink($target);
}*/
$uploaded = move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $uploadfile);
if ($uploaded) {
$file = $_FILES['fileToUpload']['name'];
}
else{
$file = $filename;
}
}
}
elseif($_FILES['fileToUpload']['name'] = " ")
{
$fileToUploadErrr = "Please Select an image!";
}
else {
$file = $filename;
}
if($nameErr == "" && $emailErr == "" && $usernameErr == "" && $passwordErr == "" && $fileToUploadErr == "" && $fileToUploadErrr == "" && $fileToUploadErrrr == "" && $fileToUploadErrrrr == "" && $fileToUploadErrrrrr == "" )
{
$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` , `Date_of_birth` , `department` ,`age` , `filename` )
VALUES ('','".$username."', '".$hashed_password."', '".$email."' , '".$name."' , '".$DateOfBirth."' , '".$department."' , '".$age."' , '".$file."')";
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"> Date Of Birth : </span>
<input type="date" class= "copy1" name="Date_of_birth" value ="<?php
if (isset($DateOfBirth))
echo $DateOfBirth;
?>">
<span class="error"> <?php echo $DateOfBirthErr;?></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>
<span style="color:#0099ff"> Department : </span>
<select name="department" class= "copy2" style="margin-left:14px" value ="<?php
if (isset($department))
echo $department;
?>">
<option value="EE">Electrical & Electronics</option>
<option value="EC">Electronics & Communication</option>
<option value="ME">Mechanical</option>
<option value="CS">Computer Science</option>
<option value="CV">Civil</option>
<option value="IS">Information Science</option>
</select>
<span class="error"> <?php echo $departmentErr;?></span>
<br><br>
<span style="color:#0099ff"> Select image : </span>
<input type="file" name="fileToUpload">
<?php if($filename !=''){ ?> <img src="<?php echo "upload/" .$filename ?>" style="width:180px;height:100px;padding:10px;"/> <?php } ?>
<span class="error"><br> <?php echo $fileToUploadErr; ?></span>
<span class="error"><br> <?php echo $fileToUploadErrr; ?></span>
<span class="error"><br> <?php echo $fileToUploadErrrr; ?></span>
<span class="error"><br> <?php echo $fileToUploadErrrrr; ?></span>
<span class="error"><br> <?php echo $fileToUploadErrrrrr; ?></span>
<input type="submit" class="button" name="submit" value="Register">
<p style="color:black">Already Registered? Login.</p>
</form>
</div>
</body>
</html>
Hi, guys I have only one small issue please help me, I have a registration form with the various input,
my problem is if I give blank space to the name input field and then if I give submit then it should
show any error that no space are allowed
i.e., their should be only letters except that it should not accept any numbers special characters and other thing please.
Can any one help me in this please ?
This line if (!preg_match("/^[a-zA-Z ]*$/",$name)) { must be like this:
if (!preg_match("/^[a-zA-Z]*$/",$name)) {
Explanation:
Your regex has a space at the end. Removing it will solve your problem.

How to update image when users tries to update?

editform.php
<?php
session_start();
if (!isset($_SESSION['id'])) {
header('location:login.php');
}
?>
<?php
$nameErr = $emailErr = $usernameErr = $DateOfBirthErr = $departmentErr = $ageErr = $fileToUploadErr = $fileToUploadErrr = $fileToUploadErrrr = $fileToUploadErrrrr = $fileToUploadErrrrrr = "";
$name = $email = $username = $DateOfBirth = $department = $age = $filename = "";
include_once 'connect.php';
$id = $_GET['id'];
$query = mysqli_query($mysqli, "select * from `users` where userid ='$id'");
$row = mysqli_fetch_array($query);
//set a default variable to hold the original value if $_POST is not triggered
$name = $row['name'];
$username = $row['username'];
$email = $row['email'];
$DateOfBirth = $row['Date_of_birth'];
$department = $row['department'];
$age = $row['age'];
// $filename = $_FILES['filename']['name'];
echo "<img alt='image' style='width:180px;height:100px;' src='upload/" . $row['filename'] . "'>";
// checking weather the form has been submitted before performing the update query
if (isset($_POST['update'])) {
//Name Section
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = $_POST["name"];
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/", $name)) {
$nameErr = "Only letters and white space allowed";
}
}
//E-mail Section
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = $_POST["email"];
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
//Username Section
if (empty($_POST["username"])) {
$usernameErr = "Username is required";
} else {
$username = $_POST["username"];
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/", $username)) {
$usernameErr = "Only letters and white space allowed";
}
}
//D.O.B Section
if (empty($_POST["Date_of_birth"])) {
$DateOfBirthErr = "Date Of Birth is required";
} else {
$DateOfBirth = $_POST["Date_of_birth"];
}
//Department Section
if (empty($_POST["department"])) {
$departmentErr = "Department is required";
} else {
$department = $_POST["department"];
}
//Age Section
if (empty($_POST["age"])) {
$ageErr = "Age is required";
} else {
$age = $_POST["age"];
}
//UPLOAD FILE
$uploaddir = 'upload/';
$uploadfile = $uploaddir . basename($_FILES['filename']['name']);
$imageFileType = pathinfo($uploadfile, PATHINFO_EXTENSION);
if ($_FILES['filename']['name'] != '') {
// Check the image is actaully image or not
$check = getimagesize($_FILES["filename"]["tmp_name"]);
if ($check == false) {
$fileToUploadErrrrr = "File is not an image.";
}
// Check if file already exists
if (file_exists($uploadfile)) {
$fileToUploadErrrrrr = "Sorry, file already exists.";
}
if ($imageFileType != "jpg" && $imageFileType != "png") {
$fileToUploadErr = "Sorry, only JPG,PNG files are allowed.";
} elseif ($_FILES['filename']['size'] > 500000) {
$fileToUploadErrrr = "Sorry, your file is too large.";
} else {
/* if ($filename != '') {
$target = "upload/" . $filename;
unlink($target);
}*/
$uploaded = move_uploaded_file($_FILES['filename']['tmp_name'], $uploadfile);
if ($uploaded) {
$file = $_FILES['filename']['name'];
} else {
$file = $filename;
}
}
} else {
$file = $filename;
}
if ($nameErr == "" && $emailErr == "" && $usernameErr == "" && $DateOfBirthErr == "" && $departmentErr == "" && $ageErr == "" && $fileToUploadErr == "" && $fileToUploadErrr == "" && $fileToUploadErrrr == "" && $fileToUploadErrrrr == "" && $fileToUploadErrrrrr == "") {
$check = "SELECT * FROM users WHERE username = '$username' and userid !='$id'";
$rs = mysqli_query($mysqli, $check);
$da = mysqli_fetch_array($rs, MYSQLI_NUM);
if ($da > 0) {
echo "Username Already in Exists";
} else {
if($file=="")
{
$sql = "update `users` set name='$name', username='$username', email='$email', Date_of_birth='$DateOfBirth', department='$department', age='$age' where userid ='$id'";
if (mysqli_query($mysqli, $sql)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error(mysqli_query);
}
mysqli_close($mysqli);
}
else{
$sql = "update `users` set name='$name', username='$username', email='$email', Date_of_birth='$DateOfBirth', department='$department', age='$age' , filename='$file' where userid ='$id'";
if (mysqli_query($mysqli, $sql)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error(mysqli_query);
}
mysqli_close($mysqli);
}
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<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 {
background-color: #f2f2f2;
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>
<div style="padding-left: 250px" class="div1">
<h2 style="color:#009999">EDIT :</h2>
<form method="POST" action="" enctype="multipart/form-data">
<input type="hidden" name="hidden_id" value="<?= $id ?>"/>
<label style="color:#0099ff">Name:</label><input class= "copy" style="margin-left: 52px" type="text" value="<?= $name ?>" name="name">
<span class="error"> <?php echo $nameErr; ?></span>
<br><br>
<label style="color:#0099ff">Username:</label><input type="text" class= "copy" style="margin-left:26px" value="<?= $username ?>" name="username">
<span class="error"><?php echo $usernameErr; ?></span>
<br><br>
<label style="color:#0099ff">E-mail:</label><input type="text" class= "copy" style="margin-left: 48px" value="<?= $email ?>" name="email">
<span class="error"><?php echo $emailErr; ?></span>
<br><br>
<label style="color:#0099ff">Date_of_birth: </label><input type="date" class= "copy1" value="<?= $DateOfBirth ?>" name="Date_of_birth">
<span class="error"> <?php echo $DateOfBirthErr; ?></span>
<br><br>
<label style="color:#0099ff">Department:</label>
<select name="department" class= "copy2" style="margin-left:14px" value="<?= $department ?>">
<option value="EE">Electrical & Electronics</option>
<option value="EC">Electronics & Communication</option>
<option value="ME">Mechanical</option>
<option value="CS">Computer Science</option>
<option value="CV">Civil</option>
<option value="IS">Information Science</option>
</select>
<span class="error"> <?php echo $departmentErr; ?></span>
<br><br>
<label style="color:#0099ff">Age:</label><input type="text" class= "copy" style="margin-left:62px" value="<?= $age ?>" name="age">
<span class="error"> <?php echo $ageErr; ?></span>
<br><br>
<label style="color:#0099ff">Select image : </label><input type="file" style="width:180px;height:100px;padding:10px;" name="filename" >
<span class="error"><br> <?php echo $fileToUploadErr; ?></span>
<span class="error"><br> <?php echo $fileToUploadErrrr; ?></span>
<span class="error"><br> <?php echo $fileToUploadErrrrr; ?></span>
<span class="error"><br> <?php echo $fileToUploadErrrrrr; ?></span>
<input type="submit" class="button" name="update" value="Update">
Back
</form>
</div>
</body>
</html>
Hi everyone i really really need you people help.
Actually i creating a registration form where users can register their details.
The registration form is absolutely working well. and even the users when logged in thats also
working good, but now when the users tries to update his details, such as name, username is getting updated
but when the user tries to update his image then the problem arises, except image the remaining portion
is getting updated when it comes to the image, the image is not getting update, please guys its my humble request
to all the people who are viewing my question please help me to solve this issue, i'm trying to fix this from four
days but im unable to do so please please please please help me i really need your help please
You should add enctype="multipart/form-data" attribute into form element:
<form method="POST" action="" enctype="multipart/form-data">
While editing edit image operation,
you should put your update sql query with if else condition.
So, basically,
if(empty($image_file_name)){
//query without image column
$sql = "update `users` set name='$name',username='$username',
email='$email', Date_of_birth='$DateOfBirth', department='$department',
age='$age' where userid ='$id'" ;
//do not forget to execute query here with mysqli_query
}
if(!empty($image_file_name)){
//query with image column
$sql = "update `users` set name='$name',username='$username',
email='$email', Date_of_birth='$DateOfBirth', department='$department',age='$age',
image_name='$image_file_name' where userid ='$id'" ;
//do not forget to execute query here with mysqli_query
}
Also make sure we can not prefetch value like textbox, in input type='file', but yes, you can preview the already uploaded image with img tag.
So, instead
<input type='file' value='<?php echo $filename; ?>' <!--do not use this-->
You should use,
<input type='file'>
<img src='your_already_uploaded_file_path' height='50px' width='50px'> <!--change height width as you wish-->
Also, make sure, you are missing enctype="multipart/form-data", with your form tag. So, do not forget to add this attribute with your form tag. This attribute is must while working with uploading files.

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.

Categories