Jump to content

users and sessions


ryanmetzler3

Recommended Posts

I followed this YouTube tutorial on how to make a registration page with a username and password. Also a login page that checks you credentials against the database and logs you in. After you are logged in, it starts a session. That's where it stopped. I want to do two things. I want to display on the site if you are logged in or if you are visiting as a guest. And my site's main purpose is photo uploading. So I would like to have under each uploaded photo the username of who uploaded it, or guest if they were not registered. I really am clueless on where to go from here. So if anyone could even point me in the right direction that would be great. I am teaching myself to program and am totally new to sessions, users etc.

 

Here is the config.php file

<?php

$sql = mysql_connect("localhost","root","") or die(mysql_error());
$slect_db = mysql_select_db("login", $sql);

?>

The registrer.php file

<?php
include ('config.php');
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
	$username = mysql_real_escape_string($_POST['username']);
	$password = mysql_real_escape_string(md5($_POST['password']));

if (empty($username)) {
	echo("You have to fill in an username!");
} else {
	if(empty($password)){
		echo ("You have to fill in a password!");
	} else {
		$query = mysql_query("SELECT * FROM users WHERE username = '$username'");
		$rows = mysql_num_rows($query);
	}
		if ($rows > 0) {
			die("Username taken!");
		} else {
			$user_input = mysql_query("INSERT INTO users (username, password) VALUES ('$username','$password')");	
			echo("Succesfuly Registered!");
		}
	}
}
?>

<html>
	
	<head>
		<title>Register</title>
	</head>
	
	<body>
		<form action="register.php" method="post">
			Username: <input type="text" name="username" /><br/>
			Password: <input type="password" name="password"/><br/>
			<input type="submit" value="Register!"/>	
		</form>
	</body>
	
</html>

and the login.php file 

<?php
include ("config.php");
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
	$username = mysql_real_escape_string($_POST['username']);
	$password = mysql_real_escape_string(md5($_POST['password']));
	$query = mysql_query("SELECT * FROM users WHERE username='$username' AND password='$password'");
	$query_rows = mysql_num_rows($query);
	
	if($query_rows > 0) {
		echo ("Succesfull Login!");
		session_start();
		$_SESSION['login'] = "1";
	} else {
		echo ("Username and/or password incorrect");
	}
}

		
?>

<html>
	
	<head>
		<title>Login</title>
	</head>
	
	<body>
		<form action="login.php" method="post">
			Username: <input type="text" name="username" /><br/>
			Password: <input type="password" name="password"/><br/>
			<input type="submit" value="Login!"/>	
		</form>
	</body>
	
</html>
Link to comment
Share on other sites

when you go to a night club, after you pay the bauncers nomaly stamp on your hand a stamp that shows other security officials that you have already paid and you have gone through the neccesary check.

 

At this point lets call a $_SESSION['login'] to be our stamp That is going to tell all pages that requires login that this person has been checked in and here is the stamp.

 

Now what you need to do is on each page where you require login, put this code right at the beggining before anything is written.

// check if session login is set from the login page.
if(!isset($_SESSION['login'])){
   header("Location: login.php");
   exit;
}
Link to comment
Share on other sites

 

when you go to a night club, after you pay the bauncers nomaly stamp on your hand a stamp that shows other security officials that you have already paid and you have gone through the neccesary check.

 

At this point lets call a $_SESSION['login'] to be our stamp That is going to tell all pages that requires login that this person has been checked in and here is the stamp.

 

Now what you need to do is on each page where you require login, put this code right at the beggining before anything is written.

// check if session login is set from the login page.
if(!isset($_SESSION['login'])){
   header("Location: login.php");
   exit;
}

That is useful information and I appreciate it! But I am going to keep all the pages available to everyone even if they did not register. I am going to have a monthly give away to the user who uploads the best pictures so they have to be registered to be eligible. But I don't want to discourage people from uploading either by making them go through the registration process if they don't want. Can you tell me how I can display the users name at the top of every page when you are logged in? And how I could associate the users name with the picture they upload? 

 

Here is my website: s--a--p--e--z--e--e--(dot)com   (take all the dashes and junk out, I just don't want this page getting crawled and showing up in search engines for my site)

 

Also here is the code I use for uploading pictures and the form for it: 

html

<head>
	<link rel="stylesheet" type="text/css" href="main.css"/>
</head>

<body>

		<form action="upload.php" method="post" enctype="multipart/form-data">
			Artist Name: </br>
			<input type="text" name="name"/> </br>
			Location:</br>
			<input type="text" name="location"/> </br>
			Date:</br>
			<input type="text" name="date"/> </br>
			Select Image: </br>
			<input type="file" name="filename" size="10"/>
			<input type="submit" value="Submit" name="submit"/>
		</form>
</body>

</html>

<html>
<head>
	<title>Upload</title>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />	
	<link rel="stylesheet" type="text/css" href="main.css" media="screen" />
</head>
<body>
	<div id="content">	
		
				
		<?php
			include "header.php";
			include "menu.php"; 
		?>
		
		<div style="clear: both;"></div>


<div id="works">
	<h2><center>Uploaded Image</center></h2>
<?php
$ext = '';
if (isset($_FILES['filename'])) 
{
	$filename = $_FILES['filename']['name'];
	switch($_FILES['filename']['type'])
	{
		case 'image/jpeg': 
			$ext = 'jpg'; 
			move_uploaded_file($_FILES['filename']['tmp_name'], $filename);
			$image = imagecreatefromjpeg($filename); 
			break;
		case 'image/gif':  
			$ext = 'gif';
			move_uploaded_file($_FILES['filename']['tmp_name'], $filename);
			$image = imagecreatefromgif($filename);
			break;
		case 'image/png':  
			$ext = 'png'; 
			move_uploaded_file($_FILES['filename']['tmp_name'], $filename);
			$image = imagecreatefrompng($filename);
			break;
		default:	$ext = '';    break;
	}	
	if($ext)
	{
		list($width, $height) = getimagesize($filename);
		if($width > $height)
		{
			$new_width = 400;
			$new_height =300;
		}
		else  
		{
			$new_width = 300;
			$new_height =400;
		}		

		if( ($width > $new_width) OR ($height > $new_height) )
		{
			$ratio1 = $width/$new_width;
			$ratio2 = $height/$new_height;
			if($ratio1 >= $ratio2)
			{
	 			$new_image = imagecreatetruecolor($new_width, $new_height); 
	 			imagecopyresampled($new_image, $image, 0, 0, 0, 0, $new_width, ($new_width/$width)*$height, $width, $height);
			}
			else
			{
				$new_image = imagecreatetruecolor($new_width, $new_height); 
	 			imagecopyresampled($new_image, $image, 0, 0, 0, 0, ($height/$new_height)*$width, $new_height, $width, $height);	
			}
		}		
	  	imagejpeg($new_image, $filename);
		
		echo "<div id='uploadtext'>We have uploaded the following image and recorded your data. Thanks for using our site!<br /></div>";
		echo "<img id='uploadstyle' src=$filename />";

	}
	else echo "'$filename' is not an accepted image file";
}
echo "</body></html>";

if (isset($_POST['submit']) AND $ext) 
{

	$con=mysqli_connect("localhost","root","","imagestore");
	// Check connection
	if (mysqli_connect_errno())
  	{
  		echo "Failed to connect to MySQL: " . mysqli_connect_error();
	}	

	@$sql="INSERT INTO store (name, location, date, imagelocation)
	VALUES
	('$_POST[name]','$_POST[location]','$_POST[date]','$filename')";

	if (!mysqli_query($con,$sql))
  	{
  		die('Error: ' . mysqli_error($con));
  	} 
}
?>
</div>
</div>



<div style="clear: both;"></div>
		</div>
	
	<?php 
	include "footer.php";
	?>
	
</body>
</html>

Link to comment
Share on other sites

Can you tell me how I can display the users name at the top of every page when you are logged in? And how I could associate the users name with the picture they upload? 

 

You would need to modify your code before doing anything else.

 

Currently, what your script does is it allows a user to login, once a successful login attempt is performed a session is created with array key login and value 1

 

So now we can see if that user is logged in but we can't find out any information about them? This is because no actual user data is stored in the session, just an understanding that the user successfully logged in.

 

Some may say, oh well we can just set the value for login to correspond to the users id. You can do this as well. My method is flawed because I'm using your query that checks if the username and password matches the $_POST data to store user information. I won't go into more detail about this unless you specifically ask.

 

You'll want something like this:

 

<?phpif ($_SERVER['REQUEST_METHOD'] == 'POST') {    $username = mysql_real_escape_string($_POST['username']);    $password = mysql_real_escape_string(md5($_POST['password']));    $query = mysql_query("SELECT * FROM users WHERE username='$username' AND password='$password'");    $query_rows = mysql_num_rows($query);     if($query_rows > 0) {        $user_data = mysql_fetch_assoc($query);        echo ("Succesfull Login!");        session_start();        $_SESSION['user'] = $user_data;    }    else {        echo ("Username and/or password incorrect");    }}if(isset($_SESSION['user'])){    echo "Welcome {$_SESSION['user']['username']}";}

 
Now, let's understand how to use the new array.
 
Say you have some extra fields in your users table, like email or location for example and you want to access it. How would you do it with this code? Simple:
echo $_SESSION['user']['email'];

 
I am a bit sleepy so I'm going to stop here. Sorry for the lack of detail within this last bit, I've grown quite tired of posting this and I'm dozing off. Ask any questions you want and I'll get to them once my mind has straightened up.
Edited by 0xMatt
Link to comment
Share on other sites

 

You would need to modify your code before doing anything else.

 

Currently, what your script does is it allows a user to login, once a successful login attempt is performed a session is created with array key login and value 1

 

So now we can see if that user is logged in but we can't find out any information about them? This is because no actual user data is stored in the session, just an understanding that the user successfully logged in.

 

Some may say, oh well we can just set the value for login to correspond to the users id. You can do this as well. My method is flawed because I'm using your query that checks if the username and password matches the $_POST data to store user information. I won't go into more detail about this unless you specifically ask.

 

You'll want something like this:

 

<?phpif ($_SERVER['REQUEST_METHOD'] == 'POST') {    $username = mysql_real_escape_string($_POST['username']);    $password = mysql_real_escape_string(md5($_POST['password']));    $query = mysql_query("SELECT * FROM users WHERE username='$username' AND password='$password'");    $query_rows = mysql_num_rows($query);     if($query_rows > 0) {        $user_data = mysql_fetch_assoc($query);        echo ("Succesfull Login!");        session_start();        $_SESSION['user'] = $user_data;    }    else {        echo ("Username and/or password incorrect");    }}if(isset($_SESSION['user'])){    echo "Welcome {$_SESSION['user']['username']}";}

 
Now, let's understand how to use the new array.
 
Say you have some extra fields in your users table, like email or location for example and you want to access it. How would you do it with this code? Simple:
echo $_SESSION['user']['email'];

 
I am a bit sleepy so I'm going to stop here. Sorry for the lack of detail within this last bit, I've grown quite tired of posting this and I'm dozing off. Ask any questions you want and I'll get to them once my mind has straightened up.

 

I understand pretty much everything you have going there. But this very last if statement I have a question on: 

if(isset($_SESSION['user']))
{
    echo "Welcome {$_SESSION['user']['username']}";
}[/php]

I tried editing the code to match what you have outlined and it works. But when it runs this if statement it echos "Welcome A". I have no idea where this "A" is coming from. I made my username Metzler when I registered and my password 456.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.