There are many questions about email confirmation, databases, and permissions on Stackoverflow, but nothing I could find that would help me with this.
This specific question is directed to an email confirmation function built with PHP. The tutorial I am using can be found here: http://www.phpeasystep.com/phptu/24.html. Everything is working, however when the user clicks the email confirmation link (which would move their information from the temp_table to the confirmed_table), I receive this error:
Error updating database: No database selected
From what I have gathered from different sites/research/Stackoverflow questions is that this is due to the permissions of the database(s) I am working with (please correct me if it is another problem). I have read that I need to change all the users to be able to READ, but am unsure whether I should do this to both the databases as a whole (I couldn't find whether you can set the privileges for all the users in a database to automatically have the READ privileged), or the PHP when I add them to the temp_table. The tutorial I showed above doesn't say anything about it, so I am confused.
Registration form code:
<?php
session_start();
if(isset($_SESSION['aI']) || isset($_SESSION['pss'])) {
header("Location: pa.php");
}
include 'db.php';
if(isset($_POST['rSub'])) {
// connects to database using PHP Data Objects, throws exception if error in connection
try {
$conn = new PDO("mysql:host=$svrHost;db=$svrDb", $sUme, $sp);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo "ERROR: " . $e->getMessage();
}
$error = '';
if($_POST['fN'] == '' || $_POST['lN'] == '' || $_POST['aI'] == '' || $_POST['eml'] == '' || $_POST['pss'] == ''
|| $_POST['pss2'] == '') {
$error = "<li style=\"color:#C70000; font-weight:bold;\"><center>- All fields are required. Try again.</font><center></li>";
}
if($error == '') {
$fN = ucfirst($_POST['fN']);
$lN = ucfirst($_POST['lN']);
$aI = $_POST['aI'];
$eml = $_POST['eml'];
$pss = $_POST['pss'];
$pss2 = $_POST['pss2'];
$admin = 0;
if($error != '') {
$error = "<ul>".$error."</ul>";
$_SESSION['error'] = $error;
}
else {
$hF = "$2y$10$"; // 2y = blowfish and 10 = num of hashes
$sa = "testsaltforwebsite1219"; //"random" 22-character sa
$fAS = $hF.$sa;
$sha = crypt($pss, $fAS);
// Random confirmation code
$c_cd=md5(uniqid(rand()));
$insert = $conn->prepare("INSERT INTO t_awhole (c_cd, fN, lN, aI, eml, pss)
VALUES (:c_cd, :fN, :lN, :aI, :eml, :pss)");
$insert->bindParam(':c_cd', $c_cd);
$insert->bindParam(':fN', $fN);
$insert->bindParam(':lN', $lN);
$insert->bindParam(':aI', $aI);
$insert->bindParam(':eml', $eml);
$insert->bindParam(':pss', $sha);
$result=$insert->execute();
// ---------------- Confirmation email ---------------- \\
// table name
$t_apart=t_awhole;
if($result){
// send e-mail to ...
$to=$eml;
// Your subject
$subject="Registration Confirmation";
// From
$header="from: no-reply#example.com"; //Need the address to send the eml to.
// Your message
$message="Copy and paste this link in your browser to activate your account: \r\n";
$message.="\n";
$message.="(serverAddress)/confirmation.php?passkey=$c_cd \r\n";
$message.="\n";
$message.="Thank you";
// send eml
$sml = mail($to,$subject,$message,$header);
}
// if not found
else {
echo "Your email Is Not Registered. Please Register.";
}
// if your email succesfully sent
if($sml){
echo '<script> window.location.href="emlC.php"</script>';
}
else {
echo "Cannot Send Confirmation Link To Your email Address.";
}
// ---------------- Confirmation email ---------------- \\
$_SESSION['aI'] = $aI;
$_SESSION['pss'] = $pss;
$_SESSION['admin'] = 0;
$stmt = $conn->prepare("SELECT DISTINCT dN, dU, ex FROM doc WHERE aI != '0'");
$stmt->execute();
$result = $stmt->fetchAll();
foreach ($result as $row)
{
$ex = $row['ex'];
$dU = $row['dU'];
$dN = $row['dN'];
$insert = $conn->prepare("INSERT INTO doc (dN, dU, aI, ex)
VALUES (:dN, :dU, :aI, :ex)");
$insert->bindParam(':aI', $aI);
$insert->bindParam(':ex', $ex);
$insert->bindParam(':dU', $dU);
$insert->bindParam(':dN', $dN);
$insert->execute();
}
}
}
?>
Confirmation page code:
<?php
include('db.php');
// passkey that got from link
$pk=$_GET['pk'];
$t_awhole_conf="t_awhole";
// Retrieve data from table where row that match this passkey
$sql_conf1="SELECT * FROM $t_awhole_conf WHERE confirm_code ='$pk'";
$result_conf=mysql_query($sql_conf1) or die ('Error updating database: '.mysql_error());
// If successfully queried
if($result_conf){
// Count how many row has this passkey
$count=mysql_num_rows($result_conf);
// if found this passkey in our database, retrieve data from table "t_awhole"
if($count==1){
$rows=mysql_fetch_array($result_conf);
$fN = $rows['fN']; // capitalizes the first letter (6-26-14)
$lN = $rows['lN']; // capitalizes the first letter (6-26-14)
$aI = $rows['aI'];
$eml = $rows['eml'];
$pss = $rows['pss'];
$pss2 = $rows['pss2'];
$a_whole_conf="a_whole";
// Insert data that retrieves from "t_awhole" into table "a_whole"
$sql_conf2="INSERT INTO $a_whole_conf(fN, lN, aI, eml, pss, admin)
VALUES ($fN, $lN, $aI, $eml, $pss, $admin)";
$result_conf2=mysql_query($sql_conf2);
}
// if not found passkey, display message "Wrong Confirmation code"
else {
echo "Wrong Confirmation code";
}
// if successfully moved data from table"t_awhole" to table "a_whole" displays message "Your account has been activated" and don't forget to delete confirmation code from table "t_awhole"
if($result_conf2){
echo "Your account has been activated";
// Delete information of this user from table "t_awholeb" that has this passkey
$sql_conf3="DELETE FROM $t_awhole_conf WHERE confirm_code = '$pk'";
$result_conf3=mysql_query($sql_conf3);
}
}
?>
In your Registration form code, you have two lines that create the connection to the database (new PDO ...). You can further use $conn to execute statements.
In your Confirmation code, you don't create any connection before calling mysql_query (why the switch from PDO to mysql functions ?).
See the mysql_query documentation here.
Related
I'm new to PHP. I'm currently doing an email validation. My code is supposed to generate a random number, send to user via email and verify it when user enters.
Here is my code:
<?php
require 'PHPMailer/PHPMailerAutoload.php';
session_start();
// initializing variables
$email = $_SESSION ['email'];
$user_code = "";
$errors = array();
// generate a four digit random number
$gen_code = strval (rand (10000, 99999));
// send code to user email
// connect to the database
$db = mysqli_connect('localhost', 'root', '', 'register');
// REGISTER USER
if (isset($_POST['email_confirm'])) {
// receive all input values from the form
$user_code = mysqli_real_escape_string($db, $_POST['code']);
// check whether both codes match
if ($user_code != $gen_code) { array_push($errors, "The codes do not match"); }
else {
// set isConfirmed == true
if (count($errors) == 0) {
$query = "UPDATE user_database SET isConfirmed = true WHERE email = '$email'";
mysqli_query($db, $query);
$_SESSION['email'] = $email;
header('location: user_details.php');
}
}
}
?>
Here email_confirm is the name of my submit button and code is the name of text box.
It all works fine when page is first loaded. I get an email with a random integer.
Problem starts when I click my submit button. I receive another email with different number and the number I already entered is not equal to the one I received from email.
Please help
If this is a simpler and an experimental application, you should store gen_code in this session soon after its sent to the user confirmation email. Otherwise, store the code in db and retrieve it when your application receives email confirm POST request and compare the code that was sent by the user against the session or db wherever you'd stored it.
if (isset($_POST['email_confirm'])) {
// receive all input values from the form
$code = $_SESSION['gen_code']; // in case you would wish to store and retrieve code from db, replace this code with one which retrieved from db by email id... SELECT code from user where email=$email
$user_code = mysqli_real_escape_string($db, $_POST['code']);
// check whether both codes match
if ($user_code != $code) {
array_push($errors, "The codes do not match");
} else {
if (count($errors) == 0) {
$query = "UPDATE user_database SET isConfirmed = true WHERE email = '$email'";
mysqli_query($db, $query);
$_SESSION['email'] = $email;
header('location: user_details.php');
}
}
}
This file is the action file .When user submits wrong values , it heads back to the file named vform.php and asks user the correct input. But for me , after entering correct values and clicking on register , neither values are entering into wamp db, nor showing successful message. below is the code for adding values into db. after successful validation , it heads toregsuccess.php where it shows registration successful message. I don't know what exactly is the reason why values are not entering into db .
<?php
ob_start();
session_start();
include("DBConnection.php"); // include the connection object from the
DBConnection.php
if ($_POST['submit'])
{
$inFullname = trim($_POST["name"]);
$inEmail = trim($_POST["email"]);
$inPhone = trim($_POST["phonenumber"]);
$_SESSION['valid_name']=$inFullname;
$_SESSION['valid_email']=$inEmail;
$_SESSION['valid_phone']=$inPhone;
if( !preg_match("/^([a-zA-Z' ]+)$/",$inFullname) ||!preg_match('',$inEmail) || !preg_match('',$inPhone) ){
if(preg_match("/^[a-zA-Z-,]+(\s{0,1}[a-zA-Z-, ])*$/",$inFullname)){
$_SESSION['valid_name']=$inFullname;
}else {
$_SESSION['name_error'] = "enter valid name";
}
if(preg_match("/^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-
Za-z]{2,4})$/",$inEmail)){
$_SESSION['valid_email']=$inEmail;
} else{
$_SESSION['mail_error'] = "enter valid mail";
}
if(preg_match("/^\d{3}-\d{3}-\d{4}$/",$inPhone)){
$_SESSION['valid_phone']=$inPhone;
} else{
$_SESSION['phone_error'] = "enter valid phone number";
}
header('Location: vform.php');
die();
}
$stmt = $db->prepare("INSERT INTO DETAILS(NAME,EMAIL,PHONENUMBER) VALUES(?,?,?)"); //Fetching all the records with input credentials
$stmt->bind_param("sss", $inFullname,$inEmail,$inPhone); //Where s indicates string type. You can use i-integer, d-double
$stmt->execute();
$result = $stmt->affected_rows;
$stmt -> close();
$db -> close();
if($result > 0) {header("location: RegSuccess.php");} // user will be taken to the success page
else{ echo 'Oops. Something went wrong. Please try again Try Login';}
}
?>
The assignment I'm working on (an E-commerce course) asks that I use php to generate a new password for a user and send the user an email with the new password. I successfully generate the password, send the email from my school's server to myself (a gmail account), using php mail() however the php variable representing the password is always blank. I have been looking for answers to this on here and other websites but cannot find what I'm doing wrong.
I am looking to solve this particular issue and am not looking to use PHPMailer or some other alternative. Also I am not looking to discuss more secure ways to send email, or discuss encryption, just looking to discuss this particular issue and why it is or isn't working. Thank you in advance for any advice.
if ($mysqli->conect_errno) {
die("Error: Could not connect to database." . $mysqli->connect_error);
} else {
echo "<p>Connected<br></p>";
}
$email = $_POST['email_input'];
try {
$password = reset_password($email, $mysqli);
notify_password($email, $password, $mysqli);
echo 'Your password has changed and has been emailed to you.<br>';
}
catch(Exception $e) {
echo 'Your password could not be reset';
}
function reset_password($email, $mysqli){
$new_password = randomString(8, 12);
if ($new_password == false) {
throw new Exception('could not generate new password');
}
$rand_number = rand(0, 999);
$new_password .= $rand_number;
echo "NEW PASSWORD: " .$new_password."\r\n";
$query = "UPDATE registration
SET password = sha1('".$new_password."')
WHERE email = '".$email."'";
$result = $mysqli->query($query);
if($result) {
echo "<br>Password Reset<br>";
}else {
echo "An error has occured";
}
}
function randomString($min_length, $max_length){
return substr(str_shuffle("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), $min_length, $max_length);
}
function notify_password($email, $password, $mysqli){
$query = "SELECT email FROM registration WHERE email='".$email."'";
$result = $mysqli->query($query);
if(!$result){
throw new Exception('could not find email address');
}else if ($result->num_rows == 0) {
throw new Exception('Could not find email address:user not in database');
}else {
$row = $result->fetch_object();
$email = $row->email;
$from = "From support#HelpFinder \r\n";
$mesg = "Your password has been changed to ".$password."\r\n"."Please change it the next time you log in.\r\n";
if(mail($email, 'HelpFinder Login Information', $mesg, $from)) {
return true;
}else {
throw new Exception('Could not send email.');
}
}
}
the email message that arrives
example from text book I'm learning from
check if you are sending the $password variable as parameter correctly,
may be its empty
First please check that you have a double $result before the if declaration.
$result = $result = $mysqli->query($query);
After that you could try to make a var_dump to $password variable to check if it was correctly passed to the notify_password function. You could also post the $password variable definition so we could check in more depth.
I'm new to php form insertion and can't seem to find an answer to my specific issue. I'm able to send the name/email to a database, however I need to specify the input table in order to keep it more organized. With my current setup, I only know how to create new databases for each product giveaway, but I'm sure there is a better way than that.
Here is my current php code, please keep in mind I'm two weeks into php! If you could specify where I need to enter anything that would help a lot.
<?php
$errors = array(); // array to hold validation errors
$data = array(); // array to pass back data
// validate the variables ======================================================
// if any of these variables don't exist, add an error to our $errors array
if (empty($_POST['name']))
$errors['name'] = 'Name is required.';
if (empty($_POST['email']))
$errors['email'] = 'Email is required.';
// return a response ===========================================================
// if there are any errors in our errors array, return a success boolean of false
if ( ! empty($errors)) {
// if there are items in our errors array, return those errors
$data['success'] = false;
$data['errors'] = $errors;
} else {
// if there are no errors process our form, then return a message
// DO ALL YOUR FORM PROCESSING HERE
mysql_connect("localhost","username","password");//database connection
mysql_select_db("myusername_mytable");
/*
* This is the "official" OO way to do it,
* BUT $connect_error was broken until PHP 5.2.9 and 5.3.0.
*/
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
include_once $_SERVER['DOCUMENT_ROOT'] . '/securimage/securimage.php';
$securimage = new Securimage();
if ($securimage->check($_POST['captcha_code']) == false) {
// the code was incorrect
// you should handle the error so that the form processor doesn't continue
// or you can use the following code if there is no validation or you do not know how
echo "The security code entered was incorrect.<br /><br />";
echo "Please go <a href='javascript:history.go(-1)'>back</a> and try again.";
exit;
}
// Get values from form
$name = $_POST['name'];
$email = $_POST['email'];
//inserting data order
$order = "INSERT INTO user_info
(name, email)
VALUES
('$name','$email')";
//declare in the order variable
$result = mysql_query($order);
// THIS CAN BE WHATEVER YOU WANT TO DO (LOGIN, SAVE, UPDATE, WHATEVER)
// show a message of success and provide a true success variable
$data['success'] = true;
$data['message'] = 'Registration Complete!';
}
*********UPDATE***********
Turns out I was using deprecated language, so I switched to PDO. Thank you all for the help!
IF any other newbies were wondering with the previous form, I was missing an incredibly easy fix where it says $order = "INSERT INTO user_info which was the table name!
Firstly, you need to be using the MySQLi or PDO libraries, which are more secure than the now deprecated mysql_ library.
Assuming you want to store information on the giveaway and the entrants, you can create a single database with two tables, entrants and giveaways.
Give giveaways the structure of
id int primary key auto_increment
name varchar(100),
start_date datetime
end_date datetime
and entrants the structure of
id int primary key auto_increment
giveaway_id int //this is a foreign key linking the entrant to the relevant giveaway
email varchar(100),
name varchar(150)
With that in mind, let's have a look at your code:
//setting your arrays for later
$data = array();
$errors = array();
//checking your posted data values
if(empty($_POST['name'])) $errors['name'] = "Name is required.";
if(empty($_POST['email'])) $errors['email'] = "Email is required.";
//find out if we had any errors
if(!empty($errors)) {
//if we did, then we return them
$data['success'] = false;
$data['errors'] = $errors;
} else {
//and if we didn't, continue
$sql = new MySQLi(/*your host, username, password and database name here */);
if($sql->connect_error) {
//if we can't get a connection to the database, kill the script and print out a handy message
die("Connection error: ".$sql->connect_error." ".$sql->connect_errorno);
}
}
//get your securimage script
include_once($_SERVER['DOCUMENT_ROOT'].'/securimage/securimage.php');
if ($securimage->check($_POST['captcha_code']) == false) {
//do some error handling for the captcha checking
echo "The security code entered was incorrect.<br /><br />";
echo "Please go <a href='javascript:history.go(-1)'>back</a> and try again.";
exit;
}
//did all that work? Awesome, let's continue
//ALWAYS escape your form data. It's not a sure win against SQL injection but it's the best place to start
$email = $sql->real_escape_string($_POST['email']);
$name = $sql->real_escape_string($_POST['name']);
//assuming that there can only be one giveaway running at any one time...
//get the id of the active giveaway, where it's end date is more than the current time
$query = "SELECT id FROM giveaways WHERE end_date > NOW()";
//query the database or kill the script and print an error (further down the line, don't print the error for security reasons
$result = $sql->query($query) or die($sql->error);
if($result->num_rows > 0) {
//if there's an active giveaway, fetch that result
$row = mysqli_fetch_assoc($result);
//and set a variable to the id we want
$id = $row['id'];
//insert into your entrants the now linked entrant details and giveaway key
$query = "INSERT INTO entrants (giveaway_id, name, email) VALUES ('$id', '$name', '$email')";
//again, query or error handling
$result = $sql->query($query) or die($sql->error);
//if that query worked, do your success message, if it didn't tell the entrant that something went wrong
if($result) {
$data['success'] = true;
$data['message'] = "Registration complete!";
} else {
$data['success'] = false;
$data['message'] = "There was an error registering you, please try again soon.";
}
}
Now, when you need to return all entrants to a specific giveaway you simply do:
SELECT name, email FROM entrants WHERE giveaway_id = //the id of the giveaway
If you change the structure of your table, you can save the giveaway name.
SQL
ALTER TABLE user_info ADD COLUMN giveaway VARCHAR(64) NOT NULL;
PHP
$giveaway = $_POST['giveaway'];
$order = "INSERT INTO user_info
(name, email, giveaway)
VALUES
('$name','$email','$giveaway')";
I'd recommend using bound parameters in your query and sanitizing your data input from $_POST, too. Check out PDO.
Hi I'm calling out for help from all the PHP Gods on Stackoverflow :)
I've created an email signup form (just 1 field for email), that is able to validate with Ajax and post a new email to the database from a basic PHP script I found.
However the next step I have to do is check if an email is already in the database before adding it. There are several questions exactly like this on Stack and I've tried all the answers however to no avail :( I'm not a PHP guy and haven't been able to hack it right yet.
Below is my current insert.php file which does work and does add a new email field into the database. However the code below that is the latest I've tried to use to check for an already existing email, but I get a send data error.
Working PHP file to add email
<?php
$con = mysql_connect("localhost","root","root");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("mydatabase", $con);
$sql="INSERT INTO newsletter (email)
VALUES
('$_POST[mail]')";
if (!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
}
echo "Thanks for subscribing!"; //Text on page
//header("Location: /thankyoupage.php"); //Redirect page
mysql_close($con)
?>
UPDATED CODE using PDO
Code below works to add emails, however still allows duplicates...
<?php
/*** mysql hostname ***/
$hostname = 'localhost';
/*** mysql username ***/
$username = 'root';
/*** mysql password ***/
$password = 'root';
/*** email ***/
$email = '$_POST[mail]';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=mydatabase", $username, $password);
//$query = SELECT count(*) AS `total` FROM `data` WHERE `email` = '{$request}'
$query = SELECT COUNT(*) as 'count' FROM `data` WHERE email = '$_POST[mail]';
$row = mysql_fetch_assoc(mysql_query($query));
if($row['total']) {
echo 'Sorry email already exists';
}
else {
/*** echo a message saying we have connected & added email ***/
echo 'Thanks for subscribing!';
/*** INSERT data ***/
$count = $dbh->exec("INSERT INTO newsletter(email) VALUES ('$_POST[mail]')");
}
/*** echo a message saying we have connected & added email ***/
//echo 'Thanks for subscribing!';
/*** INSERT data ***/
//$count = $dbh->exec("INSERT INTO newsletter(email) VALUES ('$_POST[mail]')");
/*** echo the number of affected rows ***/
/*echo $count;*/
/*** close the database connection ***/
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
Thanks in advance for anyone with the time to take a look at this :)
Extra Notes:
My database table is called newsletter and there are 2 fields (id - numbers only) & (email)
if email is an unique key, that would be simple
<?php
mysql_connect("localhost","root","root");
mysql_select_db("howdini");
$email = mysql_real_escape_string($_POST['mail']);
$sql="INSERT IGNORE INTO newsletter (email) VALUES ('$email')";
mysql_query($sql) or trigger_error(mysql_error()." ".$sql);
if (mysql_affected_rows()) {
header("Location: /thankyoupage.php"); //Redirect page
} else {
//already exists
}