PHP - Using Username Of Logged In User As Author Of New Database Entries
Im trying to create a website where users login, and then when they add a new entry to the database there name is put as the author. This is how my tables are set up. One table is named job and has the columns id, jobtext, jobdate, and authorid. Another table is called author. This table contains the columns id, username, password, and name. Authorid from the job table matches with id from the author table. When a user logins in this code is used to register the name...session_start();
$_SESSION['myusername'] = $_POST['myusername']; $_SESSION['mypassword'] = $_POST['mypassword']; header("location: index.php"); } else { echo "Wrong Username or Password"; } This is the form users use to add a new entry... if (isset($_GET['add'])) { $pagetitle = 'New Job'; $action = 'addform'; $text = ''; $authorid = ''; $id = ''; $button = 'Add job'; include $_SERVER['DOCUMENT_ROOT'] . '/jobs/includes/db.inc.php'; // Build the list of authors $sql = "SELECT id, name FROM author"; $result = mysqli_query($link, $sql); if (!$result) { $error = 'Error fetching list of authors.'; include 'error.html.php'; exit(); } while ($row = mysqli_fetch_array($result)) { $authors[] = array('id' => $row['id'], 'name' => $row['name']); } // Build the list of categories $sql = "SELECT id, name FROM category"; $result = mysqli_query($link, $sql); if (!$result) { $error = 'Error fetching list of categories.'; include 'error.html.php'; exit(); } while ($row = mysqli_fetch_array($result)) { $categories[] = array( 'id' => $row['id'], 'name' => $row['name'], 'selected' => FALSE); } include 'form.html.php'; exit(); } if (isset($_GET['addform'])) { include $_SERVER['DOCUMENT_ROOT'] . '/includes/db.inc.php'; $text = mysqli_real_escape_string($link, $_POST['text']); $author = mysqli_real_escape_string($link, $_POST['author']); if ($author == '') { $error = 'You must choose an author for this job. Click ‘back’ and try again.'; include 'error.html.php'; exit(); } $sql = "INSERT INTO job SET jobtext='$text', jobdate=CURDATE(), authorid='$author'"; if (!mysqli_query($link, $sql)) { $error = 'Error adding submitted job.'; include 'error.html.php'; exit(); } $jobid = mysqli_insert_id($link); if (isset($_POST['categories'])) { foreach ($_POST['categories'] as $category) { $categoryid = mysqli_real_escape_string($link, $category); $sql = "INSERT INTO jobcategory SET jobid='$jobid', categoryid='$categoryid'"; if (!mysqli_query($link, $sql)) { $error = 'Error inserting job into selected category.'; include 'error.html.php'; exit(); } } } header('Location: .'); exit(); } Form.html.php = <?php include_once $_SERVER['DOCUMENT_ROOT'] . '/includes/helpers.inc.php'; ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title><?php htmlout($pagetitle); ?></title> <meta http-equiv="content-type" content="text/html; charset=utf-8"/> <style type="text/css"> textarea { display: block; width: 100%; } </style> </head> <body> <?php session_start(); ?> <h1><?php htmlout($pagetitle); ?></h1> <form action="?<?php htmlout($action); ?>" method="post"> <div> <label for="text">Type your job he </label> <textarea id="text" name="text" rows="3" cols="40"><?php htmlout($text); ?></textarea> </div> <div> <label for="author">Author:</label> <select name="author" id="author"> <option value="">Select one</option> <?php foreach ($authors as $author):?> <option value="<?php htmlout($author['id']); ?>"<?php if ($author['id'] == $authorid) echo ' selected="selected"'; ?>><?php htmlout($author['name']); ?></option> <?php endforeach; ?> </select> </div> <fieldset> <legend>Categories:</legend> <?php foreach ($categories as $category): ?> <div><label for="category<?php htmlout($category['id']); ?>"><input type="checkbox" name="categories[]" id="category<?php htmlout($category['id']); ?>" value="<?php htmlout($category['id']); ?>"<?php if ($category['selected']) { echo ' checked="checked"'; } ?>/><?php htmlout($category['name']); ?></label></div> <?php endforeach; ?> </fieldset> <div> <input type="hidden" name="id" value="<?php htmlout($id); ?>"/> <input type="submit" value="<?php htmlout($button); ?>"/> </div> </form> </body> </html> Right now, under authors, it displays all the authors in the database. I want it to just show/submit the authorid of the logged in user. Similar TutorialsHello I'm new to the forum, I need your help. I want to make a review place. but i have a problem. The name of the logged in user does not appear in the comment. can you examine the code and help me. user registration, login, done everything. this is my only problem. I tried everything, it didn't work. or I'm new. I just started. I don't know php very well.but I think I've come here so well: D <?php session_start(); include('header.php'); include_once("db_connect.php"); ?> <script src="rating.js"></script> <script type="text/javascript" src="script/ajax.js"></script> <link rel="stylesheet" href="style.css"> <?php include('container.php');?> <div class="container"> // User Register Sign Place <div class="collapse navbar-collapse" id="navbar1"> <ul class="nav navbar-nav navbar-left"> <?php if (isset($_SESSION['user_id'])) { ?> <li><p class="navbar-text"><strong>Welcome!</strong> You're signed in as <strong><?php echo $_SESSION['user_name']; ?></strong></p></li> <li><a href="logout.php">Log Out</a></li> <?php } else { ?> <li><a href="login.php">Login</a></li> <li><a href="register.php">Sign Up</a></li> <?php } ?> </ul> </div> </div> // Rating Star Place <?php include_once("db_connect.php"); $ratingDetails = "SELECT ratingNumber FROM item_rating"; $rateResult = mysqli_query($conn, $ratingDetails) or die("database error:". mysqli_error($conn)); $ratingNumber = 0; $count = 0; $fiveStarRating = 0; $fourStarRating = 0; $threeStarRating = 0; $twoStarRating = 0; $oneStarRating = 0; while($rate = mysqli_fetch_assoc($rateResult)) { $ratingNumber+= $rate['ratingNumber']; $count += 1; if($rate['ratingNumber'] == 5) { $fiveStarRating +=1; } else if($rate['ratingNumber'] == 4) { $fourStarRating +=1; } else if($rate['ratingNumber'] == 3) { $threeStarRating +=1; } else if($rate['ratingNumber'] == 2) { $twoStarRating +=1; } else if($rate['ratingNumber'] == 1) { $oneStarRating +=1; } } $average = 0; if($ratingNumber && $count) { $average = $ratingNumber/$count; } ?> <br> // Rating Details <div id="ratingDetails"> <div class="row"> <div class="col-sm-3"> <h4>Rating and Reviews</h4> <h2 class="bold padding-bottom-7"><?php printf('%.1f', $average); ?> <small>/ 5</small></h2> <?php $averageRating = round($average, 0); for ($i = 1; $i <= 5; $i++) { $ratingClass = "btn-default btn-grey"; if($i <= $averageRating) { $ratingClass = "btn-warning"; } ?> <button type="button" class="btn btn-sm <?php echo $ratingClass; ?>" aria-label="Left Align"> <span class="glyphicon glyphicon-star" aria-hidden="true"></span> </button> <?php } ?> </div> <div class="col-sm-3"> <?php $fiveStarRatingPercent = round(($fiveStarRating/5)*100); $fiveStarRatingPercent = !empty($fiveStarRatingPercent)?$fiveStarRatingPercent.'%':'0%'; $fourStarRatingPercent = round(($fourStarRating/5)*100); $fourStarRatingPercent = !empty($fourStarRatingPercent)?$fourStarRatingPercent.'%':'0%'; $threeStarRatingPercent = round(($threeStarRating/5)*100); $threeStarRatingPercent = !empty($threeStarRatingPercent)?$threeStarRatingPercent.'%':'0%'; $twoStarRatingPercent = round(($twoStarRating/5)*100); $twoStarRatingPercent = !empty($twoStarRatingPercent)?$twoStarRatingPercent.'%':'0%'; $oneStarRatingPercent = round(($oneStarRating/5)*100); $oneStarRatingPercent = !empty($oneStarRatingPercent)?$oneStarRatingPercent.'%':'0%'; ?> <div class="pull-left"> <div class="pull-left" style="width:35px; line-height:1;"> <div style="height:9px; margin:5px 0;">5 <span class="glyphicon glyphicon-star"></span></div> </div> <div class="pull-left" style="width:180px;"> <div class="progress" style="height:9px; margin:8px 0;"> <div class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="5" aria-valuemin="0" aria-valuemax="5" style="width: <?php echo $fiveStarRatingPercent; ?>"> <span class="sr-only"><?php echo $fiveStarRatingPercent; ?></span> </div> </div> </div> <div class="pull-right" style="margin-left:10px;"><?php echo $fiveStarRating; ?></div> </div> <div class="pull-left"> <div class="pull-left" style="width:35px; line-height:1;"> <div style="height:9px; margin:5px 0;">4 <span class="glyphicon glyphicon-star"></span></div> </div> <div class="pull-left" style="width:180px;"> <div class="progress" style="height:9px; margin:8px 0;"> <div class="progress-bar progress-bar-primary" role="progressbar" aria-valuenow="4" aria-valuemin="0" aria-valuemax="5" style="width: <?php echo $fourStarRatingPercent; ?>"> <span class="sr-only"><?php echo $fourStarRatingPercent; ?></span> </div> </div> </div> <div class="pull-right" style="margin-left:10px;"><?php echo $fourStarRating; ?></div> </div> <div class="pull-left"> <div class="pull-left" style="width:35px; line-height:1;"> <div style="height:9px; margin:5px 0;">3 <span class="glyphicon glyphicon-star"></span></div> </div> <div class="pull-left" style="width:180px;"> <div class="progress" style="height:9px; margin:8px 0;"> <div class="progress-bar progress-bar-info" role="progressbar" aria-valuenow="3" aria-valuemin="0" aria-valuemax="5" style="width: <?php echo $threeStarRatingPercent; ?>"> <span class="sr-only"><?php echo $threeStarRatingPercent; ?></span> </div> </div> </div> <div class="pull-right" style="margin-left:10px;"><?php echo $threeStarRating; ?></div> </div> <div class="pull-left"> <div class="pull-left" style="width:35px; line-height:1;"> <div style="height:9px; margin:5px 0;">2 <span class="glyphicon glyphicon-star"></span></div> </div> <div class="pull-left" style="width:180px;"> <div class="progress" style="height:9px; margin:8px 0;"> <div class="progress-bar progress-bar-warning" role="progressbar" aria-valuenow="2" aria-valuemin="0" aria-valuemax="5" style="width: <?php echo $twoStarRatingPercent; ?>"> <span class="sr-only"><?php echo $twoStarRatingPercent; ?></span> </div> </div> </div> <div class="pull-right" style="margin-left:10px;"><?php echo $twoStarRating; ?></div> </div> <div class="pull-left"> <div class="pull-left" style="width:35px; line-height:1;"> <div style="height:9px; margin:5px 0;">1 <span class="glyphicon glyphicon-star"></span></div> </div> <div class="pull-left" style="width:180px;"> <div class="progress" style="height:9px; margin:8px 0;"> <div class="progress-bar progress-bar-danger" role="progressbar" aria-valuenow="1" aria-valuemin="0" aria-valuemax="5" style="width: <?php echo $oneStarRatingPercent; ?>"> <span class="sr-only"><?php echo $oneStarRatingPercent; ?></span> </div> </div> </div> <div class="pull-right" style="margin-left:10px;"><?php echo $oneStarRating; ?></div> </div> </div> <div class="col-sm-3"> <button type="button" id="rateProduct" class="btn btn-default">Rate this product</button> </div> </div> <div class="row"> <div class="col-sm-7"> <hr/> // Review Place <div class="review-block"> <?php $ratinguery = "SELECT ratingId, itemId, userId, ratingNumber, title, comments, created, modified FROM item_rating"; $ratingResult = mysqli_query($conn, $ratinguery) or die("database error:". mysqli_error($conn)); while($rating = mysqli_fetch_assoc($ratingResult)){ $date=date_create($rating['created']); $reviewDate = date_format($date,"M d, Y"); ?> <div class="row"> <div class="col-sm-3"> <img src="image/profile.png" class="img-rounded"> <div class="review-block-name">By <a href="#">phpcode</a></div> <div class="review-block-date"><?php echo $reviewDate; ?></div> </div> <div class="col-sm-9"> <div class="review-block-rate"> <?php for ($i = 1; $i <= 5; $i++) { $ratingClass = "btn-default btn-grey"; if($i <= $rating['ratingNumber']) { $ratingClass = "btn-warning"; } ?> <button type="button" class="btn btn-xs <?php echo $ratingClass; ?>" aria-label="Left Align"> <span class="glyphicon glyphicon-star" aria-hidden="true"></span> </button> <?php } ?> </div> <div class="review-block-title"><?php echo $rating['title']; ?></div> <div class="review-block-description"><?php echo $rating['comments']; ?></div> </div> </div> <hr/> <?php } ?> </div> </div> </div> </div> <div id="ratingSection" style="display:none;"> <div class="row"> <div class="col-sm-12"> <form id="ratingForm" method="POST"> <div class="form-group"> <h4>Rate this product</h4> <button type="button" class="btn btn-warning btn-sm rateButton" aria-label="Left Align"> <span class="glyphicon glyphicon-star" aria-hidden="true"></span> </button> <button type="button" class="btn btn-default btn-grey btn-sm rateButton" aria-label="Left Align"> <span class="glyphicon glyphicon-star" aria-hidden="true"></span> </button> <button type="button" class="btn btn-default btn-grey btn-sm rateButton" aria-label="Left Align"> <span class="glyphicon glyphicon-star" aria-hidden="true"></span> </button> <button type="button" class="btn btn-default btn-grey btn-sm rateButton" aria-label="Left Align"> <span class="glyphicon glyphicon-star" aria-hidden="true"></span> </button> <button type="button" class="btn btn-default btn-grey btn-sm rateButton" aria-label="Left Align"> <span class="glyphicon glyphicon-star" aria-hidden="true"></span> </button> <input type="hidden" class="form-control" id="rating" name="rating" value="1"> <input type="hidden" class="form-control" id="itemId" name="itemId" value="12345678"> </div> <div class="form-group"> <label for="usr">Title*</label> <input type="text" class="form-control" id="title" name="title" required> </div> <div class="form-group"> <label for="comment">Comment*</label> <textarea class="form-control" rows="5" id="comment" name="comment" required></textarea> </div> <?php if (isset($_SESSION['user_id'])) { ?> <div class="form-group"> <button type="submit" class="btn btn-info" id="saveReview">Save Review</button> <button type="button" class="btn btn-info" id="cancelReview">Cancel</button> </div> <?php } else { ?> <div class="well" style="margin-top: 20px;"> <h4 class="text-center"><a href="login.php">Sign in</a> to post a comment</h4> </div> <?php } ?> </form> </div> </div> </div> </div> <?php include('footer.php');?> in this line of code <div class="row"> <div class="col-sm-3"> <img src="image/profile.png" class="img-rounded"> <div class="review-block-name">By <a href="#">phpcode</a></div> <div class="review-block-date"><?php echo $reviewDate; ?></div> </div> How can I show the name of the user logging in this field? <div class="review-block-name">By <a href="#">phpcode</a></div> she will comment and her name will appear. When someone else logs in, if they comment in the same way, their name will appear. Whatever I tried did not happen. Can you help me ?
I have two tables. Table Name:Users Fields: User_name user_email user_level pwd 2.Reference Fields: refid username origin destination user_name in the users table and the username field in reference fields are common fields. There is user order form.whenever an user places an order, refid field in reference table will be updated.So the user will be provided with an refid Steps: 1.User needs to log in with a valid user id and pwd 2.Once logged in, there will be search, where the user will input the refid which has been provided to him during the time of order placement. 3.Now User is able to view all the details for any refid 3.Up to this we have completed. Query: Now we need to retrieve the details based on the user logged in. For eg: user 'USER A' has been provided with the referenceid '1234' during the time of order placement user 'USER B' has been provided with the referenceid '2468' during the time of order placement When the userA login and enter the refid as '2468' he should not get any details.He should get details only for the reference ids which is assigned to him. I would appreciate your assistance, there are tons of login scripts and they work just fine. However I need my operators to login and then list their activities for the other operators who are logged in to see and if desired send their clients on the desired activity. I have the login working like a charm and the activities are listed just beautifully. How do I combine the two tables in the MySQL with PHP so the operator Logged in can only make changes to his listing but see the others. FIRST THE ONE script the member logges in here to the one table in MSQL: <?php session_start(); require_once('config.php'); $errmsg_arr = array(); $errflag = false; $link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD); if(!$link) { die('Failed to connect to server: ' . mysql_error()); } $db = mysql_select_db(DB_DATABASE); if(!$db) { die("Unable to select database"); } function clean($str) { $str = @trim($str); if(get_magic_quotes_gpc()) { $str = stripslashes($str); } return mysql_real_escape_string($str); } $login = clean($_POST['login']); $password = clean($_POST['password']); if($login == '') { $errmsg_arr[] = 'Login ID missing'; $errflag = true; } if($password == '') { $errmsg_arr[] = 'Password missing'; $errflag = true; } if($errflag) { $_SESSION['ERRMSG_ARR'] = $errmsg_arr; session_write_close(); header("location: login-form.php"); exit(); } $qry="SELECT * FROM members WHERE login='$login' AND passwd='".md5($_POST['password'])."'"; $result=mysql_query($qry); if($result) { if(mysql_num_rows($result) == 1) { session_regenerate_id(); $member = mysql_fetch_assoc($result); $_SESSION['SESS_MEMBER_ID'] = $member['member_id']; $_SESSION['SESS_FIRST_NAME'] = $member['firstname']; $_SESSION['SESS_LAST_NAME'] = $member['lastname']; session_write_close(); header("location: member-index.php"); exit(); }else { header("location: login-failed.php"); exit(); } }else { die("Query failed"); } ?> ................................................. ................................ Now I need the person who logged in to the table above to be able to make multiple entries to the table below <? $ID=$_POST['ID']; $title=$_POST['title']; $cost=$_POST['cost']; $activity=$_POST['activity']; $ayear=$_POST['aday']; $aday=$_POST['ayear']; $seats=$_POST['special']; $special=$_POST['seats']; mysql_connect("xxxxxx", "xxx350234427", "========") or die(mysql_error()); mysql_select_db("xxxx") or die(mysql_error()); mysql_query("INSERT INTO `activity` VALUES ('ID','$title', '$cost','$activity', '$aday', '$ayear', '$special', '$seats')"); Print "Your information has been successfully added to the database!" ?> Click <a href="member-profile.php">HERE</a> to return to the main menu <?php ?> 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 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']; } 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 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. $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 This topic has been moved to Third Party PHP Scripts. http://www.phpfreaks.com/forums/index.php?topic=357163.0 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 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! 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 . 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. 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 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 How do I get the current logged in username or id using the Twitter API? 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? 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 ? 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. |