Jump to content
  • Announcements

    • boen_robot

      Guidelines and Netiquette   03/28/2017

      Posting Problems:   Having problems posting your topic? Read through this: To join, you agree to our terms and conditions and fill out and submit a registration form. An activation email will be sent to your email adress, so you'll need to verify your account. After that the account has to be validated by one of the moderators. This will mean that it can take up to a day to be activated. A couple of things to remember to ensure approval: Don't use an email address in one of those $2 four character .com domains eg. xyds.com. These will be deleted and the domain added to the banned list. Don't use an email address that is within a domain with a bad reputation for spam. A Google search is run on every email address and email domain. Don't sign up with an email address that doesn't exist, doesn't work or requires the sender to answer a quiz before their email can get to you. Put your country and or state and city in the signup form. Blank forms will go to the botton of the "to do" list. And make sure that your email address and your country match, saying you're from Alabama and using a .ru email address is not going to get you activated. After a membership is activated the first few posts will be monitored. Posting spam or unapproved topics described in the agreement results in an immediate ban. The email provider and the IP addresses associated with the account will be banned and all posts will be deleted. These strict measures have been deemed necessary to hinder spam. Sorry for any inconvenience this causes, but it's not liable to change. If, after reading this, you still can't post and don't understand why, contact one of the Moderators listed here.   Topic Guidelines   Including the following information can expedite an accurate response from board members: Must be a Specific Problem or Question related to web design and development Include Code in Question (wrap with   for small blocks of code and for longer blocks   ) Include Code Author Include Extra Notes/Modifications/Attempts Include web link to page/file when possible Content Guidelines   You may not post, upload, link to, or email any Content that contains, promotes, gives instruction about, or provides prohibited Content. Prohibited Content includes any Content that breaks any local, state, county, national or international law. Prohibited Content also includes: No direct or indirect advertising or websites, forums, products, services No hijacking of posts (do not post your question in someone elses) Content that infringes upon any rights [ex. MP3s and ROMs] (including, but not limited to, copyrights and trademarks) Abusive, threatening, defamatory, racist, or obscene Viruses or any other harmful computer software False Information or libel Spam, chain letters, or Pyramid schemes Gambling or Illicit drugs Terrorism Hacking or cheating for internet/online games Warez, Roms, CD-Keys, Cracks, Passwords, or Serial Numbers Pornography, nudity, or sexual material of any kind Excessive profanity Invasive of privacy or impersonation of any person/entity Hacking materials or information Posting Tips   There are more BBcodes than there are buttons for on the reply menu. To get the full list, click "BB Code Help" underneath the clickable smilie face menu. Use   for small snippets of code Use   for lengthy snippets of code Use   if your snippet is HTML (optional) Use   if your snippet is SQL (optional) Rules of Conduct   Be nice. There's no need for calling someone stupid if they ask an 'easy' question. Keep your avatars and signatures absolutely child friendly. We have a younger audience on this forum. Keep your language appropriate for the same reason above. Do not PM moderators for help on the forum. Post on the topic, or create a new one.   Spam:   Recently, as you have all without doubt noticed, we have had lots of spam and advertisement on the forum. Therefore, we'd like to alert you as to what to do when you have found any of the aforementioned annoying messages: it. Immediately. Give a clear reason, please, if the advertising is not evident. DO NOT POST! Report, let the post stay as is, and we will get to it, meanwhile if you continue to post as normal in the other threads, it won't be on the top so long. Refrain from PMing the member. This won't help at all, as they are most likely spambots anyway. Thank you.       Images in signatures:   After thinking of users on dial-up, we have decided to enforce the following rules regarding signatures. Please pay heed to them. Respecting these rules is respecting the members on this forum with dial-up. Signature rules: No animated images AT ALL. No matter the amount of animation. Maximum image widthxheight: 300x150 Maximum image (file) size: 15kb Use calm colors. Do not use highly contrasting images in your signature, as this can get really annoying when seeing several posts from one member in the same thread. The same prohibited content goes for images as for posts. Lastly, use common sense. No lengthy signatures please. Save us some scrolling. Thank you.       Links in signatures:   Please understand that w3schools.com only exists because of voluntary work and is barely supported by the advertising littered throughout the tutorials and the forum. So, please, stop advertising other sites. DO not post links that drive traffic away from the w3schools domain - especially to a site that offers similar if not identical information. Please help support the site by keeping individuals on it. Thank you. Here are some guidelines as to what you can put in your signature: w3schools links --> allowed w3.org links --> allowed browser links --> allowed html editor links --> allowed personal sites --> allowed tutorial sites competing with w3schools --> NOT allowed sites completely irrelevant to webprogramming and this forum --> NOT allowed   Thanks for understanding, and for taking the time to read this. ~W3Schools Modstaff~
Sign in to follow this  
Laurent*

user login verification + condition

Recommended Posts

Hello, I'm trying to create a user login page by going through a SQL database and finding if a user exist in the users table. After that I need to decide what page to send the user to either the admin page or the student page. I tried looking through w3 but this was the closes example I found. 

https://www.w3schools.com/php/php_mysql_select.asp

What's been done so far

  • Login page HTLM 
  • Connection test to the data base success
  • Data Base created
  • Users table created
  • 1 admin and 1 student have been populated in the users table

Share this post


Link to post
Share on other sites

If you have a username, or whatever your identifier is, then you would use a select query to get the record that has that username, and then check the other fields like password, admin, etc.  If it doesn't return a record at all then the username doesn't exist.

Share this post


Link to post
Share on other sites

How is this? It not stupid code right?

 

<?php
			$servername = "...";
			$username = "...";
			$password = "...";
			$database = "...";

			//Testing search terms
			$testUsername = "G. mane";
			$testPassword = "wrap";
			$testTable = "users";
			
			// Create connection
			$conn = new mysqli($servername, $username, $password, $database);

			// Check connection
			if ($conn->connect_error) {
				die("Connection failed: " . $conn->connect_error);
			} 

			$query = "	SELECT username, password 
						FROM $testTable 
						WHERE username = '$testUsername' AND password = '$testPassword'";
			$result = $conn->query($query);

			if ($result->num_rows > 0) {
				
				//FOUND YOU!
				echo "I Found a user";
			} 
			else 
			{
				echo "User name and password did not match or does not exist";
			}
			
			// Perform queries 
			//mysqli_query($conn,"SELECT * FROM users WHERE");
			//mysqli_query($con,"INSERT INTO Persons (FirstName,LastName,Age) 
			//VALUES ('Glenn','Quagmire',33)");

			mysqli_close($conn);
		?>

 

Edited by Ingolme
Removed database information

Share this post


Link to post
Share on other sites

The first thing you should do is try the code yourself to see if it works. I don't see any obvious errors, so I would guess that it does work, but is unsafe on a few levels.

  1. I've removed the database information from your post to keep your accounts safe from people reading the forum.
  2. Your SQL query is open to SQL injection. Read about prepared statements to keep your database safe from hackers.nencrypted
  3. The passwords are openly visible in the database. It is unsafe for the people signing up to your site because you, and anybody with access to your database, know their passwords and you can use that to hack their accounts on other websites since many people use the same password in multiple places.

To solve the password issue, you hash the passwords before storing them into your database using password_hash(). When searching for a user, you have to search by username first, pull out a hashed password and compare it to the data that was sent in the form using password_verify().

  • Like 1

Share this post


Link to post
Share on other sites

at the mysqli queries in the end, see the $conn part... the middle mysqli_query needs an "n" to the $con+n...

just to help a bit :P

Share this post


Link to post
Share on other sites

Well one problem is solved but the thread still isn't done. I tried on my own but it not working. I think my problem is with the array because the switch case never works. 

Quote

After that I need to decide what page to send the user to either the admin page or the student page

<!DOCTYPE html>
<html>
<head>
<title>Verifies login request</title>
</head>
	<body>
		<h1>Please wait to be redirected to the appropriate page</h1>
		<?php
			$servername = ".............";
			$username = "...............";
			$password = "..............";
			$database = "..............";

			//Testing search terms
			$testUsername = $_POST['uname'];
			$testPassword = $_POST['psw'];
			$testTable = "users";
			$pagelocation = "LoginPage.php";
			
			// Create connection
			$conn = new mysqli($servername, $username, $password, $database);

			// Check connection
			if ($conn->connect_error) {
				die("Connection failed: " . $conn->connect_error);
			} 

			$query = "	SELECT username, password 
						FROM $testTable 
						WHERE username = '$testUsername' AND password = '$testPassword'";
			$result = $conn->query($query);
			$row = mysqli_fetch_row($result);
			
			if ($result->num_rows > 0) 
			{
					switch ($row["title"])
					{
						case "admin": $pagelocation = "AdminSettingPage.php"; break;
						case "teacher": $pagelocation = "TeacherSettingPage.php";break;
					}
					//Send the user to the admin page
					echo "Sending you to settings page now. ";	
					mysqli_free_result($result);
			} 
			else 
			{
				//Send the user back to the login page.
				echo "I'm sorry, your user & password does not exist. Please go away......";
				//$pagelocation = "LoginPage.php";
			}		

			mysqli_close($conn);
		?>
		
		<!--Send the user where they suppose to go-->
		<a href=></a>
		<meta http-equiv="Refresh" content="5;url=<?php echo $pagelocation; ?>">
		
		
	</body>
</html>

 

Share this post


Link to post
Share on other sites

You did not select "title" from the database in your query.

Share this post


Link to post
Share on other sites

You definitely need to use prepared statements, that's the first and major thing I would say is wrong with that code.  Also, in an actual system, passwords would never be stored in the database just in plain text.  PHP has functions called password_hash and password_verify that you can use to help store passwords in a more secure format.

Share this post


Link to post
Share on other sites

I really don't have any idea what I can do. All I want is the "title" of the user  who password and username match my query/search/ect. I looked at "prepared statements" on w3 but it just an insert example and my initial problem was getting results. I even changed the array but I'm not getting anything from it. I don't know what the title of the user is and I want to figure out. How can I get the data? This is the  

 

Here what I'm thinking. Getting upset but still persisting.  Be back early tomorrow I need to cool down and think. 

<!DOCTYPE html>
<html>
<head>
<title>Verifies login request</title>
</head>
	<body>
		<h1>Please wait to be redirected to the appropriate page</h1>
		<?php
			$servername = "localhost";
			$username = "root";
			$password = "TheMango0*";
			$database = "betacode_database";

			//Testing search terms
			$testUsername = $_POST['uname'];
			$testPassword = $_POST['psw'];
			$testTitle;
			$testTable = "users";
			$pagelocation = "LoginPage.php";
			
			// Create connection
			$conn = new mysqli($servername, $username, $password, $database);

			// Check connection
			if ($conn->connect_error) {
				die("Connection failed: " . $conn->connect_error);
			} 
			
			//I can't figure out how to use this.
			/*$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email)  VALUES (:firstname, :lastname, :email)"); 
			$stmt = $conn->prepare("SELECT FROM $testTable (username, password, title) VALUES (:username, :password, :title)");
			$stmt->bindParam(':username', $testUsername);
			$stmt->bindParam(':password', $testPassword);
			$stmt->bindParam(':title', $testTitle);*/
			
			$query = "	SELECT username, password, title
						FROM $testTable 
						WHERE username = '$testUsername' AND password = '$testPassword'";
						
			$result = $conn->query($query);
			$row = mysqli_fetch_row($result);
			
			if ($result->num_rows > 0) 
			{
					//$row = $result->fetch_row();
					switch ($row[6])
					{
						case "admin": $pagelocation = "AdminSettingPage.php"; break;
						case "teacher": $pagelocation = "TeacherSettingPage.php";break;
					}
					//Send the user to the admin page
					echo "Sending you to settings page now. ";	
					mysqli_free_result($result);
			} 
			else 
			{
				//Send the user back to the login page.
				echo "I'm sorry, your user & password does not exist. Please go away......";
				//$pagelocation = "LoginPage.php";
			}
			
			// Perform queries 
			//mysqli_query($conn,"SELECT * FROM users WHERE");
			//mysqli_query($con,"INSERT INTO Persons (FirstName,LastName,Age) 
			//VALUES ('Glenn','Quagmire',33)");

			mysqli_close($conn);
		?>
		
		<!--Send the user where they suppose to go-->
		<a href=></a>
		<meta http-equiv="Refresh" content="5;url=<?php echo $pagelocation; ?>">
		
		
	</body>
</html>

 

Share this post


Link to post
Share on other sites

What you had before would have worked if you had added the `title` field to your select statement. You've replaced it with $row[6] which is probably not going to work.

Share this post


Link to post
Share on other sites

It didn't work, at least not without an error. I thought about most of the night and remembered something I found called "fetch_assoc()". Combined with ingolme bit I managed to get the page working to the minimal requirements. 

Although I'll have a bit of time before the next project after this is completely completed, it appears security might be apart of my later assignments. There is still more to do, Thank you all. 

 

<!DOCTYPE html>
<html>
<head>
<title>Verifies login request</title>
</head>
	<body>
		<h1>Please wait to be redirected to the appropriate page</h1>
		<?php
			$servername = "...........";
			$username = "..............";
			$password = "...............";
			$database = ".......................";

			//Testing search terms
			$testUsername = $_POST['uname'];
			$testPassword = $_POST['psw'];
			$testTitle;
			$testTable = "users";
			$pagelocation = "LoginPage.php";
			
			// Create connection
			$conn = new mysqli($servername, $username, $password, $database);

			// Check connection
			if ($conn->connect_error) {
				die("Connection failed: " . $conn->connect_error);
			} 
			
			
			$query = "	SELECT username, password, title
						FROM $testTable 
						WHERE username = '$testUsername' AND password = '$testPassword'";

			
			//$result = $conn->query($query);
			$result=mysqli_query($conn,$query);
			
			
				if ($result->num_rows > 0) 
				{
					//$row = $result->fetch_row();
					$row = mysqli_fetch_assoc($result);
						
							
						//Print the right message and set the right destination
						switch ($row["title"])
						{
							case "admin":	$pagelocation = "AdminSettingPage.php"; 
											//Send the user to the admin page
											echo "Sending you to settings page now. ";	
							break;
							case "teacher": $pagelocation = "TeacherSettingPage.php";
											//Send the user to the admin page
											echo "Sending you to settings page now. ";	
							break;
						}
				}
			else 
			{
				echo"I'm sorry, your user & password does not exist. Please go away......";
				$pagelocation = "LoginPage.php";
			}
			mysqli_free_result($result);
			mysqli_close($conn);
		?>
		
		<!--Send the user where they suppose to go-->
		<a href=></a>
		<meta http-equiv="Refresh" content="5;url=<?php echo $pagelocation; ?>">
		
		
	</body>
</html>

 

Share this post


Link to post
Share on other sites

I looked at "prepared statements" on w3 but it just an insert example and my initial problem was getting results.

That doesn't matter, you can use prepared statements with any kind of query.  You use a prepared statement any time you are putting data into the query.  You should never just put a PHP variable in a query like this:

$query = "    SELECT username, password, title
                        FROM $testTable 
                        WHERE username = '$testUsername' AND password = '$testPassword'";

That's a major attack vector for websites.  With that in your code, I could enter a username and password which will always log me in without needing to match any username or password in the database.  If I know the username, like "admin", then I can log in as that user without needing to know their password.  All of that because you are using PHP variables inside the SQL query.  Replace the data with placeholders, use a prepared statement to bind your variables, and you won't have that problem.

$query = "    SELECT username, password, title
                        FROM $testTable 
                        WHERE username = :username AND password = :password";

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×