PHP Tutorial: Register and Login (Split)

Post here is you are having problems with any of the tutorials.
Post Reply
nerolight
Posts: 9
Joined: Sat Aug 24, 2013 12:08 am

PHP Tutorial: Register and Login (Split)

Post by nerolight »

<?php
//checks if the given username exists in the tale//
function user_exists($user){
	$user= mysql_real_escape_string($user);
	
	$total= mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `user_name` = '{$user}' ");
	return (mysql_result($total, 0) == '1') ? true : false; 
	}


// checks if the given user info is valid //
function valid_credentials($user,$email,$pass){
	$user= mysql_real_escape_string($user);
	$email= mysql_real_escape_string($email);
	$pass= sha1($pass);
	
	$total= mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `user_name` = '{$user}' AND `user_email` = '{$email}'AND `user_password` = '{$pass}'");
	
	return (mysql_result($total, 0) == '1') ? true : false; 
}





//adds a user to the database //
function add_user($user,$email,$pass){

	$user= mysql_real_escape_string(htmlentities($user));
	$email= mysql_real_escape_string($email);
	$pass= sha1($pass);
	
	mysql_query("INSERT INTO `users` (`user_name`, `user_email`,`user-password`) VALUES ('{$user}', '{$email}' ,'{$pass}')");
	}


?>

This is the code in my user.inc file. When I try to click submit, the screen just refreshes and nothing happens. I checked in my database and the inputs were not stored. Any idea what I'm doing wrong? thanks a lot!
User avatar
Temor
Posts: 1186
Joined: Thu May 05, 2011 8:04 pm

Re: PHP Tutorial: Register and Login (Split)

Post by Temor »

Hello, first of all, please always create a new thread for your problem instead of reviving an old one.
Secondly, I'd like to see more of your code. Post all of it.

Nothing seems to be wrong with any of the code you posted, so the error is somewhere else.
I would guess it's in the html page you have the form in.

Also, could you be more specific when detailing your problem? I'm not sure if your problem is adding a user or logging in.
nerolight
Posts: 9
Joined: Sat Aug 24, 2013 12:08 am

Re: PHP Tutorial: Register and Login (Split)

Post by nerolight »

This is my init.inc file:
<?php 
session_start();

$exceptions= array('index','contactus');

$page = explode('/', $_SERVER['SCRIPT_NAME']);
$page = end($page);
$page = substr($page, 0, -4);

if (in_array($page, $exceptions) === false){
	if (isset($_SESSION['username']) === false){
		header('Location: index.php');
		die(); }}
		
$host= "localhost";
$username= "****";
$password= "******";
$db= "******";

$connect= mysql_connect($host,$username,$password);
if ($connect){
	echo "Connection successful.";
	$select= mysql_select_db($db);
	if ($select){
		echo "<br /> Connected to ".$db;
	}else{
		echo "<br /> Unable to connect to".$db;}
}else{
	echo "Failed connection.";
}

$path= dirname(__FILE__);

include("{$path}/inc/user.inc.php");
?>
This is my form in my index html:
<!--Sign up-->
<table id="signup">
<thead></thead>
<tbody><div id="signup">
<form action="" method="POST">

<tr><td><input type="text" name"username" placeholder="Username"/></td></tr>

<tr><td><input type="text" name"email" placeholder="Email"/></td></tr>

<tr><td><input type="password" name="password" placeholder="Password"/></td></tr>

<tr><td><input type="password" name="confirmpassword" placeholder="Confirm password"/></td></tr>

<tr><td id="location">Campus: <select name="select" style="width:120px" id="select" >
<option value="sca" />Sca</option>
<option value="mis" />Mis</option>
<option value="st" />St</option></select></td></tr>

<tr><td id="privacy"><input type="checkbox" name="privacy"/>I agree to <a href="">Terms</a></td></tr>

<tr><td><center><input type="submit" name="submit" value="Sign up" /></center></td></tr>
</form></div></tbody></table>
This is my php code in my index html before the html:
<?php 
include('core/init.inc.php');
$errors= array();
if (isset($_POST['username'], $_POST['email'],$_POST['password'], $_POST['confirmpassword'])){
	if (empty($_POST['username'])){
		$errors[]= 'Please enter a username';
	}
	if (empty($_POST['email'])){
		$errors[]= 'Please enter an email address';
	}
	if (empty($_POST['password']) || empty($_POST['confirmpassword'])){
		$errors[]= 'Please enter a password';
	}
	if ($_POST['password'] !== $_POST['confirmpassword']){
		$errors[]= 'Password verification failed.';
	}
	if (user_exists($_POST['username'])){
		$errors[]= 'The username you have entered already exists';
	}
	if (empty($errors)){
		add_user($_POST['username'], $_POST['email'],$_POST['password']);
		
		$_SESSION['username'] = htmlentities($_POST['username']);
	
		header('Location: contactus.php');
		die();
	}
	}
?>
I apologize for the mistakes in my last post. I am trying to create a new user by entering inputs in my registration box on my index.html. I know for a fact that I am connected to the database but no inputs are being stored (I checked my database after clicking submit and no data was stored). When I click submit, the page refreshes and then nothing happens. Thank you for your help, I really appreciate it!
ExtremeGaming
Posts: 205
Joined: Mon Jul 09, 2012 11:13 pm

Re: PHP Tutorial: Register and Login (Split)

Post by ExtremeGaming »

Are you saying that your file is named index.html? Unless you have your server configured to parse PHP in an HTML file, you will need to rename index.html to index.php. If this is not the case, you are also not displaying any of the $errors that could occur.
<?php while(!$succeed = try()); ?>
nerolight
Posts: 9
Joined: Sat Aug 24, 2013 12:08 am

Re: PHP Tutorial: Register and Login (Split)

Post by nerolight »

oops no, I meant index.php. So I know its being parsed.

I changed the code a bit to look like this:
<?php
include"init.inc.php";

$user= $_POST['username'];
$email= $_POST['email'];
$pass= md5($_POST['password']);

//checks if the given username exists in the tale//
function user_exists($user){
	$user= mysql_real_escape_string($user);
	
	
	

	return (mysql_result(mysql_query("Select count(`user_id`) From `users` where `user_name`=
'$user'"),0)==1 )? $user_id : false;
	}


// checks if the given user info is valid //
function valid_credentials($user,$email,$pass){
	$user= mysql_real_escape_string($user);
	$email= mysql_real_escape_string($email);
	$pass= sha1($pass);
	
	$total= mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `user_name` = '{$user}' AND `user_email` = '{$email}'AND `user_password` = '{$pass}'");
	
	return (mysql_result($total, 0) == '1') ? true : false; 
}





//adds a user to the database //
function add_user($user,$email,$pass){

	$user= mysql_real_escape_string(htmlentities($user));
	$email= mysql_real_escape_string($email);
	$pass= sha1($pass);
	
	$insert='INSERT INTO users (user_name, user_email, user-password) VALUES("'.$user.'", "'.$email.'" ,"'.$pass.'")';
	mysql_query($insert);
	}
	
$errors= array();
if (isset($_POST['username'], $_POST['email'],$_POST['password'], $_POST['confirmpassword'])){
	if (empty($_POST['username'])){
		$errors[]= 'Please enter a username';
	}
	elseif (empty($_POST['email'])){
		$errors[]= 'Please enter an email address';
	}
	elseif (empty($_POST['password']) || empty($_POST['confirmpassword'])){
		$errors[]= 'Please enter a password';
	}
	elseif ($_POST['password'] !== $_POST['confirmpassword']){
		$errors[]= 'Password verification failed.';
	}
	elseif (user_exists($_POST['username'])){
		$errors[]= 'The username you have entered already exists';
	}
	if (empty($errors)){
		add_user($_POST['username'], $_POST['email'],$_POST['password']);
		
		$_SESSION['username'] = htmlentities($_POST['username']);
	
		header('Location: contactus.php');
		die();
	}
	
	
}



?>  


If I take out the everything and leave only the body of the function that adds the user, the inputs is stored in database. but as soon as I change it back to the above code, it stops working. I feel that maybe the if statements are not running the functions properly. any help would be great! thank you!
ScTech
Posts: 92
Joined: Sat Aug 24, 2013 8:40 pm

Re: PHP Tutorial: Register and Login (Split)

Post by ScTech »

You shouldn't mix functions into the page. In the long run it just makes things more cluttered and disorganized. I noticed that you are missing an "=" in between your name and their value on the username and email fields. Since you aren't displaying the error from the processing, this could be the reason. To see if any errors from your form are shown you can use:
<?php
if(empty($errors) === false) {
?>

<ul>

<?php
foreach($errors as $error) {
echo "<li>{$error}</li>";
}

?>

</ul>
<?php while(!$succeed = try()); ?>
User avatar
Temor
Posts: 1186
Joined: Thu May 05, 2011 8:04 pm

Re: PHP Tutorial: Register and Login (Split)

Post by Temor »

ScTech wrote:You shouldn't mix functions into the page. In the long run it just makes things more cluttered and disorganized. I noticed that you are missing an "=" in between your name and their value on the username and email fields. Since you aren't displaying the error from the processing, this could be the reason. To see if any errors from your form are shown you can use:
<?php
if(empty($errors) === false) {
?>

<ul>

<?php
foreach($errors as $error) {
echo "<li>{$error}</li>";
}

?>

</ul>
Good eye!
nerolight
Posts: 9
Joined: Sat Aug 24, 2013 12:08 am

Re: PHP Tutorial: Register and Login (Split)

Post by nerolight »

Thanks for the help so far guys, I really appreciate it. I fixed the name but still no use. If you notice in this code:
<?php
include"init.inc.php";

$user= $_POST['username'];
$email= $_POST['email'];
$pass= md5($_POST['password']);

//checks if the given username exists in the tale//
function user_exists($user){
	$user= mysql_real_escape_string($user);
	
	
	

	return (mysql_result(mysql_query("Select count(`user_id`) From `users` where `user_name`=
'$user'"),0)==1 )? $user_id : false;
	}


// checks if the given user info is valid //
function valid_credentials($user,$email,$pass){
	$user= mysql_real_escape_string($user);
	$email= mysql_real_escape_string($email);
	$pass= sha1($pass);
	
	$total= mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `user_name` = '{$user}' AND `user_email` = '{$email}'AND `user_password` = '{$pass}'");
	
	return (mysql_result($total, 0) == '1') ? true : false; 
}





//adds a user to the database //
function add_user($user,$email,$pass){

	$user= mysql_real_escape_string(htmlentities($user));
	$email= mysql_real_escape_string($email);
	$pass= sha1($pass);
	
	$insert='INSERT INTO users (user_name, user_email, user-password) VALUES("'.$user.'", "'.$email.'" ,"'.$pass.'")';
	mysql_query($insert);
	}
	
$errors= array();
if (isset($_POST['username'], $_POST['email'],$_POST['password'], $_POST['confirmpassword'])){
	if (empty($_POST['username'])){
		$errors[]= 'Please enter a username';
	}
	elseif (empty($_POST['email'])){
		$errors[]= 'Please enter an email address';
	}
	elseif (empty($_POST['password']) || empty($_POST['confirmpassword'])){
		$errors[]= 'Please enter a password';
	}
	elseif ($_POST['password'] !== $_POST['confirmpassword']){
		$errors[]= 'Password verification failed.';
	}
	elseif (user_exists($_POST['username'])){
		$errors[]= 'The username you have entered already exists';
	}
	if (empty($errors)){
		add_user($_POST['username'], $_POST['email'],$_POST['password']);
		
		$_SESSION['username'] = htmlentities($_POST['username']);
	
		header('Location: contactus.php');
		die();
	}
	
	
}



?>  
If the code doesn't encounter any errors I'm suppose to be redirected to contaact.php. Well, when I click sign up, I'm being redirected. So like I said, I think the functions are not running for some reason and I can't seem to figure out why...
User avatar
Temor
Posts: 1186
Joined: Thu May 05, 2011 8:04 pm

Re: PHP Tutorial: Register and Login (Split)

Post by Temor »

You forgot parentheses in your include.
include"init.inc.php";
include("init.inc.php");
I also don't see the reason you changed the query:
   $insert='INSERT INTO users (user_name, user_email, user-password) VALUES("'.$user.'", "'.$email.'" ,"'.$pass.'")';
        mysql_query($insert);
        }

Here's what you should do.

Restore the code as best you can to what it looks like in the tutorial. If the problem still exists, try adding
echo mysql_error();
under your queries and
error_reporting(E_ALL | E_STRICT);
to the top of your ini file.
nerolight
Posts: 9
Joined: Sat Aug 24, 2013 12:08 am

Re: PHP Tutorial: Register and Login (Split)

Post by nerolight »

I did what you suggested. Still no change. I'm being redirected to contact.php but the inputs are not being stored in the database. I'm gonna try and rewrite the functions, maybe that will work.
ScTech
Posts: 92
Joined: Sat Aug 24, 2013 8:40 pm

Re: PHP Tutorial: Register and Login (Split)

Post by ScTech »

In the add_user function query, is user-password actually supposed to be user_password?
<?php while(!$succeed = try()); ?>
nerolight
Posts: 9
Joined: Sat Aug 24, 2013 12:08 am

Re: PHP Tutorial: Register and Login (Split)

Post by nerolight »

ScTech wrote:In the add_user function query, is user-password actually supposed to be user_password?
user_password is the title for the password input in my database, so I suppose yes, it should be user_password?
ScTech
Posts: 92
Joined: Sat Aug 24, 2013 8:40 pm

Re: PHP Tutorial: Register and Login (Split)

Post by ScTech »

Yes. That is causing an SQL error which explains why your data is not inserting. Change it to user_password.
<?php while(!$succeed = try()); ?>
nerolight
Posts: 9
Joined: Sat Aug 24, 2013 12:08 am

Re: PHP Tutorial: Register and Login (Split)

Post by nerolight »

Finally got it to work! Thank you guys for all your help :) The functions were fine. It was the if statements. I re-wrote them, and here they are in case anyone else ever needs them:
<?php
include("core/init.inc.php");
$errors= array();

if (isset($_POST['username'], $_POST['email'], $_POST['password'], $_POST['confirmpassword'])){
	if (empty($_POST['username'])){
		$errors[]= 'Please enter a username';
	
	}else if(strlen($_POST['username']) > 12){
		$errors[]= "Your username is too long";
	}else if(user_exists($_POST['username']) === false){
		$errors[]="The username you have entered is already in use.";
	}

	if(empty($_POST['email'])){
		$errors[]= 'Please enter an email address';
	}
	
	if (empty($_POST['password']) || empty($_POST['confirmpassword'])){
		$errors[]= 'Please enter a password';
	}else if ($_POST['password'] !== $_POST['confirmpassword']){
		$errors[]= 'Password verification failed.';
	}
	
	if (empty($errors)){
		add_user($_POST['username'], $_POST['email'],$_POST['password'], $_POST['confirmpassword']);
		
		$_SESSION['username'] = htmlentities($_POST['username']);
	
		header('Location: homepage.php');
		exit();
	}
}
echo mysql_error();

?>  

Oh and while I'm here: I'm trying to set up a checkbox and a dropdown list. I have already created the forms for them:
<tr><td id="location">Cam: <select name="select" style="width:120px" id="select" >
<option value="sc" />Sc</option>
<option value="mi" />Mi</option>
<option value="st" />St</option></select></td></tr>
<tr><td id="privacy"><input type="checkbox" name="privacy"/>I agree to <a href=""> Terms</a></td></tr>
<tr><td><center><input type="submit" name="submit" value="Sign up" /></center></td></tr>

I'm just wondering, how would I set up their calls in the init file? (i.e. what would be the the code). And when adding them to the database, what 'type', 'action' and any other related options would I set. If anyone can give me an example or point me in the write direction, that would be great.Thank you for all your efforts!
User avatar
Temor
Posts: 1186
Joined: Thu May 05, 2011 8:04 pm

Re: PHP Tutorial: Register and Login (Split)

Post by Temor »

an option is just like any other form input, and is treated the exact same way as you would do with an "Input type=text".

What you need to do depends on what you're going to to with the options. If you're required to be in a certain state for your offer to apply, you would have to check if the option is equal to that state.
if($_POST['location'] == "sc"){
 Echo "state is South Carolina"; // ( I'm just guessing the state here so don't judge me if I'm wrong )
}
if you're just going to use the value and append it to a user, you'd do the same as you would with say the username.
$location = $_POST['location'];
$location = mysql_real_escape_string(htmlentities($location));
$sql = "INSERT INTO `users` (`location`) VALUES ('{$location}');
mysql_query($sql);


/Edit; I forgot the checkbox.
That one is easy too.
[syntax=php]if(isset($_POST['privacy'] && !empty($_POST['privacy']){

checkbox has been checked.

}
[/syntax]
nerolight
Posts: 9
Joined: Sat Aug 24, 2013 12:08 am

Re: PHP Tutorial: Register and Login (Split)

Post by nerolight »

Temor wrote:an option is just like any other form input, and is treated the exact same way as you would do with an "Input type=text".

What you need to do depends on what you're going to to with the options. If you're required to be in a certain state for your offer to apply, you would have to check if the option is equal to that state.
if($_POST['location'] == "sc"){
 Echo "state is South Carolina"; // ( I'm just guessing the state here so don't judge me if I'm wrong )
}
if you're just going to use the value and append it to a user, you'd do the same as you would with say the username.
$location = $_POST['location'];
$location = mysql_real_escape_string(htmlentities($location));
$sql = "INSERT INTO `users` (`location`) VALUES ('{$location}');
mysql_query($sql);


/Edit; I forgot the checkbox.
That one is easy too.
[syntax=php]if(isset($_POST['privacy'] && !empty($_POST['privacy']){

checkbox has been checked.

}
[/syntax]

Haha you guessed it right, they are states. That's great, thank you! Lastly, what are the options that I need to pick when inserting the columns for the checkbox and the selection into mysql database (e.g. Type, collation, attributes,etc.)? thank you once again!
User avatar
Temor
Posts: 1186
Joined: Thu May 05, 2011 8:04 pm

Re: PHP Tutorial: Register and Login (Split)

Post by Temor »

Well, varchar is enough usually.
If you're just going to insert a few letters, then varchar is enough.
If you're inserting numbers, then use int.

And that's all you need to set, apart from the max length. The rest is default.
nerolight
Posts: 9
Joined: Sat Aug 24, 2013 12:08 am

Re: PHP Tutorial: Register and Login (Split)

Post by nerolight »

Temor wrote:Well, varchar is enough usually.
If you're just going to insert a few letters, then varchar is enough.
If you're inserting numbers, then use int.

And that's all you need to set, apart from the max length. The rest is default.

Alright perfect, thank you!
Post Reply