Activating account using Email Verification - php

There was an error. Please contact Admin at Error #####admin.com
confirming your account via email ativation, Please contact #####admin.com
Been trying to setup account verification via Email address, The email gets sent to the users address successfully, but when the user clicks the link sent to their account, Above error occurs.
Link from the Email
href="' . base_url() . 'register/validate_email/' . $email . '/' . $email_code . '"
When you click the link from your email, it directs to the
Register Controller
public function validate_email($email_address, $email_code)
{
$email_code=trim($email_code);
$validated = $this->model_user->validate_email($email_address, $email_code);
if($validated == true)
{
$this->load->view('includes/header');
$this->load->view('registration/view_email_validated', array('s_email' => $email_address));
$this->load->view('includes/footer');
}
else{
echo 'Error confirming your account via email ativation, Please contact '. $this->config->item('admin_email');
}
}
Model_user
public function validate_email($email_address, $email_code)
{
$sql = "select student_id, s_email, s_name from qcs_student where s_email = '{ $email_address }' limit 1";
$result = $this->db->query($sql);
$row = $result->row();
if($result->num_rows() == 1 && $row->s_name)
{
if(md5((string)$row->student_id) == $email_code)
{
$result = $this->activate_account($email_address);
}
else
{
$result = false;
}
if($result = true)
{
return true;
}
else
{
echo 'Something is wrong, Please contact Administrator at '. $this->config->item('admin_email');
return false;
}
}
else
{
echo 'There was an error. Please contact Admin at '. $this->config->item('admin_email');
}
}

Update $sql as bellow: (remove {} guard for email_address):
$sql = "select student_id, s_email, s_name from qcs_student where s_email = '$email_address' limit 1";

Related

Forgotten password page help [PHP/HTML]

I have a CMS, I am creating a forgotten password page, the page will require a user to enter an email address and the code will find it in the database and send them an email, in my database, i have multiple users accounts assigned to one email address.
I want it so that if the user enters an email address and it was more than one account assigned to it, to error a message saying please contact your admin, but atm, it is not doing this. Any suggestions?
Here is my forgotten password page code:
if ($lookup) {
$user->sendPasswordResetEmail();
echo"sent email";
} elseif ($lookup) {
echo "please contact your admin";
}else{
$echo"Can't find user";
}
}
}else{
echo "please enter an email address";
}
}
I take the information from a different file, here is the snippet for the code where I take the database:
$resetsystem = $db->query($qry);
if ($resetsystem && $resetsystem->num_rows == 1) {
$that->setUserData($rs->fetch_assoc());
return true;
}
if ($resetsystem && $resetsystem->num_rows > 1) {
return;
}
return false;
}
update following code:
function lookupByEmail($userID) {
global $db;
$this->id = $userID; $qry = " SELECT user_id, user_first_name, user_last_name, user_username, user_email, user_suspended FROM cms_users WHERE user_email = " . $db->SQLString($this->id) . " AND user_deleted
= 0;";
$rs = $db->query($qry);
if ($rs && $rs->num_rows == 1) {
$this->setUserData($rs->fetch_assoc());
return 1;
}
if ($rs && $rs->num_rows > 1) {
return 2;
}
return 0;
}
and then where you are checking the $found variable do these updates
if ((int)$found == 1) {
$user->sendPasswordResetEmail();
$str_Message = '<div class="success_message">User found, an email has been dispatched to you.</div>';
} elseif ((int)$found > 1) {
$errors->defineError("too_many_users", "please contact your admin", array());
}else{
$errors->defineError("user_not_found", "The specified user could not be found. Please try again.", array());
}

Doesnot receive an error

I've an member system now I've made when somebody register an account, he need to activate it by his email. He will receive an valid link in his inbox So for example:
activate.php?email=ipoon2#outlook.com&email_code=b5b90ae21e31229878d681680db16bdf This link is valid so when I go to this link, he activates the account succesfully.
You see after ?email= ipoon2#outlook.com So when I change that into ipodn2#outlook.com and the email_code is still the same, he cannot activate his account. He needs to receive an error like We cannot find that email, and when he changes the email_code He will receive an error like this problem activate your account
Thats the problem what I've got When I change the email I don't receive any error. Neither for email_code
I've a file that is called activate.php which this code is including:
<?php
} else if (isset($_GET['email'], $_GET['email_code']) === true) {
$email = urldecode(trim($_GET['email']));
$email_code = trim($_GET['email_code']);
$user = new User();
if(User::email_exists($email) === false) {
echo 'We cannot find that email'; // return error doesn't show up
} else if (User::activate($email, $email_code) === false) {
echo 'problem activate your account'; // return error doesn't show up
}
}
?>
Also I've 2 functions made, there are in the class file User.php
public function email_exists($email) {
require './config.php';
$email = urldecode(trim($_GET['email']));
$sql_30 = $db->query("SELECT COUNT(id) FROM users WHERE email = '$email'");
if ($sql_30->fetch_object() === true) {
return true;
} else if ($sql_30->fetch_object() === false) {
return false;
}
}
public function activate($email, $email_code) {
require './config.php';
$email = urldecode($email);
$email_code = $db->real_escape_string($email_code);
$sql_33 = $db->query("SELECT COUNT(`id`) FROM `users` WHERE `email` = '$email' AND `email_code` = '$email_code' AND `group` = 0");
if ($sql_33->fetch_object()) {
$db->query("UPDATE `users` SET `group` = 1 WHERE `email` = '$email' AND `email_code` = '$email_code'");
return true;
} else {
return false;
}
}
To me, your email_exists() and activate() are wrong.
if ($sql_30->fetch_object() === true) {
return true;
} else if ($sql_30->fetch_object() === false) {
return false;
}
From the php documentation of mysqli_result::fetch_object :
Returns an object with string properties that corresponds to the fetched row or NULL if there are no more rows in resultset. So your test must be :
if ($sql_30->fetch_object() !== NULL) {
return true;
}
return false;
I guess it should solve your problem.

PHP/MySQL log in system -

I'm pretty new to both PHP and MySQL and I'm struggling to get my login system to function properly. The registration works fine, but when I run the login it doesn't recognise there is anything within the table matching the entered data. Below is the code I believe to be the problem area.
Thanks in advance.
<?php
function load($page = 'login.php')
{
$url = 'http://'.$_SERVER['HTTP_HOST'].
dirname($_SERVER['PHP_SELF']);
$url = rtrim($url,'/\/');
$url.= '/'.$page;
header("location:$url");
exit();
}
function validate($dbc,$email ='',$pwd='')
{
$errors = array();
if (empty($email))
{ $errors[] = 'Enter your email address.'; }
else
{ $e = mysqli_real_escape_string($dbc,trim($email));}
if (empty($pwd))
{ $errors[] = 'Enter your password.';}
else
{ $p = mysqli_real_escape_string($dbc, trim($pwd)); }
if (empty($errors))
{
$q = "SELECT adultID, FirstName, Surname "
. "FROM adult_information "
. "WHERE Email = '$e' AND Password = SHA1('$p')";
$r = mysqli_query($dbc, $q);
if (mysqli_num_rows($r) == 1)
{ $row = mysqli_fetch_array($r, MYSQLI_ASSOC);
return array( true, $row);}
else
{$errors[]='Email address and password not found.';}
}
return array(false,$errors);
}
I believe that you'll get what you're looking for if you change
$q = "SELECT adultID, FirstName, Surname "
. "FROM adult_information "
. "WHERE Email = '$e' AND Password = SHA1('$p')";
to
$p = SHA1($p);
$q = "SELECT adultID, FirstName, Surname "
. "FROM adult_information "
. "WHERE Email = '$e' AND Password = '$p'";
Whenever a PHP-to-MySQL query isn't performing as expected, my first step is to get a look at the SQL I'm actually passing to the database. In this case, it would be by inserting a line like echo '<p>$q</p>'; immediately after assigning the value of $q.
Sometimes it immediately becomes obvious that I've got a malformed query just by looking at it. If it doesn't, I copy the SQL code that appears and run it as a query within the database manager, to see what errors it throws and/or examine the resulting data.

Why am I getting Error: Query was empty?

I am creating a login part to my web page. When a new person registers their details, pressing the register button goes to a register_ok part, showing below:
case 'register_ok':
if (!$_POST['client_username'] || !$_POST['client_password'] ||
!$_POST['client_email']) {
die('You did not fill in a required field.');
}
// check if username exists in database.
if (!get_magic_quotes_gpc()) {
$_POST['client_username'] = addslashes($_POST['client_username']);
}
$qry = "SELECT client_username FROM client WHERE client_username = '".$_POST['client_username']."'";
$result = mysql_query($qry);
if($result) {
if(mysql_num_rows($result) > 0) {
die('Sorry, the username: <strong>'.$_POST['client_username'].'</strong>'
. ' is already taken, please pick another one.');
}
}
// check e-mail format
if (!preg_match("/.*#.*..*/", $_POST['client_email']) ||
preg_match("/(<|>)/", $_POST['client_email'])) {
die('Invalid e-mail address.');
}
// no HTML tags in username, website, location, password
$_POST['client_username'] = strip_tags($_POST['client_username']);
$_POST['client_password'] = strip_tags($_POST['client_password']);
// now we can add them to the database.
// encrypt password
$_POST['client_password'] = md5($_POST['client_password']);
if (!get_magic_quotes_gpc()) {
$_POST['client_password'] = addslashes($_POST['client_password']);
$_POST['client_email'] = addslashes($_POST['client_email']);
}
$insert = "INSERT INTO client (
client_username,
client_password,
client_name,
client_email,
client_last_access)
VALUES (
'".$_POST['client_username']."',
'".$_POST['client_password']."',
'".$_POST['client_name']."',
'".$_POST['client_email']."',
'now()'
)";
if(!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
}
else{
$id= mysql_insert_id();
session_start();
echo '<script>alert("You May Now Login");</script>';
echo '<meta http-equiv="Refresh" content="0;URL=pv.php">';
}
break;
}
When I register a new person, I get the following error:
Error: Query was empty
Why is this?
In the line if(!mysql_query($sql,$con)) {, do you mean $insert instead of $sql?
Do:
if(!mysql_query($sql,$con)) {
to
if(!mysql_query($insert,$con)) {
your variable name is not correct

having the hardest time passing NULL to my database

im working on a part of program where i need to send null to my database if the textbox is empty here is what i have so far
<?php
//so if not connected to database it displays an error message instead of a php error recommend having on 1 in development mode - for warnings and error
ini_set( "display_errors", 0);
if(!$_POST) exit;
$con = mysql_connect("localhost","imstillr","password");
mysql_select_db("imstillr_crm", $con);
$company = protect($_POST['company']); //required
$primarycontact = protect($_POST['primarycontact']); //required
$primaryemail = protect($_POST['primaryemail']); //required
$preferphone = protect($_POST['preferphone']); //required
$secondarycontact = protect($_POST['secondarycontact']);
$secondaryemail = protect($_POST['secondaryemail']);
$optionalphone = protect($_POST['optionalphone']);
$department = protect($_POST['department']);
$website = protect($_POST['website']); //required*/
//database info
mysql_query("SELECT companyname FROM customerinfo WHERE companyname='" .$company. "'");
if (!$con)
{
//checks if database connection string is correct
echo '<div class="error_message">Attention! no database connection.</div>';
exit();
} else if(mysql_affected_rows() == 1) {
echo '<div class="error_message">Attention! This company already exists.</div>';
exit();
} else if(trim($company) == '') {
echo '<div class="error_message">Attention! You must enter your company name.</div>';
exit();
} else if(trim($primarycontact) == '') {
echo '<div class="error_message">Attention! You must enter a contact name.</div>';
exit();
} else if(trim($primaryemail) == '') {
echo '<div class="error_message">Attention! Please enter a valid email address.</div>';
exit();
} else if(!isEmail($primaryemail)) {
echo '<div class="error_message">Attention! You have to enter an invalid e-mail address, try again.</div>';
exit();
} else if(trim($department) == '') {
echo '<div class="error_message">Attention! Please enter a department.</div>';
exit();
} else if(trim($preferphone) == '') {
echo '<div class="error_message">Attention! Please enter a preferred phone number.</div>';
exit();
} else if(!isPhone($preferphone)) {
echo '<div class="error_message">Attention! Please enter the right format for phone.</div>';
exit();
} else if(trim($website) == '') {
echo '<div class="error_message">Attention! Please enter a website name.</div>';
exit();
}
if($error == '') {
$secondarycontact = NULL;
$secondaryemail = 'random text';
$optionalphone = 'random text';
$address = "example#yahoo.com";
$clientaddress = $primaryemail;
//admin subject
$e_subject = $primarycontact .' has successfully been registered in the database';
//client subject
$c_subject = 'You have successfully been registered in the database';
/* another way of doing admin client email as array
$admin_email = array(
'e_body' => '$primarycontact has been registered in department '$department' \r\n\n',
'e_content' => 'You have been contacted by $name with regards to $subject, their additional message is as follows.\r\n\n';
'e_reply' => 'You can contact $primarycontact via email, $primaryemail';
);*/
//admin email
$e_body = "$primarycontact has been registered in department '$department' \r\n\n";
//$e_body = "You have been contacted by $name with regards to $subject, their additional message is as follows.\r\n\n";
$e_content = "Company Name: $company\n Primary Contact: $primarycontact\n Primary Email: $primaryemail\n Preferred Phone: $preferphone\n Secondary Contact: $secondarycontact\n Secondary Email: $secondaryemail\n Optional Phone: $optionalphone\n Department: $department\n Website: $website \r\n\n";
//$e_content = "\"anything can be displayed here such as all the customers entered info\"\r\n\n";
$e_reply = "You can contact $primarycontact via email, $primaryemail ";
//client email
$c_body = "You has been registered in department '$department' \r\n\n";
$c_content = "Company Name: $company\n Primary Contact: $primarycontact\n Primary Email: $primaryemail\n Preferred Phone: $preferphone\n Secondary Contact: $secondarycontact\n Secondary Email: $secondaryemail\n Optional Phone: $optionalphone\n Department: $department\n Website: $website \r\n\n";
$c_reply = "For anymore information feel free to contact the administrator vis email, $address";
//admin msg
$msg = $e_body . $e_content . $e_reply;
//client msg
$cmsg = $c_body . $c_content . $c_reply;
//inserts information
mysql_query("INSERT INTO `imstillr_crm`.`customerinfo` (`id`, `companyname`, `primarycontact`, `primaryemail`, `prefphone`, `secondarycontact`, `secondaryemail`, `optionalphone`, `department`, `website`) VALUES (NULL, '".$company."', '".$primarycontact."', '".$primaryemail."', '".$preferphone."', '".$secondarycontact."', '".$secondaryemail."', '".$optionalphone."', '".$department."', '".$website."')");
if(mail($address, $e_subject, $msg, "From: $primaryemail\r\nReply-To: $primaryemail\r\nReturn-Path: $primaryemail\r\n")) {
//if mail was sent to admin then send to person who signed up
mail($primaryemail, $c_subject, $cmsg, "From: $address\r\nReply-To: $address\r\nReturn-Path: $address\r\n");
// Email has sent successfully, echo a success page.
echo "<fieldset>";
echo "<div id='success_page'>";
echo $secondarycontact. '<br />';
echo $secondaryemail. '<br />';
echo $optionalphone. '<br />';
//echo "<h1>User $primarycontact Successfully added onto '$department'.</h1>";
echo "<p>Thank you <strong>$primarycontact</strong>, your registration info has been submitted to us.</p>";
echo "</div>";
echo "</fieldset>";
} else {
echo 'ERROR!';
}
}
//all functions go here
//protects database from SQL injection
function protect($value) {
if(get_magic_quotes_gpc()){
return mysql_real_escape_string(stripslashes($value));
}else{
return mysql_real_escape_string($value);
}
}
function isEmail($email) { // Email address verification, do not edit.
return(preg_match("/^[-_.[:alnum:]]+#((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i",$email));
}
function isPhone($number) {
return(preg_match("/^([\(]{1}[0-9]{3}[\)]{1}[ ]{1}[0-9]{3}[\-]{1}[0-9]{4})$/",$number));
}
?>
optionalphone,secondaryemail and secondarycontact are the only values that can be null
This will not work:
$foo = null;
mysql_query("INSERT INTO ... VALUES (".$foo.")");
This will:
mysql_query("INSERT INTO ... VALUES (NULL)");
So you might want to do it this way:
function quoted_string_or_null($var) {
return $var === null ? 'NULL' : "'".$var."'";
}
$foo = null;
mysql_query("INSERT INTO ... VALUES (".quoted_string_or_null($foo).")");
However, there is another problem: there is no way you will be getting real null values from your protect function or from $_POST. So you have to decide if an empty string is a legal value, or if empty strings should be converted to null. It's probably the latter, so you can make a small change and work with this:
function quoted_string_or_null($var) {
return ($var === null || $var === '') ? 'NULL' : "'".$var."'";
}
Rather than manually quoting the strings, use something to do this for you. See http://php.net/manual/en/function.mysql-real-escape-string.php
In the comments is a function written for your issue:
<?php
function db_escape($values, $quotes = true) {
if (is_array($values)) {
foreach ($values as $key => $value) {
$values[$key] = db_escape($value, $quotes);
}
}
else if ($values === null) {
$values = 'NULL';
}
else if (is_bool($values)) {
$values = $values ? 1 : 0;
}
else if (!is_numeric($values)) {
$values = mysql_real_escape_string($values);
if ($quotes) {
$values = '"' . $values . '"';
}
}
return $values;
}
?>
Once you have escaped each value, pass it without any extra quotes to the insert command.

Categories