registration via php - php

I've been reading alot of tutorials on how to and looking at samples regarding registration. I have my database config file, reg_form and register-exec files. When I try on a production server, I get file not found for register-exec.
Here's my reg_form:
<?php
session_start ();
?>
<html>
<head>
<title>Login Form</title>
</head>
<body>
<?php
if( isset($_SESSION['ERRMSG_ARR']) && is_array($_SESSION['ERRMSG_ARR']) && count ($_SESSION['ERRMSG_ARR']) >0 ){
echo '<ul class="err">';
foreach($_SESSION['ERRMSG_ARR'] as $msg) {
echo '<li>',$msg,'</li>';
}
echo '</ul>';
unset($_SESSION['ERRMSG_ARR']);
}
?>
</body>
<form id="loginForm" name="loginForm" method="post" action="register-exec.php">
<table width="300" border="0" align="center" cellpadding="2" cellspacing="0">
<tr>
<th>Full Name</th>
<td><input name="fname" type="text" class="textfield" id="fname" /></td>
</tr>
<tr>
<th>Email Address (Must be valid)</th>
<td><input name="email" type="text" class="email" id="email" /></td>
</tr>
<tr>
<th>Password (must not be longer than 6)</th>
<td><input name="password" type="password" class="textfield" id="password" /></td>
</tr>
<tr>
<th>Confirm Password</th>
<td><input name="copassword" type="password" class="textfield" id="copassword" />"</td>
</tr>
<tr>
<td> </td>
<td><input type="hidden" name="form_submitted" value="1" />"<input type="submit" name="submit" value="Register" />"</td>
</tr>
</table>
The following is the register-exec.php file, I'm not sure where I went wrong with it.
<?php
//Start session
session_start();
//Include database
require_once('db_conn.php');
//Array to store validation errors
$errmsg_arr = array();
//Validation error flag
$errflag = false;
//Create a random 6 digit cid for users
$new_cid = mt_rand(100000, 999999);
//Create random activation key
$act_key = mt_rand().mt_rand().mt_rand().mt_rand().mt_rand();
//Connect to mysql
$link = mysql_connect (DB_HOST, DB_USER, DB_PASSWORD);
if (!$link){
die('Failed to connect to server: ' . mysql_error());
}
//Select database
$db = mysql_select_db(DB_DATABASE);
if(!$db) {
die("Unable to select database");
}
//Sanitize the values
$fname = clean($_POST['fname']);
$email = clean($_POST['email']);
$password = clean($_POST['password']);
$copassword = clean($_POST['copassword']);
//Make sure they submitted the form
if($_POST['form_submitted'] == '1'){
//Make sure they inputted information
if($fname == '') {
$errmsg_arr[] = 'Full Name missing';
$errflag = true;
}
if($email == ''){
$errmsg_arr[] = 'Email missing';
$errflag = true;
}
if($password == ''){
$errmsg_arr[] = 'Missing password';
$errflag = true;
}
if($copassword == ''){
$errmsg_arr[] = 'Confirm password missing';
$errflag = true;
}
if( strcmp($password, $copassword) != 0 ){
$errmsg_arr[] = 'Passwords do not match';
$errflag = true;
}
$sql="INSERT INTO users (fname, email, password, act_key, cid) VALUES ('$fname', '$password', '$act_key', '$new_cid')";
if (!mysql_query($sql))
{
die('Error:' . mysql_error());
}
echo "An email has been sent to $_POST[email] with an activation key. Please check your mail to complete registration.";
//Send the first activation email
$to = $_POST['email'];
$subject = "VMATSIM Registration";
$message = "Welcome to VMATSIM. You or someone using your email address has completed registration at vmatsim.net. You can complete reigstration by clicking the following link:\rhttp://vmatsim.net/register-exec.php?$act_key\r\rIf this is an error, ignore this email and you will be removed from our system.\r\rRegards, VMATSIM Team";
$headers = 'From: noreply#vmatsim.net' . "\r\n" .
'Reply-To: noreply#vmatsim.net' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject,$message,$headers);
//User is activating
} else {
$queryString = $_SERVER['QUERY_STRING'];
$query = "SELECT * FROM users";
$result = mysql_query($query) or die (mysql_error());
while($row = mysql_fetch_array($result)){
if($queryString == $row["act_key"]){
echo "Congratulations" . $row["fname"] . " is now the proud owner of a VMATSIM account.";
$sql = "UPDATE users SET act_key = ''";
if(!mysql_query($sql))
{
die('Error:' . mysql_error());
}
}
}
}
?>
Any pointers would be very helpful.

Make sure your reg_form.php, db_conn.php and register-exec.php are in the same location or make sure to specify the path to them when calling/using them.

Try to test, if you can call the files manually to see if it is a permission issue. Simply type into your browser the full path to the file.
Depending on how you copied it, you might not enjoy the same permissions on your production server and thus PHP can't access the file. Try setting it with
chmod 777 filename.php
and then if it works, make sure you revert back to the amount of privileges you need.
If the files are sitting in a different locations give the absolute path:
require_once("/var/config/my_config_files.php");

Related

Fatal error: Call to a member function prepare() on string

wait please, dont post this as a duplicate because ive done research and tried everything but cant get it to work, i keep getting this error "Fatal error: Call to a member function prepare() on string in C:\wamp64\www\Etego\dbcontroller.php on line 63" i am trying to get people on my inscription form not to use the same email twice, thanks in advance! heres the code :
dbcontroller.php
<?php
class DBController {
public $host = "localhost";
public $user = "root";
public $password = "";
public $database = "members";
public $conn;
function __construct() {
$this->conn = $this->connectDB();
}
function connectDB() {
$conn = mysqli_connect($this->host,$this->user,$this->password,$this->database);
return $conn;
}
function runQuery($query) {
$result = mysqli_query($this->conn,$query);
while($row=mysqli_fetch_assoc($result)) {
$resultset[] = $row;
}
if(!empty($resultset))
return $resultset;
}
function numRows($query) {
$result = mysqli_query($this->conn,$query);
$rowcount = mysqli_num_rows($result);
return $rowcount;
}
function updateQuery($query) {
$result = mysqli_query($this->conn,$query);
if (!$result) {
die('Invalid query1: ' . mysqli_error($this->conn));
} else {
return $result;
}
}
function insertQuery($query) {
$result = mysqli_query($this->conn,$query);
if (!$result) {
die('Invalid query2: ' . mysqli_error($this->conn));
} else {
return $result;
}
}
function deleteQuery($query) {
$result = mysqli_query($this->conn,$query);
if (!$result) {
die('Invalid query3: ' . mysqli_error($this->conn));
} else {
return $result;
}
}
}
/* Email already exists */
/*line 63*/
$db = new DBController;
$db->database->prepare("SELECT * FROM members WHERE email = ?");
$reqemail->execute(array($email));
$emailexist = $reqemail->rowCount();
if($emailexist == 0) {
} else {
$error_message = "Email already exists";
}
//end of email existance
?>
index2.php
<!-- how to make members when login "keep me signed in" and ho to make users 13+ with the date input -->
<?php
if(!empty($_POST["register-user"])) {
/* Form Required Field Validation */
foreach($_POST as $key=>$value) {
if(empty($_POST[$key])) {
$error_message = "All Fields are required";
break;
}
}
/* Password Matching Validation */
if($_POST['password'] != $_POST['confirm_password']){
$error_message = 'Passwords should be same<br>';
}
/* Email Validation */
if(!isset($error_message)) {
if (!filter_var($_POST["userEmail"], FILTER_VALIDATE_EMAIL)) {
$error_message = "Invalid Email Address";
}
}
/* Validation to check if gender is selected */
if(!isset($error_message)) {
if(!isset($_POST["gender"])) {
$error_message = " All Fields are required";
}
}
/* Validation to check if Terms and Conditions are accepted */
if(!isset($error_message)) {
if(!isset($_POST["terms"])) {
$error_message = "Accept Terms and Conditions to Register";
}
}
if(!isset($error_message)) {
require_once("dbcontroller.php");
$db_handle = new DBController();
$query = "INSERT INTO members (username, firstname, lastname, password, email, gender, dob) VALUES
('" . $_POST["userName"] . "', '" . $_POST["firstName"] . "', '" . $_POST["lastName"] . "', '" . md5($_POST["password"]) . "', '" . $_POST["userEmail"] . "', '" . $_POST["gender"] . "' , '" . $_POST["dob"] . "' )";
$result = $db_handle->insertQuery($query);
if(!empty($result)) {
$error_message = "";
$success_message = "You have registered successfully!";
unset($_POST);
} else {
$error_message = "Problem in registration. Try Again!";
}
}
}
?>
<html>
<?php
include 'C:\wamp64\www\Etego\stylesignup.css';
?>
<head>
<title>https://Etego/signup.com</title>
</head>
<body>
<form name="frmRegistration" method="post" action="">
<table border="0" width="500" align="center" class="demo-table">
<?php if(!empty($success_message)) { ?>
<div class="success-message"><?php if(isset($success_message)) echo $success_message; ?></div>
<?php } ?>
<?php if(!empty($error_message)) { ?>
<div class="error-message"><?php if(isset($error_message)) echo $error_message; ?></div>
<?php } ?>
<tr>
<td>User Name</td>
<td><input type="text" class="demoInputBox allinsc" name="userName" value="<?php if(isset($_POST['userName'])) echo $_POST['userName']; ?>"></td>
</tr>
<tr>
<td>First Name</td>
<td><input type="text" class="demoInputBox allinsc" name="firstName" value="<?php if(isset($_POST['firstName'])) echo $_POST['firstName']; ?>"></td>
</tr>
<tr>
<td>Last Name</td>
<td><input type="text" class="demoInputBox allinsc" name="lastName" value="<?php if(isset($_POST['lastName'])) echo $_POST['lastName']; ?>"></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" class="demoInputBox allinsc" name="password" value=""></td>
</tr>
<tr>
<td>Confirm Password</td>
<td><input type="password" class="demoInputBox allinsc" name="confirm_password" value=""></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" class="demoInputBox allinsc" name="userEmail" value="<?php if(isset($_POST['userEmail'])) echo $_POST['userEmail']; ?>"></td>
</tr>
<tr>
<td>Date Of birth</td>
<td><input type="date" value="<?php print(date("YYYY-MM-DD"))?>" class="demoInputBox" name="dob" value="<?php if(isset($_POST['dob'])) echo $_POST['dob']; ?>"></td>
</tr>
<tr>
<td>Gender</td>
<td><input type="radio" name="gender" value="Male" <?php if(isset($_POST['gender']) && $_POST['gender']=="Male") { ?>checked<?php } ?>> Male
<input type="radio" name="gender" value="Female" <?php if(isset($_POST['gender']) && $_POST['gender']=="Female") { ?>checked<?php } ?>> Female
<input type="radio" name="gender" value="not specified" <?php if(isset($_POST['gender']) && $_POST['gender']=="not specified") { ?>checked<?php } ?>> not specified
</td>
</tr>
<tr>
<td colspan=2>
<input type="checkbox" name="terms"> I accept Terms and Conditions <input type="submit" name="register-user" value="Register" class="btnRegister"></td>
</tr>
</table>
</form>
<div class="header1"></div>
<div class="hdetail1"></div>
<h class="etegotxt1">Etego</h>
<img src="Etego_Logo.png" alt="Etego logo" width="50" height="50" class="logo1">
</body></html>
There are a number of issues here:
Where you are trying to prepare a statement you are using $db->database->prepare() and if you look at your class the propery database it is a String containing the string members i.e. public $database = "members"; Which explains the error that is being reported
You also appear to have got the mysqli_ API and the PDO API confused and are using some PDO API functions, that will never work they are totally different beasts.
So also change this
/* Email already exists */
/*line 63*/
$db = new DBController;
$db->database->prepare("SELECT * FROM members WHERE email = ?");
$reqemail->execute(array($email));
$emailexist = $reqemail->rowCount();
if($emailexist == 0) {
} else {
$error_message = "Email already exists";
}
To
/* Email already exists */
/*line 63*/
$db = new DBController;
$stmt = $db->conn->prepare("SELECT * FROM members WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
$result = $stmt->get_result();
if($result->num_rows > 0) {
$error_message = "Email already exists";
}
and you will be using the connection object to prepare the query and all mysqli_ API functions, methods and properties.
UPDATE: Still getting dup accounts created
Your dup account check is in the wrong place in my opinion and should be moved into the index2.php.
Or after this line add a test against $error_message because you are forgetting to test if the Dup email check produced an error.
if(!isset($error_message)) {
require_once("dbcontroller.php");
if ( !isset($error_message) ) {
My strong suggestion would be to do the Dup Email check in index2 and remove it from dbconnect.php as it does not really belong in dbconnect.php as that would be run unnecessarily everytime you want to connect to a database in any script!
The thing is your $database variable is a string that does not have prepare() function. Instead you might want to use the $conn variable that is holding a valid database connection.
To do that, change
$db->database->prepare("SELECT * FROM members WHERE email = ?");
to
$stmt = $db->conn->prepare("SELECT * FROM members WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
Here is the PHP official documentation.

How to Log browser and OS information from a failed log-in attempt

This is what I've got so far:
<?php
echo '<body style="background-color:red">';
$user = $_POST["username"];
$pass = $_POST["password"];
$validated = false;
//error handler
function customError($errno, $errstr)
{
echo "<b>Error:</b> [$errno] $errstr<br />";
echo "The error has been logged.";
error_log(date (DATE_RSS)." Error: [$errno]
$errstr".chr(13).chr(10),3, "invalidlogin.txt");
}
//set error handler
set_error_handler("customError",E_USER_WARNING);
session_start();
$_SESSION['Login'] = "";
if($user!="" && $pass!="")
{
$sql = "SELECT * FROM User WHERE LoginName = '$user' AND Password ='$pass'";
$conn = mysql_connect("localhost","UserName", "3PassWord") or die ("Sorry - unable to connect to MySQL database.");
$rs = mysql_select_db ("ALL14103673_BTEC",$conn) or die ("error");
$rs = mysql_query($sql,$conn);
$result = mysql_num_rows($rs);
if ($result > 0) $validated = true;
if($validated)
{
$_SESSION['Login'] = "OK";
$_SESSION['username'] = $user;
$_SESSION['password'] = $pass;
header('Location: protected.php');
}
else
{
$_SESSION['Login'] = "";
trigger_error("Invalid username or password\n", E_USER_WARNING);
echo "Invalid username or password.";
}
}
else $_SESSION['Login'] = "";
if ($result > 0) $validated = true;
if($validated)
{
$_SESSION['login'] = "OK";
$_SESSION['username'] = $user;
$_SESSION['password'] = $pass;
$ip = $_SERVER["REMOTE_ADDR"];
$date = date("d-m-Y H:i:s");
$file = 'Login.txt';
// Open the file to get existing content
$current = file_get_contents($file);
// Append a new person to the file
$current .= "$user logged in from IP Address of $ip on $date."."\r\n";
// Write the contents back to the file
file_put_contents($file, $current, $browser);
header('Location: protected.php');
}
?>
<html>
<body>
<h1 align="center">Login Page</h1>
<p align="center">Please enter your username and password:</p>
<form action="Login.php" method="post">
<table align="center">
<tr>
<td align="center">Username: </td>
<td align="center"><input size=\"20\"
type="text" size="20" maxlength="15"
name="username"></td>
</tr>
<tr>
<td
align="center">Password: </td>
<td align="center"><input size=\"20\"
type="password" size="20"
maxlength="15" name="password"></td>
</tr>
<tr>
<td colspan="2"
align="center"><input type="submit"
value="Login"></td>
</tr>
</table>
</form>
</body>
</html>
so far, I can log basic information about failed login attempts. Such as the name and password used and when it was. How do I log the browser information and OS used to the same place?
Ok, first of all, I hope you never ever are going to use this code on a actual web page. It seems like you are storing your passwords in plain text in a database, which is never a good idea and your code is vulnerable to SQL injection, please read this: http://php.net/manual/en/security.database.sql-injection.php
Now to answer your question, have a look at this topic, there's a pretty useful function in it that does exactly what you're searching for: Get operating system info with PHP

Sending a Welcome Email after submitting form

Here is my sign_up.php code, I want users to receive a welcome email immediately after hitting the submit button, I have searched so many forums but they are not giving me what i need.
The user successfully signs up, and the details are stored in the database, but i also want to add a welcome mail feature such that the details will me sent to the email immediately after submitting the form
<?php
//We check if the form has been sent
if(isset($_POST['username'], $_POST['password'], $_POST['passverif'], $_POST['email'], $_POST['avatar']) and $_POST['username']!='')
{
//We remove slashes depending on the configuration
if(get_magic_quotes_gpc())
{
$_POST['username'] = stripslashes($_POST['username']);
$_POST['password'] = stripslashes($_POST['password']);
$_POST['passverif'] = stripslashes($_POST['passverif']);
$_POST['email'] = stripslashes($_POST['email']);
$_POST['avatar'] = stripslashes($_POST['avatar']);
$_POST['mobile'] = stripslashes($_POST['mobile']);
}
//We check if the two passwords are identical
if($_POST['password']==$_POST['passverif'])
{
//We check if the password has 6 or more characters
if(strlen($_POST['password'])>=6)
{
//We check if the email form is valid
if(preg_match('#^(([a-z0-9!\#$%&\\\'*+/=?^_`{|}~-]+\.?)*[a-z0-9!\#$%&\\\'*+/=?^_`{|}~-]+)#(([a-z0-9-_]+\.?)*[a-z0-9-_]+)\.[a-z]{2,}$#i',$_POST['email']))
{
//We protect the variables
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$email = mysql_real_escape_string($_POST['email']);
$avatar = mysql_real_escape_string($_POST['avatar']);
$mobile = mysql_real_escape_string($_POST['mobile']);
//We check if there is no other user using the same username
$dn = mysql_num_rows(mysql_query('select id from users where username="'.$username.'"'));
if($dn==0)
{
//We count the number of users to give an ID to this one
$dn2 = mysql_num_rows(mysql_query('select id from users'));
$id = $dn2+1;
//We save the informations to the databse
if(mysql_query('insert into users(id, username, password, email, avatar, mobile, signup_date) values ('.$id.', "'.$username.'", "'.$password.'", "'.$email.'", "'.$avatar.'", "'.$mobile.'", "'.time().'")'))
{
//We dont display the form
$form = false;
//mail function
//mail end
?>
<div class="message">Your Registration was successful. Please login below<br />
Log in</div>
<?php
}
else
{
//Otherwise, we say that an error occured
$form = true;
$message = 'An error occurred while signing up.';
}
}
else
{
//Otherwise, we say the username is not available
$form = true;
$message = 'The username you want to use is not available, please choose another one.';
}
}
else
{
//Otherwise, we say the email is not valid
$form = true;
$message = 'The email you entered is not valid.';
}
}
else
{
//Otherwise, we say the password is too short
$form = true;
$message = 'Your password must contain at least 6 characters.';
}
}
else
{
//Otherwise, we say the passwords are not identical
$form = true;
$message = 'The passwords you entered are not identical.';
}
}
else
{
$form = true;
}
if($form)
{
//We display a message if necessary
if(isset($message))
{
echo '<div class="message">'.$message.'</div>';
}
//We display the form
?>
<div class="content">
<?php include('adverts.php'); ?>
<br />
<h1 style="color:#666;">New User Registration</h1>
<table class="message">
<form action="sign_up.php" method="post" class="message">
<tr>
<td>Username</td><td><input type="text" name="username" value="<?php if(isset($_POST['username'])){echo htmlentities($_POST['username'], ENT_QUOTES, 'UTF-8');} ?>" /></td>
</tr>
<tr>
<td>Password<span class="small">(6 characters min.)</span></td><td><input type="password" name="password" /></td>
</tr>
<tr>
<td>Password<span class="small">(verification)</span></td><td><input type="password" name="passverif" /></td>
</tr>
<tr>
<td>Email</td><td><input type="text" name="email" value="<?php if(isset($_POST['email'])){echo htmlentities($_POST['email'], ENT_QUOTES, 'UTF-8');} ?>" /> </td>
</tr>
<tr>
<td>Gender<span class="small">(optional)</span></td><td><input type="text" name="avatar" value="<?php if(isset($_POST['avatar'])){echo htmlentities($_POST['avatar'], ENT_QUOTES, 'UTF-8');} ?>" /></td>
</tr>
<tr><td>Mobille</td><td><input type="text" name="mobile" value="<?php if(isset($_POST['mobile'])){echo htmlentities($_POST['mobile'], ENT_QUOTES, 'UTF-8');} ?>" /></td></tr>
<tr>
<td></td>
<td><input type="submit" value="Sign up" /></td>
</tr>
</form>
</table>
</div>
<?php
}
?>
on successful form submission you need to write code for your mail functionality
<?php
if(isset($_POST['submit'])){
$to = $_POST['email'];
$subject = $_POST['name'];
$message = $_POST['message'];
$from = "test#testcom";
$headers = "From:" . $from;
if(mail($to,$subject,$message,$headers))
{
echo "Mail Sent.";
}
else
{
echo "Something went wrong";
}
}
?>
The function for sending mail is mail()
add this mail($email,'Subject','Message_body'); after if(mysql_query('insert into users...
http://www.w3schools.com/php/php_mail.asp
just use the mail function and send the mail as shown below
<?php
$result = mysql_query('insert into users(id, username, password, email, avatar, mobile, signup_date) values ('.$id.', "'.$username.'", "'.$password.'", "'.$email.'", "'.$avatar.'", "'.$mobile.'", "'.time().'")');
if($result){
//We dont display the form
$form = false;
//mail function
mail("mail_address#mail.com",'Subject','Message_body');
//mail end
?>
<div class="message">Your Registration was successful. Please login below<br />
Log in</div>
<?php
}
?>
Try it user and admin will get mail
<?php
//We check if the form has been sent
if(isset($_POST['username'], $_POST['password'], $_POST['passverif'], $_POST['email'], $_POST['avatar']) and $_POST['username']!='')
{
//We remove slashes depending on the configuration
if(get_magic_quotes_gpc())
{
$_POST['username'] = stripslashes($_POST['username']);
$_POST['password'] = stripslashes($_POST['password']);
$_POST['passverif'] = stripslashes($_POST['passverif']);
$_POST['email'] = stripslashes($_POST['email']);
$_POST['avatar'] = stripslashes($_POST['avatar']);
$_POST['mobile'] = stripslashes($_POST['mobile']);
}
//We check if the two passwords are identical
if($_POST['password']==$_POST['passverif'])
{
//We check if the password has 6 or more characters
if(strlen($_POST['password'])>=6)
{
//We check if the email form is valid
if(preg_match('#^(([a-z0-9!\#$%&\\\'*+/=?^_`{|}~-]+\.?)*[a-z0-9!\#$%&\\\'*+/=?^_`{|}~-]+)#(([a-z0-9-_]+\.?)*[a-z0-9-_]+)\.[a-z]{2,}$#i',$_POST['email']))
{
//We protect the variables
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$email = mysql_real_escape_string($_POST['email']);
$avatar = mysql_real_escape_string($_POST['avatar']);
$mobile = mysql_real_escape_string($_POST['mobile']);
//We check if there is no other user using the same username
$dn = mysql_num_rows(mysql_query('select id from users where username="'.$username.'"'));
if($dn==0)
{
//We count the number of users to give an ID to this one
$dn2 = mysql_num_rows(mysql_query('select id from users'));
$id = $dn2+1;
//We save the informations to the databse
if(mysql_query('insert into users(id, username, password, email, avatar, mobile, signup_date) values ('.$id.', "'.$username.'", "'.$password.'", "'.$email.'", "'.$avatar.'", "'.$mobile.'", "'.time().'")'))
{
//We dont display the form
$form = false;
//mail function
//mail end
$to = "$email";
$subject = "Welcome to";
$message = " Hi $username,<br /><br />
Thank you for signing up with us.<br />
Thanks <br />";
// Always set content-type when sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
// More headers
$headers .= 'From: <test#gmail.com>' . "\r\n";
$mail=mail($to,$subject,$message,$headers);
if($mail)
{
$to = "admin#gmail.com";
$subject = "Following Customer Signed Up";
$message = " $username,Customer is signed up with us,<br /><br />
Customer Details:<br />First Name:$firstname<br/>Last Name:$lastname<br/>Email:$email<br/>
Phone:$phone<br/>Zip Code:$zip<br/>
Thanks <br />";
// Always set content-type when sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
// More headers
$headers .= 'From: <'.$email.'>' . "\r\n";
$mail=mail($to,$subject,$message,$headers);
}
?>
<div class="message">Your Registration was successful. Please login below<br />
Log in</div>
<?php
}
else
{
//Otherwise, we say that an error occured
$form = true;
$message = 'An error occurred while signing up.';
}
}
else
{
//Otherwise, we say the username is not available
$form = true;
$message = 'The username you want to use is not available, please choose another one.';
}
}
else
{
//Otherwise, we say the email is not valid
$form = true;
$message = 'The email you entered is not valid.';
}
}
else
{
//Otherwise, we say the password is too short
$form = true;
$message = 'Your password must contain at least 6 characters.';
}
}
else
{
//Otherwise, we say the passwords are not identical
$form = true;
$message = 'The passwords you entered are not identical.';
}
}
else
{
$form = true;
}
if($form)
{
//We display a message if necessary
if(isset($message))
{
echo '<div class="message">'.$message.'</div>';
}
//We display the form
?>
<div class="content">
<?php include('adverts.php'); ?>
<br />
<h1 style="color:#666;">New User Registration</h1>
<table class="message">
<form action="sign_up.php" method="post" class="message">
<tr>
<td>Username</td><td><input type="text" name="username" value="<?php if(isset($_POST['username'])){echo htmlentities($_POST['username'], ENT_QUOTES, 'UTF-8');} ?>" /></td>
</tr>
<tr>
<td>Password<span class="small">(6 characters min.)</span></td><td><input type="password" name="password" /></td>
</tr>
<tr>
<td>Password<span class="small">(verification)</span></td><td><input type="password" name="passverif" /></td>
</tr>
<tr>
<td>Email</td><td><input type="text" name="email" value="<?php if(isset($_POST['email'])){echo htmlentities($_POST['email'], ENT_QUOTES, 'UTF-8');} ?>" /> </td>
</tr>
<tr>
<td>Gender<span class="small">(optional)</span></td><td><input type="text" name="avatar" value="<?php if(isset($_POST['avatar'])){echo htmlentities($_POST['avatar'], ENT_QUOTES, 'UTF-8');} ?>" /></td>
</tr>
<tr><td>Mobille</td><td><input type="text" name="mobile" value="<?php if(isset($_POST['mobile'])){echo htmlentities($_POST['mobile'], ENT_QUOTES, 'UTF-8');} ?>" /></td></tr>
<tr>
<td></td>
<td><input type="submit" value="Sign up" /></td>
</tr>
</form>
</table>
</div>
<?php
}
?>
Thank you all for your help.
I have successfully added a simple mail function with the help you all have contributed, here is what i did:
I added
mail($email,'Subject','Message_body');
after
if(mysql_query('insert into users(id, username, password, email, avatar, signup_date) values ('.$id.', "'.$username.'", "'.$password.'", "'.$email.'", "'.$avatar.'", "'.time().'")'))
{
//We dont display the form
$form = false;
just like this:
mail("$email",'Welcome To Naijabloom','Dear user, <br /> Welcome to Naijabloom.com, you will start receiving mails from us to keep you updated. Remember to be active in our forums and invite your friends here. Thanks. <br /> Naijanloom Team.', 'info#naijabloom.com');
and it worked for me, thanks

How to fix this PHP Forgotten Password Script?

So basically, I'm trying to make a simple, yet secure, forgotten password script.
There are two scripts, one that allows the user to enter their email address. This will then send them an email with a link that they must visit to save their new password.
The second script is where the link leads to. This script saves the new password.
For security purposes, I made a new table within my database called 'token'. It has three fields; token, email, used. Token is a random generated string of 10 letters and numbers, email is just that users email address, and used is an integer of either 1 or 0 indicating whether or not the token has been used.
You will be able to understand far more of my structure once you read over the two scripts. They are not to long, and not complex at all.
What is going wrong
Okay, so there is only one small thing going wrong, and this is within the reset-password.php script. This is where the users come to after they receive the email. Basically, I type in a new password, and click 'Reset Password', yet nothing happens. No errors or confirmations are shown, along with nothing changing within my database. I can't seem to debug this, and have been searching and trying for hours now. All help and suggestions would be greatly appreciated.
Please try to keep in mind that I am still a newbie at PHP and MySQL. Been working with PHP for approximately 8 weeks now, and MySQL for only 2.
forgot-password.php
<?php
//Forgotten password script
//Variable to save errors
$errors = array();
$email = $_POST['email'];
include 'config.php';
mysql_connect("$db_host", "$db_username", "$db_password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$query = "SELECT email FROM users WHERE email='" . $email . "'";
$result = mysql_query($query);
$num = mysql_num_rows($result);
if($num==0)
{
echo ("<div style='color:red;'>Email address is not registered</div>");
die();
}
$token = getRandomString(10);
$query = "INSERT INTO tokens (token,email) VALUES ('".$token."','".$email."')";
mysql_query($query);
//function to renerate the token
function getRandomString($length)
{
$validCharacters = "ABCDEFGHIJKLMNPQRSTUXYVWZ123456789";
$validCharNumber = strlen($validCharacters);
$result = "";
for ($i = 0; $i < $length; $i++)
{
$index = mt_rand(0, $validCharNumber - 1);
$result .= $validCharacters[$index];
}
return $result;
}
//Send the reset link to the user
function mailresetlink($to,$token)
{
$subject = "Password Reset";
$message = '
<html>
<head>
<title>Password Reset</title>
</head>
<body>
<p>Click on the given link to reset your password Reset Password</p>
</body>
</html>
';
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers .= 'From: Password Reset <noreply#domain.com>' . "\r\n";
if(mail($to,$subject,$message,$headers))
{
echo "We have sent the password reset link to your email at <strong>".$to."</strong>";
}
}
//If email is posted, send the email
if(isset($_POST['email']))
{
mailresetlink($email,$token);
}
?>
<table align="center" style="padding-bottom:40px;">
<form action="<?php $_SERVER['PHP_SELF']; ?>" method="post">
<tr>
<td>Email Address: </td>
<td><input type="text" name="email" /></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Reset My Password" /></td></tr>
<input type="hidden" name="register" value="TRUE" />
</form>
</table>
reset-password.php
<?php
//Reset password script
$token = $_GET['token'];
$email;
include 'config.php';
mysql_connect("$db_host", "$db_username", "$db_password") or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
if(!isset($_POST['newpassword']))
{
$query = "SELECT email FROM tokens WHERE token='" . $token . "' AND used = 0";
$result = mysql_query($query);
while($row = mysql_fetch_array($result))
{
$email = $row['email'];
}
if ($email != '')
{
$_SESSION['email'] = $email;
}
else
{
echo "Invalid link or Password already changed";
}
}
$pass = $_POST['newpassword'];
$email = $_SESSION['email'];
//Save new password
if(isset($_POST['newpassword']) && isset($_SESSION['email']))
{
$query = "UPDATE users SET password = SHA('$password') WHERE email='" . $email . "'";
$result = mysql_query($query);
if($result)
{
mysql_query("UPDATE tokens SET used=1 WHERE token='" . $token . "'");
}
echo "Your password has been changed successfully";
if(!$result)
{
echo "An error occurred. Please try the again or contact us at admin#domain.com";
}
}
?>
<table align="center" style="padding-bottom:40px;">
<form action="<?php $_SERVER['PHP_SELF']; ?>" method="post">
<tr>
<td>New Password:</td>
<td><input type="password" name="newpassword" id="password"/></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Change Password"></td></tr>
<input type="hidden" name="reset" value="TRUE" />
</form>
</table>
Please, if you need any more information or code, please do not hesitate to ask.
Thanks in advance!
I don't see anywhere where you are passing the token parameter to the server on the reset page after entering the new password parameter. You should have another hidden <input /> control, I would expect. $_SERVER['PHP_SELF'] does not return query string parameters. That is likely the cause of your current problem.
Specifically,
<table align="center" style="padding-bottom:40px;">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<tr>
<td>New Password:</td>
<td><input type="password" name="newpassword" id="password"/></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Change Password"></td></tr>
<input type="hidden" name="reset" value="TRUE" />
</form>
</table>
should be
<table align="center" style="padding-bottom:40px;">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<tr>
<td>New Password:</td>
<td><input type="password" name="newpassword" id="password"/></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Change Password"></td></tr>
<input type="hidden" name="reset" value="TRUE" />
<input type="hidden" name="token" value="<?php echo $_REQUEST['token']; ?>" />
</form>
</table>
Make sure you also change any $_GET['token']s to $_REQUEST['token'] as it will be GET the first time, then POST the second.
That being said, your much larger problem is the ability for me to bypass all your security by specifying ' or 1=1 or ' as my token. Or, I could be mean and do a nice '; update users set password = SHA('IKnowThisPassword') where username = 'admin'; --
Moral of the story being parameterized SQL (How can I prevent SQL injection in PHP?)

get PHP POST from dynamically loaded page

I have a page that gets updated dynamically using ajax, I have a form loaded dynamically and when the submit button is clicked it dynamically loads another page. How would I access my POST variables when doing this? I've tried the $_POST['variable'] with no luck.
ajaxloader.js
register-form.php
<?php
session_start();
if( isset($_SESSION['ERRMSG_ARR']) && is_array($_SESSION['ERRMSG_ARR']) && count($_SESSION['ERRMSG_ARR']) >0 ) {
echo '<ul class="err">';
foreach($_SESSION['ERRMSG_ARR'] as $msg) {
echo '<li>',$msg,'</li>';
}
echo '</ul>';
unset($_SESSION['ERRMSG_ARR']);
}
?>
<form id="loginForm" name="loginForm" method="post" action="javascript:ajaxpage('account/register-exec.php', 'content');">
<table width="300" border="0" align="center" cellpadding="2" cellspacing="0">
<tr>
<th>First Name </th>
<td><input name="firstName" type="text" class="textfield" id="firstName" /></td>
</tr>
<tr>
<th>Last Name </th>
<td><input name="lastName" type="text" class="textfield" id="lastName" /></td>
</tr>
<tr>
<th>Username</th>
<td><input name="username" type="text" class="textfield" id="username" /></td>
</tr>
<tr>
<th>Password</th>
<td><input name="password" type="password" class="textfield" id="password" /></td>
</tr>
<tr>
<th>Confirm Password </th>
<td><input name="cpassword" type="password" class="textfield" id="cpassword" /></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="Submit" value="Register" /></td>
</tr>
</table>
</form>
register-exec.php
<?php
//Start session
session_start();
//Include database connection details
require_once('config.php');
//Array to store validation errors
$errmsg_arr = array();
//Validation error flag
$errflag = false;
//Connect to mysql server
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) {
die('Failed to connect to server: ' . mysql_error());
}
//Select database
$db = mysql_select_db(DB_DATABASE);
if(!$db) {
die("Unable to select database");
}
//Function to sanitize values received from the form. Prevents SQL injection
function clean($str) {
$str = #trim($str);
if(get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
//Sanitize the POST values
$firstName = clean($_POST['firstName']);
$lastName = clean($_POST['lastName']);
$username = clean($_POST['username']);
$password = clean($_POST['password']);
$cpassword = clean($_POST['cpassword']);
//Input Validations
if($firstName == '') {
$errmsg_arr[] = 'First name missing';
$errflag = true;
}
if($lastName == '') {
$errmsg_arr[] = 'Last name missing';
$errflag = true;
}
if($username == '') {
$errmsg_arr[] = 'Username missing';
$errflag = true;
}
if($password == '') {
$errmsg_arr[] = 'Password missing';
$errflag = true;
}
if($cpassword == '') {
$errmsg_arr[] = 'Confirm password missing';
$errflag = true;
}
if( strcmp($password, $cpassword) != 0 ) {
$errmsg_arr[] = 'Passwords do not match';
$errflag = true;
}
//Check for duplicate username
if($username != '') {
$qry = "SELECT * FROM member WHERE username='$username'";
$result = mysql_query($qry);
if($result) {
if(mysql_num_rows($result) > 0) {
$errmsg_arr[] = 'Username already in use';
$errflag = true;
}
#mysql_free_result($result);
}
else {
die("Query failed");
}
}
//If there are input validations, redirect back to the registration form
if($errflag) {
$_SESSION['ERRMSG_ARR'] = $errmsg_arr;
session_write_close();
header("location: register-form.php");
exit();
}
//Create INSERT query
$qry = "INSERT INTO member(firstName, lastName, username, password) VALUES('$firstName','$lastName','$username','".md5($_POST['password'])."')";
$result = #mysql_query($qry);
//Check whether the query was successful or not
if($result) {
header("location: register-success.php");
exit();
}else {
die("Query failed");
}
?>
You can see my full form by clicking the "Join" button at tri-peoria.org and clicking on the 2nd link.
Your javascript is not sending any data and is using a GET request, not a POST. You will need to extract the data from your form into a variable to send. Replace the parameter names and elementIDs below with your form element IDs.
formData = buildData();
page_request.open('POST', url, true);
page_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
page_request.send(formData);
function buildData() {
//build a variable to store the form data, use encodeURI to encode any chars that require encoding
var postFormVars = "addressLine1=" + encodeURI( document.getElementById("addressLine1").value ) +
"&addressLine2=" + encodeURI( document.getElementById("addressLine2").value ) +
"&addressLine3=" + encodeURI( document.getElementById("addressLine3").value ) +
"&town=" + encodeURI( document.getElementById("town").value ) +
"&postcode=" + encodeURI( document.getElementById("postcode").value );
return postFormVars;
}
Your Javascript is sending a GET request and as per your statement you are checking $_POST
page_request.open('GET', url, true)
So update those to match then try again

Categories