Login Script Problem

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
jayshields
DevNet Resident
Posts: 1912
Joined: Mon Aug 22, 2005 12:11 pm
Location: Leeds/Manchester, England

Login Script Problem

Post by jayshields »

Hi again,

I have just resorted to making a login page with sessions for my script, because HTTP Authentication won't work because of my web server.

Anyway, I seem to be logged in all the time, and when I use my logout page it says:

Code: Select all

PHP Warning: session_destroy(): Trying to destroy uninitialized session in D:\Webspace\wrightandshields.co.uk\wwwroot\PHPJayMail\index.php on line 89
Here is my login code:

Code: Select all

//***LOGIN***

if ((isset($_SESSION['username'])) || (isset($_SESSION['password']))) { //If the username or password do not match
	
	if (isset($_POST['login'])) {

		if (($_POST['username'] == PJMUSER) && ($_POST['password'] == PJMPASS)) {

			//Start the session and register the values
			session_start();
			$_SESSION['username'] = $_POST['username'];
			$_SESSION['password'] = $_POST['password'];
		
		} else {

			$message = "<font color=\"red\">Sorry, your username and password did not match.<br>Please try again!</font><br>";

		}

	}

	//Display the title image
	echo "<img src=\"images/login.jpg\" alt=\"Login!\"><br>";

	//Display the error message if there is one
	if (isset($message)) {
		echo $message;
	}

	//Start the login form/table
	echo '<form action="index.php" action="post">';
	echo '<table border="0">';
	echo '<tr>';
	echo '<td><b>Username: </b></td>';
	echo '<td><input type="text" size="20" value="'; 
	if (isset($_POST['username'])) {
			echo $_POST['username'];
	}
	echo '"></td>';
	echo '</tr>';
	echo '<tr>';
	echo '<td><b>Password: </b></td>';
	echo '<td><input type="password" size="20"></td>';
	echo '</tr>';
	echo '<tr>';
	echo '<td colspan="2" align="center"><input type="submit" name="login" value="Login"></td>';
	echo '</tr>';
	echo '</table>';
	echo '</form>';

} else { //If the session is set run the rest of the script

//*********
Ok, so after the else is all my script, and the if statement is ended right at the bottom.

My logout script is here:

Code: Select all

//***LOGOUT***

if ($_GET['page'] == "logout") {
	
	//if (isset($_SESSION['username'])) {
		//Log the user out
		$_SESSION = array(); //Destroy the variables in the $_SESSION array
		session_destroy(); //Destroy the session itself
		setcookie (session_name(), '', time()-300, '/', '', 0); //Destroy the cookie
	//}

	//Show the image header
	echo '<img src="images/logout.jpg" alt="Logout!"><br><br>';

	//Show the success message
	echo 'You are now logged out.<br><br>';

}

//*********
If you want the full script instead of just snippets say so and I'll post it, but it's 361 lines long.

Thanks in advance.
Sander
Forum Commoner
Posts: 38
Joined: Sat Aug 06, 2005 12:43 pm

Post by Sander »

What the error means is that either you never started the session, or that the session was already destroyed (In any case, there isn't an active session).

Are you sure you did a session_start() ? You always have to start the session, even when you only want to destroy it. Another reason could be that you already destroyed the session.
User avatar
jayshields
DevNet Resident
Posts: 1912
Joined: Mon Aug 22, 2005 12:11 pm
Location: Leeds/Manchester, England

Post by jayshields »

thanks for your input but as you can see in the login section, i start the session just before i assign the variables to the session array.

i only use session_destroy(); once in my whole script, and that is there, on the logout section.

what i am trying to get across is that i do not understand why it is showing me the contents of my script (udner the login section) when i have not logged in, also, when i try to logout, it tells me that i do not have a session to destroy, meaning that i am obviously not logged in, leading back to the question i first stated, i shouldnt even be able to see the logout page because i am not logged in! (the logout section is in the } else { section after the login section.

to help confusion i will post my full script in pastebin to not waste too much room on this thread, the link is here:
http://pastebin.com/345332
please be aware that pastebin postings time out in around 2 days, so if you viewing this 2 days after i posted it the link wont work, pm me if you want to see it and it isnt working.

thanks in advance for any more help.
Sander
Forum Commoner
Posts: 38
Joined: Sat Aug 06, 2005 12:43 pm

Post by Sander »

jayshields wrote:thanks for your input but as you can see in the login section, i start the session just before i assign the variables to the session array.
There's your problem, you're only starting the session in the login section :wink:
User avatar
jayshields
DevNet Resident
Posts: 1912
Joined: Mon Aug 22, 2005 12:11 pm
Location: Leeds/Manchester, England

Post by jayshields »

ok i moved session_start() to the included header and put it on the very first line, i don't get the error anymore, but i still have the same problem, i go to index.php, and it is asif im logged in, i can access all the pages, and if i go to the logout page, it logs me out, but i can stil navigate the index.php asif i am logged in.

My full index.php is here:

Code: Select all

<?php

/* ------------------------------------------ *
 *                                            *
 *        --== [ PHPJayMail ] ==--            *
 *                                            *
 * All aspects of this script were designed   *
 * and created by Jay Shields. You can email  *
 * me with any questions at                   *
 * jay@jay-designs.co.uk. I would also be     *
 * grateful if you paid a visit to my website *
 * at http://www.jay-designs.co.uk. If you    *
 * would like to use my script please leave   *
 * the copyright footer and logo intact as    *
 * it is copyright Jay-Designs.co.uk 2005.    *
 *                                            *
 * Thanks, and have fun using my script!      *
 * ------------------------------------------ */

//**DO NOT EDIT ANYTHING IN THIS FILE UNLESS YOU KNOW WHAT YOU ARE DOING!**

//Connect to MySQL
require_once ('config.php');

//Include the HTML header
include ('includes/header.html');

//***LOGIN***

if ((isset($_SESSION['username'])) || (isset($_SESSION['password']))) { //If the username or password do not match
	
	if (isset($_POST['login'])) {

		if (($_POST['username'] == PJMUSER) && ($_POST['password'] == PJMPASS)) {

			//Register the values of the session
			$_SESSION['username'] = $_POST['username'];
			$_SESSION['password'] = $_POST['password'];
		
		} else {

			$message = "<font color=\"red\">Sorry, your username and password did not match.<br>Please try again!</font><br>";

		}

	}

	//Display the title image
	echo "<img src=\"images/login.jpg\" alt=\"Login!\"><br>";

	//Display the error message if there is one
	if (isset($message)) {
		echo $message;
	}

	//Start the login form/table
	echo '<form action="index.php" action="post">';
	echo '<table border="0">';
	echo '<tr>';
	echo '<td><b>Username: </b></td>';
	echo '<td><input type="text" size="20" value="'; 
	if (isset($_POST['username'])) {
			echo $_POST['username'];
	}
	echo '"></td>';
	echo '</tr>';
	echo '<tr>';
	echo '<td><b>Password: </b></td>';
	echo '<td><input type="password" size="20"></td>';
	echo '</tr>';
	echo '<tr>';
	echo '<td colspan="2" align="center"><input type="submit" name="login" value="Login"></td>';
	echo '</tr>';
	echo '</table>';
	echo '</form>';

} else { //If the session is set run the rest of the script

//*********

//***LOGOUT***

if ($_GET['page'] == "logout") {
	
	//if (isset($_SESSION['username'])) {
		//Log the user out
		$_SESSION = array(); //Destroy the variables in the $_SESSION array
		session_destroy(); //Destroy the session itself
		setcookie (session_name(), '', time()-300, '/', '', 0); //Destroy the cookie
	//}

	//Show the image header
	echo '<img src="images/logout.jpg" alt="Logout!"><br><br>';

	//Show the success message
	echo 'You are now logged out.<br><br>';

}

//*********

//***ERROR PAGE***

if ($_GET['page'] != "" && $_GET['page'] != "sendmail" && $_GET['page'] != "recipients" && $_GET['page'] != "logout") {
	echo "<font color=\"red\">You are trying to access a page which doesn't exist!</font>";
}

//*********

//***HOME***
if ($_GET['page'] == "") {

	//Print the content
	echo '<img src="images/welcome.jpg" alt="Welcome!"><br><br>';
	echo 'Please select a page from the list below:<br>';
	echo '<a href="index.php?page=recipients">Recipients</a><br>';
	echo '<a href="index.php?page=sendmail">Send Mail</a>';

}
//*********

//***SENDMAIL***

if ($_GET['page'] == "sendmail") {
	
	//Start the if send conditional
	if (isset($_POST['send'])) {
		
		//Fetch the mailing list
		$query = "SELECT * FROM " . TBL_NAME; //Build the query to select all the info
		$result = @mysql_query ($query); //Execute the query
		
		//Initialize an approved check variable
		$approvedchk = "wrong";

		//Send the mail
		while ($row = mysql_fetch_array ($result, MYSQL_NUM)) { //while there are records being fetched from the table
			if ($row['3'] == 'Y') { //if the user has been approved

				//Set the approved check variable to right
				$approvedchk = "right";
				
				//Set the first 2 mail params
				$to = $row['1']; //Store the users email in the to parameter
				$subject = $_POST['subject']; //Set the subject from the form input
				
				//Make the headers param
				if ($_POST['templates'] == "None") { //If no template is being used...
					echo ""; //Do nothing
				} else { //If a template is being used
					$headers = 'MIME-Version: 1.0' . "\r\n"; //Set the headers to enable HTML email
					$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
				}

				$from = "From: " . NAME . ' <' . EMAILADD . '>' . "\r\n"; //Make the from section of the headers param
				if (REPLYNAME == '' && REPLYEMAILADD == '') { //If there isnt a replyname or replyemail set...
					echo ""; //Do nothing
				} else { //If there is a reply name or a replay email set
					$replyto = "Reply-To: " . REPLYNAME . ' <' . REPLYEMAILADD . '>' . "\r\n"; //Make the reply to section of the headers param
				}
				$headers .= $from . $replyto; //combine the from and reply to sections and add them to the headers param
				
				//Variables which can be used in templates
				$toname = $row['2']; //Set the persons name
				$date = date("d.m.y"); //Set the current date

				//Build the message
				if ($_POST['templates'] == "none") { //If no template is being used...
					$message = nl2br($_POST['newsletterbody']); //Just send the newsletter body
				} elseif ($_POST['templates'] == "WrightandShields") { //If the WrightandShields template is being used...
					$message = file_get_contents ('templates/' . $_POST['templates'] . '/header1.html'); //Send the top of the header
					$message .= $date; //Then the date
					$message .= file_get_contents ('templates/' . $_POST['templates'] . '/header2.html'); //Then the middle of the header
					$message .= $toname; //Then the name
					$message .= file_get_contents ('templates/' . $_POST['templates'] . '/header3.html'); //Then the bottom of the header
					$message .= $_POST['newsletterbody']; //Then the newsletter body
					$message .= file_get_contents ('templates/' . $_POST['templates'] . '/footer.html'); //Then the footer
				} else { //If any other template is being used...
					$message = file_get_contents ('templates/' . $_POST['templates'] . '/header.html'); //Send the header
					$message .= $_POST['newsletterbody']; //Then the newsletter body
					$message .= file_get_contents ('templates/' . $_POST['templates'] . '/footer.html'); //Then the footer
				}
				
				//Send the email
				mail ($to, $subject, $message, $headers);

				//Set a success message
				$success = "<font color=\"green\">Your emails have been successfully sent!</font><br>";

			}
		}

	} //End the if send conditional

	//Print the title
	echo '<img src="images/sendmail.jpg" alt="Send Mail!"><br>';

	//Show the messages if there are any...
	if ($approvedchk == "wrong") {
		echo '<font color="red">No emails were sent because no one on your mailing list has been approved!<br>Please go to the <a href="index.php?page=recipients">Recipients page</a> and approve some people!</font><br>';
	}
	
	if (isset($success)) {
		echo $success;
	}

	//Get the templates
	$dir = "templates/";
	
	//Start the form
	echo '<form action="index.php?page=sendmail" method="post">';

	//Start the table
	echo '<table border="0">';

	//Start the drop down selection box
	echo '<tr><td><b>Select a template: </b></td>';
	echo '<td align="left"><select align="left" name="templates">';
	echo '<option value="none">None</option>';

	// Open a known directory, and proceed to read its contents
	if (is_dir($dir)) {
	   if ($dh = opendir($dir)) {
		   while (($file = readdir($dh)) !== false) {
			    if ($file == ".." || $file == ".") {
					echo "";
				} else {
					echo "<option value=\"$file\">$file</option>\n";
				}
		   }
		   echo '</select></td></tr>';
		   closedir($dh);
	   }
	}
	
	//Show the subject entry input box
	echo '<tr><td><b>Subject: </b></td><td align="left"><input align="left" type="text" name="subject" size="20" maxlength="30"></td>';

	//Show the main email input
	echo '<tr><td colspan="2"><b>Newsletter Body: </b></td></tr>';
	echo '<tr><td colspan="2" align="left"><textarea cols="60" rows="20" name="newsletterbody"></textarea></td></tr>';

	//Show the Send button and finish the form
	echo '<tr><td colspan="2" align="center"><input type="submit" name="send" value="Send!"></td></tr>';
	echo '</table>';
	echo '</form>';

}

//*********

//***RECIPIENTS***
if ($_GET['page'] == "recipients") {

	//If records need to be changed...
	if ($_POST['delete'] || $_POST['approve'] || $_POST['unapprove']) {
		
		if (isset($_POST['box'])) { //If a checkbox has been ticked...
			
			//Make and set the values of the boxArray
			$boxArray = array();
			$boxArray = $_POST['box'];

			foreach ($boxArray as $x) { //For each value in the boxArray
				
				if ($_POST['delete']) { //If the user wants to delete a record...
					$query = "DELETE FROM " . TBL_NAME . " WHERE user_id = " . $x; //Make a query to delete the record
					$result = @mysql_query ($query); //Execute the query
					$message = "<font color=\"green\">You successfully deleted the record(s)!</font><br>"; //Set the message
				}

				if ($_POST['approve']) { //If the user wants to approve a record...
					$query = "UPDATE " . TBL_NAME . " SET approved = 'Y' WHERE user_id = " . $x; //Make a query to approve a record
					$result = @mysql_query ($query); //Execute the query
					$message = "<font color=\"green\">You successfully approved the record(s)!</font><br>"; //Set the message
				}

				if ($_POST['unapprove']) { //If the user wants to unapprove a record...
					$query = "UPDATE " . TBL_NAME . " SET approved = 'N' WHERE user_id = " . $x; //Make a query to unapprove a record
					$result = @mysql_query ($query); //Execute the query
					$message = "<font color=\"green\">You successfully unapproved the record(s)!</font><br>"; //Set the message
				}

			}

		}

	} //End of the change records conditional

	//Print the title
	echo '<img src="images/recipients.jpg" alt="Recipients!">';

	//Print the message if there is one
	if (isset($message)) {
		echo '<br><br>' . $message;
	}

	//Fetch the mailing list
	$query = "SELECT * FROM " . TBL_NAME . " ORDER BY name ASC";
	$result = @mysql_query ($query);

	if ($row = mysql_fetch_array ($result)) { //If no records are in the table make an empty one...
		echo "";
	} else {
		echo '<form action="index.php?page=recipients" method="post">';
		echo '<table border="1" bordercolor="black">';
		echo '<tr bgcolor="black">';
		echo '<td><b><font color="white">Name</font></b></td><td><b><font color="white">Email</font></b></td><td><b><font color="white">Approved?</font></b></td><td><b><font color="white">Select</font></b></td>';
		echo '</tr>';
		echo '<tr>';
		echo '<td colspan="4" align="center">';
		echo 'There are no records to display!';
		echo '</td>';
		echo '</tr>';
	}

	//Initialise the $first variable
	$first = 1;
	
	//Print the mailing list
	while ($row = mysql_fetch_array ($result, MYSQL_NUM)) {
		if ($first) {
			echo '<form action="index.php?page=recipients" method="post">';
			echo '<table border="1" bordercolor="black">';
			echo '<tr bgcolor="black">';
			echo '<td><b><font color="white">Name</font></b></td><td><b><font color="white">Email</font></b></td><td><b><font color="white">Approved?</font></b></td><td><b><font color="white">Select</font></b></td>';
			echo '</tr>';
		}
		echo '<tr';
		if ($row['3'] == "N") { //If the record is not approved...
			echo ' bgcolor="#FF6666"'; //Make the background of the row yellow
		} elseif ($row['3'] == "Y") { //If the record is approved...
			echo ' bgcolor="white"'; //Make the background of the row pink
		}
		echo '>';
		echo '<td>' . $row['2'] . '</td>';
		echo '<td>' . $row['1'] . '</td>';
		echo '<td align="center">' . $row['3'] . '</td>';
		echo '<td align="center"><input type="checkbox" name="box[' . $row[0] . ']" value="' . $row[0] . '">';
		echo '</tr>';
		$first = 0;
	}
	echo '<tr>';
	echo '<td colspan="4" align="center">With selected: <input type="submit" name="delete" value="Delete"> <input type="submit" name="approve" value="Approve"> <input type="submit" name="unapprove" value="Unapprove"></td>';
	echo '</tr>';
	echo '</form>';
	echo '</table>';

} 
//*********

//Close the MySQL connection
mysql_close();

//Include the HTML footer
include ('includes/footer.html');

} //End the login conditional

?>
That should give you a clearer picture of what i am trying to achieve.

If you would like the code for the header and footer HTML files just says so.

TIA.
josh
DevNet Master
Posts: 4872
Joined: Wed Feb 11, 2004 3:23 pm
Location: Palm beach, Florida

Post by josh »

stick some var_dump($_SESSION) all over the place, so you can see if the session is really being destroyed, or if the session is being destroyed but your script thinks you're still logged in etc... also make sure your script forces the user to have a consistent www. in front of the domain, if a session is initialized at example.com and then you go to http://www.example.com the session could be lost under certain configurations.
User avatar
jayshields
DevNet Resident
Posts: 1912
Joined: Mon Aug 22, 2005 12:11 pm
Location: Leeds/Manchester, England

Post by jayshields »

this is not the problem. if the session wasnt/isnt set, it would show me the login page, but it doesnt! and it never has shown me it!

so there must be a session set somewhere, but when i destroy it, i still dont get shown the login page!

also, the www. doesnt make any difference, because if it didnt recognise the session because of that, it would ofcourse show me the login page! which it doesnt!

!!!!!!!!

hehe.

sorry for the exclamation marks :)

tia.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

the script you most recently posted requires that a session exist and one of the variables as well for it to even try to match the login information as well as the login page.

your setcookie() call will do nothing, by the way.
User avatar
jayshields
DevNet Resident
Posts: 1912
Joined: Mon Aug 22, 2005 12:11 pm
Location: Leeds/Manchester, England

Post by jayshields »

there were a few problems i found in my script thanks to your help.

first of all my first conditional should be !isset || !isset, to make sure either arent set. also i didnt include names for the username and password input boxes!

for some strange reason, the form uses the get method even though it is set to post, so i had to change to $_GET['username'] and same for the other variables.

but atleast now it is working, but my script runs really slow :(
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

it's actually not set to post, it's action is set to post. You want to use method="post" ;)
User avatar
jayshields
DevNet Resident
Posts: 1912
Joined: Mon Aug 22, 2005 12:11 pm
Location: Leeds/Manchester, England

Post by jayshields »

LOL indeed. i should stop trying to code at 2am, i did the HTML form for the login page then, and i didnt name the input boxes and used action=post instead of method=post !

DOH!

but thanks for spotting them and helping me.

now all i need is some people to test my script for me...

is there a special forum for posting finished scripts for testing?

cheers.
d3ad1ysp0rk
Forum Donator
Posts: 1661
Joined: Mon Oct 20, 2003 8:31 pm
Location: Maine, USA

Post by d3ad1ysp0rk »

Not really, that seems to be done by the developer themselves ;)
User avatar
jayshields
DevNet Resident
Posts: 1912
Joined: Mon Aug 22, 2005 12:11 pm
Location: Leeds/Manchester, England

Post by jayshields »

as far as i know it works a treat.

but i would like someone else to follow my instructions in my readme.txt and see if they can install it properly and make sure it works fine for them also, i wouldnt want to release a script that doesnt work now would i? :)
d3ad1ysp0rk
Forum Donator
Posts: 1661
Joined: Mon Oct 20, 2003 8:31 pm
Location: Maine, USA

Post by d3ad1ysp0rk »

You could always set up a site for it and make sure everyone knows it's BETA, and have a place for them to submit errors they get?
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

this sounds like an excellent opportunity to learn about unit tests
Post Reply