• 0

[PHP][MySQL] compare session info to db in a query


Question

Hi,

I got a log-in script going and I have it so it sets up a new session() when it logs the user in.

i have on my index.php a session_start() that stores $_SESSION['user_id'] = $row['user_id']; and $_SESSION['username'] = $row['username'].

then in my account.php I thought of doing the samething and add to my session more information so I did another db query and tried to created my $_SESSION variables to store the extra info I wanted to pull out.

My syntax is correct, and my SQL query is correct aswell.

include 'dbc.php';
page_protect();
session_start(); 	

$row = mysql_fetch_assoc(mysql_query("SELECT company_name FROM agent_company WHERE agent_id = '{$_SESSION['user_id']}'"));

		if($row['company_name'])
		{
			$_SESSION['company_name'] = $row['company_name'];

			exit;
		}

as you can see I'm trying to pull the data by comparing that it will only pull that data that belongs to the user of the current session. I used my $_SESSION['user_id'] that was created in my index.php here.

Can I not pull session data on a new page with an existing session? or do I need to add ALL the information I want to use all in one swoop? then just access it later on when I need it...?

in my page_protect() function I have this

function page_protect() {
session_start();

//check for cookies

if(isset($_COOKIE['user_id']) && isset($_COOKIE['username'])){
 	$_SESSION['user_id'] = $_COOKIE['user_id'];
 	$_SESSION['username'] = $_COOKIE['username'];
 }


if (!isset($_SESSION['user_id']))
{
header("Location: account.php");
}

Recommended Posts

  • 0
  On 04/05/2010 at 02:49, theblazingangel said:

The sessions error is because you're probably still calling session_start() twice, I told you about that a while back ;)

I've updated the code a little, try the latest copy! (above)

yeah, i don't get the syntax for line 90~ are you suppose to use "\\" ? hmmm, it looks like its breaking the code from there

  • 0

The backslash is the escape character, if i want to echo a double quote, like echo "foo " bar";, that's not going to work because it'll think the string ends after the second quote, not the third. To correct this, you either enclose in single quotes (not always possible/desirable), or you escape the quote like so: echo "foo \" bar";! Things that follow the backslash in a string that's enclosed in double quotes are treated where possible in a special way, e.g. "\t" is a tab, and "\n" is a new line. So if you want an actual backslash in a string enclosed in double quotes, you need to escape it: "foo\\bar", or alternatively ise single quotes: 'foo"bar'.

So yes, the double backslashes are supposed to be there, that's not the problem.

I'm working on it, just got some stupid syntax error which I can't find the source of blocking me at the moment...

  • 0

Okay, fixed that problem I had, the backslash seems to effect single quotes too, don;t know why I didn't know that, will have to experiment some more...

The code now recursively creates each of the folders in turn if the full path does not exists, rather than trying to create the entire path at once, which fixes some of the errors here. I'm still getting an error, but it might just be down to permissions on my system, try this latest copy of the code on the server and let me know how it goes...

<?php

//Temporarily turn on error reporting
@ini_set('display_errors', 1);
error_reporting(E_ALL);

// Set default timezone (New PHP versions complain without this!)

	date_default_timezone_set("GMT");

// Common

	set_time_limit(0);

	require_once('dbc.php');
	require_once('sessions.php');

	page_protect();

// Image settings

	define('IMG_FIELD_NAME', 'cons_image');

	// Max upload size in bytes (for form)
	define ('MAX_SIZE_IN_BYTES', '512000');

	// Width and height for the thumbnail
	define ('THUMB_WIDTH', '150');
	define ('THUMB_HEIGHT', '150');

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">;html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
	<title>whatever</title>
	<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
	<style type="text\css">
		.validationerrorText { color:red; font-size:85%; font-weight:bold; }
	</style>
</head>
<body>
	<h1>Change image</h1>
<?php

$errors = array();

// Process form
if (isset($_POST['submit'])) {

	// Get filename
	$filename = stripslashes($_FILES['cons_image']['name']);

	// Validation of image file upload
	$allowedFileTypes = array('image/gif', 'image/jpg', 'image/jpeg', 'image/png');
	if ($_FILES[IMG_FIELD_NAME]['error'] == UPLOAD_ERR_NO_FILE) {

		$errors['img_empty'] = true;

	} elseif (($_FILES[IMG_FIELD_NAME]['type'] != '') && (!in_array($_FILES[IMG_FIELD_NAME]['type'], $allowedFileTypes))) {

		$errors['img_type'] = true;

	} elseif (($_FILES[IMG_FIELD_NAME]['error'] == UPLOAD_ERR_INI_SIZE) || ($_FILES[IMG_FIELD_NAME]['error'] == UPLOAD_ERR_FORM_SIZE) || ($_FILES[IMG_FIELD_NAME]['size'] > MAX_SIZE_IN_BYTES)) {

		$errors['img_size'] = true;

	} elseif ($_FILES[IMG_FIELD_NAME]['error'] != UPLOAD_ERR_OK) {

		$errors['img_error'] = true;

	} elseif (strlen($_FILES[IMG_FIELD_NAME]['name']) > 200) {

		$errors['img_nametoolong'] = true;

	} elseif ( (file_exists(__DIR__ . "\\uploads\\{$username}\\images\\banner\\{$filename}")) || (file_exists(__DIR__ . "\\uploads\\{$username}\\images\\banner\\thumbs\\{$filename}")) ) {

		$errors['img_fileexists'] = true;
	}

	if (! empty($errors)) { 
		unlink($_FILES[IMG_FIELD_NAME]['tmp_name']); //cleanup: delete temp file
	}

	// Create thumbnail
	if (empty($errors)) {

		// Make directory if it doesn't exist
		if (!is_dir(__DIR__."\\uploads\\{$username}\\images\\banner\\thumbs\\")) {

			// Take directory and break it down into folders
			$dir = "uploads\\{$username}\\images\\banner\\thumbs";
			$folders = explode("\\", $dir);

			// Create directory, adding folders as necessary as we go (ignore mkdir() errors, we'll check existance of full dir in a sec)
			$dirTmp = '';
			foreach ($folders as $fldr) {
				if ($dirTmp != '') { $dirTmp .= "\\"; }
				$dirTmp .= $fldr;
				mkdir(__DIR__."\\".$dirTmp); //ignoring errors deliberately!
			}

			// Check again whether it exists
			if (!is_dir(__DIR__."\\uploads\\$username\\images\\banner\\thumbs\\")) {
				$errors['move_source'] = true;
				unlink($_FILES[IMG_FIELD_NAME]['tmp_name']); //cleanup: delete temp file
			}
		}

		if (empty($errors)) {

			// Move uploaded file to final destination
			if (! move_uploaded_file($_FILES[IMG_FIELD_NAME]['tmp_name'], "/uploads/$username/images/banner/$filename")) {
				$errors['move_source'] = true;
				unlink($_FILES[IMG_FIELD_NAME]['tmp_name']); //cleanup: delete temp file

			} else {

				// Create thumbnail in new dir
				if (! make_thumb("/uploads/$username/images/banner/$filename", "/uploads/$username/images/banner/thumbs/$filename")) {
					$errors['thumb'] = true;
					unlink("/uploads/$username/images/banner/$filename"); //cleanup: delete source file
				}
			}
		}
	}

	// Record in database
	if (empty($errors)) {

		// Find existing record and delete existing images
		$sql = "SELECT `bannerORIGINAL`, `bannerTHUMB` FROM `agent_settings` WHERE (`agent_id`={$user_id}) LIMIT 1";
		$result = mysql_query($sql);
		if (!$result) {
			unlink("/uploads/$username/images/banner/$filename"); //cleanup: delete source file
			unlink("/uploads/$username/images/banner/thumbs/$filename"); //cleanup: delete thumbnail file
			die("<div><b>Error: Problem occurred with Database Query!</b><br /><br /><b>File:</b> " . __FILE__ . "<br /><b>Line:</b> " . __LINE__ . "<br /><b>MySQL Error Num:</b> " . mysql_errno() . "<br /><b>MySQL Error:</b> " . mysql_error() . "</div>");
		}
		$numResults = mysql_num_rows($result);
		if ($numResults == 1) {
			$row = mysql_fetch_assoc($result);

			// Delete old files
			unlink("/uploads/$username/images/banner/" . $row['bannerORIGINAL']); //delete OLD source file
			unlink("/uploads/$username/images/banner/thumbs/" . $row['bannerTHUMB']); //delete OLD thumbnail file
		}

		// Update/create record with new images
		if ($numResults == 1) {
			$sql = "INSERT INTO `agent_settings` (`agent_id`, `bannerORIGINAL`, `bannerTHUMB`) VALUES ({$user_id}, '/uploads/$username/images/banner/$filename', '/uploads/$username/images/banner/thumbs/$filename')";
 		} else {
 			$sql = "UPDATE `agent_settings` SET `bannerORIGINAL`='/uploads/$username/images/banner/$filename', `bannerTHUMB`='/uploads/$username/images/banner/thumbs/$filename' WHERE (`agent_id`={$user_id})";
 		}
		$result = mysql_query($sql);
		if (!$result) {
			unlink("/uploads/$username/images/banner/$filename"); //cleanup: delete source file
 			unlink("/uploads/$username/images/banner/thumbs/$filename"); //cleanup: delete thumbnail file
			die("<div><b>Error: Problem occurred with Database Query!</b><br /><br /><b>File:</b> " . __FILE__ . "<br /><b>Line:</b> " . __LINE__ . "<br /><b>MySQL Error Num:</b> " . mysql_errno() . "<br /><b>MySQL Error:</b> " . mysql_error() . "</div>");
		}
	}

	// Print success message and how the thumbnail image created
	if (empty($errors)) {
		echo "<p>Thumbnail created Successfully!</p>\n";
		echo "<img src=\"/uploads/$username/images/banner/thumbs/$filename\" alt=\"New image thumbnail\" />\n";
		echo "<br />\n";
	}
}
if (isset($errors['move_source'])) { echo "\t\t<div>Error: Failure occurred moving uploaded source image!</div>\n"; }
if (isset($errors['thumb'])) { echo "\t\t<div>Error: Failure occurred creating thumbnail!</div>\n"; }
?>
	<form action="" enctype="multipart/form-data" method="post">
		<input type="hidden" name="MAX_FILE_SIZE" value="<?php echo MAX_SIZE_IN_BYTES; ?>" />
		<label for="<?php echo IMG_FIELD_NAME; ?>">Image:</label> <input type="file" name="<?php echo IMG_FIELD_NAME; ?>" id="<?php echo IMG_FIELD_NAME; ?>" />
<?php
if (isset($errors['img_empty'])) { echo "\t\t<div class=\"validationerrorText\">Required!</div>\n"; }
if (isset($errors['img_type'])) { echo "\t\t<div class=\"validationerrorText\">File type not allowed! GIF/JPEG/PNG only!</div>\n"; }
if (isset($errors['img_size'])) { echo "\t\t<div class=\"validationerrorText\">File size too large! Maximum size should be " . MAX_SIZE_IN_BYTES . "bytes!</div>\n"; }
if (isset($errors['img_error'])) { echo "\t\t<div class=\"validationerrorText\">File upload error occured! Error code: {$_FILES[IMG_FIELD_NAME]['error']}</div>\n"; }
if (isset($errors['img_nametoolong'])) { echo "\t\t<div class=\"validationerrorText\">Filename too long! 200 Chars max!</div>\n"; }
if (isset($errors['img_fileexists'])) { echo "\t\t<div class=\"validationerrorText\">An image file already exists with that name!</div>\n"; }
?>
		<br /><input type="submit" name="submit" id="image1" value="Upload image" />
	</form>
</body>
</html>
<?php

#################################
#
#      F U N C T I O N S
#
#################################

/*
 *  Function: make_thumb
 *
 *  Creates the thumbnail image from the uploaded image
 *  the resize will be done considering the width and
 *  height defined, but without deforming the image
 *
 *  @param   $sourceFile   Path anf filename of source image
 *  @param   $destFile     Path and filename to save thumbnail as
 *  @param   $new_w        the new width to use
 *  @param   $new_h        the new height to use
*/
function make_thumb($sourceFile, $destFile, $new_w=false, $new_h=false)
{
	if ($new_w === false) { $new_w = THUMB_WIDTH; }
	if ($new_h === false) { $new_h = THUMB_HEIGHT; }

	// Get image extension
	$ext = strtolower(getExtension($img_name));

	// Copy source
	switch($ext) {
		case 'jpg':
		case 'jpeg':
			$img_src = imagecreatefromjpeg($sourceFile);
			break;
		case 'png':
			$img_src = imagecreatefrompng($sourceFile);
			break;
		case 'gif':
			$img_src = imagecreatefromgif($sourceFile);
			break;
		default:
			return false;
	}
	if (!$img_src) { return false; }

	// Get dimmensions of the source image
	$old_x = imageSX($src_img);
	$old_y = imageSY($src_img);

	// Calculate the new dimmensions for the thumbnail image
	// 1. calculate the ratio by dividing the old dimmensions with the new ones
	// 2. if the ratio for the width is higher, the width will remain the one define in WIDTH variable
	//    and the height will be calculated so the image ratio will not change
	// 3. otherwise we will use the height ratio for the image
	//    as a result, only one of the dimmensions will be from the fixed ones
	$ratio1 = $old_x / $new_w;
	$ratio2 = $old_y / $new_h;
	if ($ratio1 > $ratio2) {
		$thumb_w = $new_w;
		$thumb_h = $old_y / $ratio1;
	} else {
		$thumb_h = $new_h;
		$thumb_w = $old_x / $ratio2;
	}

	// Create a new image with the new dimmensions
	$dst_img = ImageCreateTrueColor($thumb_w, $thumb_h);

	// Resize the big image to the new created one
	imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $thumb_w, $thumb_h, $old_x, $old_y);

	// Output the created image to the file. Now we will have the thumbnail into the file named by $filename
	switch($ext) {
		case 'jpg':
		case 'jpeg':
			$result = imagepng($dst_img, $destFile);
			break;
		case 'png':
 			$result = imagegif($dst_img, $destFile);
			break;
		case 'gif':
			$result = imagejpeg($dst_img, $destFile);
			break;
		default:
			//should never occur!
	}
	if (!$result) { return false; }

	// Destroy source and destination images
	imagedestroy($dst_img);
	imagedestroy($src_img);

	return true;
}

/*
 *  Function: getExtension
 *
 *  Returns the file extension from a given filename/path
 *
 *  @param   $str   the filename to get the extension from
*/
function getExtension($str)
{
	return pathinfo($filename, PATHINFO_EXTENSION);
}

?>

  • 0

oh hmmm, ya interesting.

well you included some breaks in some lines, or maybe just the way the code was pasted into the forum, so it caused some syntax errors.

um, ok so now it shows but then after an upload this happens

Notice: A session had already been started - ignoring session_start() in /services7/webpages/util/s/a/saiya.site.aplus.net/helixagent.com/public/dbc.php on line 56

Change image

Notice: Use of undefined constant __DIR__ - assumed '__DIR__' in /services7/webpages/util/s/a/saiya.site.aplus.net/helixagent.com/public/upload.php on line 75

Notice: Use of undefined constant __DIR__ - assumed '__DIR__' in /services7/webpages/util/s/a/saiya.site.aplus.net/helixagent.com/public/upload.php on line 76

Notice: Use of undefined constant __DIR__ - assumed '__DIR__' in /services7/webpages/util/s/a/saiya.site.aplus.net/helixagent.com/public/upload.php on line 89

Notice: Use of undefined constant __DIR__ - assumed '__DIR__' in /services7/webpages/util/s/a/saiya.site.aplus.net/helixagent.com/public/upload.php on line 101

Notice: Use of undefined constant __DIR__ - assumed '__DIR__' in /services7/webpages/util/s/a/saiya.site.aplus.net/helixagent.com/public/upload.php on line 101

Notice: Use of undefined constant __DIR__ - assumed '__DIR__' in /services7/webpages/util/s/a/saiya.site.aplus.net/helixagent.com/public/upload.php on line 101

Notice: Use of undefined constant __DIR__ - assumed '__DIR__' in /services7/webpages/util/s/a/saiya.site.aplus.net/helixagent.com/public/upload.php on line 101

Notice: Use of undefined constant __DIR__ - assumed '__DIR__' in /services7/webpages/util/s/a/saiya.site.aplus.net/helixagent.com/public/upload.php on line 101

Notice: Use of undefined constant __DIR__ - assumed '__DIR__' in /services7/webpages/util/s/a/saiya.site.aplus.net/helixagent.com/public/upload.php on line 105

Error: Failure occurred moving uploaded source image!

what does undefined mean? Also, I have permissions to 777 on my folders, so i'm hoping thats not the problem... let me see if the mk_dir function needs some fine tuning

hey, i got around those errors tho...

error_reporting(E_ALL & ~E_NOTICE);

atleast it makes the screen more neater and only shows me whats actually wrong

  • 0

__DIR__ is a special constant created by PHP and works just like the ones we create ourselves like define('MY_NAME', 'Lyndon Brown'); echo MY_NAME;

I'm using it to help specify the exact location of directories

The problem is that the __DIR__ only exists in PHP version 5.3 or greater, and I guess your host has an older version... :(

I've just fixed a few more bugs I found, and I'll attach it this time, in case the forum messes it up again:

whatever.phpFetching info...

whatever2.phpFetching info...

The second has __DIR__ removed

On my system the second now works perfectly, aside from it creating the directories in C:\ instead of my web directory, and that's because I'm using the version without __DIR__ now, the one with causes an error, which I think is simply due to permissions on my system.

Try the one without and see how it goes, it might be that it tries to create the directories in the root of the web server which isn't good, in which case, there are two solutions:

a) you convince your webhost to upgrade PHP to v5.3 for you (would be great anyway!), and you try the one with __DIR__, and it then works perfectly

b) we'll (i'll) have to come up with some code to generate the base directory some other way

  • 0
  On 04/05/2010 at 04:47, theblazingangel said:

__DIR__ is a special constant created by PHP and works just like the ones we create ourselves like define('MY_NAME', 'Lyndon Brown'); echo MY_NAME;

I'm using it to help specify the exact location of directories

The problem is that the __DIR__ only exists in PHP version 5.3 or greater, and I guess your host has an older version... :(

I've just fixed a few more bugs I found, and I'll attach it this time, in case the forum messes it up again:

whatever.phpFetching info...

whatever2.phpFetching info...

The second has __DIR__ removed

On my system the second now works perfectly, aside from it creating the directories in C:\ instead of my web directory, and that's because I'm using the version without __DIR__ now, the one with causes an error, which I think is simply due to permissions on my system.

Try the one without and see how it goes, it might be that it tries to create the directories in the root of the web server which isn't good, in which case, there are two solutions:

a) you convince your webhost to upgrade PHP to v5.3 for you (would be great anyway!), and you try the one with __DIR__, and it then works perfectly

b) we'll (i'll) have to come up with some code to generate the base directory some other way

I tried both,

you can access the page again if you log in... upload.php is with __DIR__ upload2.php without

  • 0
  On 04/05/2010 at 04:47, theblazingangel said:

__DIR__ is a special constant created by PHP and works just like the ones we create ourselves like define('MY_NAME', 'Lyndon Brown'); echo MY_NAME;

I'm using it to help specify the exact location of directories

The problem is that the __DIR__ only exists in PHP version 5.3 or greater, and I guess your host has an older version... :(

I've just fixed a few more bugs I found, and I'll attach it this time, in case the forum messes it up again:

whatever.phpFetching info...

whatever2.phpFetching info...

The second has __DIR__ removed

On my system the second now works perfectly, aside from it creating the directories in C:\ instead of my web directory, and that's because I'm using the version without __DIR__ now, the one with causes an error, which I think is simply due to permissions on my system.

Try the one without and see how it goes, it might be that it tries to create the directories in the root of the web server which isn't good, in which case, there are two solutions:

a) you convince your webhost to upgrade PHP to v5.3 for you (would be great anyway!), and you try the one with __DIR__, and it then works perfectly

b) we'll (i'll) have to come up with some code to generate the base directory some other way

hey, I just popped into the root folder and found a bunch directories that got made... a bunch of __DIR__\...\...\ and a \uploads. Maybe there's a slash somewhere that shouldn't be? thats why its not recognizing my dirs?

heh, look what happens when you try to upload an image

post-15029-12729496292109.jpg

  • 0

Right, well now it's just down to directory issues. First thing you need to do is go and plead with your webhost to upgrade you to PHP 5.3. If they won't then that causes problems! (if they do, the one WITH __DIR__ should work!)

Edit: the __DIR__ directories are there because, since you've got an old version of PHP (which version btw?), PHP decided to treat __DIR__ as the string '__DIR__' and used it as part of the directory name to create. delete all of these dir's!

  • 0
  On 04/05/2010 at 05:08, theblazingangel said:

Right, well now it's just down to directory issues. First thing you need to do is go and plead with your webhost to upgrade you to PHP 5.3. If they won't then that causes problems! (if they do, the one WITH __DIR__ should work!)

hmmm, i see... hey quick question. what did you mean about the sessions thing being called twice?

I have a session_start() in my dbc.php > page_protect() function. and in the sessions.php

in the sessions.php i have page_protect() declared at the top. I tried all sorts of combinations but when I do, my sessions variables I called in the sessions.php aren't showing whenever I echo them out.

p.s. do you have paypal?

  • 0

precisely, when the code runs, session_start() is being run twice, once in the dbc.php code, and once by page_protect(). You only want it to run once! When you include a file, php runs the code in it!

e.g. if i had these three files:

a.php

<?php echo 'a'; ?>

b.php

<?php echo 'b'; ?>

c.php

<?php
include('a.php');
include('b.php');
echo 'c';
?>

and you run c.php, you'll end up with 'abc'!!!

Yes, I'll pm you my paypal if your being generous :p :cool:

Really got to get to sleep now, 7am here...

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • Xbox July Update brings PC app cloud upgrades and Rewards support by Pulasthi Ariyasinghe The Xbox team at Microsoft has another major series of updates hitting its platforms. The Xbox July Update is primarily bringing new features to the PC application, while cloud gaming services are also being upgraded. A lot of these additions were a part of Insider testing sessions previously, but now they are ready for prime time. First off, Game Pass Ultimate members can now stream supported games over the cloud, as long as they own a copy on the Xbox store. The Stream Your Own Game feature can be accessed via the Cloud Gaming section on the Xbox PC app. The feature now boasts over 250 supported games too, with recent additions including classic Assassin's Creed titles, LEGO games, and the Saints Row series. Upcoming games to the lineup include RoboCop: Rogue City – Unfinished Business, Tetris Effect Connected, Wo Long Fallen Dynasty, and more. Check here to get a full list of games. Don't forget that cross-device play histories on the app also landed for Xbox Insiders earlier this month, letting players see what games they have been playing regardless of console, PC, or cloud Xbox platform being used. Another new feature announced today as landing on the PC app this month is Rewards with Xbox. Only available in select markets and only for those above 18, Rewards can now be found in the Home section with easy access to checking out how to get more points, track progress, and more. The Xbox and Antstream Arcade joint venture, the Retro Classics app, is gaining seven more games too. These are Caesar, Conquests of Camelot: The Search for the Grail, Gabriel Knight: Sins of the Fathers, Hard Head, Okie Dokie, Skate Boardin’, and Skeleton+. Lastly, mouse and keyboard as well as touch controls continue to roll out for more games, with Police Simulator: Patrol Officers getting support for the former while South of Midnight has gained the latter.
    • https://www.neowin.net/news/a-...erating-online-chat-client/ It looks like they're trying to reinvent the abaonded wheel.
  • Recent Achievements

    • Week One Done
      NeoWeen earned a badge
      Week One Done
    • One Month Later
      BA the Curmudgeon earned a badge
      One Month Later
    • First Post
      Doreen768 earned a badge
      First Post
    • One Month Later
      James_kobe earned a badge
      One Month Later
    • Week One Done
      James_kobe earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      657
    2. 2
      ATLien_0
      255
    3. 3
      Xenon
      166
    4. 4
      neufuse
      146
    5. 5
      +FloatingFatMan
      121
  • Tell a friend

    Love Neowin? Tell a friend!