validation error while sending email - javascript

I want to send an email. it gives me validation error 'fields are mandatory' when I click on email buttons and page get refreshed, even-though i entered correct email id. If i entered correct email id then also it gives error.
I don't know where i am going wrong. Can anybody tell me. Here is my php code:
function validation1()
{
document.getElementById("emailid").innerHTML="";
var emailpattern=/^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}$/;
if(document.form1.email.value=="")
{
document.getElementById("emailid").innerHTML="fields are mandetory";
document.form1.email.focus();
return false;
}
else if(!emailpattern.test(document.form1.email.value))
{
document.getElementById("emailid").innerHTML="enter valid id";
document.form1.email.focus();
return false;
}
return true;
}
<?php include 'send-email.php';?>
<form name="form1" method="post">
<input type="submit" name="email" value="email" onclick="return validation1()" />
<input type="text" size="50" name="email" id="email" placeholder="*************" />
<span id="emailid"></span>
</form>
send-email.php code
<?php include 'connection.php'; ?>
<?php
if(isset($_POST['submit'])) {
#$email=$_POST["email"];
$email=strip_tags($_POST["email"]);
$email=mysqli_real_escape_string($con,trim($email));
$to="sa#vs.com";
$to=mysqli_real_escape_string($con,trim($to));
$headers="From:".$email;
$message="Interested in VAPT";
$subject="email id";
if(mail($to,$subject,$message,$headers))
{
$email="'".$email."'";
$sql="insert into email_to_admin values($email)";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
}
mysqli_close($con);
}
?>

You have no if() statement to control when the mail is sent. As soon as the page load, you instantly mail. Use
if(isset($_POST['email'])) {}

if(isset($_POST["email"]) && isset($_POST["email"] !="" )
{
//send the email
}
Personally I would recommend also placing an antispam captcha, this way it will make sure that the new rendom value is not the same
And since you have another step which helps you, you may also mark the email address plus some other value like subject unique in the email_to_admin MySQL Table, if a record is inserted, you carry on
$sql="insert into email_to_admin values($email , $subject)";
.....................
$num = #mysql_affected_rows();
if($num > 0)
{
//semd the email
}

Try below for mail :-
if($_POST["email"]){ // Add this if condition so that your mail will be send when button gets clicked.
$to="sa#vs.com";
$to=mysqli_real_escape_string($con,trim($to));
$headers="From:".$email;
$message="Interested in VAPT";
$subject="email id";
if(mail($to,$subject,$message,$headers))
{
$email="'".$email."'";
$sql="insert into email_to_admin values($email)";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
}
}

Related

Login with POST Form, which trigger a javascript validation, and AJAX to a PHP file. Trouble storing data to PHP

Brief
I am now stuck at a part of AJAX, as I do now know how to extract the data out from the AJAX part and put into the PHP variables, so that I could access it and use it later. It also does not redirect me to another page ("Map.php").
I tried looking online for the answers, but to no avail. Can anyone with experience please help. Also, I am not sure if my method of doing is correct, please let me know where I have done wrong.
In details
I want to do a "Login.php", which will use a form to take the email and password from the user. There will be a "Login" button on the form which will trigger a javascript for the purpose of validation.
Upon validation, I will use AJAX to call another php file called "Auth.php", which will have make a connection with a MySQL database, to search for that particular user verify the user.
The "Auth.php" will then return a json data of the user's particulars, which I intend to use in "Login.php" page, and to start a session with the $_SESSION[] variable of php. I also want the page to redirect the user to another page ("Map.php") upon successful login.
Below are parts of my codes in the "Login.php" and "Auth.php".
Login.php
<form name="myForm" action="Map.php" method="post" onsubmit="return validateForm()">
<fieldset>
<div class="form-group">
<input class="form-control" placeholder="E-mail" name="email" type="email" autofocus value="<?php echo isset($_POST["email"])? $_POST["email"]: ""; ?>">
</div>
<div class="form-group">
<input class="form-control" placeholder="Password" name="password" type="password" value="<?php echo isset($_POST["password"])? $_POST["password"]: ""; ?>">
</div>
<input type="submit" value="Login" class="btn btn-lg btn-success btn-block"/>
</fieldset>
</form>
<script>
function validateForm() {
//event.preventDefault();
var email = document.forms["myForm"]["email"].value;
var password = document.forms["myForm"]["password"].value;
var re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (email == null || email == "") {
alert("Email must be filled.");
return false;
}
if (password == null || password == "") {
alert("Password must be filled.");
return false;
}
if(re.test(email)) {
var data = {
"email": email,
"password": password
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "GET",
dataType: "json",
url: "auth.php",
data: data,
success: function(data) {
alert("You have successfully logged in!");
// TODO store user details in session
return true; // return true to form, so will proceed to "Map.php"
}
});
return false;
}
else {
alert("You have entered an invalid email address!");
return false;
}
return false;
}
</script>
Auth.php
$connection = mysqli_connect("localhost", "root", "", "bluesky");
// Test if connection succeeded
if(mysqli_connect_errno()) {
die("Database connection failed: " . mysqli_connect_error() . " (" . mysqli_connect_errno() . ") " .
"<br>Please retry your last action. Please retry your last action. " .
"<br>If problem persist, please follow strictly to the instruction manual and restart the system.");
}
$valid=true;
if (isset($_GET['email']) && isset($_GET['password'])) {
$email = addslashes($_GET['email']);
$password = addslashes($_GET['password']);
} else {
$valid = false;
$arr=array('success'=>0,'message'=>"No username or password!");
echo json_encode($arr);
}
if($valid == true){
$query = "SELECT * FROM user WHERE email='$email' and password='$password'";
$result = mysqli_query($connection, $query);
if(mysqli_num_rows($result) == 1){
$row = mysqli_fetch_assoc($result);
$arr=array('success'=>1,'type'=>$row['type'],'user_id'=>$row['id'],'email'=>$row['email'],'name'=>$row['name'],'phone'=>$row['phone'],'notification'=>$row['notification']);
echo json_encode($arr);
}else{
$arr=array('success'=>0,'message'=>"Login failed");
echo json_encode($arr);
}
}
// close the connection that was established with MySQL for the SQL Query
mysqli_close($connection);
Your ajax call should be like this:
data = $(this).serialize() + "&" + $.param(data)
$.post('auth.php', data, function(response){
console.log(response);
});
you must use post method because you are getting password and email so its not a good practice. And for validation there is many jQuery plugins.

how to link php, sql, and Javascript together,

I'm doing a log in page, i have javascript doing validations ( checking if field is blank) sql storing the data and php doing what php does (idk).... anyway when I press submit it tells me Cannot POST /login.php
is there away to test it on a website and see if it actually works or is the code completely wrong.
<?php
$server = 'localhost';
$username = 'root';
$passowrd = 'cosc_453';
$dbname = 'login'
if(!empty($_POST['user']))
{ $query = mysql_query("SELECT * FROM UserName where userName ='$_POST[user]' AND pass = '$_POST[pass]'") or die(mysql_error());
$row = mysql_fetch_array($query) or die(mysql_error());
{ $_SESSION['userName'] = $row['pass']; echo "SUCCESSFULLY LOGIN TO USER PROFILE PAGE..."; }
else { echo "SORRY... YOU ENTERD WRONG ID AND PASSWORD... PLEASE RETRY...";
}
}
}
if(isset($_POST['submit']))
{ SignIn();
} ?>
php external
function validate(){
if ( document.getElementById (user).value=="")
{
alert ("Please enter your user name");
}
else if ( document.getElementById(pass).value=="")
alert("Please enter you password");
else {
alert("Processing Login........");
}
}
javscript external
CREATE TABLE UserName (
UserNameID int(9) NOT NULL auto_increment,
userName VARCHAR(40) NOT NULL,
pass VARCHAR(40) NOT NULL,
PRIMARY KEY(UserNameID) );
INSERT INTO
UserName (userName, pass)
VALUES
("cosc" , "453");
sql external
<!DOCTYPE HTML>
<html>
<head>
<title>Sign-In</title>
<link rel="stylesheet" type="text/css" href="home.css">
<script src ="login.js"></script>
</head>
<body id="body-color">
<div id="Sign-In">
<fieldset style="width:30%">
<legend>LOG-IN HERE</legend>
<form method="Post" action="login.php" submit =" validate()">
User:<br><input type="text" name="user" size="40"><br>
Password:<br><input type="password" name="pass" size="40"><br>
<input id="button" type="submit" name="submit" value="Log-In">
</form>
< /fieldset>
</div>
</body>
</html>
Your mysql do not have a connection to database. And please stop using mysql, use mysqli instead
<?php
$con = mysqli_connect("localhost","root","cosc_453","login");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM UserName WHERE userName ='".$_POST[user]."' AND pass = '".$_POST[pass]."'";
$result = mysqli_query($conn,$sql);
$count_result = mysqli_num_rows($result);
// Login Success URL
if($count_result == 1)
{
// If you validate the user you may set the user cookies/sessions here
#setcookie("logged_in", "user_id");
#$_SESSION["logged_user"] = "user_id";
$_SESSION["secret_id"] = $row['secret_id'];
if($row['level'] == 1)
{
// Set the redirect url after successful login for admin
$resp['redirect_url'] = 'admin/';
}
else if($row['level'] == 2)
{
// Set the redirect url after successful login for user
$resp['redirect_url'] = 'user/';
}
}
else
{
echo "Invalid username or pass";
}
?>
To add onto what Eh Ezani stated, you have an issue in your HTML. Your form attribute reads submit when I believe what you meant is onsubmit. Might want to try something like.
<form method="Post" action="login.php" onsubmit ="return validate()">
User:<br><input type="text" name="user" size="40"><br>
Password:<br><input type="password" name="pass" size="40"><br>
<input id="button" type="submit" name="submit" value="Log-In">
</form>
Also, "Use MySQLi over the older MySQL functions. The "i" stands for "improved". The list of improvements can be found in the docs.
-credited to
Difference between mysqli and mysql?

I have a blank page after submitting mailchimp subscribe php

I use bellow html code to submit user email in my mailchimp account list using mailchimp API.
Form Code:
.....
<form id="signup-form" action="php/newsletter-subscribe.php" method="post">
<input type="email" name="email" id="email" placeholder="Email Address" />
<br>
<input type="submit" value="Go!" onclick="wating()" />
</form>
......
newsletter-subscribe PHP code:
require_once 'mailchimp/MailChimp.php';
use \DrewM\MailChimp\MailChimp;
// Email address verification
function isEmail($email) {
return filter_var($email, FILTER_VALIDATE_EMAIL);
}
if($_POST) {
$mailchimp_api_key = 'xxxxxxxxxxxxxxxxxxxxx-xx'; // enter your MailChimp API Key
$mailchimp_list_id = 'xxxxxxxxxx'; // enter your MailChimp List ID
$subscriber_email = addslashes( trim( $_POST['email'] ) );
if( !isEmail($subscriber_email) ) {
echo '<script type="text/javascript">swal("Error!", "Please try again.", "error")</script>';
} else {
$array = array();
$MailChimp = new MailChimp($mailchimp_api_key);
$result = $MailChimp->post("lists/$mailchimp_list_id/members", [
'email_address' => $subscriber_email,
'status' => 'subscribed',
]);
if($result == false) {
$array = '<script type="text/javascript">swal("Error!", "Please try again.", "error")</script>';
} else {
$array = '<script type="text/javascript">swal("Great!", "Your email has been subscribed", "success")</script>';
}
echo json_encode($array);
}
}
The problem is after i submit the form i get blank page without any error log and the email added to my mailchimp account without any error.
I try to change the echo javascript in line 22, 35 and 38 with another java script alert like alert("Text Here"); and it's work except i get the same thing blank page
How to solve this problem and echo the javascript alert in the same html form page without redirect to blank page?
First you are setting:
$array = array();
However later, you do:
if($result == false) {
$array = '<script type="text/javascript">swal("Error!", "Please try again.", "error")</script>';
} else {
$array = '<script type="text/javascript">swal("Great!", "Your email has been subscribed", "success")</script>';
}
echo json_encode($array);
In other words, you are changing array to a string.
Try to change the code to:
if($result == false) {
$array = array('<script type="text/javascript">swal("Error!", "Please try again.", "error")</script>');
} else {
$array = array('<script type="text/javascript">swal("Great!", "Your email has been subscribed", "success")</script>');
}
echo json_encode($array);
Also, I would avoid using <script type="text/javascript"> there and I would just return a proper json response. Then, you call this file with ajax (jquery), decode the json and show the alert.
Perhaps something like this will give you an idea:
http://labs.jonsuh.com/jquery-ajax-php-json/

having an error invalid login or username after adding sh1 into my script

i have made my own login authentication script into php, it's working fine when i use it without using "sh1"... and successfully uploaded username and password into my database, but i want to encrypt password into database due to security reason, now i'm using $hash_key=sha1($_POST['password']); into script, when i check into database it successfully encrypted see my pic..
But as i logged in, it's giving me an error
So, i decided to remove "sh1" and directly save my password into database once to check..
and it's working fine:
But using sha1 it's working and showing an error message invalid username and password..
Please help, what's wrong into my code??
Here is a code for insert.php
<?php
$con=mysqli_connect("localhost","root","Bhawanku","members");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$hash_key=sha1($_POST['password']);
$sql="INSERT INTO admin
VALUES
('', '$_POST[username]','$hash_key')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
and here is a code for login.php
<?php
include("config.php");
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST")
{
// username and password sent from Form
$myusername=addslashes($_POST['username']);
$mypassword=addslashes($_POST['password']);
$sql="SELECT * FROM admin WHERE username='$myusername' AND passcode='.sha1[$mypassword]' ";
$result=mysql_query($sql);
$row=mysql_fetch_array($result);
$active=$row['active'];
$count=mysql_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1)
{
$_SESSION["myusername"];
$_SESSION['login_user']=$myusername;
header("location: welcome.php");
}
else
{
echo "Your Login Name or Password is invalid";
}
}
?>
<form action="" method="post">
<label>UserName :</label>
<input type="text" name="username"/><br />
<label>Password :</label>
<input type="password" name="password"/><br/>
<input type="submit" value=" Submit "/><br />
</form>
This line in select query
passcode='.sha1[$mypassword]'
$sql="SELECT * FROM
admin WHERE username='$myusername'
AND passcode='.sha1[$mypassword]' ";
should be
$sql="SELECT * FROM
admin WHERE username='$myusername'
AND passcode='".sha1($mypassword)."'";
UPDATE
The problem appears to be while saving the password the field was set to varchar(30) sha1() will return string longer than that. so that needs to be increased. And the password needs to be re-inserted since old passwords will not work.
Now
$myusername=addslashes($_POST['username']);
$mypassword=addslashes($_POST['password']);
Should be replaced as
$myusername=mysql_real_escape_string(trim($_POST['username']));
$mypassword=mysql_real_escape_string(trim($_POST['password']));
The query is already mentioned above.
And if there are more that one user with the same username and password then the condition
if($count==1)
will fail
For password field you don't need to use addslashes()
$mypassword = sha1($_POST['password']);
$query = "SELECT *
FROM admin
WHERE username = '$myusername' AND passcode ='$mypassword'";
$rs = mysql_query($query);
if ($rs && mysql_num_rows($rs) > 0)
{
// login ok
}
else {
// login failed
}
Your query fromation has problem try below line and check
$sql="SELECT * FROM admin WHERE username='".$myusername."' AND passcode='".sha1[$mypassword]."'";

I need a registration button that sends data to a mySQL server to also Redirect on click

So i am making a registration page on my website. At the moment it is more just a test then anything. I have it working more or less and when a user attempts to sign up it works just fine HOWEVER there is no change on the page. I have created a Confirmation page but no matter what i try i can't seem to get the button to redirect as well.
<form name="register" method="post" action="register.php">
Username:<input name="user" type="text" id="user">
<br>
Password:<input name="pass" type="password" id="pass">
<br>
Repeat Password:<input name="rpass" type="password" id="rpass">
<br>
<input type="submit" name="submit" value="Register">
</form>
From what i can tell in the last few hours of research the reason onclick and wrapping the button in a link does not work is because the type="submit" instead of "button". Is there any way do make this button redirect? If not with HTML perhaps with a JS or PHP ?
<?php
session_start(); //Must Start a session.
require "config.php"; //Connection Script, include in every file!
//Check to see if the user is logged in.
//'isset' check to see if a variables has been 'set'
if(isset($_SESSION['username'])){
header("location: members.php");
}
//Check to see if the user click the button
if(isset($_POST['submit']))
{
//Variables from the table
$user = $_POST['user'];
$pass = $_POST['pass'];
$rpass = $_POST['rpass'];
//Prevent MySQL Injections
$user = stripslashes($user);
$pass = stripslashes($pass);
$rpass = stripslashes($rpass);
$user = mysqli_real_escape_string($con, $user);
$pass = mysqli_real_escape_string($con, $pass);
$rpass = mysqli_real_escape_string($con, $rpass);
//Check to see if the user left any space empty!
if($user == "" || $pass == "" || $rpass == "")
{
echo "Please fill in all the information!";
}
else
{
//Check too see if the user's Passwords Matches!
if($pass != $rpass)
{
echo "Passwords do not match! Try Again";
}
//CHECK TO SEE IF THE USERNAME IS TAKEN, IF NOT THEN ADD USERNAME AND PASSWORD INTO THE DB
else
{
//Query the DB
$query = mysqli_query($con,"SELECT * FROM members WHERE username = '$user'") or die("Can not query the TABLE!");
//Count the number of rows. If a row exist, then the username exist!
$row = mysqli_num_rows($query);
if($row == 1)
{
echo "Sorry, but the username is already taken! Try again.";
}
//ADD THE USERNAME TO THE DB
else
{
$add = mysqli_query($con,"INSERT INTO members (id, username, password) VALUES (null, '$user' , '$pass') ") or die("Can't Insert! ");
}
}
}
}
?>
As I commented, simply do
else
{
$add = mysqli_query($con,"INSERT INTO members (id, username, password) VALUES (null, '$user' , '$pass') ") or die("Can't Insert! ");
header("location: thankyou.html");
}

Categories