Forum Moderators: coopster

Message Too Old, No Replies

How to make pages available only to those who are logged in

         

paseo

7:11 pm on Jan 30, 2008 (gmt 0)

10+ Year Member



Hey,

I was able to successfully setup a very basic user login using php sessions. The thread should still be close to the top if you want to reference it.

My question/problem: I have within my index.php file a function called myaccount. This is just an h3 line with data that is pulled dynamically from MySQL. Easy enough...What i wanted was for the main content on index.php to be replaced with the myaccount table when somebody requests index.php?myaccount. Everything worked great except for when a user is not logged in and manually types in index.php?myaccount into the url. The content is replaced with the h3 line however no dynamic data is filled in (as expected). My goal was to make the myaccount function available only to those who have logged in (i.e. $_SESSION['id]') is active. The only possible way i found for this to work was to create another function, and place all my main content into this function and call on this function when appropriate. I have posted my code below...I KNOW there has to be a better way of doing this.

I check to make sure that $_SESSION['id'] is active first to give access to the myaccount function. I.E. i want to make sure that the user is logged in first before accessing the myaccount function. I then check to see if myaccount is _GET (index.php?myaccount). if it is, then the myaccount function is called. If it isnt, then i stil want my main content to be displayed...If the $_SESSION['id'] is not populated, then just display the content..I hope this makes sense.

THANKS!

<?php
if ($_SESSION['id']) {

if (isset($_GET["myaccount"])) {
myaccount(); }
else {content(); }
}

else {
content();
}

function myaccount() {
<h2>Account Details for: <?php echo $_SESSION['lastname'],", ",$_SESSION['firstname'];?></h2>
}

function content() {
echo "<p>THIS IS THE MAIN PAGE CONTENT</p>";
}
?>

cameraman

7:56 pm on Jan 30, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



There's several ways you could do it. Assuming that you've got all the appropriate html stuff and this is just filling in the parts of the body:
if (isset($_SESSION['id']) && isset($_GET["myaccount"])) {
myaccount();
exit;
} // EndIf signed in & wants account line
Anything below this won't get sent to the browser if the if statement evaluates true, so you can take your other content back out of the function.

paseo

7:57 pm on Jan 30, 2008 (gmt 0)

10+ Year Member



Thats exactly what i needed..a way to say AND in an IF statement.

THANKS!

coopster

8:26 pm on Jan 30, 2008 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



They are called logical operators [php.net], paseo.