custome login message for a user

Zenax

Active Member
Messages
1,377
Reaction score
4
Points
38
Hey guys,

Just getting back into PHP programming and thought I would start with the basics. I created a very basic login script, and when i say basic it is so basic, there is no encrpytion on the passwords. (something to learn next :D)

I want to add a custom message to display for each user after they have logged in

example if user123 logged in it would say "Welcome user123, your potatoes are here!" and if user456 logged in it would say "Welcome user 456, isn't windy outside!

or is it possible to have a message display for a single user and not everyone else?

I am using sessions and a very basic mySQL table for the user base.

Any help would be apperciated.

Regards,
Zenax
 

gomarc

Member
Messages
516
Reaction score
18
Points
18
I want to add a custom message to display for each user after they have logged in

Hi Zenax,

An easy way is to add a field to your DB-table (say custom_message) and retrieve this information in the same way you get the user_name.

Modify your SELECT query to include this ‘custom_message’.
 

denzil

New Member
Messages
134
Reaction score
3
Points
0
If you haven't come right yet after gomarc's advice, let us know (if you need more details).
 

Zenax

Active Member
Messages
1,377
Reaction score
4
Points
38
Hey,

I understand the advice the I have been given. I basically want to display a message to one user but not another. I have created a custom message column in the database, but how do I go about getting one value for one user and none for another.

Example: if user1 logs in it reads "Hello user1! The sun is lovely today" .... user2 logs in "Hello user2!"

would I have to create a new mysql table and start again? I can show you the code if you guys want? I followed it from a tutorial, just to get back into the feel of things, and re-jog my memory from some of the stuff that I have done before hand :D

regards,
zenax
 

gomarc

Member
Messages
516
Reaction score
18
Points
18
They are many ways of doing this.

Please show your SQL query code and how you get the user name value to display. (Please do not show passwords!)

I'm thinking you can simply concatenate the $user_name and $custom_message. If there is no $custom_message for that user, only the user name will display.
 

Zenax

Active Member
Messages
1,377
Reaction score
4
Points
38
Hey,

At the minute it is really basic :D I am in the process of writing version two, and have already started adding in injection protection as well as md5 hash password encryption.


Login Form:
PHP:
<?php
session_start();
?>
<html>
<head>
</head>

<body>
<?php
if(!session_is_registered("username")){?>
<form action="loginFunction.php" method="post">
<b style="font-size:150%;">Log in</b><br/>
Username: <input type="text" name="username"/><br/>
Password: <input type="password" name="password"/><br/>
<input type="submit" value="Log in"/>
</form>
Don`t have an account?
<form action="registrationFunction.php" method="post"><br/>
<b style="font-size:150%;">Register</b><br/>
Username: <input type="text" name="user"/><br/>
Password: <input type="password" name="pass"/><br/>
Retype password: <input type="password" name="pass1"/><br />
<input type="submit" value="Register" />
</form> 
<?php }
else{
   echo 'Welcome ' . $_SESSION["username"] . '<br/><a href="logout.php">Log out</a>';
   

}?>
</body>
</html>

loginFunction.php
PHP:
<?php
include('config.inc.php');
if(mysql_num_rows(mysql_query("SELECT * FROM users WHERE username='".$_POST["username"]."' and password='".$_POST["password"]."'"))==1){
   session_register("username");
   $_SESSION['username'] = $_POST['username'];
   header("location:login.php");
}
else {
   echo 'Wrong username or password!';
}
?>

registrationFunction.php
PHP:
<?php

	include('config.inc.php');
	
	// Check to see if the username has already been taken
	
	if(mysql_num_rows(mysql_query("SELECT * from users WHERE username='" . $_POST['user']. "'")) == 1) {
		
		echo "Sorry this username is not available. Please pick another username and try again";
	}
	
	// Checking to see if the two passwords enter match
	
	else if ($_POST['pass'] !== $_POST['pass1']) {
		echo "The two passwords entered do not match. Please go back and try again!";
	}
	
	// Checking the length of the username 
	
	else if (strlen($_POST['user']) > 15) {
		echo "The username you have chosen is too long!";
	}
	
	else if (strlen($_POST['user']) < 6) {
		echo "The username you have chosen is too short!";
	}
	
	// Checking the length of the password
	
	else if (strlen($_POST['pass']) >15) {
		echo "The password you have chosen is too long!";
	}
	
	else if (strlen($_POST['pass']) < 6) {
		echo "The password you have chosen is too short!";
		
	}
	
	// checking for invalid characters in the username and password
	
	else if(preg_match('/[^0-9A-Za-z]/',$_POST['user'])){
   		echo "Invalid characters in username!";
	}
	else if(preg_match('/[^0-9A-Za-z]/',$_POST['pass'])){
   		echo "Invalid characters in password!";
	}
	
		
	
	else{
	
	// Insert the data into the database
	
	mysql_query("INSERT into users VALUES ('".$_POST['user']."','".$_POST['pass']."')") or die(mysql_error());
	
	}
	

	// redirects to success page
	
	header('location:login.php');
	
?>

No passwords shown as they are stored in a database, and as you can see the connection info to the DB is written as a separate file :D

Regards, Zenax
 

gomarc

Member
Messages
516
Reaction score
18
Points
18
Hi there,

Before we continue, I would like to say that I hope you are developing this code on your computer using a local server to test, something like XAMPP or equivalent, because as you probably know, it's not a good idea to go live while still having security issues to sort out.

So assuming that only you have access to these files, let's make some minimum changes to get the custom message to display. After you get the satisfaction of getting this code to work, you can make the necessary adjustments/changes to make it safe.

In your login.php form

REPLACE:
PHP:
else{
   echo 'Welcome ' . $_SESSION["username"] . '<br/><a href="logout.php">Log out</a>';
   

}?>

WITH:
PHP:
else{
   $dump = 'Welcome ';
   $dump .= $_SESSION["username"] . '! ';
   $dump .= $_SESSION["salute"];
   $dump .= '<br/><a href="logout.php">Log out</a>';
   
   echo $dump;

}?>


Your loginFunction.php has changed the most.

PHP:
<?php
include('config.inc.php');

//A minimum protection against SQL injection 
$query = sprintf("SELECT * FROM users 
            WHERE username='%s' AND password='%s'",
            mysql_real_escape_string($_POST['username']),
            mysql_real_escape_string($_POST['password']));

$result = mysql_query($query);

if (mysql_num_rows($result)==1)
{
    $row = mysql_fetch_assoc($result);
    
    session_register("username");
    $_SESSION['username'] = $row['username'];
    
    session_register("salute");
    // 'message' is the field name of custom message in the table
    $_SESSION['salute'] = $row['message'];
    
    header("location:login.php");
}
else {
    echo 'Wrong username or password!';
}
?>


Notice that now we are getting the value of username out of the database table column/fieldname 'username' and not the POST:

Code:
$_SESSION['username'] = $row['username'];

And we do the same for the custom message. The name of the field where I store the message is 'message', but yours may be different of course.

Code:
$_SESSION['salute'] = $row['message'];

Your registrationFunction.php will also need to be revised.

Please consider using PDO to connect to your database, as it is much safer. Introduction to PHP PDO
 

Zenax

Active Member
Messages
1,377
Reaction score
4
Points
38
Sorry, for a late reply, and dragging up perhaps now an old thread ....

Can someone tell me whats wrong with this code?

PHP:
	mysql_query("INSERT into users (user, pass, email) VALUES ('$user, $passmd5, $email')");

It emits no errors, and takes me to the success page, but the table itself is not displaying any values?!?

Regards,
Zenax
 

gomarc

Member
Messages
516
Reaction score
18
Points
18
You are missing apostrophes wrapping the variables:

Code:
... VALUES ('$user[COLOR="red"]'[/COLOR], [COLOR="red"]'[/COLOR]$passmd5[COLOR="red"]'[/COLOR], [COLOR="red"]'[/COLOR]$email')
 

misson

Community Paragon
Community Support
Messages
2,572
Reaction score
72
Points
48
Sorry, for a late reply, and dragging up perhaps now an old thread ....
It's your thread, and less than two weeks between posts, so no worries.

Can someone tell me whats wrong with this code?
Other than it uses the outdated mysql extension? You may think that leaving out the quotes was a simple mistake (which it is) of little consequence, but consider how much time this one little thing cost you. Even if it didn't cost much time, little mistakes build up.

Steve McConnell echoes Socrates when he writes "[t]he people who are best at programming are the people who realize how small their brains are. [...] The more you learn to compensate for your small brain, the better a programmer you’ll be." (Jeff Atwood comments on this in "Why I'm The Best Programmer In The World*", where you can read a longer quote). They achieve this in part by picking tools and practices that make up for their inadequacies.

In this instance, PDO is the tool that can help you because you don't need to interpolate values into the SQL statement. By keeping values separate from the statement, there are no quotes to forget. There's also no escaping to forget, which wasn't a mistake made here, but could happen in other cases.

PHP:
<?php 
session_start();
include('config.inc.php'); 

$query = $db->prepare("SELECT username, message FROM users WHERE username=:username AND password=:password"); 
$query->execute(array('username' => $_POST['username'], 
                       'password' => $_POST['password']);

# Note rowCount isn't used so as to keep this code portable across DBs
if (($user = $query->fetch(PDO::FETCH_ASSOC)) !== False) {      
    $_SESSION['username'] = $user['username']; 
    // 'message' is the field name of custom message in the table 
    $_SESSION['salute'] = $user['message']; 
     
    header("Location: login.php"); 
} else { 
    echo 'Wrong username or password!'; 
} 
?>

Note also that SELECT * has been replaced.
 
Top