Sessions and Database Help

I need help with this code

Page 1 of 1

9 Replies - 4358 Views - Last Post: 20 April 2009 - 08:38 PM Rate Topic: -----

#1 Zerobu  Icon User is offline

  • Black Hatter

Reputation: 13
  • View blog
  • Posts: 1,822
  • Joined: 14-January 08

Sessions and Database Help

Posted 18 April 2009 - 05:32 PM

the assignment can be found here

Hi, I need help with a php script that allows a person to create a profile that has a picture of themselves and they should be able to edit their username and their password, or change their picture

Here is create_account.php


<?php session_start(); ?>

<html>
<head><title>MyFaceSpace: Create Account</title></head>
<body>

<?php

if ($_SERVER['REQUEST_METHOD'] == 'GET')
{
?>
   <h2>Create Account</h2>

   <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST"
enctype="multipart/form-data">
   <input type="hidden" name="MAX_FILE_SIZE" value="50000000">

	   <table>
			   <tr><td>Name</td><td><input type="text" name="name" /></td></tr>
			   <tr><td>Username</td><td><input type="text" name="username" /></td></tr>
			   <tr><td>Password</td><td><input type="password" name="password" /></td></tr>
			   <tr><td>Profile Image</td><td><input type="file" name="imgfile" /></td></tr>
	   </table>
   <br />
   <input type="submit" value="Create Account" />
   </form>

</body>
</html>
<?php

}
else   // POST
{
	   require("image-util.php");   // To use functions that upload and resize images

	   // Connecting, selecting database
	   $db_username = "sharris2";
	   $db_password = "sharris2";
	   $db_database = "sharris2";
   $db = mysql_connect("taz.harding.edu", $db_username, $db_password)
	   or die("Could not connect : " . mysql_error());
   mysql_select_db($db_database) or die("Could not select database$db_database");

	   // Get submitted data and verify it wasn't left blank
	   $name = trim(mysql_real_escape_string($_POST['name']));
	   $username = trim(mysql_real_escape_string($_POST['username']));
	   $password = trim(mysql_real_escape_string($_POST['password']));

	   if ($name == '')
			   Error("Go back and enter your name.");

	   if ($username == '' || strlen($username) < 3)
			   Error("Go back and enter a username that is at least 3 characters.");

	   if ($password == '')
			   Error("Go back and enter a password.");


	   $upload_dir = 'myfacespace/images';
	   $upload_url = "/~sharris2/$upload_dir";

	   // This is the directory the uploaded images will be placed in.
	   // It must have priviledges sufficient for the web server to write to it
	   $upload_directory_full = "/home/sharris2/public_html/$upload_dir";
	   if (!is_writeable($upload_directory_full))
			   Error("The directory $upload_directory is not writeable.\n");


	   $image_filename = "$upload_directory_full/$username.jpg";

	   // Save the uploaded image to the given filename
	   $error_msg = UploadSingleImage($image_filename);
	   if ($error_msg != "")
			   Error($error_msg);


	   // Save uploaded image with a maximum width or height of 300 pixels
	   CreateThumbnailImage($image_filename, $image_filename, 300);

	   // Create a very small thumbnail of the image to be used later
	   $image_thumbnail = $username . "_thumb.jpg";
	   CreateThumbnailImage($image_filename,
"$upload_directory_full/$image_thumbnail", 60);

	   // Get the MD5 hash of the password for inserting into the database
	   $password_hash = md5($password);

	   // Insert record into the database
	   $cmd = "INSERT INTO Users VALUES ('$username', '$password_hash',
'$name', '', NULL)";
	   $result = mysql_query($cmd); //or error(mysql_error() . "<p>Command =$cmd</p>");
	   if (!$result)
			   Error("Sorry, but that username already exists. Please go back and
use another.");

	   print "<h1>Account Created</h1>\n" .
			   "<p><img src='$upload_url/$username.jpg' style='float:left; margin:
0pt 10pt 10px 10px;'>" .
			   "<h2>$name</h2></p>\n".
			   "<p><a href='edit_account.php'>Edit Account</a></p>\n";

	   // Set session variable for use in other pages
	   $_SESSION['username'] = $username;

}  // end POST


function Error($error)
{
?>
   <h1>Unable to create account</h1>
   <p><?= $error ?></p>
	   <p><a href="java script:history.back()">Go back</a></p>
</body>
</html>
<?php
   exit;
}



Here is image-util.php. This script is needed to upload a picture
<?php

// This code is combined from a number of locations and modified
// by Frank McCown, Harding University, 2009.


// Return empty string if uploaded image is successfully saved as
// $image_filename or an error message.
// $image_filename should be saved in a directory that the web
// server can write to.
function UploadSingleImage($image_filename)
{
	// This function is greatly modified code from
	// http://www.webdeveloper.com/forum/showthread.php?t=101466
	
	
	// possible PHP upload errors
	$errors = array(1 => 'php.ini max file size exceeded',
				2 => 'html form max file size exceeded',
				3 => 'file upload was only partial',
				4 => 'no file was attached');
	
	/*
print "<pre>";
print_r($_FILES);
print "</pre>\n";
*/

	// check if any files were uploaded and if
	// so store the active $_FILES array keys
	$active_keys = array();
	foreach($_FILES as $key => $file)
	{
		if(!empty($file['name']))
		{
			$active_keys[] = $key;
		}
	}

	// check at least one file was uploaded
	if (count($active_keys) == 0)
		return 'No files were uploaded';
		
	// check for standard uploading errors
	foreach ($active_keys as $key)
	{
		if ($_FILES[$key]['error'] > 0)
			return $_FILES[$key]['tmp_name'] . ': ' . $errors[$_FILES[$key]['error']];
	}
	
	// check that the file we are working on really was an HTTP upload
	foreach ($active_keys as $key)
	{
		if (!is_uploaded_file($_FILES[$key]['tmp_name']))
			return $_FILES[$key]['tmp_name'] . ' not an HTTP upload';
	}
	
	// validation... since this is an image upload script we
	// should run a check to make sure the upload is an image
	foreach ($active_keys as $key)
	{
		if (!getimagesize($_FILES[$key]['tmp_name']))
			return $_FILES[$key]['tmp_name'].' is not an image';
	}
		

	// Save every uploaded file to the same filename (normally we'd want to
	// save each file with its own unique name, but we are assuming there
	// is only one file).
	foreach ($active_keys as $key)
	{
		if (!move_uploaded_file($_FILES[$key]['tmp_name'], $image_filename))
			return 'receiving directory (' . $image_filename . ') has insuffiecient permission';
	}
	
	// If you got this far, everything has worked and the file has been successfully saved.

	return '';
}  


// This function uses Unix utilities to create a thumbnail image.  
// $scr_filename = The pull path to where the image file resizes.
// $dest_filename = The pull path of the thumbnail image to be created.
// $thumb_max_size = The longest width or height the image should have.
// Normally resizing is done with imagecreatefromjpeg, but this is not
// working on Taz (JPEG support is only available if PHP was compiled against
// GD-1.8 or later).
function CreateThumbnailImage($src_filename, $dest_filename, $thumb_max_size)
{
	$max_width = $thumb_max_size;
	$max_height = $thumb_max_size;

	list($width, $height) = getimagesize($src_filename);
	
	if ($width < $thumb_max_size && $height < $thumb_max_size)
	{
		// No need to resize since image is smaller than thumb, so
		// just make copy
		copy($src_filename, $dest_filename);
		return;
	}

	$x_ratio = $max_width / $width;
	$y_ratio = $max_height / $height;

	if (($width <= $max_width) && ($height <= $max_height))
	{
		$tn_width = $width;
		$tn_height = $height;
	}
	elseif (($x_ratio * $height) < $max_height)
	{
		$tn_height = ceil($x_ratio * $height);
		$tn_width = $max_width;
	}
	else
	{
		$tn_width = ceil($y_ratio * $width);
		$tn_height = $max_height;
	}

	// Where to store temp img file 
	$tmpimg = tempnam("/tmp", "MKPH");

	// Extract file extension 
	$i = strrpos($src_filename, ".");
	if (!$i) 
	{
		echo "Unable to find filename extension.";
		return;
	}

	$len = strlen($src_filename) - $i;
	$ext = strtolower(substr($src_filename, $i+1, $len));
	
	// Convert image to PNM
	if ($ext != "jpg") 
	{ 
		echo("Extension is not .jpg."); 
		return;		
	}
	
	system("djpeg $src_filename >$tmpimg"); 

	// Scale image using pnmscale and output using cjpeg
	system("pnmscale -xy $tn_height $tn_width $tmpimg | cjpeg -smoo 10 -qual 50 >$dest_filename");
}
?> 




And Finally here is what i've written edit account.php
<?php session_start(); ?>

<html>
<head><title>MyFaceSpace: Edit Account</title></head>
<body>

<?php

  // Connecting, selecting database
	   $db_username = "sharris2";
	   $db_password = "sharris2";
	   $db_database = "sharris2";
   $db = mysql_connect("taz.harding.edu", $db_username, $db_password)
	   or die("Could not connect : " . mysql_error());
   mysql_select_db($db_database) or die("Could not select database$db_database");



if ($_SERVER['REQUEST_METHOD'] == 'GET')
{
?>
   <h2>Edit Account</h2>

   <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST"
enctype="multipart/form-data">
   <input type="hidden" name="MAX_FILE_SIZE" value="50000000">

	   <table>
<?php

$username = $_SESSION["username"];

$query = "SELECT * FROM Users WHERE username = $username";  
$result = mysql_query($query, $db);



echo ("$username");
	
		echo ("<tr><td>Name</td><td><input type=text name=name /></td></tr>");
			echo ("<tr><td>Username</td><td><input type=text name=username /></td></tr>");
			echo  ("<tr><td>Password</td><td><input type=password name=password /></td></tr>");
			echo  ("<tr><td>Profile Image</td><td><input type=file name=imgfile /></td></tr>");
?>
	   </table>
   <br />
   <input type="submit" value="Save" />
   </form>

</body>
</html>
<?php

}
else   // POST
{
	   require("image-util.php");   // To use functions that upload and resize images

	   // Connecting, selecting database
	   $db_username = "sharris2";
	   $db_password = "sharris2";
	   $db_database = "sharris2";
   $db = mysql_connect("taz.harding.edu", $db_username, $db_password)
	   or die("Could not connect : " . mysql_error());
   mysql_select_db($db_database) or die("Could not select database
$db_database");

	   // Get submitted data and verify it wasn't left blank
	   $name = trim(mysql_real_escape_string($_POST['name']));
	   $username = trim(mysql_real_escape_string($_POST['username']));
	   $password = trim(mysql_real_escape_string($_POST['password']));

	   if ($name == '')
			   Error("Go back and enter your name.");

	   if ($username == '' || strlen($username) < 3)
			   Error("Go back and enter a username that is at least 3 characters.");

	   if ($password == '')
			   Error("Go back and enter a password.");


	   $upload_dir = 'myfacespace/images';
	   $upload_url = "/~sharris2/$upload_dir";

	   // This is the directory the uploaded images will be placed in.
	   // It must have priviledges sufficient for the web server to write to it
	   $upload_directory_full = "/home/sharris2/public_html/$upload_dir";
	   if (!is_writeable($upload_directory_full))
			   Error("The directory $upload_directory is not writeable.\n");


	   $image_filename = "$upload_directory_full/$username.jpg";

	   // Save the uploaded image to the given filename
	   $error_msg = UploadSingleImage($image_filename);
	   if ($error_msg != "")
			   Error($error_msg);


	   // Save uploaded image with a maximum width or height of 300 pixels
	   CreateThumbnailImage($image_filename, $image_filename, 300);

	   // Create a very small thumbnail of the image to be used later
	   $image_thumbnail = $username . "_thumb.jpg";
	   CreateThumbnailImage($image_filename,
"$upload_directory_full/$image_thumbnail", 60);

	   // Get the MD5 hash of the password for inserting into the database
	   $password_hash = md5($password);

	   // Insert record into the database
	   $cmd = "INSERT INTO Users VALUES ('$username', '$password_hash',
'$name', '', NULL)";
	   $result = mysql_query($cmd); //or error(mysql_error() . "<p>Command =$cmd</p>");
	   if (!$result)
			   Error("Sorry, but that username already exists. Please go back and
use another.");

	   print "<h1>Account Successfully Modified</h1>\n" .
			   "<p><img src='$upload_url/$username.jpg' style='float:left; margin:
0pt 10pt 10px 10px;'>" .
			   "<h2>$name</h2></p>\n".
			   "<p><a href='edit_account.php'>Edit Account</a></p>\n";

	   // Set session variable for use in other pages
	   $_SESSION['username'] = $username;

}  // end POST


function Error($error)
{
?>
   <h1>Unable to create account</h1>
   <p><?= $error ?></p>
	   <p><a href="java script:history.back()">Go back</a></p>
</body>
</html>
<?php
   exit;
}
?>



My problem in edit_account php is that for some reason, when i try read the session variable's they say that their undefined. The only one that is defined is username

$username = $_SESSION["username"];
$name = $-SESSION["name"];   //I get an message saying this is undefined.




Is it because something i did wrong in the database?
Didn't i make a correct query?

This post has been edited by Zerobu: 18 April 2009 - 05:34 PM


Is This A Good Question/Topic? 0
  • +

Replies To: Sessions and Database Help

#2 SpaceMan  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 10
  • View blog
  • Posts: 507
  • Joined: 20-February 03

Re: Sessions and Database Help

Posted 18 April 2009 - 06:30 PM

right off the bat i see $-SESSION["name"]; should be an underscore.
Was This Post Helpful? 0
  • +
  • -

#3 SpaceMan  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 10
  • View blog
  • Posts: 507
  • Joined: 20-February 03

Re: Sessions and Database Help

Posted 18 April 2009 - 06:38 PM

also did not happen to see you set it in this anywhere in this code you posted, where does it first get put into the session?

as a user, may i recommend completing the sign up and confirmation before uploading a pic...

less errors = less to fix.

if it fails for some reason, like username used will have to repic and reupload my pics?
Was This Post Helpful? 0
  • +
  • -

#4 Zerobu  Icon User is offline

  • Black Hatter

Reputation: 13
  • View blog
  • Posts: 1,822
  • Joined: 14-January 08

Re: Sessions and Database Help

Posted 18 April 2009 - 06:50 PM

It should have come in through the sessions array form in create_account .php
When the user enters their name it should be saved on the server?

This post has been edited by Zerobu: 18 April 2009 - 06:52 PM

Was This Post Helpful? 0
  • +
  • -

#5 Zerobu  Icon User is offline

  • Black Hatter

Reputation: 13
  • View blog
  • Posts: 1,822
  • Joined: 14-January 08

Re: Sessions and Database Help

Posted 18 April 2009 - 08:52 PM

bump
Was This Post Helpful? 0
  • +
  • -

#6 Hary  Icon User is offline

  • D.I.C Regular

Reputation: 44
  • View blog
  • Posts: 427
  • Joined: 23-September 08

Re: Sessions and Database Help

Posted 19 April 2009 - 04:11 AM

Bump within 2 hours? Pffff, get a life...

I do not get your new problem, did you correct the error SpaceMan pointed to?

The $_SESSION variable is a thing you have in all php pages, in which you have session_start. Nothing gets in it automatically, but you can put in everything you want. If you want to store a logged in username, or a user identifier, then you can put it in.
Was This Post Helpful? 0
  • +
  • -

#7 SpaceMan  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 10
  • View blog
  • Posts: 507
  • Joined: 20-February 03

Re: Sessions and Database Help

Posted 19 April 2009 - 06:17 AM

this was not rhetorical, you say it is... what line, show me...

i don't see it, so you seem to be checking a session that was never set.

View PostZerobu, on 18 Apr, 2009 - 05:50 PM, said:

It should have come in through the sessions array form in create_account .php
When the user enters their name it should be saved on the server?

This post has been edited by SpaceMan: 19 April 2009 - 06:17 AM

Was This Post Helpful? 0
  • +
  • -

#8 hajoura  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 20-April 09

Re: Sessions and Database Help

Posted 20 April 2009 - 12:23 PM

Hi,
I am a computer sciences student from Tunisia. I am doing my end-of-studies project with PHP. actually i don't know anything about PHP. Can you help me with tips? Can I ask you whenver i have a problem?? I Will be so thankful and i am so sorry for disturbing you.
Take care.
Bye.
Was This Post Helpful? 0
  • +
  • -

#9 Hary  Icon User is offline

  • D.I.C Regular

Reputation: 44
  • View blog
  • Posts: 427
  • Joined: 23-September 08

Re: Sessions and Database Help

Posted 20 April 2009 - 12:49 PM

Sure, but please do not highjack someone else's thread. Start a new one for your question(s)
Was This Post Helpful? 0
  • +
  • -

#10 Zerobu  Icon User is offline

  • Black Hatter

Reputation: 13
  • View blog
  • Posts: 1,822
  • Joined: 14-January 08

Re: Sessions and Database Help

Posted 20 April 2009 - 08:38 PM

yes i have corrected the error, I didn't assign the session variables in create_account.php.
Was This Post Helpful? 1
  • +
  • -

Page 1 of 1