php - FILTER _VALIDATE_EMAIL check - php

I have a PHP script where I want to verify a valid email address using filter_var() but it is not working.
html form:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" type="text/css" href="style.css">
<title>CRUD Operations</title>
</head>
<body>
<div id="container"><!--container-->
<div id="wrapper">
<div id="form-element">
<div id="headings">
<h1>PHP Contact Form</h1>
</div>
<form method="post" action="operations.php" enctype="multipart/form-data">
<span>Name:</span><br>
<input type="text" name="name" value=""><br><br>
<span>Email:</span><br>
<input type="text" name="mail" value=""><br><br>
<span>Gender:</span><br>
<input type="radio" name="gender" value="Male"> Male
<input type="radio" name="gender" value="Female"> Female<br><br>
<span>Message</span><br>
<div id="message">
<textarea cols="36" rows="4" name="message"></textarea><br>
</div>
<div id="submit">
<input type="submit" value="Submit" name="submit">
</div>
</form>
</div>
</div>
</div><!--container-->
</body>
</html>
php code:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" type="text/css" href="style.css">
<title>CRUD Operations</title>
</head>
<?php
include_once('config.php');
$name = $mail = $gender = $message = '';
$email_err = '';
if(isset($_POST['submit'])){
$name= $_POST['name'];
$mail = $_POST['mail'];
if(!isset($_POST['gender'])){
}
else {
$gender = $_POST['gender'];
}
$message = $_POST['message'];
if(empty($name) || empty($mail) || empty($gender)|| empty($message)) {
if(empty($name)){
echo'<div class="error">*Dear User fill the Name field properly</div>';
}
if(empty($mail)){
echo'<div class="error">*Dear User fill the Email field properly</div>';
}
else {
if(!filter_var($mail, FILTER_VALIDATE_EMAIL)){
$email_err = "*valid Email is required";
}
}
if(empty($gender)){
echo'<div class="error">*Dear User please select your gender</div>';
}
if(empty($message)){
echo'<div class="error">*Dear User please Leave your Message</div>';
}
}
else {
$query = mysql_query("INSERT INTO users(`name`, `mail`, `gender`, `message`) VALUES('".$name."','".$mail."','".$gender."','".$message."')");
if($query) {
echo '<div class="success">Congratulations You Are Registered Successfully</div>';
echo 'View Records';
}
else {
echo 'not';
}
}
}
?>
</html>
Any help would be appreciated!

You're setting the validation error to the $email_err variable, but you're not doing anything with that variable after that.
But more importantly, the filter_var() call will never be hit. You have it in the block that checks for any of $name $mail $gender $messsage are empty. So the only way to get your code to do an email validation would be if someone entered an email address, but left gender blank.
You need to move the filter_var() call out of that block:
if(empty($name) || empty($mail) || empty($gender)|| empty($message)) {
if(empty($name)){
echo'<div class="error">*Dear User fill the Name field properly</div>';
}
if(empty($mail)){
echo'<div class="error">*Dear User fill the Email field properly</div>';
}
if(empty($gender)){
echo'<div class="error">*Dear User please select your gender</div>';
}
if(empty($message)){
echo'<div class="error">*Dear User please Leave your Message</div>';
}
}
elseif(!filter_var($mail, FILTER_VALIDATE_EMAIL)){
echo'<div class="error">*valid Email is required</div>';
}
else {
$query = mysql_query("INSERT INTO users(`name`, `mail`, `gender`, `message`) VALUES('".$name."','".$mail."','".$gender."','".$message."')");
if($query) {
echo '<div class="success">Congratulations You Are Registered Successfully</div>';
echo 'View Records';
}
else {
echo 'not';
}
}

When I write validation code such as this I try to avoid using conditionals that check so many things at once. Instead, validate each input in turn and abort if that is not valid; returning an error to the user at that point. Then you could move all of this validation to a single sub-routine. In this routine, if any validation checks fail - it returns immediately with an error. Only if your sub-routine makes it to the end would a user be created. And it prevents one from checking a variable $mail and then later validating it after it's already passed your truth check.

Related

How to properly validate a login request?

I wrote a code for a login page in PHP and MySQL. The code that I wrote is given below.
logintest.php:
<?php
session_start();
require_once('csrf.php');
?>
<?php
//session_start();
require_once('connect.php');
$csrf = new csrf();
// Generate Token Id and Valid
$token_id = $csrf->get_token_id();
$token_value = $csrf->get_token($token_id);
// Generate Random Form Names
$form_names = $csrf->form_names(array('email', 'password'), false);
if(isset($_POST[$form_names['email']], $_POST[$form_names['password']])) {
// Check if token id and token value are valid.
if($csrf->check_valid('post')) {
// Get the Form Variables.
$email = $_POST[$form_names['email']];
$password = $_POST[$form_names['password']];
// Form Function Goes Here
}
// Regenerate a new random value for the form.
$form_names = $csrf->form_names(array('email', 'password'), true);
}
if(isset($_POST) && !empty($_POST)) {
if(!isset($email) || empty($email)) {
$error[] = "email is required";
}
if(empty($email) && empty($password)) {
die("Please Enter your email and Password");
}
if(empty($email)) {
die("Please Enter your E-mail");
}
if(empty($password)) {
die("Please Fill in the password field");
}
if(!isset($password) || empty($password)) {
$error[] = "password is required";
}
if(!isset($error) || empty($error)) {
$sql = "SELECT email, password FROM loginsystem WHERE email = ? AND password = ?";
if($stmt = $connection->prepare("$sql")) {
$bound_params = $stmt->bind_param("ss", $email, $password);
$execute = $stmt->execute();
$storeResult = $stmt->store_result();
$rows = $stmt->num_rows();
} else {
"";
}
if($rows === 1) {
$_SESSION['email'] = $email;
header("location: home.php"); //redirects to home.php if everything's okay.
} else {
echo "Sorry $email, Wrong email & Password combination";
}
$stmt->close();
}
$connection->close();
}
?>
<html>
<head>
<title>Login System Test</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" >
</head>
<body>
<div class="container">
<div class="row">
<form class="" method="post" >
<div class="form-group">
<input type="hidden" name="<?= $token_id; ?>" value="<?= $token_value; ?>" />
<label for="form-element">Email</label>
<input type="text" name="<?= $form_names['email']; ?>" class="form-control" id="email" placeholder="Email">
</div>
<div class="form-group">
<label for="form-element">Password</label>
<input type="password" name="<?= $form_names['password']; ?>" class="form-control" id="password" placeholder="Password">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
</div>
</body>
</html>
Now the following is the code for home.php that I wrote:
<?php
session_start();
$email = $_SESSION['email'];
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<style type="text/css">
<!--
.style1 {
font-size: 36px;
font-weight: bold;
}
-->
</style>
</head>
<body>
<p><center>hello <?php echo $_SESSION['email'] ?></center></p>
<p align="center">logout</p>
</body>
</html>
Now by principle, we are allowed to enter the home.php file if and only if we provide the correct username and password and it does the same here too. But the problem is that if I go to home.php using this url : http://localhost/path/to/file/home.php , I come across this type of screen:
A Session ID is assigned and the login succeeds even if email or password are not provided through logintest.php. It clearly shows that I am missing out on some checkgates through which I can avoid happening that thing.
So, for avoiding this thing I want to make my code do a redirect to the logintest.php if anyone tries to access the home.php directly without providing proper credentials in the logintest.php file.
How can I achieve this? Early help will greatly be appreciated.
[P.S: I am new to PHP, so I often fall in such type of silly mistakes that ruin a day or two or my entire week.]
create a page called session.php and add this code
<?php
// check if the session is avilable if not go to login
$site = 'url address';// website address
if (!(isset($_SESSION['email']) && $_SESSION['email'] != '')) {
#header ("location: ".$site."login/");
}
// if you don't want any page redirection put this code to your page
session_start();
if (!(isset($_SESSION['email']) && $_SESSION['email'] != '')) {
//echo 'please login'; // heady login page
}else {
//echo 'logged in'; // go to member page
// logged in
// getting the logged in user - session
if($_SESSION['email']){
$welc = $_SESSION['email'].'';
}
//echo 'Welcome user:'.$welc. '<br>';
?>
Then call the page to every page you want to be accessed by the member. you may use require.
then to get the active session.
session_start();
if($_SESSION['email']){
$welc = $_SESSION['email'].'';
}
//echo 'Welcome user:'.$welc. '<br>';
update your login checks with this. i think it will help you
It was done right by setting a session variable and checking its presence in every page. This was easy and it consumed my whole week😡

Previous data auto insert when browser reloading in PHP

I have some data input area.Here is my file.
Here is my db.php:
<?php
$username = "root";
$password = "";
try {
$db = new PDO('mysql:host=localhost;dbname=task', $username, $password);
echo "Connection Successfull";
} catch (PDOException $e) {
die("Error: Database connection");
}
?>
And my index.php is:
<?php
include "db.php";
?>
<!DOCTYPE html>
<html>
<head>
<title>This is title</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div class="wrap1">
<form method="POST" action="">
<input type="text" name="name" required> Username</br></br>
<input type="email" name="email" required> Email</br></br>
<input type="text" name="website" required> Website</br></br>
<input type="submit" value="Submit">
</form>
</div>
<?php
$username = $_POST['name'];
$emailadd = $_POST['email'];
$webadd = $_POST['website'];
$sql = "INSERT INTO users (name,email,website) VALUES ('$username','$emailadd','$webadd')";
if(empty($username) || empty($emailadd) || empty($webadd)){
echo "Please input all field";
}
else{
if ($db->query($sql)) {
echo "Inserted!";
}
else{
echo "Error";
}
}
$db = null;
?>
</body>
</html>
When i first go to index.php page then it's showing some notice.
Notice: Undefined index: name in
C:\xampp\htdocs\techmasters\begin\index.php on line 21
Notice: Undefined index: email in
C:\xampp\htdocs\techmasters\begin\index.php on line 22
Notice: Undefined index: website in
C:\xampp\htdocs\techmasters\begin\index.php on line 23
but if i input any data then it going to be inserted fine.My problem is that if i reload the browser then previous inserted data going to inserted again.How can i solve this problem?
Thanks in advanced.
Its because, you are not checking whether form is submitted or not.
On every page request, data is getting inserted, add a check.
<?php
if (isset($_POST['name']) && ! empty($_POST['name'])) {
$username = $_POST['name'];
$emailadd = $_POST['email'];
$webadd = $_POST['website'];
$sql = "INSERT INTO users (name,email,website) VALUES ('$username','$emailadd','$webadd')";
if (empty($username) || empty($emailadd) || empty($webadd)){
echo "Please input all field";
}
else{
if ($db->query($sql)) {
echo "Inserted!";
}
else{
echo "Error";
}
}
$db = null;
$_POST = NULL;
}
?>
This will ensure that database insert will be done only in case of form submit.
EDIT:
If you submit a form to same page and then reload the page, it will
ask you to resubmit the form. Either change method to get and check
for duplicity or submit the form to another file (move form submit
code to other file and set it as form action).
When you reload the page it's asking for form re-submission. When you click on resend then it will post all data again and inserted in database. To overcome this issue you can use jquery.
Try this code :
html file :
<!DOCTYPE html>
<html>
<head>
<title>This is title</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div class="wrap1">
<form method="POST" id="frm" action="">
<input type="text" name="name" required> Username</br></br>
<input type="email" name="email" required> Email</br></br>
<input type="text" name="website" required> Website</br></br>
<input type="submit" class="sub" value="Submit">
</form>
</div>
<script>
$(".sub").click(function (e) {
e.preventDefault();
$.post("test.php",$("#frm").serialize(),function(data){
if(data == "Inserted!") {
//You can reload your page here
} else {
//Display error message.
}
});
});
</script>
</body>
</html>
You php code (test.php) :
<?php
include "db.php";
if(isset($_POST['name']) && $_POST['name'] != "") {
$username = $_POST['name'];
$emailadd = $_POST['email'];
$webadd = $_POST['website'];
$sql = "INSERT INTO users (name,email,website) VALUES ('$username','$emailadd','$webadd')";
if(empty($username) || empty($emailadd) || empty($webadd)){
echo "Please input all field";
} else {
if ($db->query($sql)) {
echo "Inserted!";
}
else{
echo "Error";
}
}
$db = null;
exit;
}
?>
Don't forget to add jquery file in your html.

Echo in php is not showing up on the web page after form is submitted

I am using foundation 5 and php for this web page.
When I go to the web page and fill in all the spaces and press create account, none of the echos are showing up on the web page. The page just refreshes and just makes a new page like if I just reloaded the page. No text shows up and none of the function are working.
Here is my code:
<?php
error_reporting(0);
#ini_set('display_errors', 0);
?>
<!doctype html>
<html class="no-js" lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>AskmanProducts</title>
<link rel="stylesheet" href="css/foundation.css" />
<script src="js/vendor/modernizr.js"></script>
<script src="js/signinvaldator.js"></script>
</head>
<body>
<?php
if ($_POST['registerbtn']) {
$getuser = $_POST['user'];
$getemail = $_POST['email'];
$getpass = $_POST['pass'];
$getconfirmpass = $_POST['confirmpass'];
if ($getuser) {
if ($getemail) {
if ($getpass){
if ($getconfirmpass) {
if ($getpass === $getconfirmpass) {
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
require ("connect.php");
$query = mysql_query("SELECT * FROM users WHERE username='$getuser'");
$numrows = mysql_num_rows($query);
if ($numrows == 0) {
$query = mysql_query("SELECT * FROM users WHERE email='$getemail'");
$numrows = mysql_num_rows($query);
if ($numrows == 0) {
$password = md5(md5("kjfiufj".$getpass."Fj56fj"));
$date = date("F d, Y");
$code = md5(rand());
mysql_query("INSERT INTO users VALUES (
'', '$getuser', '$password', '$getemail', '0', '$code', '$date'
)");
$query = mysql_query("SELECT * FROM users WHERE username='$getuser'");
$numrows = mysql_num_rows($query);
if ($numrows == 1) {
$site = "http://localhost/Projects/project";
$webmaster = "donotreply#askmanproducts.com";
$headers = "From: $webmaster";
$subject = "Activate Your Account";
$message = "Thanks For Registering. Click The Link Below To Activate Your Account.\n";
$message .= "$site/activate.php?user=$getuser&code=$code\n";
$message .= "You Must Activate Your Account To Login.";
if (mail($getemail, $subject, $message, $headers)) {
echo "You have been registered. You must activate your account from the activation link sent to <b>$getemail</b>";
$getuser = "";
$getemail = "";
}
else {
echo "An error has occured. You activation email was not sent.";
}
}
else {
echo "An error has occured. Your account was not created.";
}
}
else {
echo "There is already a user with that email.";
}
}
else {
echo "There is already a user with that username.";
}
mysql_close();
}
else {
echo "You must enter a valid email address to register.";
}
}
else {
echo "Your password do not match.";
}
}
else {
echo "You must confirm your password to register.";
}
}
else {
echo "You must enter your password to register.";
}
}
else {
echo "You must enter your email to register.";
}
}
else {
echo "You must enter your username to register.";
}
}
else {
}
$form = "<form action='register.php' method='post'>
<div class='row' style='margin-top:10%'>
<div align='center'><h2>Create an Account</h2></div>
<br />
<div class='medium-6 medium-centered large-centered large-6 columns'>
<form data-abide>
<div class='name-field'>
<label>Username</label>
<input type='text' name='user' value='$getuser'></input>
<div class='email-field'>
<label>Email</label>
<input type='email' name='email' value='$getemail'></input>
<label for='password'>Password</label>
<input type='password' name='pass' value=''></input>
<label for='confirmPassword'>Confirm Password</label>
<input type='password' name='confirmpass' value=''></input>
<br />
<br />
<button type='submit' name='registerbtn'>Create Account</button>
<a href='login.php' class='button'>Log In</a>
<br />
</form>
</div>
</div>
<script src='js/vendor/jquery.js'></script>
<script src='js/foundation.min.js'></script>
<script>
$(document).foundation();
</script>
</form>";
echo $form;
?>
</body>
</html>
Your form has action='register.php' as its destination. When you do this, by pressing the Submit button, the page will jump to register.php before giving your error checking code any chance to fire.
I recommend you use
action='<?php echo $_SERVER['PHP_SELF']; ?>'
so that your Submit button keeps you on the same page, then when your error checking process passes, use:
header('Location: register.php');
Either that, or pass each of your POST variables to register.php where the error checking is carried out.
In this solution I have altered your code considerably but I use this logic all the time on my sites. I'll explain the code under it.
NOTE:
I did review your processing but did not test... Judging from the initial comments you are getting outdated information regarding programming. your mysql query code is outdated and depreciated and you should be making use of parameterised queries as pointed out in the comments by #Dave below this answer.
I suggest you go to youtube and search for pdo tutorials to learn modern methods of querying mysql. The provided code shows how to process forms through jQuery and a processing php file.
HTML & jQuery
<!doctype html>
<html class="no-js" lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>AskmanProducts</title>
<link rel="stylesheet" href="css/foundation.css" />
<script src="js/vendor/modernizr.js"></script>
<script src="js/signinvaldator.js"></script>
</head>
<body>
<input type="hidden" name="processRegistrationURL" value="register.php">
<div id="showRegistrationResults" class="row" style="margin-top:10%">
<div align="center"><h2>Create an Account</h2></div>
<br />
<div class="medium-6 medium-centered large-centered large-6 columns">
<form data-abide>
<div class="name-field">
<label>Username</label>
<input type="text" is="user" name="user" value="$getuser"></input>
<div class="email-field">
<label>Email</label>
<input type="email" id="email" name="email" value="$getemail"></input>
<label for="password">Password</label>
<input type="password" id="pass" name="pass" value=""></input>
<label for="confirmPassword">Confirm Password</label>
<input type="password" id="confirmpass" name="confirmpass" value=""></input>
<br />
<br />
<button type="submit" id="registerbtn" name="registerbtn">Create Account</button>
Log In
<br />
</div>
</div>
<script src='js/vendor/jquery.js'></script>
<script src='js/foundation.min.js'></script>
<script>
$(document).foundation();
</script>
<script>
$(function() {
$( "#registerbtn" ).click(function(){
var url = $('#processRegistrationURL').val();
var user = $('#user').val();
var email = $('#email').val();
var pass = $('#pass').val();
var confirmpass = $('#confirmpass').val();
var postit = $.post( url, {
user:user,
email:email,
pass:pass,
confirmpass:confirmpass
});
postit.done(function( data ) {
var result = data.split('|');
if(result[0] == 1){alert(result[1]);}
else if(result[0] == 2){
$('#showRegistrationResults').html(result[1]);
}
});
});
});
</script
</body>
</html>
There are no form tags... the form processing is handled on register.php which is stored in a hidden input <input type="hidden" name="processRegistrationURL" value="register.php">
I have added id to each form and the submit button.
register.php
$getuser = $_POST['user'];
$getemail = $_POST['email'];
$getpass = $_POST['pass'];
$getconfirmpass = $_POST['confirmpass'];
if ($getuser) {
if ($getemail) {
if ($getpass){
if ($getconfirmpass) {
if ($getpass === $getconfirmpass) {
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
require ("connect.php");
$query = mysql_query("SELECT * FROM users WHERE username='$getuser'");
$numrows = mysql_num_rows($query);
if ($numrows == 0) {
$query = mysql_query("SELECT * FROM users WHERE email='$getemail'");
$numrows = mysql_num_rows($query);
if ($numrows == 0) {
$password = md5(md5("kjfiufj".$getpass."Fj56fj"));
$date = date("F d, Y");
$code = md5(rand());
mysql_query("INSERT INTO users VALUES (
'', '$getuser', '$password', '$getemail', '0', '$code', '$date'
)");
$query = mysql_query("SELECT * FROM users WHERE username='$getuser'");
$numrows = mysql_num_rows($query);
if ($numrows == 1) {
$site = "http://localhost/Projects/project";
$webmaster = "donotreply#askmanproducts.com";
$headers = "From: $webmaster";
$subject = "Activate Your Account";
$message = "Thanks For Registering. Click The Link Below To Activate Your Account.\n";
$message .= "$site/activate.php?user=$getuser&code=$code\n";
$message .= "You Must Activate Your Account To Login.";
if (mail($getemail, $subject, $message, $headers)) {
echo "You have been registered. You must activate your account from the activation link sent to <b>$getemail</b>";
$getuser = "";
$getemail = "";
}
else {
echo "2|An error has occurred. You activation email was not sent. Please refresh this page and try again. If this issue persists please contact administration.";
}
}
else {
echo "2|An error has occurred. Your account was not created. Please refresh this page and try again. If this issue persists please contact administration.";
}
}
else {
echo "1|There is already a user with that email.";
}
}
else {
echo "1|There is already a user with that username.";
}
mysql_close();
}
else {
echo "1|You must enter a valid email address to register.";
}
}
else {
echo "1|Your password do not match.";
}
}
else {
echo "1|You must confirm your password to register.";
}
}
else {
echo "1|You must enter your password to register.";
}
}
else {
echo "1|You must enter your email to register.";
}
}
else {
echo "1|You must enter your username to register.";
}
else {
echo "2|WHATEVER YOU WANT TO RENDER IN #showRegistrationResults";
}
When the button is clicked it fires the jQuery which in turn passes the form submission to register.php
You will notice in each echo there is a 1 or a 2 with a pipe. echo "1|You must enter your password to register.php"; The echo will return to the jQuery as data.
The jQuery then splits the data at the pipe (|). If result[0] == 1 the jQuery fires an alert leaving the form intact for corrections to be made. If result[0] == 2 the jQuery will replace the content of #showRegistrationResults which wraps the form (it will replace the form) with the data returned through the echo.
Review the echos on register.php. The first two replace the form as an error in processing has occurred. All other return an alert message.
You can toggle these as desired.
Improve your password security
You can improve your password security with the following code:
$hash_key = trim(file_get_contents('PATH-TO/key.dat'));
$password = hash_hmac('sha512', $getpass, $hash_key);
key.dat simply contains a key: for example: 72093OT7Yw6g0925T9Ly07G6y7WhI2v5
Hope this helps
Pete

registration page with php and mysql not working

Trying to create a registration page that adds new users to a database with php, i can't seem to get the information to add to the database, it is most likely something stupid that I have doing wrong or have missed out in my code.
Here is my code
<?php
session_start();
?>
<!DOCTYPE html>
<html class="no-js">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title></title>
<meta name="author" content="" />
<meta name="description" content="" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<script src="boilerplate/js/vendor/modernizr-2.7.1.min.js"></script>
<link rel="stylesheet" type="text/css" href="../css/party.css" media="screen" />
<script type="text/javascript" src="javascript/jquery_min.js"></script>
<script type="text/javascript" src="javascript/cookies.js"></script>
</head>
<body>
<?php include 'header.php'; ?>
<div id="container_register">
<div id="content_register">
<h2>Register</h2>
<?php
include "connect.php";
if (isset($_POST['formsubmitted'])) {
$error = array(); //Declare An Array to store any error message
if (empty($_POST['up_username'])) { //if no name has been supplied
$error[] = 'Please Enter a name '; //add to array "error"
} else {
$name = $_POST['up_username']; //else assign it a variable
}
if (empty($_POST['up_email'])) {
$error[] = 'Please Enter your Email ';
} else {
if (preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*#([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/",
$_POST['up_email'])) {
//regular expression for email validation
$Email = $_POST['up_email'];
} else {
$error[] = 'Your EMail Address is invalid ';
}
}
if (empty($_POST['up_password'])) {
$error[] = 'Please Enter Your Password ';
} else {
$Password = $_POST['up_password'];
}
if (empty($error)) //send to Database if there's no error '
{ // If everything's OK...
// Make sure the email address is available:
$query_verify_email = "SELECT * FROM users WHERE Email ='$Email'";
$result_verify_email = mysqli_query($dbc, $query_verify_email);
if (!$result_verify_email) { //if the Query Failed ,similar to if($result_verify_email==false)
echo ' Database Error Occured ';
}
if (mysqli_num_rows($result_verify_email) == 0) { // IF no previous user is using this email .
// Create a unique activation code:
$query_insert_user =
"INSERT INTO `users` ( `Username`, `Email`, `Password`) VALUES ( '$name', '$Email', '$Password')";
$result_insert_user = mysqli_query($dbc, $query_insert_user);
if (!$result_insert_user) {
echo 'Query Failed ';
}
echo '<div class="success">Thank you for
registering! </div>';
} else { // If it did not run OK.
echo '<div class="errormsgbox">You could not be registered due to a systemdiv>';
}
} else { // The email address is not available.
echo '<div class="errormsgbox" >That email address has already been registered.</div>';
}
} else { //If the "error" array contains error msg , display them
echo '<div class="errormsgbox"> <ol>';
foreach ($error as $key => $values) {
echo ' <li>' . $values . '</li>';
}
echo '</ol></div>';
}
mysqli_close($dbc); //Close the DB Connection
// End of the main Submit conditional.
?>
<form name="signup" id="signup" action="register.php" method="post">
<label for="up_username"><span class="required">*</span> Name</label>
<input type="text" name="up_username" id="up_username" placeholder="First Surname" />
<br>
<label for="up_email"><span class="required">*</span> Email</label>
<input type="email" name="up_email" id="up_email" placeholder="username#email.com" />
<br>
<label for="up_password"><span class="required">*</span> Password</label>
<input type="password" name="up_password" id="up_password" />
<br>
<label for="up_password_c"><span class="required">*</span> Confirm Password</label>
<input type="password" name="up_password_c" id="up_password_c" />
<div class="div_submit">
<input id="register_submit" type="submit" value="Sign up" />
</div>
</form><!--#sign up end-->
<p class="required">* Indicates a required field</p>
</div><!--content div end-->
</div><!--container div end-->
The If conditions you have written is always retrun false.
To Resolve this Please set the name attribute of submit button to formsubmitted like as follows
<input id="register_submit" name= "formsubmitted" type="submit" value="Sign up" />
Since the formsubmitted is not present inside the form the values is not set for $_POST['formsubmitted'], So the If part of your if statement is never executed.
Here is a similar script I often use, feel free to alter it at your discretion.
<?
if ($_POST['submit']){
$username = $_POST['username'];
$password = md5($_POST['password']);
$confirm = $_POST['confirm'];
$email = $_POST['email'];
if (!$username || !$password || !$confirm || !$email){
$response = "Please fill in all the boxes";
}else{
$check = mysql_num_rows(mysql_query("SELECT * FROM users WHERE username='$username'"));
if ($check != 0){
$response = "Username taken, Please choose an alternative";
}else{
$check = mysql_num_rows(mysql_query("SELECT * FROM users WHERE email='$email'"));
if ($check != 0){
$response = "This Email has already been registered";
}else{
mysql_query("INSERT INTO `users` (`id`, `username`, `password`, `email`) VALUES ('', '$username', '$password', '$email');");
$response = "Account Created";
}
}
}
}
echo "$response"; ?>

Can't Log in on Usercake

Im trying to integrate usercake onto my website. I installed it and registered an account. When i try to login with that account, the browser loads then nothing happens and i cant get into an account.
<?php
/*
UserCake
http://usercake.com
Developed by: Adam Davis
*/
require_once("models/config.php");
//Prevent the user visiting the logged in page if he/she is already logged in
if(isUserLoggedIn()) { header("Location: account.php"); die(); }
?>
<?php
/*
Below is a very simple example of how to process a login request.
Some simple validation (ideally more is needed).
*/
//Forms posted
if(!empty($_POST))
{
$errors = array();
$username = trim($_POST["username"]);
$password = trim($_POST["password"]);
//Perform some validation
//Feel free to edit / change as required
if($username == "")
{
$errors[] = lang("ACCOUNT_SPECIFY_USERNAME");
}
if($password == "")
{
$errors[] = lang("ACCOUNT_SPECIFY_PASSWORD");
}
//End data validation
if(count($errors) == 0)
{
//A security note here, never tell the user which credential was incorrect
if(!usernameExists($username))
{
$errors[] = lang("ACCOUNT_USER_OR_PASS_INVALID");
}
else
{
$userdetails = fetchUserDetails($username);
//See if the user's account is activation
if($userdetails["Active"]==0)
{
$errors[] = lang("ACCOUNT_INACTIVE");
}
else
{
//Hash the password and use the salt from the database to compare the password.
$entered_pass = generateHash($password,$userdetails["Password"]);
if($entered_pass != $userdetails["Password"])
{
//Again, we know the password is at fault here, but lets not give away the combination incase of someone bruteforcing
$errors[] = lang("ACCOUNT_USER_OR_PASS_INVALID");
}
else
{
//Passwords match! we're good to go'
//Construct a new logged in user object
//Transfer some db data to the session object
$loggedInUser = new loggedInUser();
$loggedInUser->email = $userdetails["Email"];
$loggedInUser->user_id = $userdetails["User_ID"];
$loggedInUser->hash_pw = $userdetails["Password"];
$loggedInUser->display_username = $userdetails["Username"];
$loggedInUser->clean_username = $userdetails["Username_Clean"];
//Update last sign in
$loggedInUser->updateLastSignIn();
$_SESSION["userCakeUser"] = $loggedInUser;
//Redirect to user account page
header("Location: account.php");
die();
}
}
}
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Login</title>
<link href="cakestyle.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="wrapper">
<div id="content">
<div id="left-nav">
<?php include("layout_inc/left-nav.php"); ?>
<div class="clear"></div>
</div>
<div id="main">
<h1>Login</h1>
<?php
if(!empty($_POST))
{
?>
<?php
if(count($errors) > 0)
{
?>
<div id="errors">
<?php errorBlock($errors); ?>
</div>
<?php
} }
?>
<div id="regbox">
<form name="newUser" action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
<p>
<label>Username:</label>
<input type="text" name="username" />
</p>
<p>
<label>Password:</label>
<input type="password" name="password" />
</p>
<p>
<label> </label>
<input type="submit" value="Login" class="submit" />
</p>
</form>
</div>
</div>
<div class="clear"></div>
</div>
</div>
</body>
</html>
Its ok. The problem was with my web host and their php sessions configuration.

Categories