PHP - User Sessions To Determine Accounts Logged In
I would like my website to show which users are logged in.
Is there a simple way of retrieving all session ids from the server that have been allocated and are active in order to do this? I know this could lead to faulty information, but would appear to be the simplest and reliable. Thanks. Similar TutorialsI 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."; } ?> Hey everybody,
I'm a noob when it comes to PHP so I have a few questions.
I'm in the planning stages for a new website and I need it to do something but I'm not sure how. People would have to log into my website in order to make a purchase and I need to be able to link their account with the software they bought. Think of it like a bit like Steam, you buy the game and its right there in your library.
The way I see it working is they buy their software and when they look in their profile they see a list of the stuff they've bought and have the ability to open it.
The Ecommerce company I'm looking to sign up with to make the transactions and keep the money side of it in order (FastSpring) don't have a way of tracking user purchases so I have to come up with a way of doing my end.
What I would like to know is what language is best to do this? I assume PHP would be the best especially considering the website itself is likely to be built in WordPress.
Secondly does anybody have any links to articles, videos or tutorials on this as I have not been able to find any all afternoon. I know they're going to be out there but I'm not having any luck finding them
Thanks for your time
I'm working on a new user submission form and I was wondering whether it's safe to send a confirmation letter to the user using their hashed password as their confirmation code? Since this is a hashed password it can't be decrypted (I believe), the password is useless because it's always hashed before login so it can't be used to login to the system, it's only being emailed to the user who's account is tied to the account, and it would save me the option of having to store a confirmation code field in my DB. Is this safe? Hello, i've got some shop script which has 2 payment modules which i'd like to use for something else, the payment modules only work if the user is logged in though, i tried to make them standalone scripts but that didn't work out too well. So now i decided to go another way and just let everyone have the same session so everyone will be using the same username&password automatically. the index file looks like this: Code: [Select] <?php include('./inc/config.php'); include('./inc/functions.php'); include('./lang/'.$language.'.lng'); $id = addslashes($_REQUEST["id"]); $user = addslashes($_REQUEST["username"]); $pass = addslashes($_REQUEST["password"]); $language = strtolower($language); if(empty($id)) $id =1; $file = mysql_query('SELECT * FROM navi_'.$language.' WHERE id="'.$id.'"'); if(mysql_num_rows($file)>0) $file = mysql_fetch_array($file); else $file = mysql_fetch_array(mysql_query('SELECT * FROM navi_'.$language.' WHERE id="404"')); if(!empty($user) AND !empty($pass)) {$query = mysql_query('SELECT * FROM users WHERE username="'.$user.'" AND pass="'.md6($pass).'"'); if(mysql_num_rows($query) == 1) {$_SESSION[$session_prefix."user"] = ucfirst($user); echo'<meta http-equiv="refresh" content="0; url=index.php?id=8">';} else $error = 'Username oder Passwort ist falsch.';} include('./designe/'.$designe.'/head.tpl'); include('./designe/'.$designe.'/navi.php'); include('./designe/'.$designe.'/middle.tpl'); if(file_exists('./pages/'.$file["file"])) {echo'<h1>'.ucfirst($file["title"]).'</h1>'; include('./pages/'.$file["file"]);} if(!empty($error)) echo '<font color="red">'.$error.'</font>'; include('./designe/'.$designe.'/foot.tpl'); ?> Now i tried alot of things including adding: Code: [Select] session_start(); $_SESSION["username"] = "peter"; $_SESSION["user"] = "peter"; $_SESSION["id"] = "1"; $_SESSION["pass"] = "peter"; $_SESSION["password"] = "peter"; or Code: [Select] $id = "1"; $user = "peter"; $username = "peter"; $pass = "peter"; $password = "peter"; also a combination of both, nothing works, but i don't understand why ? Any help is appreciated. /Edit, i tried adding it to the paymentmodule .php aswell, but no luck. 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 want to add another form field to determine if a user is human and not spam bots. I looked into CAPTCHA, but I think those are annoying. I was thinking about just having the user enter (5+5) and if the answer is not ten, then displaying a incorrect value message. If correct submit form and info to the Database. Not sure how to do that with what I currently have coded though so need some help with that part. Here is the current code. <?PHP require_once "formvalidator.php"; $show_form=true; if(isset($_POST['Submit'])) { $validator = new FormValidator(); $validator->addValidation("FirstName","req","Please fill in FirstName"); $validator->addValidation("LastName","req","Please fill in LastName"); $validator->addValidation("UserName","req","Please fill in UserName"); $validator->addValidation("Password","req","Please fill in a Password"); $validator->addValidation("Password2","req","Please re-enter your password"); $validator->addValidation("Password2","eqelmnt=Password","Your passwords do not match!"); $validator->addValidation("email","email","The input for Email should be a valid email value"); $validator->addValidation("email","req","Please fill in Email"); $validator->addValidation("Zip","req","Please fill in your Zip Code"); $validator->addValidation("Security","req","Please fill in your Security Question"); $validator->addValidation("Security2","req","Please fill in your Security Answer"); if($validator->ValidateForm()) { $con = mysql_connect("localhost","beatthis","Jim2Drew!") or die('Could not connect: ' . mysql_error()); mysql_select_db("beatthis_beatthis") or die(mysql_error()); $FirstName=mysql_real_escape_string($_POST['FirstName']); //This value has to be the same as in the HTML form file $LastName=mysql_real_escape_string($_POST['LastName']); //This value has to be the same as in the HTML form file $UserName=mysql_real_escape_string($_POST['UserName']); //This value has to be the same as in the HTML form file $Password= md5($_POST['Password']); //This value has to be the same as in the HTML form file $Password2= md5($_POST['Password2']); //This value has to be the same as in the HTML form file $email=mysql_real_escape_string($_POST['email']); //This value has to be the same as in the HTML form file $Zip=mysql_real_escape_string($_POST['Zip']); //This value has to be the same as in the HTML form file $Birthday=mysql_real_escape_string($_POST['Birthday']); //This value has to be the same as in the HTML form file $Security=mysql_real_escape_string($_POST['Security']); //This value has to be the same as in the HTML form file $Security2=mysql_real_escape_string($_POST['Security2']); //This value has to be the same as in the HTML form file $sql="INSERT INTO Profile (`FirstName`,`LastName`,`Username`,`Password`,`Password2`,`email`,`Zip`,`Birthday`,`Security`,`Security2`) VALUES ('$FirstName','$LastName','$UserName','$Password','$Password2','$email','$Zip','$Birthday','$Security','$Security2')"; //echo $sql; if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); } else{ mail('webguync@gmail.com','A profile has been submitted!',$FirstName.' has submitted their profile',$body); echo "<h3>Your profile information has been submitted successfully.</h3>"; } mysql_close($con); $show_form=false; } else { echo "<h3 class='ErrorTitle'>Validation Errors:</h3>"; $error_hash = $validator->GetErrors(); foreach($error_hash as $inpname => $inp_err) { echo "<p class='errors'>$inpname : $inp_err</p>\n"; } } } if(true == $show_form) { ?> <form name="test" id="ContactForm" method="POST" accept-charset="UTF-8" action="<?php echo $_SERVER['PHP_SELF'];?>"> <fieldset> <div class='normal_field'><label for="LastName">First Name</label></div> <div class='element_label'> <input type='text' name='FirstName' size='20'> </div> <div class='normal_field'><label for="LastName">Last Name</label></div> <div class='element_label'> <input type='text' name='LastName' size='20'> </div> </fieldset> <fieldset> <div class='normal_field'><label for="UserName">User Name</label></div> <div class='element_label'> <input type='text' name='UserName' size='20'> </div> <div class='normal_field'><label for="Password">Password</label></div> <div class='element_label'> <input type='password' name='Password' size='20'> </div> <div class='normal_field'><label for="Password2">Re-Enter Password</label></div> <div class='element_label'> <input type='password' name='Password2' size='20'> </div> <div class='normal_field'><label for="Email">Email</label></div> <div class='element_label'> <input type='text' name='email' size='20'> </div> </fieldset> <fieldset> <div class='normal_field'><label for="Zip">Zip Code</label></div> <div class='element_label'> <input type='text' name='Zip' size='20'> </div> <div class='normal_field'><label for="Birthday">Birthday(mm/dd/yyyy format)</label></div> <div class='element_label'> <input type='text' name='Birthday' size='20'> </div> <div class='normal_field'><label for="Security">Security Question</label></div> <div class='element_label'> <input type='text' name='Security' size='20'> </div> <div class='normal_field'><label for="Security2">Security Answer</label></div> <div class='element_label'> <input type='text' name='Security2' size='20'> </div> <div class='normal_field'><label for="math">What is 5 + 5?</label></div> <div class='element_label'> <input type='text' name='math' size='20'> </div> </fieldset> <div id="agree"> <label for="tos"> <input type="checkbox" id="tos" name="tos" value="yes" /> I have read and agree to the <a href="ajax/serviceterms.html" id="terms">Terms of Service</a>. </label> </div> <fieldset> <div id="service-terms" class="box rounded-all"></div> <div class="controls"> <input id="submit" type="submit" name="Submit" value="CREATE PROFILE"/> </div> </fieldset> </form> <?PHP }//true == $show_form ?> Hi there,
I've been searching the internet for the best way to check if the user has been logged in. Some codes have security breaches. So I'm not sure where to start.
Here's what I've come up with:
The user logs in and is checked whether he/she is a valid user, if not return false and if true carry on and create session, I read the post that Jacques1 made about session feedback and implemented what he said. After that the session variables are assigned and then the user id, session_id and a unique identifier to check against on each page load are inserted into a database and then the user is logged in.
Here's my code: (please note this is in a class and only shows the login function)
function Login($username, $password) { try { $db = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME.";charset=utf8", DB_USERNAME, DB_PASSWORD); $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); } catch(PDOException $ex) { echo "Unable to connect to DB"; error_log($ex->getMessage()); } try { $User_Info = $db->prepare("SELECT * FROM users WHERE username=:username"); $User_Info->bindValue(":username", $username, PDO::PARAM_STR); $User_Info->execute(); $Info = $User_Info->fetchAll(PDO::FETCH_ASSOC); $salt = $Info['salt']; $password = $salt . $password; $password = $this->CreateHash($password); $unique_key = $this->GenerateRandom(); $unique_key = $this->CreateHash($unique_key); $Check_User = $db->prepare("SELECT * FROM users WHERE username=:username AND password=:password"); $Check_User->bindValue(":username", $username, PDO::PARAM_STR); $Check_User->bindValue(":password", $password, PDO::PARAM_STR); $Check_User->execute(); if($Check_User->rowCount() > 0) { while($row = $Check_User->fetchAll(PDO::FETCH_ASSOC)) { session_destroy(); session_start(); $_SESSION = array(); session_regenerate_id(true); $_SESSION['username'] = $row['username']; $session_id = session_id(); $user_id = $row['id']; $Check_Logged_In = $db->prepare("DELETE FROM logged_in_users WHERE user_id=:userid"); $Check_Logged_In->bindValue(":user_id", $user_id, PDO::PARAM_STR); $Check_Logged_In->execute(); $has_changed = $Check_Logged_In->rowCount(); if($has_changed > 0) { $Logged_In = $db->prepare("INSERT INTO logged_in_users (id, user_id, session_id, unique_key) VALUES (NULL, :user_id, :session_id, :unique_key)"); $Logged_In->bindValue(":user_id", $user_id, PDO::PARAM_STR); $Logged_In->bindValue(":session_id", $session_id, PDO::PARAM_STR); $Logged_In->bindValue(":unique_key", $unique_key, PDO::PARAM_STR); $Logged_In->execute(); $affected_rows = $Logged_In->rowCount(); if($affected_rows > 0) { return true; } } return false; } } return false; } catch(PDOException $ex) { echo "Unable to complete query"; error_log($ex->getMessage()); } }Thanks 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']; } In the site I am making, the client wants one account for everyone (don't ask me why, it's a long, silly reason) And I'm wondering how I would configure mySQL to deal with that (I asked this in the mySQL area) and in PHP (For you guys ) what would I need to put in order for this to work. I'm very new with PHP and mySQL, so please forgive the nooby question. *EDIT* the admins have their own username and psw for adding, deleting, and editing articles. and that works. But all users that register will have this set user and psw displayed to them. I want to make it so they have to log in to see an article. Hi, I'm trying to display a user review system allowing user's to vote. This works fine, but I'm trying to user php to only display the rating system if the user is logged in and display alternate text if they are not. I am getting the following error: Parse error: syntax error, unexpected T_ELSE in XXXXXX on line 182 Here's the code: Code: [Select] <?php if ($_SESSION['username']){ $query = mysql_query("SELECT * FROM locations WHERE name = '$location'"); while($row = mysql_fetch_array($query)) { $rating = (int)$row[rating] ?> <div class="floatleft"> <div id="rating_<?php echo $row[id]; ?>"> <span class="star_1"><img src="fivestars/star_blank.png" alt="" <?php if($rating > 0) { echo"class='hover'"; } ?> /></span> <span class="star_2"><img src="fivestars/star_blank.png" alt="" <?php if($rating > 1.5) { echo"class='hover'"; } ?> /></span> <span class="star_3"><img src="fivestars/star_blank.png" alt="" <?php if($rating > 2.5) { echo"class='hover'"; } ?> /></span> <span class="star_4"><img src="fivestars/star_blank.png" alt="" <?php if($rating > 3.5) { echo"class='hover'"; } ?> /></span> <span class="star_5"><img src="fivestars/star_blank.png" alt="" <?php if($rating > 4.5) { echo"class='hover'"; } ?> /></span> </div> </div> <div class="star_rating"> (Rated <strong><?php echo $rating; ?></strong> Stars) </div> <div class="clearleft"> </div> } } <?php else { echo "Log in to review"; } ?> Thanks in advance for any help. I'm sure it's something trivial but I can't see it! How do I get the current logged in username or id using the Twitter API? I want to show data for logged in user, i am using sessions to login. This is the code i already have: // Connect to server and select database. mysql_connect("$host", "$username", "$password")or die("cannot connect"); mysql_select_db("$db_name")or die("cannot select DB"); //this selects everything for the current user, ready to be used in the script below $result = mysql_query("SELECT id, points, ingame_points, ingame_money, ingame_items FROM members; WHERE username = $_SESSION['myusername']"); //this function will take the above query and create an array while($row = mysql_fetch_array($result)) { //with the array created above, I can create variables (left) with the outputted array (right) $points = $row['points']; $id = $row['id']; $ingame_points = $row['ingame_points']; $ingame_money = $row['ingame_money']; $ingame_items = $row['ingame_items']; } Help ? This will be a little difficult to explain, but keep with me. On the profile.php page. It starts a new session. Code: [Select] // Connect to MySQL... $conn = mysql_connect($hostname, $username, $password) or die("Connecting to MySQL failed"); mysql_select_db($database, $conn) or die("Selecting MySQL database failed"); // Run our query, see if session username exists in session field... $sql="select username,email from user where username='{$_SESSION['user']}' limit 1"; $result=mysql_query($sql,$conn); // Parse our results into $data (as an associative array)... $data=mysql_fetch_assoc($result); // If one row was found in the result set, username exists... if (mysql_num_rows($result)==1) { $_SESSION['sellername'] = $data['username']; So what I am hoping that is doing, is the session named "sellername" is stored with the variable of the logged in user. In this example "testuser". Now the page updates.php will have an id attached to like so: updates.php?id=13. Which will have info only available for testuser's eyes. On the page it does this. Code: [Select] // Connect to MySQL... $conn = mysql_connect($hostname, $username, $password) or die("Connecting to MySQL failed"); mysql_select_db($database, $conn) or die("Selecting MySQL database failed"); // Run our query, see if session username exists in session field... $sql="select username from user where username='{$_SESSION['user']}' limit 1"; $result=mysql_query($sql,$conn); // Parse our results into $data (as an associative array)... $data=mysql_fetch_assoc($result); // If one row was found in the result set, username exists... if (mysql_num_rows($result)==1) { $query='select seller from listings where seller = "'.$data['username'].'"'; $queryresult=mysql_query($query,$conn); while($info = mysql_fetch_assoc($queryresult)){ if ( $_SESSION['sellername'] == $info['seller'] ){ The if statement should process: "If the session variable for 'sellername' equals the database entry 'seller' then display the rest of the page." However, no matter what user is logged, it will display the page. Any ideas? $sql = "SELECT id,username, date1, date2, total FROM datetable WHERE username = '".$_SESSION['uid']['username'] ."'"; Hello again, I ran into problem when trying to pull information for logged in user. I'm trying to display results for current user only who is signed in. Now I do have session_start(); and my query works if I replace '".$_SESSION['uid']['username'] ."'"; with 'specificusername' but when I run my current query displayed above it returns me all records with username = empty (I have some empty usernames for testing reasons). So that tells me that query cant find unique user name that is logged in. I don't get any errors and query still goes through. My datetable structure is
My uid is defined in another document like so and uses another table called "users" session_start(); $_SESSION['id'] = $row['idUsers']; $_SESSION['uid'] = $row['uidUsers']; $_SESSION['email'] = $row['emailUsers']; header("Location: ../member.php?login=success"); exit(); This query works on another page where it displays logged in username in html document. <?php echo $_SESSION['uid']; ?>
I have tried many different ways yesterday to modify my request ( WHERE username = $_SESSION['uid']; WHERE username = '".$_SESSION["uid"]) many other variations, but no matter what never returns logged in user information only empty username records. Can anyone see a problem with that query? or is it due to something else I'm missing?
Sorry, maybe this goes in MySQL thread not here in PHP page. If someone can, please move it. Thanks. Edited April 25, 2020 by sfia comment on where to post this topic on all my secured pages at the the very top the code is Code: [Select] <?php require ("u_check_login.php"); ?> and then the u_check_login.php code is Code: [Select] <?php require('database.php'); //Include DB connection information $ip = mysql_real_escape_string($_SERVER["REMOTE_ADDR"]); //Get user's IP Address $email = mysql_real_escape_string($_COOKIE['uemail']); //Get username stored in cookie $pp = mysql_real_escape_string($_COOKIE['pp']); if ($pp == 1){ $sessionid = mysql_real_escape_string($_COOKIE['sessionid']); //Get user's session ID $check = mysql_query("SELECT * FROM `users` WHERE `email` = '$email' AND `session_id` = '$sessionid' AND `login_ip` = '$ip' AND `pp` = '1' ") or die(mysql_error()); //Check if all information provided from the user is valid by checking in the DB $answer = mysql_num_rows($check); //Return number of results found. Equal to 0 if not logged in or 1 if logged in. if ($answer == 0 || $sessionid == '') { //Check if login is valid. If not redirect user to login page header('Location: ulogin.php'); exit(); } $row = mysql_fetch_array($check); $email = stripslashes($row['email']); }else{ header('Location: ulogin.php'); } ?> and this error is being displayed on my page that is supposed to not have let me on because i was not logged in Code: [Select] Warning: Cannot modify header information - headers already sent by (output started at /home/content/03/8587103/html/pinkpanthers/pinkpanthers.php:1) in /home/content/03/8587103/html/pinkpanthers/u_check_login.php on line 17 i need to display the fullname and email of the logged in user. <?php session_start(); mysql_connect("localhost", "root", "") or die(mysql_error()); mysql_select_db("db_register") or die(mysql_error()); $query = "SELECT` fullname`, `email` FROM `members` WHERE `username`='".$_SESSION['user']."' LIMIT 1"; if($doQuery = mysql_query($query)) { if(mysql_num_rows($doQuery)) { $user = mysql_fetch_assoc($doQuery); print_r($user); } else { echo 'No result returned for the query: '.$query; } } else { echo 'The following query failed: '.$query; } $id = $user['id']; $fullname = $user['fullname']; $email = $user['email']; } ?> <br> Fullname : <?php echo $fullname; ?> <br> Email : <? echo $email; ?> ?> HELP please . This topic has been moved to Third Party PHP Scripts. http://www.phpfreaks.com/forums/index.php?topic=357163.0 Hello, I'm trying to build a registration/login system. I managed to set it up but i need that for the user when he/she is logged in to display his own information and to manage to edit them, First i need to display them, because i seem to not be doing it.. i know it's easy in principal but i am really new at this... So here is my code: The login.php page Code: [Select] <?php include ('database_connection.php'); if (isset($_POST['formsubmitted'])) { // Initialize a session: session_start(); $error = array();//this aaray will store all error messages if (empty($_POST['e-mail'])) {//if the email supplied is empty $error[] = 'You forgot to enter your Email '; } else { if (preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/", $_POST['e-mail'])) { $Email = $_POST['e-mail']; } else { $error[] = 'Your EMail Address is invalid '; } } if (empty($_POST['Password'])) { $error[] = 'Please Enter Your Password '; } else { $Password = $_POST['Password']; } if (empty($error))//if the array is empty , it means no error found { $query_check_credentials = "SELECT * FROM members WHERE (Email='$Email' AND password='$Password') AND Activation IS NULL"; $result_check_credentials = mysqli_query($dbc, $query_check_credentials); if(!$result_check_credentials){//If the QUery Failed echo 'Query Failed '; } if (@mysqli_num_rows($result_check_credentials) == 1)//if Query is successfull { // A match was made. $_SESSION = mysqli_fetch_array($result_check_credentials, MYSQLI_ASSOC);//Assign the result of this query to SESSION Global Variable header("Location: page.php"); }else { $msg_error= 'Either Your Account is inactive or Email address /Password is Incorrect'; } } else { echo '<div class="errormsgbox"> <ol>'; foreach ($error as $key => $values) { echo ' <li>'.$values.'</li>'; } echo '</ol></div>'; } if(isset($msg_error)){ echo '<div class="warning">'.$msg_error.' </div>'; } /// var_dump($error); mysqli_close($dbc); } // End of the main Submit conditional. ?><!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>Login Form</title> <style type="text/css"> body { font-family:"Lucida Grande", "Lucida Sans Unicode", Verdana, Arial, Helvetica, sans-serif; font-size:12px; } .registration_form { margin:0 auto; width:500px; padding:14px; } label { width: 10em; float: left; margin-right: 0.5em; display: block } .submit { float:right; } fieldset { background:#EBF4FB none repeat scroll 0 0; border:2px solid #B7DDF2; width: 500px; } legend { color: #fff; background: #80D3E2; border: 1px solid #781351; padding: 2px 6px } .elements { padding:10px; } p { border-bottom:1px solid #B7DDF2; color:#666666; font-size:11px; margin-bottom:20px; padding-bottom:10px; } a{ color:#0099FF; font-weight:bold; } /* Box Style */ .success, .warning, .errormsgbox, .validation { border: 1px solid; margin: 0 auto; padding:10px 5px 10px 60px; background-repeat: no-repeat; background-position: 10px center; font-weight:bold; width:450px; } .success { color: #4F8A10; background-color: #DFF2BF; background-image:url('images/success.png'); } .warning { color: #9F6000; background-color: #FEEFB3; background-image: url('images/warning.png'); } .errormsgbox { color: #D8000C; background-color: #FFBABA; background-image: url('images/error.png'); } .validation { color: #D63301; background-color: #FFCCBA; background-image: url('images/error.png'); } </style> </head> <body> <form action="login.php" method="post" class="registration_form"> <fieldset> <legend>Login Form </legend> <p>Enter Your username and Password Below </p> <div class="elements"> <label for="name">Email :</label> <input type="text" id="e-mail" name="e-mail" size="25" /> </div> <div class="elements"> <label for="Password">Password:</label> <input type="password" id="Password" name="Password" size="25" /> </div> <div class="submit"> <input type="hidden" name="formsubmitted" value="TRUE" /> <input type="submit" value="Login" /> </div> </fieldset> </form> Go Back to <a href="#">Account Verification on sign up</a> </body> </html> This is the page's code where user is redirected after login Code: [Select] <?php ob_start(); session_start(); if(!isset($_SESSION['Username'])){ header("Location: login.php"); } ?> <!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>Member Area </title> <style type="text/css"> .success { border: 1px solid; margin: 0 auto; padding:10px 5px 10px 60px; background-repeat: no-repeat; background-position: 10px center; font-weight:bold; width:450px; color: #4F8A10; background-color: #DFF2BF; background-image:url('images/success.png'); } </style> </head> <body> <div class="success">Welcome , <?php echo $_SESSION['Username'] ; ?></div> <? $b = time (); $date1 =date( "Y-m-d;h:i:s" , mktime(date("h")+6, date("i"), date("s"), date("m") , date("d"), date("Y"))); $str_time = "&receivedtimestamp="; $str_msg = "&msg=bkt"; $str_from = "from="; ?> <a href="http://testext.i-movo.com/api/receivesms.aspx?<?echo $str_from;?><?echo $_SESSION['phone'];?><?echo $str_time;?><?echo $date1;?><?echo $str_msg;?>">Get a Cupon</a> </br> <?php echo $_SESSION['Email'] ; ?> </br> <?php echo $_SESSION['phone'] ; ?> <p><strong>My Account</strong></p> <a href="myaccount.php">My Account</a><br> <a href="mysettings.php">Settings</a><br> <a href="logout.php">Logout </a> </body> </html> And finally the database structure is this one ... Code: [Select] CREATE TABLE IF NOT EXISTS `members` ( `Memberid` int(10) NOT NULL AUTO_INCREMENT, `Username` varchar(20) NOT NULL, `Email` varchar(50) NOT NULL, `Password` varchar(10) NOT NULL, `phone` varchar(25) NOT NULL, `Activation` varchar(60) DEFAULT NULL, PRIMARY KEY (`Memberid`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=30 ; Please help me with this because i'm going mad Hi Guys, Just a quick introduction I am NOT a student I am a IT Technician in a School in the South of the United Kingdom. I am trying to write a PHP Script with a Function that Checks if the user is logged in, if the user is logged in then it shows the user the content on the page but if they are not logged in then to show a blank page with a link to the Login Page. I need it to be simple. I just want it to check if a useer is logged in but if there not only show some content on a page. Can anyone help? My Users login into a php Session. Thanks for any help you can offer. Best Regards Thomas I have a problem which I've been trying to fix for a while now with htmlentities. I've written my own small cms which is available for the public, and recently I recieved a report that it's vulnerable to an XSS attack: http://host/editText.php?fieldname=slogan&content=slogan<img src=x onerror=alert("XSS")> This vulnerability only works if the user is logged in. I want to secure it anyway to give the security companies contacting me about this a break. I've been rolling around the internet trying to find a simple answer how to prevent this XSS attack with HTMLENTITIES. I've even tried writing my own solutions with the htmlentities and it doesn't seem to solve the problem/stop the attack. I'm thinking something like htmlEntities($content); //but again, this won't do the job. Here's the editText.php Code: [Select] <?php session_start(); function getSlug( $page ) { $page = strip_tags( $page ); preg_match_all( "/([a-z0-9A-Z-_]+)/", $page, $matches ); $matches = array_map( "ucfirst", $matches[0] ); $slug = implode( "-", $matches ); return $slug; } $fieldname = $_REQUEST['fieldname']; $encrypt_pass = @file_get_contents("files/password"); if ($_COOKIE['wondercms']!=$encrypt_pass) { echo "You must login before using this function!"; exit; } $content = rtrim(stripslashes($_REQUEST['content'])); // if to only allow specified tags if($fieldname=="title") $content = strip_tags($content); else $content = strip_tags($content,"<audio><source><embed><iframe><p><h1><h2><h3><h4><h5><h6><a><img><u><i><em><strong><b><strike><center><pre>"); $content = trim($content); $content = nl2br($content); if(!$content) $content = "Please be sure to enter some content before saving. Just type anything in here."; $content = preg_replace ("/%u(....)/e", "conv('\\1')", $content); if($fieldname>0 && $fieldname<4) $fname = "attachment$fieldname"; else $fname = $fieldname; $file = @fopen("files/$fname.txt", "w"); if(!$file) { echo "<h2 style='color:red'>*** ERROR *** unable to open content_$fieldname</h2><h3>But don't panic!</h3>". "Please set the correct read/write permissions to the files folder.<br/> Find the /files/ folder and CHMOD it to 751.<br /><br /> If this still gives you problems, open up the /files/ folder, select all files and CHMOD them to 640.<br /><br /> If this doesn't work, contact me <a href='http://krneky.com/en/contact'>right here</a>."; exit; } fwrite($file, $content); fclose($file); echo $content; // convert udf-8 hexadecimal to decimal function conv($hex) { $dec = hexdec($hex); return "&#$dec;"; } ?> There are only 3 files altogether, if someone needs index I'll post that too. |