PHP - List Of Logged In Users.
Hi all,
Does anyone know of an effective way of find out whether a user is still logged in and they haven't left? Sam Similar TutorialsWhat are the different ways you can keep a User "logged in"? From what I *vaguely* recall from a year or two ago when I read a whole hoard of PHP books, you commonly use cookies and sessions. But I'm asking this more from an OOP standpoint than a PHP standpoint. Let's say I have a User record in my database, and a User comes along and attempts to log in. In OOP terms, I would think you'd call some class to help log them in, and upon successfully logging in, you would "load" the User object into memory and set the "LoggedIn" field to "True". Then as long as that field was set in their object, they could surf all over the place and do things like change their account and buy things. Is that how you would do it in OOP? TomTees Sites such as this one often show the logged on users and guests.
I have no reason to need to do so, but am curious on how this is accomplished.
For users, yes, you've authenticated them and logged them on regardless of IP address, but how do you know they didn't just close their browser?
For guests, are they just using IP address? And still, how do you know when they leave?
PS. How should I include an image in a post like I did? What I did was first attach a file, and then edit the post to include that file as an image. Couldn't seem to include an image off my local PC. Not a better way?
Attached Files
Capture.PNG 4.13KB
0 downloads Hello all...fairly new to this php/mysql thing... working on my final project thats due in about 24 hours... and i hit a rut... im making a pretty basic, online classifieds site. users can sign up, login, post new listings and view others listings by clicking on different categories. the problem i am having right now is this...When the user clicks on "My listings" i need it to pull only the listings that were created by that users user_id, which is the primary key in my user_info table...my professor suggested storing it in hidden field through the login submit button...very confused and frustrated... any help is much appreciated... I am trying to build my own custom login script. What I am trying to achieve is once a user has logged in depending on wether they have checked the keep me logged in checkbox they have two options. If they haven't checked it then it creates session variables only, and if they have checked it it also creates cookie variable as well as the session variables. If they then close their browser / tab without logging out and then revisit the site they will get redirected to login page because the active session variable is no longer there. As soon as they land on the loggin page, it automatically checks for the cookie variable and if it exists, it uses it to login and redirect them automatically. However the problem that I am facing is that the session variable is still being trashed after a default amount of idle time and forcing a login. My goal is that the user shouldn't have to re-login unless they have either clicked the logout button. Can someone please have a look through my solution and advise me as to wether this is the correct method that I am implementing, if there is an easier way to achieve what I want, and is this a secure way to handle user logins. Thanks in advance. Andrew Here is the check code I have placed at the top of each admin page. Code: [Select] <?php session_start(); $url = (!empty($_SERVER['HTTPS'])) ? "https://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'] : "http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']; $uid = $_SESSION['uid']; if (!isset($uid)) { header('location:login.php?redirect='.$url); exit(); } ?> Next we have the code for the login.php file. Code: [Select] <?php include ('functions.php'); ?> <?php get_header('login'); ?> <div id="login-result"> <?php connect(); $redirect = htmlspecialchars(mysql_real_escape_string(addslashes($_GET['redirect']))); if(isset($_COOKIE['remembered'])){ $username = htmlspecialchars(mysql_real_escape_string(addslashes($_COOKIE['remembered']['username']))); $password = htmlspecialchars(mysql_real_escape_string(addslashes($_COOKIE['remembered']['password']))); $sql = "SELECT * FROM usersT WHERE username='$username' AND password='$password'"; $result = mysql_query($sql); $count = mysql_num_rows($result); $row = mysql_fetch_array($result); $uid = $row['uid']; $fname = $row['firstname']; $lname = $row['lastname']; $role = $row['role']; if($count==1){ $sql2 = "UPDATE usersT SET status = '1' WHERE uid = '$uid'"; $result2 = mysql_query($sql2); if($result2){ session_register("uid"); session_register("uname"); session_register("ulevel"); $_SESSION["uid"] = $uid; $_SESSION["uname"] = $fname; $_SESSION["ufullname"] = $fname . " " .$lname; $_SESSION["urole"] = $role; $home = get_option('home'); if(!empty($redirect)) { header( 'Location: '. $redirect ) ; exit(); } else { header( $home ) ; exit(); } } } else { echo "<div class=\"error rounded5 shadow\">Invalid username or password!</div>"; } } else if (isset($_POST['admin_login'])){ if(isset($_POST["username"]) && isset($_POST["password"])){ $username_p = htmlspecialchars(mysql_real_escape_string(addslashes($_POST["username"]))); $password_p = htmlspecialchars(mysql_real_escape_string(addslashes($_POST["password"]))); $psw = md5($password_p); $sql3 = "SELECT * FROM usersT WHERE username='$username_p' AND password='$psw'"; $result3 = mysql_query($sql3); $count3 = mysql_num_rows($result3); $row3 = mysql_fetch_array($result3); $uid = $row3['uid']; $fname = $row3['firstname']; $lname = $row3['lastname']; $role = $row3['role']; if($count3==1){ $sql4 = "UPDATE usersT SET status = '1' WHERE uid = '$uid'"; $result4 = mysql_query($sql4); if($result4){ session_register("uid"); session_register("uname"); session_register("ulevel"); $_SESSION["uid"] = $uid; $_SESSION["uname"] = $fname; $_SESSION["ufullname"] = $fname . " " .$lname; $_SESSION["urole"] = $role; $home = get_option('home'); if(isset($_POST['remember'])) { setcookie("remembered[username]", $username, time() + 86400 * 365 * 2); setcookie("remembered[password]", $psw, time() + 86400 * 365 * 2); } if(!empty($redirect)) { header( 'Location: '. $redirect ) ; exit(); } else { header( $home ) ; exit(); } } } else { echo "<div class=\"error rounded5 shadow\">Invalid username or password!</div>"; } } } ?> </div><!-- / login-results --> <div id="login" class="rounded5 shadow"> <form name="loginform" id="loginform" action="<?php $_SERVER['PHP_SELF']; ?>" method="post"> <p> <label for="username">Username<br> <input type="text" name="username" id="username" class="rounded5" value="<?php echo $username_p; ?>" size="20" tabindex="10" /></label> </p> <p> <label for="password">Password<br> <input type="password" name="password" id="password" class="rounded5" value="<?php echo $password_p; ?>" size="20" tabindex="20" /></label> </p> <p class="submit"> Keep me logged in<input type="checkbox" name="remember" id="remember" /><br /><br /><a href="" class="left">Lost your password?</a> <input type="submit" name="admin_login" id="admin_login" class="btn rounded10 right" value="Log In" tabindex="100" /> </p> <div class="cleaner"></div><!-- / cleaner --> </form> </div><!-- / login--> <?php get_footer('login'); ?> Finally here is the code I am using for the logout.php page. Code: [Select] <?php session_start(); include ('functions.php'); connect(); $uid = mysql_real_escape_string($_SESSION['uid']); $sql = "UPDATE usersT SET status = '0' WHERE uid = '$uid'"; $result = mysql_query($sql); if($result) { session_unset(); session_destroy(); if(isset($_COOKIE['remembered'])){ setcookie("remembered[username]", $username, time() - 3600); setcookie("remembered[password]", $psw, time() - 3600); header("location: login.php"); } exit(); } else { echo "You couldn't be logged out at this time."; } ?> Hai..
currently i am developing client dashboard using php/mysql.Here is my problem i need to create a tab named as notes.Using this tab the logged in users can add a new note or edit his existing note and save as text file.. I have dynamic images that have the "Like" button, it's basically like a wishlist. The way I want it to work is that when a user is not logged in, the 'Like' button will navigate them to a login popup (which I already made). how can I list a user from a table and show the results in a grid with different color eg frist in blue color second on white , 3rd on blue 4th in with etc
I do need to set select command and I have db name and ip on a file called dbconfig.php from wd calendar so I just need to read the info
ps: I cant post links so search for wd calendar and see the dbconfig.php in php folder
The following code is what I have already done, but I have just realised that the way I have done this will not enable me to display the online users in alphabetical order, I do not know a way how to do this. Any help or suggestions? Thanks $friend_query = mysql_query("SELECT * FROM friend_request WHERE user='{$user_id}'"); $friend_id_array = ""; while($row = mysql_fetch_assoc($friend_query)) { $friend_id = $row['friend_id']; $more_query = mysql_query("SELECT * FROM friend_request WHERE friend_id='{$user_id}'"); while($row_more = mysql_fetch_assoc($more_query)) { $more_friend_id = $row_more['user']; //all friends in an array $friend_id_array = $friend_id_array.$friend_id."/".$more_friend_id; $friend_id_array = explode('/', $friend_id_array); $friend_count = count($friend_id_array); //how many of the friends are online $online_count = 0; for($i=0;$i<$friend_count;$i++) { $query_online = mysql_query("SELECT loggedin, fname, mname, lname FROM users WHERE id='{$friend_id_array[$i]}'"); //get loggedin and names $row = mysql_fetch_assoc($query_online); $loggedin = $row['loggedin']; if($loggedin == "1") //if logged in { $online_count++; // final number off people online } } } } Quote Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /home/largemus/public_html/assets/inc/upcoming.php on line 15 i have hidden connection details for this example Code: [Select] <?php $host=""; // Host name $username=""; // Mysql username $password=""; // Mysql password $db_name=""; // Database name $tbl_name=""; // Table name // Connect to server and select database. mysql_connect("$host", "$username", "$password")or die("cannot connect server "); mysql_select_db("$db_name")or die("cannot select DB"); $sql="SELECT * FROM $tbl_name WHERE user = $session->clientid ORDER BY date ASC LIMIT 3;"; $result=mysql_query($sql); while($rows=mysql_fetch_array($result)){ ?> <div style="width:385px;"> <table style="width: 385px; text-align:center;"> <tr> <td style="width: 121px"><h3>Client</h3></td> <td style="width: 100px"><h3>Occasion</h3></td> <td style="width: 80px"><h3>Location</h3></td> <td><h3>Date</h3></td> </tr> </table> <table style="width: 385px"> <tr> <td style="width: 121px"> <p><? echo $rows['clientid']; ?></p> </td> <td style="width: 100px"> <p><? echo $rows['occasion']; ?></p> </td> <td style="width: 80px"> <p><? echo $rows['location']; ?></p> </td> <td> <p><? echo $rows['date']; ?></p> </td> </tr> </table> </div> <? } mysql_close(); //close database ?> Hello
I am trying to work out how many regular users I have to my site and how long those users tend to be users..
So, I have a table that logs every time a user visits my site and logs in, it stores the date / time as a unix timestamp and it logs their user id.
I started by getting the id's of any user who logs in more than 5 times in a specified period, but now I want to extend that...
SELECT userID as user, count(userID) as logins FROM login_history where timestamp > UNIX_TIMESTAMP('2014-06-01 00:00:00') and timestamp < UNIX_TIMESTAMP('2014-07-01 00:00:00') group by user having logins > 5; I just discovered that I have a major security flaw with my website. Anyone who logs in to the website can easily access other users information as well as delete and edit other users information just by changing the ID variable in the address bar. I have user ID Session started on these pages but still people can do anything they like with other users information just by editing the address bar. For example if your logged in in the address bar of www.mywebsite.com/delete_mystuff.php?id=5 and change the "5" say to a "9" then you will have access to user#9 information. Every important page that I have has this code: Code: [Select] session_start(); if (!isset($_SESSION['user_id'])) { // Start defining the URL. $url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']); // Check for a trailing slash. if ((substr($url, -1) == '/') OR (substr($url, -1) == '\\') ) { $url = substr ($url, 0, -1); // Chop off the slash. } // Add the page. $url .= '/index.php'; ob_end_clean(); // Delete the buffer. header("Location: $url"); exit(); // Quit the script. } else { //Else If Logged In Run The Script if((isset($_GET['id'])) && (is_numeric($_GET['id']))) { $id = (int) $_GET['id']; } elseif ((isset($_POST['id'])) && (is_numeric($_POST['id']))) { $id = (int) $_POST['id']; } else { echo ' No valid ID found, passed in url or form element'; exit(); } What am I doing wrong? Please help if you know how to correct this. Many thanks in advance. Alright, so I'm fairly new to PHP coding and I still have a ton to learn, so it's not surprising that I ran into a problem pretty quickly. I've setup a database and even managed to scrap together a SIMPLE member management system. All of it works, but I still need one thing. A lot of sites I visit which allow users to signup have this at the top; Login or Register. Nothing huge, just in the corner, know what I mean? I was wondering how I do this? Also, after someone logs in, how do I change that to show "You are logged in as [username] and then a logout option? Hi guys, Im building a website for a company http://www.eminence-logistics.co.uk and the client wants a log in system which im having problems with. The registration system is all working fine. If you go to the website you can see where the login form is. Now when the user isn't logged in i need the form to show, but when the user IS logged in i would like a message replacing the form saying welcome, along with a log out button. How do i do this? Thankyou very much Enlighten Hi guys, Have a wierd scenario where my brain is simply refusing to think. I have small script which let's a user log in through a login screen. Thats ok. I can check whether the user is already logged in the same machine through sessions. My requirement is : I need to restrict the same username logging in from multiple computers at any one given time. In other words, a user can not use two machines to login at the same time. Can someone please suggest a method to solve this scenario. Your help is very much appreciated. Cheers Elabuwa Hello all, This has probably been asked before but I couldn't find through search. And I'm pretty sure is not possible, but... Is there a way of displaying the windows logged on user? or get the name of the compter? as I know I can get the ip address. The reason I ask. Each user has their own network account but on occasion we need to log on a user as a generic account we have. And I want to check if it's this user accessing the page so different options etc can be displayed. I could use the computer name to check this as we log all activity. I could then query the log using the comp name to find logged on user. Unfortunately the log does not hold ip, which would seem obvious but it doesn't Many Thanks Hi i am wondering how i can redirect someone that's not logged in?
I am making a login system and I have done it before. ryanweekly.com is the site I am trying to put it on. Here is the script to the home page. Here is the code I am having a problem with: Code: [Select] <?php if (empty($username)) include ("loginbar.php"); if (!empty($username)) include ("logged.php"); ?> Code: [Select] <?PHP $username = $_SESSION['MM_Username']; ?> <?php require_once('Connections/ryanweeklyusers.php'); ?> <?php if (!function_exists("GetSQLValueString")) { function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") { if (PHP_VERSION < 6) { $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue; } $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue); switch ($theType) { case "text": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "long": case "int": $theValue = ($theValue != "") ? intval($theValue) : "NULL"; break; case "double": $theValue = ($theValue != "") ? doubleval($theValue) : "NULL"; break; case "date": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "defined": $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue; break; } return $theValue; } } ?> <?php // *** Validate request to login to this site. if (!isset($_SESSION)) { session_start(); } $loginFormAction = $_SERVER['PHP_SELF']; if (isset($_GET['accesscheck'])) { $_SESSION['PrevUrl'] = $_GET['accesscheck']; } if (isset($_POST['username'])) { $loginUsername=$_POST['username']; $password=$_POST['password']; $MM_fldUserAuthorization = ""; $MM_redirectLoginSuccess = "index.php"; $MM_redirectLoginFailed = "index.php?reg=loger"; $MM_redirecttoReferrer = false; mysql_select_db($database_ryanweeklyusers, $ryanweeklyusers); $LoginRS__query=sprintf("SELECT username, password FROM users WHERE username=%s AND password=%s", GetSQLValueString($loginUsername, "text"), GetSQLValueString($password, "text")); $LoginRS = mysql_query($LoginRS__query, $ryanweeklyusers) or die(mysql_error()); $loginFoundUser = mysql_num_rows($LoginRS); if ($loginFoundUser) { $loginStrGroup = ""; if (PHP_VERSION >= 5.1) {session_regenerate_id(true);} else {session_regenerate_id();} //declare two session variables and assign them $_SESSION['MM_Username'] = $loginUsername; $_SESSION['MM_UserGroup'] = $loginStrGroup; if (isset($_SESSION['PrevUrl']) && false) { $MM_redirectLoginSuccess = $_SESSION['PrevUrl']; } header("Location: " . $MM_redirectLoginSuccess ); } else { header("Location: ". $MM_redirectLoginFailed ); } } $ruser = $_REQUEST['Y2User-53201']; ?> <!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"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Ryan Weekly</title> <style type="text/css"> body { background-color: #E3E5E2; } </style> <script src="SpryAssets/SpryValidationTextField.js" type="text/javascript"></script> <link href="SpryAssets/SpryValidationTextField.css" rel="stylesheet" type="text/css" /> </head> <style type="text/css"> <!-- body { font-size:12px; font-family:Verdana, Arial, Helvetica, sans-serif; } div#wrapper { width: 80%; background-color:#FFFFFF; margin-top: 50px; margin-bottom: 50px; margin-left: auto; margin-right: auto; padding: 0px; border: thin solid #000000; } div#header { padding: 15px; margin: 0px; text-align: center; } div#nav { width: 25%; padding: 10px; margin-top: 1px; float: left; border: thin solid #000000; } div#main { margin-left: 30%; margin-top: 1px; padding: 10px; border: thin solid #000000; } div#underhead { padding: 15px; margin: 0px; border-top: thin solid #000000; } { ul.nav a:hover, ul.nav a:active, ul.nav a:focus { /* this changes the background and text color for both mouse and keyboard navigators */ background: #6F7D94; color: #FFF; } .content ul, .content ol { padding: 0 15px 15px 40px; /* this padding mirrors the right padding in the headings and paragraph rule above. Padding was placed on the bottom for space between other elements on the lists and on the left to create the indention. These may be adjusted as you wish. */ } /* ~~ The navigation list styles (can be removed if you choose to use a premade flyout menu like Spry) ~~ */ ul.nav { list-style: none; /* this removes the list marker */ border-top: 1px solid #666; /* this creates the top border for the links - all others are placed using a bottom border on the LI */ margin-bottom: 15px; /* this creates the space between the navigation on the content below */ } ul.nav li { border-bottom: 1px solid #666; /* this creates the button separation */ } ul.nav a, ul.nav a:visited { /* grouping these selectors makes sure that your links retain their button look even after being visited */ padding: 5px 5px 5px 15px; display: block; /* this gives the link block properties causing it to fill the whole LI containing it. This causes the entire area to react to a mouse click. */ text-decoration: none; background: #8090AB; color: #000; } ul.nav a:hover, ul.nav a:active, ul.nav a:focus { /* this changes the background and text color for both mouse and keyboard navigators */ background: #6F7D94; color: #FFF; } /* ~~ The footer ~~ */ .footer { padding: 10px 0; background: #6F7D94; position: relative;/* this gives IE6 hasLayout to properly clear */ clear: both; /* this clear property forces the .container to understand where the columns end and contain them */ } /* ~~ miscellaneous float/clear classes ~~ */ .fltrt { /* this class can be used to float an element right in your page. The floated element must precede the element it should be next to on the page. */ float: right; margin-left: 8px; } .fltlft { /* this class can be used to float an element left in your page. The floated element must precede the element it should be next to on the page. */ float: left; margin-right: 8px; } .clearfloat { /* this class can be placed on a <br /> or empty div as the final element following the last floated div (within the #container) if the #footer is removed or taken out of the #container */ clear:both; height:0; font-size: 1px; line-height: 0px; } --> </style> <body> <div align="Left"> <p><img src="indexp.png" width="728" height="90" /></p> </div> <div id="underhead"> <?php if (empty($username)) include ("loginbar.php"); if (!empty($username)) include ("logged.php"); ?> <?PHP $justreg = $_REQUEST['reg']; if ($justreg == yes) echo 'Thanks For Registering!'; if ($justreg == loger) echo 'There was an error while tring to log you in.'; if ($justreg == out) echo 'You were logged out!'; ?> </div> <?php include("menu.php"); ?> <div id="main"> <p>Welcome To Ryan Weekly! The all new and improved site!</p> <p>I have a song on itunes!</p> <p> <object width="400" height="160"> <param name="movie" value="http://widget.tunecore.com/swf/tc_run_h_v2.swf?widget_id=62316" /> <param name="allowFullScreen" value="true" /> <param name="allowscriptaccess" value="always" /> <embed src="http://widget.tunecore.com/swf/tc_run_h_v2.swf?widget_id=62316" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="400" height="160"></embed> </object> </p> </div> Ryan Weekly 2009 - 2011 (May 11, 2011 at 6:00PM Is our 3 Year anniversary!) <script type="text/javascript"> var sprytextfield1 = new Spry.Widget.ValidationTextField("sprytextfield1"); var sprytextfield2 = new Spry.Widget.ValidationTextField("sprytextfield2"); </script> </body> </html> hello i am stuck and hoping you can help, i have created this function and its not working correctly, what i am trying to do is when someone is logged in they get this line of code echo "<a href=\"update-content.php?id=5\">Edit</a> | <a href=\"delete-content.php?id=5\">Delete</a>"; which is ok as i dont want that to work yet and if your not logged in you dont get it. i have added //show when logged in and show not logged in so you know which code i want it to load when at the moment its only loading the not logged in one even if you are. i have looked on google read up on php sites but cant figure out how to do it, so hoping you guys will tell me were i gone wrong and how to correct it, thanks again heres the code. function get_left() { if (isset($_GET['page'])) { $page = $_GET['page']; //Show Page not logged in $sql = "SELECT title,body FROM content WHERE page = '$page' AND location = 'left' AND disabled = 'no' ORDER BY id"; $res = mysql_query($sql) or die (mysql_error()); while($row = mysql_fetch_assoc($res)){ echo '<h1>' . $row['title'] . '</h1>'; echo '<p>' . $row['body'] . '</p>'; } } //show when logged in elseif ($_SESSION['username']&&(isset($_GET['page']))){ $sql = "SELECT title,body FROM content WHERE page = '$page' AND location = 'left' AND disabled = 'no' ORDER BY id"; $res = mysql_query($sql) or die (mysql_error()); while($row = mysql_fetch_assoc($res)){ echo '<h1>' . $row['title'] . '</h1>'; echo '<p>' . $row['body'] . '</p>'; echo "<a href=\"update-content.php?id=5\">Edit</a> | <a href=\"delete-content.php?id=5\">Delete</a>"; } } } Please help with my register page: http://www.retroandvintage.co.uk/register.php after someone has registered they are stuck on reg_script.php and don't get redirected back to main.php being already logged in?! here is my code: Code: [Select] <?php session_start(); include_once("config.php"); //include_once("functions.php"); require_once('captcha/recaptchalib.php'); $privatekey = "6Ldhhr4SAAAAAKFoL2INOZV0_VuF6_z3OwDjVFNn"; $resp = recaptcha_check_answer ($privatekey, $_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]); if (!$resp->is_valid) { // What happens when the CAPTCHA was entered incorrectly die ("The reCAPTCHA wasn't entered correctly. Go back and try it again." . "(reCAPTCHA said: " . $resp->error . ")"); } else { // Your code here to handle a successful verification $rsPostCode = $_POST['rsPostCode']; $rsGender = $_POST['rsGender']; $rsUser = $_POST['rsUser']; $rsPass = $_POST['rsPass']; $rsEmail = $_POST['rsEmail']; $rsMobile = $_POST['rsMobile']; $rsAge = $_POST['rsAge']; $sql = "INSERT INTO members_copy (RSPOSTCODE, RSGENDER, RSUSER, RSPASS, RSEMAIL, RSMOBILE, RSAGE) VALUES ('$rsPostCode', '$rsGender', '$rsUser', '$rsPass', '$rsEmail', '$rsMobile', '$rsAge');"; //echo $sql; mysql_query($sql); $ebits = ini_get('error_reporting'); error_reporting($ebits ^ E_NOTICE); /* Login script: This script does the following: Checks that the user is NOT already logged in - if they are they are redirected to the members page by the 'checkLoggedIn()' function. Checks if the login form has been submitted - if so, the 'login' and 'password' fields are checked to ensure they are of the correct format and length. If there are any problems here an error is added to the $messages array and then the script executes the 'doIndex()' function - this function basically outputs the main 'index' page for this script - ie the login form. If there are no problems with the previous step, the 'login' and 'password' field data is passed to the 'checkPass' function to check that an entry exists in the 'users' table for that login/password pair. If nothing is returned from the 'checkPass()' function, an error is added to the $messages array and the 'doIndex()' function is called as above. If a row of data is returned from the 'users' table, the data is passed to the 'cleanMemberSession()' function - which initializes session variables and logs the user in. The user is then forwarded to the members page. If the form hasn't yet been submitted, then the 'doIndex()' function is called and the login page is displayed. */ // Check user not logged in already: checkLoggedIn("no"); // Page title: $title="Member Login Page"; // if $submit variable set, login info submitted: if(isset($_POST["Register"])) { // // Check fields were filled in // // login must be between 4 and 15 chars containing alphanumeric chars only: field_validator("rsUser", $_POST["rsUser"], "alphanumeric", 4, 15); // password must be between 4 and 15 chars - any characters can be used: field_validator("rsPass", $_POST["rsPass"], "string", 4, 15); // if there are $messages, errors were found in validating form data // show the index page (where the messages will be displayed): if($messages){ doIndex(); // note we have to explicity 'exit' from the script, otherwise // the lines below will be processed: exit; } // OK if we got this far the form field data was of the right format; // now check the user/pass pair match those stored in the db: /* If checkPass() is successful (ie the login and password are ok), then $row contains an array of data containing the login name and password of the user. If checkPass() is unsuccessful however, $row will simply contain the value 'false' - and so in that case an error message is stored in the $messages array which will be displayed to the user. */ if( !($row = checkPass($_POST["rsUser"], $_POST["rsPass"])) ) { // login/passwd string not correct, create an error message: $messages[]="Incorrect login/password, try again"; } /* If there are error $messages, errors were found in validating form data above. Call the 'doIndex()' function (which displays the login form) and exit. */ if($messages){ doIndex(); exit; } /* If we got to this point, there were no errors - start a session using the info returned from the db: */ cleanMemberSession($row["rsUser"], $row["rsPass"]); // and finally forward user to members page (populating the session id in the URL): header("Location: main.php"); /* This function displays the default 'index' page for this script. This consists of just a simple login form for the user to submit their username and password. */ } } ?> Hi, I want have this code (below), how would I check if a user is logged in? I want to make it so they can only see 500 chars, or the full thing if they're logged in. Thanks! Code: [Select] public function __construct( $data=array() ) { if ( isset( $data['id'] ) ) $this->id = (int) $data['id']; if ( isset( $data['publicationDate'] ) ) $this->publicationDate = (int) $data['publicationDate']; if ( isset( $data['title'] ) ) $this->title = preg_replace ( "/[^\.\,\-\_\'\"\@\?\!\:\$ a-zA-Z0-9()]/", "", $data['title'] ); if ( isset( $data['summary'] ) ) $this->summary = preg_replace ( "/[^\.\,\-\_\'\"\@\?\!\:\$ a-zA-Z0-9()]/", "", $data['summary'] ); if ( isset( $data['content'] ) ) $this->content = $data['content']; if ( isset( $data['tags'] ) ) $this->tags = $data['tags']; } |