PHP echoing JQuery on failed form submit - php

I'm working on a signup form in PHP. The form is a div which opens when you click on a button. Here's my code:
if(!$fieldsFilled){
$unfilledFormsError = '<br><font class="text-error" id="unfilled-forms-error">One of more of the fields are empty.</font><br>';
echo "
<script type='text/javascript'>
$(document).ready(function(){
$('#home-sign-up-box').show();
console.log('test passed');
});
</script>";
}
This all executes after my form is submitted:
if (isset($_POST['signUp']))
Full PHP code:
<?php require 'dbconnect.php'; ?>
<?php
//Error message variable declarations
$unmatchedPasswordsError = "";
$unfilledFormsError = "";
$emailError = "";
//If sign up submit POST recieved
if (isset($_POST['signUp']))
{
//Start session
session_start();
$email = $connection->real_escape_string($_POST['suEmail']);
$result = mysqli_query($connection, "SELECT * FROM users WHERE email='".$email."'");
if ($result->num_rows)
{
$emailInUse = true;
}
else
{
$emailInUse = false;
}
//Search for empty fields
$required = array('suFirstName', 'suLastName', 'suEmail', 'suPassword', 'suVerifyPassword', 'suDisplayName');
$fieldsFilled = true;
foreach($required as $field)
{
if (empty($_POST[$field]))
{
$fieldsFilled = false;
}
else
{
$fieldsFilled = true;
}
}
if ($emailInUse)
{
$emailError = "The email is already in use.";
echo "
<script type='text/javascript'>
$(document).ready(function(){
$('#home-sign-up-box').show();
});
</script>";
}
else
{
if(!$fieldsFilled)
{
$unfilledFormsError = '<br><font class="text-error" id="unfilled-forms-error">One of more of the fields are empty.</font><br>';
echo "
<script type='text/javascript'>
$(document).ready(function(){
$('#home-sign-up-box').show();
console.log('test passed');
});
</script>";
}
else
{
if (!filter_var($email, FILTER_VALIDATE_EMAIL))
{
$emailError = "The email is not valid.";
echo "
<script type='text/javascript'>
$(document).ready(function(){
$('#home-sign-up-box').show();
});
</script>";
}
else
{
//Check for unverified password
if ($_POST['suPassword']!= $_POST['suConfirmPassword'])
{
$unmatchedPasswordsError = "The passwords do not match.";
echo "
<script type='text/javascript'>
$(document).ready(function(){
$('#home-sign-up-box').show();
});
</script>";
}
else
{
//Variable declaration for sign up POST values
$suFirstName = $_POST['suFirstName'];
$suLastName = $_POST['suLastName'];
$suEmail = $_POST['suEmail'];
$suPassword = $_POST['suPassword'];
$suDisplayName = $_POST['suDisplayName'];
//Insert POST values into database
$sql = $connection->query("INSERT INTO users (firstName,lastName,email,password,displayName)Values('{$suFirstName}','{$suLastName}','{$suEmail}','{$suPassword}','{$suDisplayName}')");
//Redirect to 'email sent' webpage
header('Location: emailSent.php');
}
}
}
}
}
//If log in submit POST recieved
if (isset($_POST['logIn']))
{
//Variable declaration for log in POST values
$liEmail = $_POST['liEmail'];
$liPassword = $_POST['liPassword'];
//Search for log in credentials in dabase
$result = $connection->query("select * from users where email = '$liEmail' AND password = '$liPassword'");
$row = mysqli_fetch_array($result, MYSQLI_BOTH);
//TODO: CHECK FOR REMEMBER ME CHECK
session_start();
$_SESSION['userID'] = $row['userID'];
}?>
HTML sign up div/form code:
<!-- Sign Up Box -->
<div class="sign-up-box" id="home-sign-up-box">
<img src="images/icons/x-close.png" class="x-close" id="home-sign-up-close" src="x-close">
<font class="subheader-bold font-raleway" id="box-sign-up-text">Sign Up</font>
<form method="post" action="" id="home-sign-up-form">
<input type="text" name="suFirstName" placeholder="First Name" class="text-input-minor" id="sign-up-first-name-text-input" value="<?php if(isset($_POST['suFirstName'])){echo $_POST['suFirstName'];}?>">
<input type="text" name="suLastName" placeholder="Last Name" class="text-input-minor" id="sign-up-last-name-text-input" value="<?php if(isset($_POST['suLastName'])){echo $_POST['suLastName'];}?>">
<input type="text" name="suEmail" placeholder="Email" class="text-input-minor" id="sign-up-email-text-input"value="<?php if(isset($_POST['suEmail'])){echo $_POST['suEmail'];}?>">
<?php
echo '<br><font class="text-error" id="email-error">',$emailError,'</font>';
?>
<input type="password" name="suPassword" placeholder="Password" class="text-input-minor" id="sign-up-password-text-input">
<input type="password" name="suConfirmPassword" placeholder="Confirm Password" class="text-input-minor" id="sign-up-confirm-password-text-input">
<?php
echo '<br><font class="text-error" id="passwords-unmatched-error">',$unmatchedPasswordsError,'</font>';
?>
<input type="text" name="suDisplayName" placeholder="Display Name (you can change this later)" class="text-input-minor" id="sign-up-display-name-text-input" value="<?php if(isset($_POST['suDisplayName'])){echo $_POST['suDisplayName'];}?>">
<?php
echo $unfilledFormsError;
?>
<label><input type="checkbox" name="suRememberMe" value="yes" id="sign-up-remember-me-checkbox"><font id="sign-up-remember-me-text">Remember me</font></label>
<input name="signUp" type="submit" value="Sign Up" id="sign-up-submit">
</form>
<font class="text-minor" id="agree-tos-pp-text">By signing up, you agree to our terms of service and <br>privacy policy.</font>
</div>
The "test passed" does log to the console, however the div is not showing after the page refresh (due to form submission). Any help is appreciated! Thank you so much!

I have customized as your requirement and database connection i have used
Mysqli replace whatever you want also change database credentials.
Full code will be in same page. Try and comment if you don't understand anything.
<?php
session_start();
//require 'dbconnect.php';
$connection=mysqli_connect("localhost","root","","test"); // I have use it for testing
$errors = array();
if (isset($_POST['signUp'])) {
$email = mysqli_real_escape_string($connection, $_POST['suEmail']);
$result = mysqli_query($connection, "SELECT * FROM users WHERE email='".$email."'");
//email check
if(mysqli_num_rows($result)>0){
$errors[] = "The email is already in use.";
}elseif(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$errors[] = "The email is not valid.";
}
//Search for empty fields
$required = array('suFirstName', 'suLastName', 'suEmail', 'suPassword', 'suConfirmPassword', 'suDisplayName');
foreach($required as $field){
if (empty($_POST[$field])){
$errors[] = $field." Cannot be empty.";
}
}
if(count($errors)==0){
if($_POST['suPassword']!=$_POST['suConfirmPassword']){
$errors[] = "The passwords do not match.";
}else{
$suFirstName = $_POST['suFirstName'];
$suLastName = $_POST['suLastName'];
$suEmail = $_POST['suEmail'];
$suPassword = $_POST['suPassword'];
$suDisplayName = $_POST['suDisplayName'];
//$sql = $connection->query("INSERT INTO users (firstName,lastName,email,password,displayName)Values('{$suFirstName}','{$suLastName}','{$suEmail}','{$suPassword}','{$suDisplayName}')");
$sql = mysqli_query($connection, "INSERT INTO users (firstName,lastName,email,password,displayName)Values('{$suFirstName}','{$suLastName}','{$suEmail}','{$suPassword}','{$suDisplayName}')");
if($sql){
header('Location: emailSent.php');
}else{
$errors[] = "Failed to insert.";
}
}
}
}
if (isset($_POST['logIn'])){
$liEmail = $_POST['liEmail'];
$liPassword = $_POST['liPassword'];
//$result = $connection->query("select * from users where email = '$liEmail' AND password = '$liPassword'");
$result = mysqli_query($connection, "select * from users where email = '$liEmail' AND password = '$liPassword'");
if($result){
$row = mysqli_fetch_assoc($result);
$_SESSION['userID'] = $row['userID'];
}
}
?>
<?php
if(!empty($errors)){
foreach ($errors as $value) {
echo "<span style='color:red;'>".$value."</span><br>";
}
}
?>
<button type="button" id="showSignup">Show Sign-up</button><br><br>
<!-- Sign Up Box -->
<div class="sign-up-box" id="home-sign-up-box">
<img src="images/icons/x-close.png" class="x-close" id="home-sign-up-close" src="x-close">
<font class="subheader-bold font-raleway" id="box-sign-up-text">Sign Up</font>
<form method="post" action="" id="home-sign-up-form">
<input type="text" name="suFirstName" placeholder="First Name" class="text-input-minor" id="sign-up-first-name-text-input" value="<?php if(isset($_POST['suFirstName'])){echo $_POST['suFirstName'];}?>">
<input type="text" name="suLastName" placeholder="Last Name" class="text-input-minor" id="sign-up-last-name-text-input" value="<?php if(isset($_POST['suLastName'])){echo $_POST['suLastName'];}?>">
<input type="text" name="suEmail" placeholder="Email" class="text-input-minor" id="sign-up-email-text-input"value="<?php if(isset($_POST['suEmail'])){echo $_POST['suEmail'];}?>">
<input type="password" name="suPassword" placeholder="Password" class="text-input-minor" id="sign-up-password-text-input">
<input type="password" name="suConfirmPassword" placeholder="Confirm Password" class="text-input-minor" id="sign-up-confirm-password-text-input">
<input type="text" name="suDisplayName" placeholder="Display Name (you can change this later)" class="text-input-minor" id="sign-up-display-name-text-input" value="<?php if(isset($_POST['suDisplayName'])){echo $_POST['suDisplayName'];}?>">
<label><input type="checkbox" name="suRememberMe" value="yes" id="sign-up-remember-me-checkbox"><font id="sign-up-remember-me-text">Remember me</font></label>
<input name="signUp" type="submit" value="Sign Up" id="sign-up-submit">
</form>
<font class="text-minor" id="agree-tos-pp-text">By signing up, you agree to our terms of service and <br>privacy policy.</font>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type='text/javascript'>
$(document).ready(function(){
<?php if(isset($_POST['signUp']) && count($errors)>0){ ?>
$('#home-sign-up-box').show();
<?php }elseif(isset($_POST['signUp']) && count($errors)==0){ ?>
//$('#home-sign-up-box').hide();
<?php }else{?>
//$('#home-sign-up-box').show();
<?php }?>
$("#showSignup").click(function(){
$('#home-sign-up-box').toggle();
visible_check();
});
visible_check();
});
function visible_check(){
var isVisible = $( "#home-sign-up-box" ).is( ":visible" );
if(isVisible){
$("#showSignup").html("Hide Sign-up");
}else{
$("#showSignup").html("Show Sign-up");
}
}
</script>

Related

How to create a login with multiple passwords

I tried this but it doesn't works.
HTML:
<form id="login" method="post">
<input type="text" name="login"><br>
<input type="password" name="pass">
<input type="submit">
</form>
PHP
$login = "citybank";
$pass = array("ticket3", "ticket2", "ticket1");
if(isset($_POST["login"])){
if($_POST["login"] == $login and $_POST["pass"] == $pass){
echo 'You are logged';
echo "
<script>
var post = document.querySelector('#login');
post.style.display = 'none';
</script>
";
}else{
echo "You are not logged.";
}
}
I think i have a problem with my array.
I dont know if its right the way i am using.
Thanks
First of all you have syntax error here:
$pass = array("ticket3", "ticket2, "ticket1"); // missing "
Also you searched for value in array, so you should use in_array():
<form id="login" method="post">
<input type="text" name="login"><br>
<input type="password" name="pass">
<input type="submit">
</form>
<?php
$login = "citybank";
$pass = array("ticket3", "ticket2", "ticket1");
if(isset($_POST["login"])){
if($_POST["login"] == $login and in_array($_POST["pass"], $pass)){
echo 'You are logged';
echo "
<script>
var post = document.querySelector('#login');
post.style.display = 'none';
</script>
";
}else{
echo "You are not logged.";
}
}
?>
Warning: Never, ever implement login logic like that, if it is for test it's OK, but on production environment is FORBIDDEN!
Here is example of login system which is secured.
You can use in_array() function to solve your issue.
But you should use database to store password.
php
$login = "citybank";
$pass = array("ticket3", "ticket2", "ticket1");
if(isset($_POST["login"])){
if($_POST["login"] == $login && in_array($_POST["pass"], $pass)){
echo 'You are logged';
echo "
<script>
var post = document.querySelector('#login');
post.style.display = 'none';
</script>
";
}else{
echo "You are not logged.";
}
}
<?php
$login = "citybank";
$pass = array("ticket3", "ticket2", "ticket1");
if(isset($_POST["login"]))
{
$count=0;
if($_POST["login"] == $login)
{
for($i=0;$i<3;$i++)
{
if($_POST["pass"] == $pass[$i])
{
{
$count=1;
echo 'You are logged';
echo "
<script>
var post = document.querySelector('#login');
post.style.display = 'none';
</script>
";
break;
}
}
}
if($count==0)
{
echo "You are not logged.";
}
}
}
?>

Can I handle a form with php if else statement in action attribute of HTML form?

I am writing a form to create a login username and password.
If the account creation is successful, I would like the user to then be taken to the actual LOGIN form.
I have created a series of checks with the variable $errcheck being passed so the program knows what to do. If there is an error, $errcheck will be set to 1. Its default is 0.
If there are errors in the input fields, the account creation form will be displayed again and if everything is fine then it will INSERT user details into the table and take the user to the LOGIN page.
However, I can only get the page to reload itself each time after the info is added to the table. Is what I'm doing with the action part of the form even allowed? I went ahead and included all of my code in case there were any questions about it. Thank you.
<!DOCTYPE html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
$busow_namef = $busow_namel= $owner_email = $bus_psswd = $psswd_confirm = "";
$busname_ERR = $busowname_ERR = $owneremail_ERR = $psswd_ERR =
$psswdconfirm_ERR = "";
$errcheck = 0;
if ($_SERVER["REQUEST_METHOD"]=="POST") {
//??????????????????? Check Login information ???????????????????
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if (empty($_POST["busow_namef"])) {
$busowname_ERR = "Business owner's name is required";
$errcheck = 1;
} else {
$busownamef = test_input($_POST["busow_namef"]);
}
if (empty($_POST["busow_namel"])) {
$busowname_ERR = "business owner's name is required";
$errcheck = 1;
} else {
$busownamel = test_input($_POST["busow_namel"]);
}
if (empty($_POST["bus_psswd"])) {
$psswd_ERR = "You must enter a password.";
$errcheck = 1;
} else if ((mb_strlen($_POST["bus_psswd"])) < 8) {
$psswd_ERR = "The password must be 8-10 characters long and only include numbers and letters.";
$errcheck = 1;
} else {
$bus_psswd = test_input($_POST["bus_psswd"]);
}
if (empty($_POST["psswd_confirm"])) {
$psswdconfirm_ERR = "Please confirm password.";
$errcheck= 1;
} else if ($_POST["psswd_confirm"] != $_POST["bus_psswd"]) {
$psswdconfirm_ERR = "The passwords do not match.";
$errcheck = 1;
} else {
$psswd = test_input($_POST["psswd_confirm"]);
$h_psswd = password_hash($psswd, PASSWORD_DEFAULT);
}
if (empty($_POST["tandc"])) {
$checktandc_ERR= "You must accept the terms and conditions.";
$errcheck= 1;
} else {
$tandc = test_input($_POST["tandc"]);
}
if (empty($_POST["owner_email"])) {
$owneremail_ERR = "Please enter an email address.";
$errcheck = 1;
} else {
$_POST["owner_email"] = (filter_var($_POST["owner_email"], FILTER_SANITIZE_EMAIL));
}
if (filter_var($_POST["owner_email"] , FILTER_VALIDATE_EMAIL)){
$owneremail = $_POST["owner_email"];
} else {
$owneremail_ERR = "Please enter a valid email address.";
$errcheck = 1;
}
//???????????????? Connect to database ??????????????????????????
$link = mysqli_connect('domain', 'user', 'passwd');
if (!$link) {
die('Could not connect: ' . mysqli_error());
}
mysqli_select_db(database, $link);
if (!mysqli_select_db(louisville_ky1, $link)) {
echo "database not selected";
} else {
$sql = "SELECT owner_email FROM 3bus_owners WHERE owner_email = '$owneremail' ";
$result = mysql_query($sql, $link);
if (mysql_num_rows($result) > 0 ) {
$errcheck = 1;
$owneremail_ERR = "This email is already registered. Please register with another address or click login.";
} else {
$errcheck = 0;
$query = "INSERT INTO 3bus_owners (owner_email, h_psswd, busow_namef, busow_namel) VALUES ('$owneremail', '$h_psswd', '$busownamef',
'$busownamel')";
$result2 = mysql_query($query, $link);
} //end if num rows >0
}//end connection check
} // ???????????????????? end if server request method ????????????????
?>
<!-- ~~~~~~~~~~~~~~~~~~~~~~~~Begin HTML FORM~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<h2>Create Business Login</h2>
<br>
<form method="post" action="<?php if ($errcheck = 1) { echo
htmlspecialchars($_SERVER["PHP_SELF"]);
} else { echo 'ownersignin.php'; }?>">
Business Owner's Name:<br>
First Name:<br><input type="text" name="busow_namef" value="<?php echo
$busow_namef;?>">
<span class="error">* <?php echo $busowname_ERR;?></span>
<br>
Last Name:<br><input type="text" name="busow_namel"value="<?php echo
$busow_namel;?>">
<span class="error">* <?php echo $busowname_ERR;?></span>
<br>
Business Owner's E-mail: *this will be your username for login and does not have to be posted in listing
<br>
<input type="text" name="owner_email" size="40"value="<?php echo
$owner_email;?>">
<span class="error">*<?php echo $owneremail_ERR;?></span>
<br><br>
Password: <input type="password" name="bus_psswd" size="11" maxlength="10">
<span class="error">*<?php echo $psswd_ERR;?></span>
<br>
Confirm Password: <input type="password" name="psswd_confirm" size="11" maxlength="10">
<span class="error">*<?php echo $psswdconfirm_ERR;?></span>
<br>
<br>
<input type="checkbox" name="tandc">I have read and accept the
<a href="/termsandconditions.php" target= "_blank">Terms and
Conditions</a>.
<span class="error">*<?php echo $checktandc_ERR;?></span>
<br>
<br>
<input type="submit" name="submit" value="Create Login">
</form>
</body>
snippit from above:
<form method="post" action="<?php if ($errcheck = 1) { echo htmlspecialchars($_SERVER["PHP_SELF"]); } else { echo 'ownersignin.php'; }?>">
I have never seen a form action attribute written like this, but... try changing the "double quotes" around "PHP_SELF" to single quotes: $_SERVER['PHP_SELF']. That could be causing a problem because it might be getting interpreted as:
action="<?php if ($errcheck = 1) { echo htmlspecialchars($_SERVER["
Then, verify that this code sample didn't come from the page: "ownersignin.php". It just sounds like that would be the name of this page instead of the name of the page the form would redirect to.
echo 'ownersignin.php';
If this is the name of the page your code is in, it would send you in an infinite loop.
You shouldn't reprint the registration form when the registration is successful. Instead, redirect the user to the signin form.
After all the validation checks, do:
if (!$errcheck) {
header("Location: ownersignup.php");
exit;
}
?>
<!-- ~~~~~~~~~~~~~~~~~~~~~~~~Begin HTML FORM~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<h2>Create Business Login</h2>
<br>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
...

How do i verify query record with form input

In my code below i have two form section first one is to fetch information from database and second one is verify a record in the database my problem is how do verify a record and redirect to error page or if the input form do not march any record redirect to index page this my code;
<?php
include_once 'init.php';
$error = false;
//check if form is submitted
if (isset($_POST['book'])) {
$book = mysqli_real_escape_string($conn, $_POST['book']);
$action = mysqli_real_escape_string($conn, $_POST['action']);
if (strlen($book) < 6) {
$error = true;
$book_error = "booking code must be alist 6 in digit";
}
if (!is_numeric($book)) {
$error = true;
$book_error = "Incorrect booking code";
}
if (empty($_POST["action"])) {
$error = true;
$action_error = "pick your action and try again";
}
if (!$error) {
if(preg_match('/(check)/i', $action)) {
echo "6mameja";
}
if (preg_match('/(comfirm)/i', $action)) {
if(isset($_SESSION["user_name"]) && (trim($_SESSION["user_name"]) != "")) {
$username=$_SESSION["user_name"];
$result=mysqli_query($conn,"select * from users where username='$username'");
}
if ($row = mysqli_fetch_array($result)) {
$id = $row["id"];
$username=$row["username"];
$idd = $row["id"];
$username = $row["username"];
$ip = $row["ip"];
$ban = $row["validated"];
$balance = $row["balance"];
$sql = "SELECT `item_name` , `quantity` FROM `books` WHERE `book`='$book'";
$query = mysqli_query($conn, $sql);
while ($rows = mysqli_fetch_assoc($query)) {
$da = $rows["item_name"]; $qty = $rows["quantity"];
$sqll = mysqli_query($conn, "SELECT * FROM promo WHERE code='$da' LIMIT 1");
while ($prow = mysqli_fetch_array($sqll)) {
$pid = $prow["id"];
$price = $prow["price"];
$count = 0;
$count = $qty * $price;
$show = $count + $show;
}
}
echo "$show";
echo "$balance";
if ($show<$balance) {
if (isset($_POST["verify"])) {
$pass = mysqli_real_escape_string($conn, $_POST["pass"]);
if ($pass != "$username") {
header("location: index.php");
}
elseif ($pass = "$username") {
header("location: ../error.php");
}
}
echo '<form action="#" method="post" name="verify"><input class="text" name="pass" type="password" size="25" /><input class="text" type="submit" name="verify" value="view"></form>';
echo "you cant buy here";
exit();
}
} else {
$errormsg = "Error in registering...Please try again later!";
}
}
}
}
?>
<form role="form" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="booking">
<fieldset>
<legend>Check Booking</legend>
<div class="form-group">
<label for="name">Username</label>
<input type="text" name="book" placeholder="Enter Username" required value="<?php if($error) echo $book; ?>" class="form-control" />
<span class="text-danger"><?php if (isset($book_error)) echo $book_error; ?></span>
</div>
<input type="submit" name="booking" value="Sign Up" class="btn btn-primary" />
<table>
<input type="radio" name="action" value="comfirm" <?php if(isset($_POST['action']) && $_POST['action']=="comfirm") { ?>checked<?php } ?>>
<input type="radio" name="action" value="check" <?php if(isset($_POST['action']) && $_POST['action']=="check") { ?>checked<?php } ?>> Check booking <span class="text-danger"><?php if (isset($action_error)) echo $action_error; ?></span>
</div>
</table>
</fieldset>
</form>
in achievement am expected to redirect to error or index page but my code above refress back to first form what are my doing wrong. Big thanks in advance

captcha code are not working

code:
<?php
session_start();
if(isset($_POST['insert']) && !empty($_POST['insert']))
{
extract($_POST);
$query = "select * from enquires2 where email = '$email'";
$result = mysqli_query($link,$query);
$row = mysqli_fetch_array($result);
if($row > 0 )
{
$msg .="<h5 style='text-align:center;color:red;'>EmailId already exists please login with different emailid</h5>";
}
else
{
if(!empty($_POST['captcha_code']))
{
$captchaCode = $_SESSION['captchaCode'];
$enteredcaptchaCode = $_POST['captcha_code'];
$sql = "insert into enquires2(name,email,phone,message)values('$name','$email','$phone','$message')";
$result=mysqli_query($link,$sql);
if($result == true)
{
$msg .="<h4 style='text-align:center;color:green;'>Your Data Has Been Submitted.</h4>";
}
else
{
$errMsg = 'Captcha code not matched, please try again.';
}
}
else
{
$msg .="<h4 style='text-align:center;color:red;'>Error</h4>";
}
}
}
?>
html code:
<?php echo $msg; ?>
<?php if(!empty($errMsg)) echo '<p style="color:#EA4335;">'.$errMsg.'</p>';?>
<?php if(!empty($succMsg)) echo '<p style="color:#34A853;">'.$succMsg.'</p>';?>
<form method="post">
<input type="text" name="name" id="name" placeholder="Enter Your Name">
<input type="text" name="email" id="email" placeholder="Enter Your Email">
<input type="text" name="phone" id="phone" placeholder="Enter Your Phone">
<input type="text" name="message" id="message" placeholder="Enter Your Message" >
<input name="captcha_code" type="text" value="" placeholder="Enter the code" >
<img src="captcha.php" id="capImage"/>
<br/>Can't read the image? click here to refresh.
<input type="submit" name="insert" value="Submit" placeholder="Enter Your Message" >
</form>
When I click on submit button it shows data has been submitted successfully while captcha code is right or worng it insert form value into database. So, how can I fix this problem ?
Thank You
Please use this code:
<?php
session_start();
if(isset($_POST['insert']) && !empty($_POST['insert']))
{
extract($_POST);
$query = "select * from enquires2 where email = '$email'";
$result = mysqli_query($link,$query);
$row = mysqli_fetch_array($result);
if($row > 0 )
{
$msg .="<h5 style='text-align:center;color:red;'>EmailId already exists please login with different emailid</h5>";
}
else
{
if(!empty($_POST['captcha_code']))
{
$captchaCode = $_SESSION['captchaCode'];
$enteredcaptchaCode = $_POST['captcha_code'];
if($captchaCode == $enteredcaptchaCode)
{
$sql = "insert into enquires2(name,email,phone,message)values('$name','$email','$phone','$message')";
$result=mysqli_query($link,$sql);
if($result == true)
{
$msg .="<h4 style='text-align:center;color:green;'>Your Data Has Been Submitted.</h4>";
}
else
{
$msg .= "<h4 style='text-align:center;color:green;'>Your Data Has Not Been Submitted.</h4>";
}
}
else
{
$errMsg = 'Captcha code not matched, please try again.';
}
}
else
{
$msg .="<h4 style='text-align:center;color:red;'>Error</h4>";
}
}
}
?>

PHP Email Subscription, cannot post php file

Hey I have some trouble with my email subscription I'm trying to log into a textfile.
<!-- Signup Form -->
<form id="signup-form" action="form.php" method="post">
<input type="email" name="email" id="email" placeholder="Email Address" />
<input type="submit" value="Sign Up" />
</form>
Here's my PHP code:
<?php
if(empty($_POST['submit']) === false) {
$email = htmlentities(strip_tags($_POST['email']));
$logname = 'email.txt';
$logcontents = file_get_contents($logname);
if(strpos($logcontents,$email)) {
die('You are already subscribed.');
} else {
$filecontents = $email.',';
$fileopen = fopen($logname,'a+');
$filewrite = fwrite($fopen,$filecontents);
$fileclose = fclose($fileopen);
if(!$fileopen or !$filewrite or !$fileclose) {
die('Error occured');
} else {
echo 'Your email has been added.';
}
}
}
?>
I keep getting Cannot POST /form.php eventho the php file is at that path, someone knows what I'm possibly doing wrong? I'm quit noob at this :(
First of all add name attribute to your submit button, as in POST you will not get the form value of "submit" and your code will never go further
<form id="signup-form" action="form.php" method="post">
<input type="email" name="email" id="email" placeholder="Email Address" />
<input type="submit" name="submit" value="Sign Up" />
</form>
Now in your php code, you just need to check $_POST['submit'] in if condition and you have also done a typo, you have used a variable $fopen which is not defined, change that.
<?php
if($_POST['submit']) {
$email = htmlentities(strip_tags($_POST['email']));
$logname = 'email.txt';
$logcontents = file_get_contents($logname);
if(strpos($logcontents,$email)) {
die('You are already subscribed.');
} else {
$filecontents = $email.',';
$fileopen = fopen($logname,'a+');
$filewrite = fwrite($fileopen,$filecontents);
$fileclose = fclose($fileopen);
if(!$fileopen or !$filewrite or !$fileclose) {
die('Error occured');
} else {
echo 'Your email has been added.';
}
}
}
?>

Categories