I'm trying to make a registration form for my website. I'm using the code below. All the error handlers work fine since it's adding the users into my database. I've trid to add ob_start. I removed all white spaces using a plugin for sublime text. I tried to use javascript instead of php (top.window). I also tried to use full url instead of just directories. But when I click submit it doesnt redirect me to the address I put after Location. When I click the button it takes me to this php file but doesnt redirect me back to the registration page which is a seperate file(I know there are a lot of similar questions that have been asked but they dont seem to work for my situation).
Does anyone know how to fix that?
if (isset($_POST['submit'])){
include_once 'db.php';
$uid = mysqli_real_escape_string($conn, $_POST['uid']);
$pwd = mysqli_real_escape_string($conn, $_POST['pwd']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
//error handlers
//Check for empty fields
if (empty($uid) || empty($pwd) || empty($email)) {
header("Location : /login/register.php?signup=empty");
exit();
} else{
//Check if input characters are valid
if (!preg_match("/^[a-zA-Z]*$/", $uid)) {
header('Location: /login/register.php?signup=invalid');
exit();
} else {
//Check if email is valid
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
header('Location : /login/register.php?signup=email');
exit();
} else {
$sql = "SELECT * FROM users WHERE user_uid='$uid'";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
header('Location : /login/register.php?signup=usertaken');
exit();
} else {
//Hashing the password
$hashedPwd = password_hash($pwd, PASSWORD_DEFAULT);
//Insert the user into the databse
$sql = "INSERT INTO users (user_uid, user_pwd, user_email) VALUES ('$uid', '$hashedPwd', '$email');";
mysqli_query($conn, $sql);
header('Location : /login/register.php?signup=success');
exit();
}
}
}
}
} else {
header('Location : /login/register.php');
exit();
}
Solved - Removing space after "location" answer by Nigel Ren
Make sure you don't have a space after location and before the :...
header('Location : /login/register.php');
should be
header('Location: /login/register.php');
Try to use absolute URI
$host = $_SERVER['HTTP_HOST'];
header("Location: ".$host."/login/register.php?signup=empty");
replace all header to location.assign
header('Location : /login/register.php');
replace to
echo "<script>location.assign('/login/register.php')</script>";
after use location assign , maybe problem sol..
Related
This is the code where this used to verify the token by getting it from url and matching it with databse. and when matches it updates a db field and gives a alert that account is verified according to code. It works good. but when url token is wrong and it doesnt updates databse field but still gives same alert that account is verified. but it should use that else fumction. But still it uses that if function. What is the reason behind this error?
session_start();
include 'partials/_dbconnect.php';
if(isset($_GET['token'])){
$token = $_GET['token'];
$updatequery ="UPDATE `users` SET `status` = 'active' WHERE `users`.`token` = '$token' " ;
$query = mysqli_query($conn, $updatequery);
if($query){
echo '<script>alert("Your account is verified successfully. Please login now. !")</script>';
echo '<script> window.location.href = "/login.php"</script>';
}
else{
echo '<script>alert("This link is not valid. Acoount verification failed !")</script>';
echo '<script> window.location.href = "/index.php"</script>';
}
}
?>``
`
$query will return as true as long as the query executed successfully. You aren't matching the token at all. You're updating it. If the token doesn't match, the database doesn't update, but the query itself still returns true, that 0 rows were updated.
What you need to do is check if the token exists in the database first. If it does exist, then update it. Something like this:
if(isset($_GET['token'])){
$token = $_GET['token'];
$checkquery ="SELECT `token` FROM `users` WHERE `users`.`token` = '$token' " ;
$result = mysqli_query($conn, $checkquery);
if(mysqli_num_rows($result) >0){
$updatequery ="UPDATE `users` SET `status` = 'active' WHERE `users`.`token` = '$token' " ;
$query = mysqli_query($conn, $updatequery);
echo '<script>alert("Your account is verified successfully. Please login now. !")</script>';
echo '<script> window.location.href = "/login.php"</script>';
}
else{
echo '<script>alert("This link is not valid. Acoount verification failed !")</script>';
echo '<script> window.location.href = "/index.php"</script>';
}
}
I'm a new php learner and currently I'm trying to develop a job portal system. Everything else is running smoothly but I encounter problems when I need to prepare the php for uploading resume and image into the database. I have both the source code to upload image and pdf file separately but I don't know what to do if I have to combine them. Can anyone give me ideas of combining the php source code for both image and pdf file?
edit: I have a form where users need to upload their picture and attach their resume, hence the reason why I need to combine both of my resume and image source code below.
image.php
<?php
//To Handle Session Variables on This Page
session_start();
//Including Database Connection From db.php file to avoid rewriting in all files
require_once("db.php");
//If user clicked register button
if(isset($_POST)) {
//Escape Special Characters In String First
$email = mysqli_real_escape_string($conn, $_POST['email']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
//Encrypt Password
$password = base64_encode(strrev(md5($password)));
//sql query to check if email already exists or not
$sql = "SELECT email FROM user WHERE email='$email'";
$result = $conn->query($sql);
//if email not found then we can insert new data
if($result->num_rows == 0) {
//This variable is used to catch errors doing upload process. False means there is some error and we need to notify that user.
$uploadOk = true;
//Folder where you want to save your image. THIS FOLDER MUST BE CREATED BEFORE TRYING
$folder_dir = "uploads/logo/";
//Getting Basename of file. So if your file location is Documents/New Folder/myResume.pdf then base name will return myResume.pdf
$base = basename($_FILES['image']['name']);
//This will get us extension of your file. So myimage.pdf will return pdf. If it was image.doc then this will return doc.
$imageFileType = pathinfo($base, PATHINFO_EXTENSION);
//Setting a random non repeatable file name. Uniqid will create a unique name based on current timestamp. We are using this because no two files can be of same name as it will overwrite.
$file = uniqid() . "." . $imageFileType;
//This is where your files will be saved so in this case it will be uploads/image/newfilename
$filename = $folder_dir .$file;
//We check if file is saved to our temp location or not.
if(file_exists($_FILES['image']['tmp_name'])) {
//Next we need to check if file type is of our allowed extention or not. I have only allowed pdf. You can allow doc, jpg etc.
if($imageFileType == "jpg" || $imageFileType == "png") {
//Next we need to check file size with our limit size. I have set the limit size to 5MB. Note if you set higher than 2MB then you must change your php.ini configuration and change upload_max_filesize and restart your server
if($_FILES['image']['size'] < 500000) { // File size is less than 5MB
//If all above condition are met then copy file from server temp location to uploads folder.
move_uploaded_file($_FILES["image"]["tmp_name"], $filename);
} else {
//Size Error
$_SESSION['uploadError'] = "Wrong Size. Max Size Allowed : 5MB";
$uploadOk = false;
}
} else {
//Format Error
$_SESSION['uploadError'] = "Wrong Format. Only jpg & png Allowed";
$uploadOk = false;
}
} else {
//File not copied to temp location error.
$_SESSION['uploadError'] = "Something Went Wrong. File Not Uploaded. Try Again.";
$uploadOk = false;
}
//If there is any error then redirect back.
if($uploadOk == false) {
header("Location: candidateform.php");
exit();
}
//sql new registration insert query
$sql = "INSERT INTO user(email, password,logo) VALUES ('$email', '$password', '$file')";
if($conn->query($sql)===TRUE) {
//If data inserted successfully then Set some session variables for easy reference and redirect to company login
$_SESSION['registerCompleted'] = true;
header("Location: login.php");
exit();
} else {
//If data failed to insert then show that error. Note: This condition should not come unless we as a developer make mistake or someone tries to hack their way in and mess up :D
echo "Error " . $sql . "<br>" . $conn->error;
}
} else {
//if email found in database then show email already exists error.
$_SESSION['registerError'] = true;
header("Location: candidateform.php");
exit();
}
//Close database connection. Not compulsory but good practice.
$conn->close();
} else {
//redirect them back to register page if they didn't click register button
header("Location: candidateform.php");
exit();
}
and here is the resume.php
resume.php
<?php
//To Handle Session Variables on This Page
session_start();
//Including Database Connection From db.php file to avoid rewriting in all files
require_once("db.php");
//If user Actually clicked register button
if(isset($_POST)) {
//Escape Special Characters In String First
$email = mysqli_real_escape_string($conn, $_POST['email']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
//Encrypt Password
$password = base64_encode(strrev(md5($password)));
//sql query to check if email already exists or not
$sql = "SELECT email FROM users WHERE email='$email'";
$result = $conn->query($sql);
//if email not found then we can insert new data
if($result->num_rows == 0) {
//This variable is used to catch errors doing upload process. False means there is some error and we need to notify that user.
$uploadOk = true;
//Folder where you want to save your resume. THIS FOLDER MUST BE CREATED BEFORE TRYING
$folder_dir = "uploads/resume/";
//Getting Basename of file. So if your file location is Documents/New Folder/myResume.pdf then base name will return myResume.pdf
$base = basename($_FILES['resume']['name']);
//This will get us extension of your file. So myResume.pdf will return pdf. If it was resume.doc then this will return doc.
$resumeFileType = pathinfo($base, PATHINFO_EXTENSION);
//Setting a random non repeatable file name. Uniqid will create a unique name based on current timestamp. We are using this because no two files can be of same name as it will overwrite.
$file = uniqid() . "." . $resumeFileType;
//This is where your files will be saved so in this case it will be uploads/resume/newfilename
$filename = $folder_dir .$file;
//We check if file is saved to our temp location or not.
if(file_exists($_FILES['resume']['tmp_name'])) {
//Next we need to check if file type is of our allowed extention or not. I have only allowed pdf. You can allow doc, jpg etc.
if($resumeFileType == "pdf") {
//Next we need to check file size with our limit size. I have set the limit size to 5MB. Note if you set higher than 2MB then you must change your php.ini configuration and change upload_max_filesize and restart your server
if($_FILES['resume']['size'] < 500000) { // File size is less than 5MB
//If all above condition are met then copy file from server temp location to uploads folder.
move_uploaded_file($_FILES["resume"]["tmp_name"], $filename);
} else {
//Size Error
$_SESSION['uploadError'] = "Wrong Size. Max Size Allowed : 5MB";
$uploadOk = false;
}
} else {
//Format Error
$_SESSION['uploadError'] = "Wrong Format. Only PDF Allowed";
$uploadOk = false;
}
} else {
//File not copied to temp location error.
$_SESSION['uploadError'] = "Something Went Wrong. File Not Uploaded. Try Again.";
$uploadOk = false;
}
//If there is any error then redirect back.
if($uploadOk == false) {
header("Location: register-candidates.php");
exit();
}
$hash = md5(uniqid());
//sql new registration insert query
$sql = "INSERT INTO users(email, password,resume, hash) VALUES ('$email', '$password','$file', '$hash')";
if($conn->query($sql)===TRUE) {
// Send Email
// $to = $email;
// $subject = "Job Portal - Confirm Your Email Address";
// $message = '
// <html>
// <head>
// <title>Confirm Your Email</title>
// <body>
// <p>Click Link To Confirm</p>
// Verify Email
// </body>
// </html>
// ';
// $headers[] = 'MIME-VERSION: 1.0';
// $headers[] = 'Content-type: text/html; charset=iso-8859-1';
// $headers[] = 'To: '.$to;
// $headers[] = 'From: hello#yourdomain.com';
// //you add more headers like Cc, Bcc;
// $result = mail($to, $subject, $message, implode("\r\n", $headers)); // \r\n will return new line.
// if($result === TRUE) {
// //If data inserted successfully then Set some session variables for easy reference and redirect to login
// $_SESSION['registerCompleted'] = true;
// header("Location: login.php");
// exit();
// }
// //If data inserted successfully then Set some session variables for easy reference and redirect to login
$_SESSION['registerCompleted'] = true;
header("Location: login.php");
exit();
} else {
//If data failed to insert then show that error. Note: This condition should not come unless we as a developer make mistake or someone tries to hack their way in and mess up :D
echo "Error " . $sql . "<br>" . $conn->error;
}
} else {
//if email found in database then show email already exists error.
$_SESSION['registerError'] = true;
header("Location: candidateform.php");
exit();
}
//Close database connection. Not compulsory but good practice.
$conn->close();
} else {
//redirect them back to register page if they didn't click register button
header("Location: candidateform.php");
exit();
}
Thank you very much for every guidance, suggestions and helps in advance
From your question it appears that you want to upload multiple files (one PDF and one image) in a form and send it to PHP. There are multiple guides written on this:
Upload two files using PHP
Or for more verbosity, check:
http://findnerd.com/list/view/How-to-upload-two-separate-files-in-php/3268/
If you want to add multiple files to the same upload button, then check:
https://daveismyname.blog/upload-multiple-files-with-a-single-input-with-html-5-and-php
In terms of your code, you will need to do something like:
<input type="file" name="resume" />
<input type="file" name="image" />
Then in your PHP, you will need to do something like:
<?php
//To Handle Session Variables on This Page
session_start();
//Including Database Connection From db.php file to avoid rewriting in all files
require_once("db.php");
//If user Actually clicked register button
if(isset($_POST)) {
//Escape Special Characters In String First
$email = mysqli_real_escape_string($conn, $_POST['email']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
//Encrypt Password
$password = base64_encode(strrev(md5($password)));
//sql query to check if email already exists or not
$sql = "SELECT email FROM users WHERE email='$email'";
$result = $conn->query($sql);
//if email not found then we can insert new data
if($result->num_rows == 0) {
//This variable is used to catch errors doing upload process. False means there is some error and we need to notify that user.
$uploadOk = true;
// Code for image
//Folder where you want to save your image. THIS FOLDER MUST BE CREATED BEFORE TRYING
$folder_dir = "uploads/logo/";
//Getting Basename of file. So if your file location is Documents/New Folder/myResume.pdf then base name will return myResume.pdf
$base = basename($_FILES['image']['name']);
//This will get us extension of your file. So myimage.pdf will return pdf. If it was image.doc then this will return doc.
$imageFileType = pathinfo($base, PATHINFO_EXTENSION);
//Setting a random non repeatable file name. Uniqid will create a unique name based on current timestamp. We are using this because no two files can be of same name as it will overwrite.
$file = uniqid() . "." . $imageFileType;
//This is where your files will be saved so in this case it will be uploads/image/newfilename
$filename = $folder_dir .$file;
if(file_exists($_FILES['image']['tmp_name'])) {
//Next we need to check if file type is of our allowed extention or not. I have only allowed pdf. You can allow doc, jpg etc.
if($imageFileType == "jpg" || $imageFileType == "png") {
//Next we need to check file size with our limit size. I have set the limit size to 5MB. Note if you set higher than 2MB then you must change your php.ini configuration and change upload_max_filesize and restart your server
if($_FILES['image']['size'] < 500000) { // File size is less than 5MB
//If all above condition are met then copy file from server temp location to uploads folder.
move_uploaded_file($_FILES["image"]["tmp_name"], $filename);
} else {
//Size Error
$_SESSION['uploadError'] = "Wrong Size. Max Size Allowed : 5MB";
$uploadOk = false;
}
} else {
//Format Error
$_SESSION['uploadError'] = "Wrong Format. Only jpg & png Allowed";
$uploadOk = false;
}
} else {
//File not copied to temp location error.
$_SESSION['uploadError'] = "Something Went Wrong. File Not Uploaded. Try Again.";
$uploadOk = false;
}
// Code for resume
//Folder where you want to save your resume. THIS FOLDER MUST BE CREATED BEFORE TRYING
$folder_dir = "uploads/resume/";
//Getting Basename of file. So if your file location is Documents/New Folder/myResume.pdf then base name will return myResume.pdf
$base = basename($_FILES['resume']['name']);
//This will get us extension of your file. So myResume.pdf will return pdf. If it was resume.doc then this will return doc.
$resumeFileType = pathinfo($base, PATHINFO_EXTENSION);
//Setting a random non repeatable file name. Uniqid will create a unique name based on current timestamp. We are using this because no two files can be of same name as it will overwrite.
$file = uniqid() . "." . $resumeFileType;
//This is where your files will be saved so in this case it will be uploads/resume/newfilename
$filename = $folder_dir .$file;
//We check if file is saved to our temp location or not.
if(file_exists($_FILES['resume']['tmp_name'])) {
//Next we need to check if file type is of our allowed extention or not. I have only allowed pdf. You can allow doc, jpg etc.
if($resumeFileType == "pdf") {
//Next we need to check file size with our limit size. I have set the limit size to 5MB. Note if you set higher than 2MB then you must change your php.ini configuration and change upload_max_filesize and restart your server
if($_FILES['resume']['size'] < 500000) { // File size is less than 5MB
//If all above condition are met then copy file from server temp location to uploads folder.
move_uploaded_file($_FILES["resume"]["tmp_name"], $filename);
} else {
//Size Error
$_SESSION['uploadError'] = "Wrong Size. Max Size Allowed : 5MB";
$uploadOk = false;
}
} else {
//Format Error
$_SESSION['uploadError'] = "Wrong Format. Only PDF Allowed";
$uploadOk = false;
}
} else {
//File not copied to temp location error.
$_SESSION['uploadError'] = "Something Went Wrong. File Not Uploaded. Try Again.";
$uploadOk = false;
}
//If there is any error then redirect back.
if($uploadOk == false) {
header("Location: register-candidates.php");
exit();
}
$hash = md5(uniqid());
//sql new registration insert query
$sql = "INSERT INTO users(email, password,resume, hash) VALUES ('$email', '$password','$file', '$hash')";
if($conn->query($sql)===TRUE) {
// Send Email
// $to = $email;
// $subject = "Job Portal - Confirm Your Email Address";
// $message = '
// <html>
// <head>
// <title>Confirm Your Email</title>
// <body>
// <p>Click Link To Confirm</p>
// Verify Email
// </body>
// </html>
// ';
// $headers[] = 'MIME-VERSION: 1.0';
// $headers[] = 'Content-type: text/html; charset=iso-8859-1';
// $headers[] = 'To: '.$to;
// $headers[] = 'From: hello#yourdomain.com';
// //you add more headers like Cc, Bcc;
// $result = mail($to, $subject, $message, implode("\r\n", $headers)); // \r\n will return new line.
// if($result === TRUE) {
// //If data inserted successfully then Set some session variables for easy reference and redirect to login
// $_SESSION['registerCompleted'] = true;
// header("Location: login.php");
// exit();
// }
// //If data inserted successfully then Set some session variables for easy reference and redirect to login
$_SESSION['registerCompleted'] = true;
header("Location: login.php");
exit();
} else {
//If data failed to insert then show that error. Note: This condition should not come unless we as a developer make mistake or someone tries to hack their way in and mess up :D
echo "Error " . $sql . "<br>" . $conn->error;
}
} else {
//if email found in database then show email already exists error.
$_SESSION['registerError'] = true;
header("Location: candidateform.php");
exit();
}
//Close database connection. Not compulsory but good practice.
$conn->close();
} else {
//redirect them back to register page if they didn't click register button
header("Location: candidateform.php");
exit();
}
Please note that this can be further shortened and is not the best programming IMHO.
Finally I have figured this out and not only that, I can upload different type of files without confusing them anymore. I hope my answer can be off help to another. Here it is;
adduser.php
<?php
//To Handle Session Variables on This Page
session_start();
//Including Database Connection From db.php file to avoid rewriting in all files
require_once("db.php");
//If user Actually clicked register button
if(isset($_POST)) {
$user_name = mysqli_real_escape_string($conn, $_POST['user_name']);
$ic_no = mysqli_real_escape_string($conn, $_POST['ic_no']);
$nationality = mysqli_real_escape_string($conn, $_POST['nationality']);
$gender = mysqli_real_escape_string($conn, $_POST['gender']);
$race = mysqli_real_escape_string($conn, $_POST['race']);
$ic_no = mysqli_real_escape_string($conn, $_POST['ic_no']);
$contactno = mysqli_real_escape_string($conn, $_POST['contactno']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$address = mysqli_real_escape_string($conn, $_POST['address']);
$highest_qualification = mysqli_real_escape_string($conn, $_POST['highest_qualification']);
$university = mysqli_real_escape_string($conn, $_POST['university']);
$major = mysqli_real_escape_string($conn, $_POST['major']);
$current_position = mysqli_real_escape_string($conn, $_POST['current_position']);
$position_applied = mysqli_real_escape_string($conn, $_POST['position_applied']);
$current_monthly_salary = mysqli_real_escape_string($conn, $_POST['current_monthly_salary']);
$expected_monthly_salary = mysqli_real_escape_string($conn, $_POST['expected_monthly_salary']);
$prefered_working_location = mysqli_real_escape_string($conn, $_POST['prefered_working_location']);
$avaibility = mysqli_real_escape_string($conn, $_POST['avaibility']);
$malay = mysqli_real_escape_string($conn, $_POST['malay']);
$english = mysqli_real_escape_string($conn, $_POST['english']);
$mandarin = mysqli_real_escape_string($conn, $_POST['mandarin']);
$other = mysqli_real_escape_string($conn, $_POST['other']);
$aboutme = mysqli_real_escape_string($conn, $_POST['aboutme']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
$password = base64_encode(strrev(md5($password)));
//sql query to check if email already exists or not
$sql = "SELECT email FROM users WHERE email='$email'";
$result = $conn->query($sql);
//if email not found then we can insert new data
if($result->num_rows == 0) {
//This variable is used to catch errors doing upload process. False means there is some error and we need to notify that user.
$uploadOk = true;
// Code for image
$folder_dir = "uploads/logo/";
$base = basename($_FILES['image']['name']);
$imageFileType = pathinfo($base, PATHINFO_EXTENSION);
$file = uniqid() . "." . $imageFileType;
$filename = $folder_dir .$file;
if(file_exists($_FILES['image']['tmp_name'])) {
if($imageFileType == "jpg" || $imageFileType == "png") {
if($_FILES['image']['size'] < 500000) { // File size is less than 5MB
move_uploaded_file($_FILES["image"]["tmp_name"], $filename);
} else {
$_SESSION['uploadError'] = "Wrong Size. Max Size Allowed : 5MB";
$uploadOk = false;
}
} else {
$_SESSION['uploadError'] = "Wrong Format. Only jpg & png Allowed";
$uploadOk = false;
}
} else {
$_SESSION['uploadError'] = "Something Went Wrong. File Not Uploaded. Try Again.";
$uploadOk = false;
}
// Code for resume
$folder_dir = "uploads/resume/";
$base = basename($_FILES['resume']['name']);
$resumeFileType = pathinfo($base, PATHINFO_EXTENSION);
$file1 = uniqid() . "." . $resumeFileType;
$filename = $folder_dir .$file1;
if(file_exists($_FILES['resume']['tmp_name'])) {
if($resumeFileType == "pdf"|| $resumeFileType == "doc") {
if($_FILES['resume']['size'] < 500000) {
move_uploaded_file($_FILES["resume"]["tmp_name"], $filename);
} else {
$_SESSION['uploadError'] = "Wrong Size. Max Size Allowed : 5MB";
$uploadOk = false;
}
} else {
$_SESSION['uploadError'] = "Wrong Format. Only PDF Allowed";
$uploadOk = false;
}
} else {
//File not copied to temp location error.
$_SESSION['uploadError'] = "Something Went Wrong. File Not Uploaded. Try Again.";
$uploadOk = false;
}
//If there is any error then redirect back.
if($uploadOk == false) {
header("Location: register-candidates.php");
exit();
}
$hash = md5(uniqid());
//sql new registration insert query
$sql="INSERT INTO users (user_name, ic_no, gender, email, password, address, nationality, contactno, highest_qualification, university, major, current_position,
position_applied, current_monthly_salary, expected_monthly_salary, prefered_working_location, avaibility, malay, english, mandarin, other, logo, resume, hash, aboutme) VALUES
('$user_name', '$ic_no', '$gender', '$email', '$password', '$address', '$nationality', '$contactno', '$highest_qualification', '$university', '$major', '$current_position',
'$position_applied', '$current_monthly_salary', '$expected_monthly_salary', '$prefered_working_location', '$avaibility', '$malay', '$english', '$mandarin',
'$other', '$file', '$file1', '$hash', '$aboutme')";
if($conn->query($sql)===TRUE) {
// Send Email
// $to = $email;
// $subject = "Job Portal - Confirm Your Email Address";
// $message = '
// <html>
// <head>
// <title>Confirm Your Email</title>
// <body>
// <p>Click Link To Confirm</p>
// Verify Email
// </body>
// </html>
// ';
// $headers[] = 'MIME-VERSION: 1.0';
// $headers[] = 'Content-type: text/html; charset=iso-8859-1';
// $headers[] = 'To: '.$to;
// $headers[] = 'From: hello#yourdomain.com';
// //you add more headers like Cc, Bcc;
// $result = mail($to, $subject, $message, implode("\r\n", $headers)); // \r\n will return new line.
// if($result === TRUE) {
// //If data inserted successfully then Set some session variables for easy reference and redirect to login
// $_SESSION['registerCompleted'] = true;
// header("Location: login.php");
// exit();
// }
// //If data inserted successfully then Set some session variables for easy reference and redirect to login
$_SESSION['registerCompleted'] = true;
header("Location: login-candidates.php");
exit();
} else {
//If data failed to insert then show that error. Note: This condition should not come unless we as a developer make mistake or someone tries to hack their way in and mess up :D
echo "Error " . $sql . "<br>" . $conn->error;
}
} else {
//if email found in database then show email already exists error.
$_SESSION['registerError'] = true;
header("Location: candidate-register.php");
exit();
}
//Close database connection. Not compulsory but good practice.
$conn->close();
} else {
//redirect them back to register page if they didn't click register button
header("Location: candidate-register.php");
exit();
}
?>
I am trying to use jQuery, AJAX, PHP, and MySQL to check if an email entered into a form already exists in a database.
This is my current jQuery code :
$.post('check-email.php', {'suEmail' : $suEmail}, function(data) {
if(data=='exists') {
validForm = false;
$suRememberMeCheckbox.css('top', '70px');
$suRememberMeText.css('top', '68px');
$signUpSubmit.css('top', '102px');
$tosppText.css('top', '115px');
$suBox.css('height', '405px');
$suBox.css('top', '36%');
$errorText.text('The email has been taken.');
return false;
};
});
And this is my PHP code:
<?php include("dbconnect.php") ?>
<?php
$sql = "SELECT email FROM users WHERE email = " .$_POST['suEmail'];
$select = mysqli_query($connection, $sql);
$row = mysqli_fetch_assoc($select);
if (mysqli_num_rows($row) > 0) {
echo "exists";
}
?>
When I go through with the sign up form, when I use an email already in the database, the error text never changes to what I specified, but instead to some other error cases I have coded. Why is this not working! Thanks so much!
Use This Code: Working Perfectly:
<?php
include("dbconnect.php");
$sql = "SELECT email FROM users WHERE email = '" .$_POST['suEmail']."' ";
$select = mysqli_query($connection, $sql);
$row = mysqli_fetch_assoc($select);
if (mysqli_num_rows($select) > 0) {
echo "exists";
}
?>
If its not changing that means you might have a error with your query. Check developer options on your browser under network. There you can see all ajax calls being made. Click on look at the response. Check to see if there was an error with your query.
Also you have to validate the form submission.
Something like.
if($_SERVER['REQUEST_METHOD'] = 'POST')
{
//maybe send a token over with the form to prevent form spoofing
if($_POST['token'] === $_SESSION['token'])
{
// all your code goes in here
// you provably want to check that is a real email also
// check email input against regular expression
if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL))
{
//if valid email to variable and escape data
$e = sanitizeString($_POST['email']);
}else
{
/// if not a real email to errors array
$reg_errors['email'] = 'Please enter a valid email address!';
}
}
}
You have to use prepare statements in your queries.
Ok, so I've successfully linked a Contact Form for my website to a MySQL database and I'm super stoked about figuring it out, however on my registration page my code isn't working. I ran this connection check:
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
} else {
echo "It's Working!";
}
and it says: "It's working!" So i know i've established a connection to my SQL database.
Let me try to clarify further:
I've got 2 main files for this particular program (obviously we won't be needing to care about styles.css or the linked files for other pages in my site): register.php and db.php. Here is my code for both. It's simply a project website so i don't care if people see/use my code... It's not working anyway so knock yourselves out, LOL!
First, db.php:
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_DATABASE', 'forms1');
$db = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
Now here's the php in register.php, which I've place at the top BEFORE any HTML at all:
include ("db.php");
$msg = "";
if(isset($_POST["submit"]))
{
$name = $_POST["name"];
$lname = $_POST["lname"];
$a1 = $_POST["a1"];
$a2 = $_POST["a2"];
$city = $_POST["city"];
$state = $_POST["state"];
$zip = $_POST["zip"];
$phone = $_POST["phone"];
$email = $_POST["email"];
$password = $_POST["password"];
$name = mysqli_real_escape_string($db, $name);
$lname = mysqli_real_escape_string($db, $lname);
$a1 = mysqli_real_escape_string($db, $a1);
$a2 = mysqli_real_escape_string($db, $a2);
$city = mysqli_real_escape_string($db, $city);
$state = mysqli_real_escape_string($db, $state);
$zip = mysqli_real_escape_string($db, $zip);
$phone = mysqli_real_escape_string($db, $phone);
$email = mysqli_real_escape_string($db, $email);
$password = mysqli_real_escape_string($db, $password);
$password = md5($password);
$sql="SELECT email FROM users WHERE email='$email'";
$result=mysqli_query($db,$sql);
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
if(mysqli_num_rows($result) == 1)
{
$msg = "Sorry...This email already exist...";
}
else
{
$query = mysqli_query($db, "INSERT INTO users(name,lname,a1, a2, city, state, zip, phone, email, password) VALUES ('$name', '$lname', '$a1', '$a2', '$city', '$state', '$zip', '$phone', '$email', '$password')");
if($query)
{
$msg = "Thank You! you are now registered.";
}
}
}
mysqli_close($db);
I should probably mention that JavaScript is included in the HEAD section of my HTML:
(function(H){H.className=H.className.replace(/\bno-js\b/,'js')})(document.documentElement)
$(document).ready(function() {
$('form.required-form').simpleValidate({
errorElement: 'em',
ajaxRequest: true,
completeCallback: function($el) {
var formData = $el.serialize();
}
});
});
$("form[name='form1']").submit(function(){
.... JS code ....
return error;
});
</script>
<script type= "text/javascript">
var RecaptchaOptions = {
theme: 'clean'
};
Well, I tried to include the HTML code for the form but it wasn't appearing properly, but believe me when i tell you that ALL the inputs of the the form fields have a name="" that corresponds to the fields within my table within my database within MySQL. The HTML is most certainly not the problem. I've check syntax and spelling over and over. It's not the HTML. Somewhere there is an error, though.
PLEASE HELP!!!
Thank you all very much.
-Maj
P.S. I purposely deleted the opening and closing php/html tags here in these examples so it'd be easier to read, but i have them placed in my original code.
After that if($query){ } block try adding else { print(mysqli_error($db)); }
perhaps there's an error, but what is the response you got from register.php?
you should start to debug your source code, but if you don't use a debugger, put some "die(SOME VARIABLE);" to locate your trouble area and without javascript, for the first. Just use some simple html-formular and to get row datas, put the answer into <PRE> tags ( or use curl in a terminal, i like this way, but for you it is not necessary ).
If you don't debug your php-code or you your browser-relevant-code, means "html, css, javascript, ..." (you can see with firebug, what data you are sending and what is coming back), you can use echo "INSERT .... BLA ...$VAR ...;" and copy-paste the SQL-Statement and testing it in PhpMyAdmin, to see you get a proper statement, maybe there is a type-converting-problem or many other thinks are possible.
If everything is going well, it is probably some trouble in your javascript-code. But probably you need to convert a type of some variable, you should copy and paste your SQL-Statement and execute it in phpmyadmin to make a verification of your SQL-Statements which you put in your Php-Code. Cheers.
I found and fixed a little bit I am not so good with PHP but any improvements are welcome.
The problem is that sometimes in Chrome and Opera but only sometimes after login sucess the script redirect to a welcome page with javascript redirection after 5 secs. But sometimes it just get stuck and does not redirect but just show a white page without error and other times it redirect and worls fine. What can it be?
Here is the code
<?php session_start();?>
<?php
include 'inc/connection.php';
$db=mysqli_connect($dbserver, $dbuser, $dbpass, $dbname)or die("DB connection error...");
$username_to_sanitize = $_POST['username'];
$password_to_sanitize = $_POST['password'];
$sanitized_username = mysqli_real_escape_string($db, $username_to_sanitize);
$sanitized_password = mysqli_real_escape_string($db, $password_to_sanitize);
$query = "SELECT password, salt, privilege, username FROM members WHERE username = '$sanitize_username'";
$result = mysqli_query($db, $query);
if(mysqli_num_rows($result) == 0) // User not found. Redirected to login page.
{header('Location:login.php?message=Username not found, please try again');}
$userData = mysqli_fetch_array($result, MYSQL_ASSOC);
$hash = hash('sha256', $userData['salt'] . hash('sha256', $sanitized_password) );
if($hash != $userData['password']) // Incorrect passw. Redirected to login page.
{header('Location:error.php?message=Wrong password, please try again');}
else if($userData['privilege']=="ADMIN"){session_start();
$_SESSION['username']=$userData['username'];
header('Location:redirection.php?URL=admins/index.php');}
else if($userData['privilege']=="MODERATOR"){session_start();
$_SESSION['username']=$userData['username'];
header('Location:redirection.php?URL=moderators/index.php');}
else if($userData['privilege']=="MEMBER"){session_start();
$_SESSION['username']=$userData['username'];
header('Location:redirection.php?URL=members/index.php');}
else if($userData['privilegio']=="BANNED"){session_start();
$_SESSION['username']=$userData['username'];
header('Location:redirection.php?URL=banned/index.php');}
else{
header('Location:error.php?message=su need privileges to acces this site');
exit();
}
?>
After reading and testing new scripts found on internet I still cannot fix this problem after 2 months. Any idea?
You have a lot of duplication in your code, which is bad because each place that you duplicate means that you need to change it when you update the code, which means that there are more places for bugs to pop up later.
To help, I placed in only one session_start(), and I converted the if/elseif/elseif/elseif... to a switch statement.
Instead of dealing with the location headers themselves, I've replaced those with the http_redirect function, which basically does it for you. To boot, it encodes the URLs for you so you don't have to worry about that.
If you keep seeing a blank page, then you should check the webserver's logs (apache or nginx or php-fpm, or whatever) to see if the errors are there. Otherwise, turn on better error reporting; quite often blank pages are just errors that haven't been reported.
<?php
session_start();
include 'inc/connection.php';
$db = mysqli_connect($dbserver, $dbuser, $dbpass, $dbname) or die('DB connection error...');
$sanitized_username = mysqli_real_escape_string($db, $_POST['username']);
$sanitized_password = mysqli_real_escape_string($db, $_POST['password']);
$query = "SELECT password, salt, privilege, username FROM members WHERE username = '$sanitized_username'";
$result = mysqli_query($db, $query);
if (mysqli_num_rows($result) == 0) {
// User not found. Redirected to login page.
http_redirect('login.php', array('message' => 'Username not found, please try again'), true);
}
$userData = mysqli_fetch_array($result, MYSQL_ASSOC);
$hash = hash('sha256', $userData['salt'] . hash('sha256', $sanitized_password) );
if($hash != $userData['password']) {
// Incorrect passw. Redirected to login page.
http_redirect('error.php', array('message' => 'Wrong password, please try again'), true);
}
// Just set the username once
$_SESSION['username'] = $userData['username'];
switch ( $userData['privilege'] ) :
case 'ADMIN':
http_redirect('redirection.php', array('URL' => 'admins/index.php'), true);
break;
case 'MODERATOR' :
http_redirect('redirection.php', array('URL' => 'moderators/index.php'), true);
break;
case 'MEMBER' :
http_redirect('redirection.php', array('URL' => 'members/index.php'), true);
break;
case 'BANNED' :
http_redirect('redirection.php', array('URL' => 'banned/index.php'), true);
break;
default:
// The message is weird. Should it be:
// 'You need privileges to access this site' or something like that?
http_redirect('error.php', array('message' => 'su need privileges to acces this site'), true);
break;
endswitch;
http_redirect('error.php', array('message' => 'su need privileges to acces this site'), true);
?>