PHP - Session Value Doesn't Remain From Login Page To Another Page While Others Do
ONE of my SESSION values isn't remaining after login while others do.
This works fine on my localhost, it's on the live site that there is a problem and it just started yesterday. Before that it worked great. Out of the four SESSIONs made I can only echo three values on other pages, member id the most important doesn't transfered to other pages Notes: all these files are in the same folder, there is a SESSION started for the member id on the login page, you can see that it is used in the redirect below and the redirect works fine with the redirect going to the correct page " $home/member/index.php?user=$id_mem " Here is the login page // Here's the basic login page info <?php # login.php session_start(); ob_start() ...connect to db & header called... ...Form validation..... if ($e && $p) { // If everything's OK. // Query the database: $q = "SELECT id_mem, display_name, mem_group FROM sn_members WHERE (email='$e' AND password=SHA1('$p')) AND active IS NULL"; $r = mysqli_query ($dbc, $q) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc)); // or die("Error: ".mysqli_error($dbc)); if (@mysqli_num_rows($r) == 1) { // If a match was made. // Register the values & redirect: // Give SELECTED elements a session $_SESSION = mysqli_fetch_array ($r, MYSQLI_ASSOC); $_SESSION['agent'] = md5($_SERVER['HTTP_USER_AGENT']); mysqli_free_result($r); // Update db for last login $id_mem = $_SESSION['id_mem']; // <<< SESSION member id has a value here because it's used in the redirect below $ip = $_SERVER['REMOTE_ADDR']; // Get ip address of person logging in $q = "UPDATE sn_members SET last_login = Now(), ip = '$ip' WHERE id_mem = '$id_mem' LIMIT 1"; $r = mysqli_query ($dbc, $q) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc)); header("Location: $home/member/index.php?user=$id_mem"); exit(); // Quit the script. } ?> Here is the main page that a user would be redirect to above <?php // /member/ all member info is through this folder session_start(); ob_start(); if (isset($_GET['user']) && is_numeric($_GET['user'])) { $user = $_GET['user']; $user = $user; if ($user < 0) { header("Location: $home/index.php"); exit(); } } if ((!isset($_SESSION['id_mem'])) && (!isset($_SESSION['agent']) OR ($_SESSION['agent'] != md5($_SERVER['HTTP_USER_AGENT'])))){ // If not a logged in member redirect header("Location: $home/index.php"); exit(); // Quit the script. } ?> Thanks in advance for the help SJ Similar TutorialsI have a strange problem. When a guest visits my contact-user.php page, they get a message telling them the must login before viewing the page. After the guest logs in, they view the same page and it tells them they have to login again (keeps on looping). But if they manually refresh that page with the "you must be logged in" message, it recognizes the login and lets them in. How can I get this page to immediately recognize that the user is logged in and not require them to refresh the page manually? Here is my code for contact-user.php <?php session_start(); header("Cache-Control: private, max-age=10800, pre-check=10800"); header("Pragma: private"); header("Expires: " . date(DATE_RFC822,strtotime("+2 day"))); include("connection.php"); mysql_select_db("database"); if (isset($_SESSION['username'])) { ******** MY HTML PAGE CONTENT ******** } else { echo "<meta http-equiv='REFRESH' content='2;url=http://www.mysite.com/login.php'> <center><font color='#EE0000'><p>You must be logged in before negotiating. You will now be redirect to the login page.</p></font></center>"; } ?> Here is my code for login.php script: <?php include("connection.php"); mysql_select_db("database"); session_start(); if(isset($_POST['login'])){ $username = mysql_real_escape_string($_POST['username']); $password = mysql_real_escape_string($_POST['password']); $tUnixTime = time(); $sGMTMySqlString = gmdate("Y-m-d H:i:s", $tUnixTime); if (!$username || !$password) { print "Please fill out all fields."; exit; } $logres = mysql_num_rows(mysql_query("SELECT * FROM members WHERE username = '$username' and password = '$password'")); if ($logres <= 0) { print "Login failed. If you have not already, please signup. Otherwise, check your spelling and login again."; exit; } else { $_SESSION['username'] = $username; if (isset($_SESSION)) { echo'You are now logging in'; mysql_query("UPDATE members SET activity = '$sGMTMySqlString' WHERE username = '$username'"); } else { echo "You are not logged in!"; } echo'<html><head><meta http-equiv="REFRESH" content="1;url=http://www.mysite.com/members/' . $_SESSION['username'] . '/"></head><body></body></html>'; exit; } } ?> Some code from my pages ,
Page1 ( Redirecting page )
<html> <title>login_redirect.</title> body> <form name="redirect" action="http://mysite/page2.php" method="post"> <input type="hidden" name="mac" value="$(mac)"> </form> <script language="JavaScript"> <!-- document.redirect.submit(); //--> </script> </body> </html>Page 2 ( select product ) <?php session_start(); ini_set('display_errors',1); error_reporting(E_ALL); include '../lib/config.php'; include '../lib/opendb.php'; // get user mac adres from redirect post page1 $_SESSION['macid'] = $_POST['mac']; // set $macid for other use ( maybe not needed, am learning ) $macid = $_SESSION['macid']; // echo $macid does show mac adress, so variable is not empty here if (!empty($_POST["submit"])) { $product_choice = $_POST['accounttype']; $query= "SELECT AccountIndex, AccountCost, AccountName FROM AccountTypes WHERE AccountIndex='$product_choice'"; $result = mysql_query($query) or die('Query failed. ' . mysql_error()); while($row = mysql_fetch_array($result)) { $_SESSION['AccountIndex'] = $row['AccountIndex']; $_SESSION['AccountCost'] = $row['AccountCost']; $_SESSION['AccountName'] = $row['AccountName']; } header('Location: page3.php'); } // did leave out the other/html/form stuff herePage 3 ( show Session variables ) <?php ini_set('display_errors',1); error_reporting(E_ALL); session_start(); print_r($_SESSION); ?>Now, on page 3 i do see the right session varables, only the "macid" is empty. why ? Can someoneplease help, I need to setup an error page like IF Username and Password are wrong then show an error also if there is no username or password in the fields and I just click LOGIN, I get a blank page?! Can someone please help me here or point me to a relevant tutorial? thanks here is my page: http://www.retroandvintage.co.uk/default.php here is my code: Code: [Select] <?php session_start(); include_once("config.php"); $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["submit"])) { // // 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"); } else { // The login form wasn't filled out yet, display the login form for the user to fill in: doIndex(); } /* 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. */ function doIndex() { /* Import the global $messages array. If any errors were detected above, they will be stored in the $messages array: */ global $messages; /* also import the $title for the page - note you can normally just declare all globals on one line - ie: global $messages, $title; */ global $title; } // drop out of PHP mode to display the plain HTML: ?> <!doctype html> <html> <head> <title>List of Pubs and Bars in the UK</title> <meta name="description" content="Pubs and bars in the UK, nightlife for food and drink" /> <meta name="keywords" content="Pubs, bars, List, uk, nightlife, drinking, drinks, beer, lager, food" /> <meta name="Content-Language" content="en-gb" /> <meta name="robots" content="FOLLOW,INDEX" /> <meta name="revisit-after" content="2 days" /> <meta name="copyright" content="jbiddulph.com" /> <meta name="author" content="John Biddulph - Professional web site design and development in the south of england mainly worthing and brighton" /> <meta name="distribution" content="Global" /> <meta name="resource-type" content="document" /> <link rel="stylesheet" type="text/css" href="css/reset.css" /> <link rel="stylesheet" type="text/css" href="css/ui-lightness/jquery-ui-1.8.6.custom.css" title="default" /> <link rel="alternate stylesheet" type="text/css" href="css/south-street/jquery-ui-1.8.6.custom.css" title="1" /> <link rel="alternate stylesheet" type="text/css" href="css/redmond/jquery-ui-1.8.6.custom.css" title="2" /> <script type="text/javascript" src="js/stylechanger.js"></script> <script type="text/javascript" src="js/jquery-1.4.2.min.js"></script> <script type="text/javascript" src="js/jquery-ui-1.8.6.custom.min.js"></script> <script type="text/javascript"> $(function(){ // Accordion $("#accordion").accordion({ header: "h3" }); // Tabs $('#tabs').tabs(); // Dialog $('#dialog').dialog({ autoOpen: false, width: 600, buttons: { "Ok": function() { $(this).dialog("close"); }, "Cancel": function() { $(this).dialog("close"); } } }); // Dialog Link $('#dialog_link').click(function(){ $('#dialog').dialog('open'); return false; }); // Datepicker $('#datepicker').datepicker({ inline: true }); //hover states on the static widgets $('#dialog_link, ul#icons li').hover( function() { $(this).addClass('ui-state-hover'); }, function() { $(this).removeClass('ui-state-hover'); } ); }); </script> <script type="text/javascript"> function lookup(inputString) { if(inputString.length == 0) { // Hide the suggestion box. $('#suggestions').hide(); } else { $.post("rpc.php", {queryString: ""+inputString+""}, function(data){ if(data.length >0) { $('#suggestions').show(); $('#autoSuggestionsList').html(data); } }); } } // lookup function fill(thisValue) { $('#inputString').val(thisValue); setTimeout("$('#suggestions').hide();", 200); } </script> </head> <body> <?php if($messages) { displayErrors($messages); }?> <header> <div id="title"> <h1>My Pub Space <a href="#" onClick="setActiveStyleSheet('default'); return false;"><img src="images/0.gif" width="15" height="15" border="0" alt="css style" /></a> <a href="#" onClick="setActiveStyleSheet('1'); return false;"><img src="images/1.gif" width="15" height="15" border="0" alt="css style" /></a> <a href="#" onClick="setActiveStyleSheet('2'); return false;"><img src="images/2.gif" width="15" height="15" border="0" alt="css style" /></a> <span> <form method="post" class="textbox" action="search.php"> Town/City: <input type="text" size="26" class="searchbox" value="" name="rsTown" id="inputString" onKeyUp="lookup(this.value);" onBlur="fill();" /> <div class="suggestionsBox" id="suggestions" style="display: none;"> <img src="images/upArrow.png" style="position: relative; top: -36px; left: 105px; z-index:1;" alt="upArrow" /> <div class="suggestionList" id="autoSuggestionsList"> </div> </div> <input type="image" src="images/go.png" height="30" with="30" value="GO" /> </form> </span> </h1> </div> </header> <nav> <ul> <li class="selected"><a href="default.php">Home</a></li> <li><a href="#">Pubs</a></li> <li><a href="#">Members</a></li> <li><a href="#">Events</a></li> <li><a href="register.php">Register</a></li> </ul> </nav> <section id="intro"> <header> <h2>Your social guide to going down the pub, online!</h2> </header> <p>Stuck in town with nowhere to go? Not sure if up the road or down the street is best? Need to be somewhere warm, cosy and friendly. Need a drink?....<br />You've come to the right place, mypubspace has it all!</p> <img src="images/pub.jpg" alt="pub" /> </section> <div id="content"> <div id="mainContent"> <section> <article class="blogPost"> <header> <h2>Pubs and Bars UK Listing</h2> </header> <?php $tableName="pubs"; $targetpage = "default.php"; $limit = 20; $query = "SELECT COUNT(*) as num FROM $tableName"; $total_pages = mysql_fetch_array(mysql_query($query)); $total_pages = $total_pages['num']; $stages = 3; $page = mysql_escape_string($_REQUEST['page']); if( isset($_REQUEST['page']) && ctype_digit($_REQUEST['page']) ) { $page = (int) $_GET['page']; $start = ($page - 1) * $limit; }else{ $start = 0; } // Get page data $query1 = "SELECT * FROM $tableName LIMIT $start, $limit"; $result = mysql_query($query1); // Initial page num setup if ($page == 0){$page = 1;} $prev = $page - 1; $next = $page + 1; $lastpage = ceil($total_pages/$limit); $LastPagem1 = $lastpage - 1; $paginate = ''; if($lastpage > 1) { $paginate .= "<div class='paginate'>"; // Previous if ($page > 1){ $paginate.= "<a href='$targetpage?page=$prev'>previous</a>"; }else{ $paginate.= "<span class='disabled'>previous</span>"; } // Pages if ($lastpage < 7 + ($stages * 2)) // Not enough pages to breaking it up { for ($counter = 1; $counter <= $lastpage; $counter++) { if ($counter == $page){ $paginate.= "<span class='current'>$counter</span>"; }else{ $paginate.= "<a href='$targetpage?page=$counter'>$counter</a>";} } } elseif($lastpage > 5 + ($stages * 2)) // Enough pages to hide a few? { // Beginning only hide later pages if($page < 1 + ($stages * 2)) { for ($counter = 1; $counter < 4 + ($stages * 2); $counter++) { if ($counter == $page){ $paginate.= "<span class='current'>$counter</span>"; }else{ $paginate.= "<a href='$targetpage?page=$counter'>$counter</a>";} } $paginate.= "..."; $paginate.= "<a href='$targetpage?page=$LastPagem1'>$LastPagem1</a>"; $paginate.= "<a href='$targetpage?page=$lastpage'>$lastpage</a>"; } // Middle hide some front and some back elseif($lastpage - ($stages * 2) > $page && $page > ($stages * 2)) { $paginate.= "<a href='$targetpage?page=1'>1</a>"; $paginate.= "<a href='$targetpage?page=2'>2</a>"; $paginate.= "..."; for ($counter = $page - $stages; $counter <= $page + $stages; $counter++) { if ($counter == $page){ $paginate.= "<span class='current'>$counter</span>"; }else{ $paginate.= "<a href='$targetpage?page=$counter'>$counter</a>";} } $paginate.= "..."; $paginate.= "<a href='$targetpage?page=$LastPagem1'>$LastPagem1</a>"; $paginate.= "<a href='$targetpage?page=$lastpage'>$lastpage</a>"; } // End only hide early pages else { $paginate.= "<a href='$targetpage?page=1'>1</a>"; $paginate.= "<a href='$targetpage?page=2'>2</a>"; $paginate.= "..."; for ($counter = $lastpage - (2 + ($stages * 2)); $counter <= $lastpage; $counter++) { if ($counter == $page){ $paginate.= "<span class='current'>$counter</span>"; }else{ $paginate.= "<a href='$targetpage?page=$counter'>$counter</a>";} } } } // Next if ($page < $counter - 1){ $paginate.= "<a href='$targetpage?page=$next'>next</a>"; }else{ $paginate.= "<span class='disabled'>next</span>"; } $paginate.= "</div>"; } echo $total_pages.' Results'; // pagination echo $paginate; ?> <div id="accordion"> <?php while($row = mysql_fetch_array($result)) { echo '<div><h3><a href=\"#\">'.$row['rsPubName'].'</a></h3><div>'.$row['rsAddress'].'<br />'.$row['rsTown'].', '.$row['rsCounty'].'<br />'.$row['rsPostCode'].'<br /><br />Region: '.$row['Region'].'<br /><br />Telephone: '.$row['rsTel'].'</div></div>'; } ?> </div> </article> </section> </div> <aside> <section> <header> <h3>Members Login Area</h3> </header> <form method="post" class="textbox" action="<?php print $_SERVER["PHP_SELF"]; ?>"> Username: <br /> <input type="text" class="textbox" name="rsUser" value="<?php print isset($_POST["rsUser"]) ? $_POST["rsUser"] : "" ; ?>"> Password: <br /> <input type="password" class="textbox" name="rsPass"> <br /> <br /> <input name="submit" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" type="submit" value="Login"> <br /> </form> <ul> <li><button id="button" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" role="button" aria-disabled="false"><span class="ui-button-text"><a href="register.php">Sign up</a></span></button></li> <li><button id="button" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" role="button" aria-disabled="false"><span class="ui-button-text"><a href="forgot.php">Forgot Password</a></span></button></li> </ul> </section> <section> <header> <h3>Quick Search</h3> </header> <ul> <li><a href="#">Coming Soon!</a></li> </ul> </section> </aside> </div> <footer> <div> <section id="about"> <header> <h3>About</h3> </header> <p>My Pub Space is one of the largest and newest UK Pubs and Bars Listing sites online. It is not just a list of pubs, we have added a touch of interactive social pubbing experience online! Once registered, you can view information on pubs in your area, write reviews, organise your evenings out!</p> </section> <section id="blogroll"> <header> <h3>Links</h3> </header> <ul> <li><a href="#">Coming Soon!</a></li> </ul> </section> <section id="popular"> <header> <h3>Popular</h3> </header> <ul> <li><a href="#">Coming Soon!</a></li> </ul> </section> </div> </footer> </body> </html> Hi, I am a php newbie, who has a page that relies on some php scripts, and to which I am trying to add a login page written in php. I took the example from he http://www.howtodothings.com/computers-internet/how-to-make-a-login-system-for-your-website Basically it consists of adding: <? require("log.php"); ?> to the top of any page I want to protect, a log.php file which performs the actions of the form, linking to a mySQL database, and a login.php file which contains the form. I have the login working fine, but it breaks one of the PHP scripts on the page that is protected. It is an upload script, called Weaverbox, based on FancyUpload. The uploads which are handled by a file called upload.php, aren't happening. The progress shows that they are being uploaded, but nothing is uploaded, and there is no success message. As soon as I remove the code from the top of the page requiring log.php all works fine again. I think I may have to add some rules/extensions to resolve this conflict, but I don't know how to go about this. Would someone be able to help me get it sorted? Thanks Nick hi i need help an idea how can i separate members from admins since i dont know how to create login form i used tutorial ( http://www.youtube.com/watch?v=4oSCuEtxRK8 ) (its session login form only that i made it work other tutorials wre too old or something) how what i want to do is separate members and admins because admin need more rights to do now i have idea but dont know will it work like that what i want to do is create additional row in table named it flag and create 0 (inactive user) 1 (member) 2 (admin) will that work? and how can i create different navigation bars for users and admins? do you recommend that i use different folders to create it or just script based on session and flag? Quesion: Show each movie in the database on its own page, and give the user links in a "page 1, Page 2, Page 3" - type navigation system. Hint: Use LIMIT to control which movie is on which page. I have provided 3 files: 1st: configure DB, 2nd: insert data, 3rd: my code for the question. I would appreciate the help. I am a noob by the way. First set up everything for DB: <?php //connect to MySQL $db = mysql_connect('localhost', 'root', '000') or die ('Unable to connect. Check your connection parameters.'); //create the main database if it doesn't already exist $query = 'CREATE DATABASE IF NOT EXISTS moviesite'; mysql_query($query, $db) or die(mysql_error($db)); //make sure our recently created database is the active one mysql_select_db('moviesite', $db) or die(mysql_error($db)); //create the movie table $query = 'CREATE TABLE movie ( movie_id INTEGER UNSIGNED NOT NULL AUTO_INCREMENT, movie_name VARCHAR(255) NOT NULL, movie_type TINYINT NOT NULL DEFAULT 0, movie_year SMALLINT UNSIGNED NOT NULL DEFAULT 0, movie_leadactor INTEGER UNSIGNED NOT NULL DEFAULT 0, movie_director INTEGER UNSIGNED NOT NULL DEFAULT 0, PRIMARY KEY (movie_id), KEY movie_type (movie_type, movie_year) ) ENGINE=MyISAM'; mysql_query($query, $db) or die (mysql_error($db)); //create the movietype table $query = 'CREATE TABLE movietype ( movietype_id TINYINT UNSIGNED NOT NULL AUTO_INCREMENT, movietype_label VARCHAR(100) NOT NULL, PRIMARY KEY (movietype_id) ) ENGINE=MyISAM'; mysql_query($query, $db) or die(mysql_error($db)); //create the people table $query = 'CREATE TABLE people ( people_id INTEGER UNSIGNED NOT NULL AUTO_INCREMENT, people_fullname VARCHAR(255) NOT NULL, people_isactor TINYINT(1) UNSIGNED NOT NULL DEFAULT 0, people_isdirector TINYINT(1) UNSIGNED NOT NULL DEFAULT 0, PRIMARY KEY (people_id) ) ENGINE=MyISAM'; mysql_query($query, $db) or die(mysql_error($db)); echo 'Movie database successfully created!'; ?> ******************************************************************** *********************************************************************** second file to load info into DB: <?php // connect to MySQL $db = mysql_connect('localhost', 'root', '000') or die ('Unable to connect. Check your connection parameters.'); //make sure you're using the correct database mysql_select_db('moviesite', $db) or die(mysql_error($db)); // insert data into the movie table $query = 'INSERT INTO movie (movie_id, movie_name, movie_type, movie_year, movie_leadactor, movie_director) VALUES (1, "Bruce Almighty", 5, 2003, 1, 2), (2, "Office Space", 5, 1999, 5, 6), (3, "Grand Canyon", 2, 1991, 4, 3)'; mysql_query($query, $db) or die(mysql_error($db)); // insert data into the movietype table $query = 'INSERT INTO movietype (movietype_id, movietype_label) VALUES (1,"Sci Fi"), (2, "Drama"), (3, "Adventure"), (4, "War"), (5, "Comedy"), (6, "Horror"), (7, "Action"), (8, "Kids")'; mysql_query($query, $db) or die(mysql_error($db)); // insert data into the people table $query = 'INSERT INTO people (people_id, people_fullname, people_isactor, people_isdirector) VALUES (1, "Jim Carrey", 1, 0), (2, "Tom Shadyac", 0, 1), (3, "Lawrence Kasdan", 0, 1), (4, "Kevin Kline", 1, 0), (5, "Ron Livingston", 1, 0), (6, "Mike Judge", 0, 1)'; mysql_query($query, $db) or die(mysql_error($db)); echo 'Data inserted successfully!'; ?> ************************************************************** **************************************************************** MY CODE FOR THE QUESTION: <?php $db = mysql_connect('localhost', 'root', '000') or die ('Unable to connect. Check your connection parameters.'); mysql_select_db('moviesite', $db) or die(mysql_error($db)); //get our starting point for the query from the URL if (isset($_GET['offset'])) { $offset = $_GET['offset']; } else { $offset = 0; } //get the movie $query = 'SELECT movie_name, movie_year FROM movie ORDER BY movie_name LIMIT ' . $offset . ' , 1'; $result = mysql_query($query, $db) or die(mysql_error($db)); $row = mysql_fetch_assoc($result); ?> <html> <head> <title><?php echo $row['movie_name']; ?></title> </head> <body> <table border = "1"> <tr> <th>Movie Name</th> <th>Year</th> </tr><tr> <td><?php echo $row['movie_name']; ?></td> <td><?php echo $row['movie_year']; ?></td> </tr> </table> <p> <a href="page.php?offset=0">Page 1</a>, <a href="page.php?offset=1">Page 2</a>, <a href="page.php?offset=2">Page 3</a> </p> </body> </html> Please delete. Hi im trying to pass a variable through a url. Here's the code : echo"<td class='tableContent'><span onmouseover=\"tooltip.show('Click to add details to ".$result['workObject']."');\" onmouseout=\"tooltip.hide();\"><a href='addRemarksBucc.php?workObject=".$result['workObject']."'>".$result['systemRemarks']."</a></span></td>"; and here's the code to the next page: <table width="550" border="0" cellspacing="5" cellpadding="0"> <tr> <td width="78" valign="top">Work Object</td> <td><input name="workObject" id="workObject" type="text" value="<?php $_GET['workObject']; ?>" /></td> </tr> <tr> <td valign="top">Remark Details</td> <td><textarea name="errorMessage2" cols="50" rows="10" id="errorMessage2" accesskey="p" tabindex="1"></textarea> <input name="workObject2" type="hidden" value="" /></td> </tr> <tr> <td valign="top"> </td> <td> </td> </tr> <tr> <td> </td> <td><input name="submit" type="submit" class="btn" id="submit" accesskey="R" tabindex="11" value="Submit" /> <input name="reset" type="reset" class="btn" id="reset" accesskey="e" tabindex="12" value="Reset" /></td> </tr> </table> What am I doing wrong? The address bar shows the right url but the second page doesn't display any value for workObject. Thanks! Hi, I have a user/password protected page that displays a list of clients. When clicking on them you're redirected to the client record update page. This is how I am linking to taht page now: Code: [Select] <a href="DIST_clientes_update.php?id_cliente=<?php echo $row_clients_RS['id_cliente']; ?>The problem with this is that the client id is appended to the url and so if the user chnges it will be able to access records from a different user...and I dont want that. So I have created a session: Code: [Select] $_SESSION["idCliente"] = $row_clients_RS['id_cliente'];but how do I pass it to the update page without showing in the url? Thanks hey guys i'am newb in php and i'am doing some algorithm in php, in some codes i need to use session but in that particular page the code does not know if session_start() has been called or not. wonder to if there is anyway that i can get if session is started or not in my code? thanks in advance I have my php pages set up like this: 1. log in with login.php 2. that sends you to main.php 3. in main.php, there are links to page-a.php, page-b.php, page-c.php, etc. when you type in a password at login.php, it passes your input to main.php. the correct password is hardcoded in main.php. if it matches, a session variable is set, which should be able to be used on page-a.php, page-b.php, page-c.php, etc. to verify that whoever accesses those pages has gone through the login process. if the session variable doesn't match (or null) the user is redirected to the login page. also the session variable is checked (recursively) when accessing main.php, just like the other pages. the problem is, it's as if each page starts over. the session variable does not make it beyond the page that sets it. it should be passed on to the next page but it's not. I used an echo statement in page-a.php to verify and rem'd out the rest of the code. no echo because session value is null, page goes on to load the html. without the code rem'd out it redirects the user to login.php. code: LOGIN.PHP <? session_start(); if(isset($_SESSION['aaa'])) unset($_SESSION['aaa']); ?> <html> <head> <title>title</title> </head> <body> <table width="400" align="center" border="0" bordercolor="#000099" bordercolordark="#000066" bordercolorlight="#6666FF"> <tr bgcolor="#B0C4DE"> <td> <form action="main.php" method="POST"> <p align="center"><strong><font size="2" face="Verdana, Arial, Helvetica, sans-serif" color="#FFFFFF"><br> Password</font></strong> <input name="pwfield" type="password" value size="20" maxlength=20> <input type="submit" value="Login"></p> </form> </td></tr></table> </body></html> MAIN.PHP <? if ($_SESSION['aaa']!="abcdef") { $password="twinkies"; if ($_POST["pwfield"]==$password) $_SESSION['aaa']="abcdef"; // successful login else {header("Location: login.php"); exit();} } ?> <html> <head> <title>title</title> </head> <body> <a href="page-a.php">Page A</a> <a href="page-b.php">Page B</a> <a href="page-c.php">Page C</a> </body></html> PAGE-A.PHP <? echo $_SESSION['aaa']; //if ($_SESSION['aaa']!="abcdef") //header("Location: login.php"); //exit(); ?> <html> <head> <title>title</title> </head> <body> ... I'm building a login page that then redirects to a new page. But it seems the session isn't working. But I don't know much about sessions, so I'm not sure what I might be doing wrong. The login page sets the session with this code: Code: [Select] // Fetch the result - This will tell us whether this user exists $userExists = mysql_fetch_assoc($doQuery); // If user exists log them in if($userExists){ mysql_free_result($doQuery); mysql_close(); // Set the SESSION variables $_SESSION['first_name'] = $userExists['first_name']; $_SESSION['id'] = $userExists['id']; The page that it redirects to is this: Code: [Select] <?php session_start(); if(isset($_SESSION['id'])) { echo "<html><body><p> You are now logged in,{$_SESSION['ID']}.</p>"; } else { echo 'something went wrong'; exit(); } ob_end_flush(); ?> Hi. I have problem and I would like to know if anyone here has any ideas on how to fix it. My home page is where my log in form resides. If I leave the home page to browse other pages of my site I want to stay logged in. However, when I return to the home page I see the log in form. The log in form should not be there if I already logged in. Instead I should see the welcome message. Which does appear after loggin in but does not stay on the home page when I leave the page and come back. Code: [Select] <?php //Starts the PHP Sesssion session_start(); //Includes the MYSLQ Connection Info from another PHP Page include ('spartacus_mysql.php'); //Submits Log In Info to Database and encrypts Password if (isset ($_POST['loginsubmit'])) { $username = mysql_escape_string($_POST['username']); $userpassword = mysql_escape_string(md5($_POST['userpassword'])); if (!empty ($username) && !empty ($userpassword)) { //Runs Query to Selects the Username and Password from the Database $sql = mysql_query ("SELECT * FROM users WHERE username='".$username."' AND userpassword='".$userpassword."' LIMIT 1"); //Finds and Matches the Log In Info from the Database to the one submitted if(mysql_num_rows ($sql) > 0) { $_SESSION['loggedin'] = true; $_SESSION['username'] = $username; //Runs This Message if the right Username/Password is entered echo '<div id="welcome_member"> Welcome, '.$_SESSION['username'].'.<br /> You are now logged in!<br/> The Combat Tips and Downloads is now accessible!<br /> Enjoy!<br /> </div>'; } else { //Runs This Error if the Username/Password do not match the Database echo '<div id="welcome_member"> Your username and/or password is incorrect! <a href="spartacus_home.php">Try Again</a> </div>'; } } else { //Runs This Code if the Log In Form is Left Blank echo '<div id="welcome_member"> You must enter a username and a password! <a href="spartacus_home.php">Try Again</a> or <a href="spartacus_joinsite.php">Register</a> </div>'; } } else { //This is the code for the Log in Form echo'<div id="join"> <a href="spartacus_joinsite.php">{ JOIN! }</a><br /> </div> <div class="signin"> <div id="titles"> { SIGN IN } </div><br /> <form method="post" action="spartacus_home.php"> <table> <tr><td> Username: <input type="text" name="username" /> </td></tr> <tr><td> Password: <input type="password" name="userpassword"/> </td></tr> <tr><td> <input class="submit" name="loginsubmit" type="submit" /> </tr></td> </table> </form> </div>'; } ?> <!--end sign in PHP--> Here is my code Please help with Ajax call, when clicking login button nothing happens when it should go to mainpageloggedin.php deano Hi, On my website I have a booking calendar which you login to with a username and password. That interactive part of the website now looks very different from the rest of the website, but unfortunately it's not possible to recode that calendar to look like the rest of the site. As a workaround I'd like users to be able to login to that calendar from the home page, with just a simple username and password field at the top of the page. On submit this would then send the details to the existing login page, and also log them in straight away. My php knowledge is limited. I've searched a lot on Google but can't find any code that seems to do the trick. Does anyone know if this is even possible? thanks in advance Hi im trying to create a sign up page for my website that contains different paths dependin on the membership that you select. I am an unexperienced programmer and need help as nothing is working at the moment. I would appreciate if people could reply to this post as soon as possible as I need it sorted today! Below is my code! Can you please send me suggestive improvement? Thanks <?php if (isset ($_POST['firstname'])){ //grab data from the form $username = preg_replace('#[^A-Za-z0-9]#i', '', $_POST['username']); // filter everything but letters and numbers $firstname = preg_replace('#[^A-Za-z]#i', '', $_POST['firstname']); // filter everything but Letters $lastname = preg_replace('#[^A-Za-z]#i', '', $_POST['lastname']); // filter everything but Letters $phone = preg_replace('#[^0-9]#i', '', $_POST['phone']); // filter everything but numbers $address= preg_replace('#[^A-Za-z]#i', '', $_POST['address']); // filter everything but Letters $postcode= preg_replace('#[^A-Za-z]#i', '', $_POST['postcode']); // filter everything but Letters $town= preg_replace('#[^A-Za-z]#i', '', $_POST['town']); // filter everything but Letters $housenumber= preg_replace('#[^0-9]#i', '', $_POST['housenumber']); // filter everything but numbers $b_m = preg_replace('#[^0-9]#i', '', $_POST['birth_month']); // filter everything but numbers $b_d = preg_replace('#[^0-9]#i', '', $_POST['birth_day']); // filter everything but numbers $b_y = preg_replace('#[^0-9]#i', '', $_POST['birth_year']); // filter everything but numbers $email1 = $_POST['email1']; $email2 = $_POST['email2']; $pass1 = $_POST['pass1']; $pass2 = $_POST['pass2']; $email1 = stripslashes($email1); $pass1 = stripslashes($pass1); $email2 = stripslashes($email2); $pass2 = stripslashes($pass2); $email1 = strip_tags($email1); $pass1 = strip_tags($pass1); $email2 = strip_tags($email2); $pass2 = strip_tags($pass2); //connect to db $connection = mysql_connect('linuxproj.ecs.soton.ac.uk', 'db_alw3g08', 'pasta'); $db = mysql_select_db('db_alw3g08', $connection); $emailCHecker = mysql_real_escape_string($email1); $emailCHecker = str_replace("`", "", $emailCHecker); // Database duplicate username check setup for use below in the error handling if else conditionals $sql_uname_check = mysql_query("SELECT username FROM Members WHERE username='$username'"); $uname_check = mysql_num_rows($sql_uname_check); // Database duplicate e-mail check setup for use below in the error handling if else conditionals $sql_email_check = mysql_query("SELECT email FROM Members WHERE email='$emailCHecker'"); $email_check = mysql_num_rows($sql_email_check); // Error handling for missing data if ((!$username) || (!$firstname) || (!$lastname) || (!$address) || (!$postcode) || (!$town) || (!$b_m) || (!$b_d) || (!$b_y) || (!$email1) || (!$email2) || (!$pass1) || (!$pass2)) { $errorMsg = 'ERROR: You did not submit the following required information:<br /><br />'; if(!$username){ $errorMsg .= ' * User Name<br />'; } if(!$firstname){ $errorMsg .= ' * First Name<br />'; } if(!$lastname){ $errorMsg .= ' * Last Name<br />'; } if(!$address){ $errorMsg .= ' * Address<br />'; } if(!$postcode){ $errorMsg .= ' * postcode<br />'; } if(!$town){ $errorMsg .= ' * town<br />'; } if(!$b_m){ $errorMsg .= ' * Birth Month<br />'; } if(!$b_d){ $errorMsg .= ' * Birth Day<br />'; } if(!$b_y){ $errorMsg .= ' * Birth year<br />'; } if(!$email1){ $errorMsg .= ' * Email Address<br />'; } if(!$email2){ $errorMsg .= ' * Confirm Email Address<br />'; } if(!$pass1){ $errorMsg .= ' * Login Password<br />'; } if(!$pass2){ $errorMsg .= ' * Confirm Login Password<br />'; } } else if ($email1 != $email2) { $errorMsg = 'ERROR: Your Email fields below do not match<br />'; } else if ($pass1 != $pass2) { $errorMsg = 'ERROR: Your Password fields below do not match<br />'; } else if (strlen($username) < 6) { $errorMsg = "<u>ERROR:</u><br />Your User Name is too short. 6 - 20 characters please.<br />"; } else if (strlen($username) > 20) { $errorMsg = "<u>ERROR:</u><br />Your User Name is too long. 6 - 20 characters please.<br />"; } else if ($uname_check > 0){ $errorMsg = "<u>ERROR:</u><br />Your User Name is already in use inside of our system. Please try another.<br />"; } else if ($email_check > 0){ $errorMsg = "<u>ERROR:</u><br />Your Email address is already in use inside of our system. Please use another.<br />"; } else { // Error handling is ended, process the data and add member to database $email1 = mysql_real_escape_string($email1); $pass1 = mysql_real_escape_string($pass1); // Add MD5 Hash to the password variable $password = md5($pass1); // Convert Birthday to a DATE field type format(YYYY-MM-DD) out of the month, day, and year supplied $dateofbirth = "$b_y-$b_m-$b_d"; // Add user info into the database table for the main site table $sql = mysql_query("INSERT INTO members (username, firstname, lastname, email, password, dateofbirth, phone, lastlogin) VALUES('$username','$firstname','$lastname','$email1','$password', '$dateofbirth','$phone', now())") or die (mysql_error()); $sql = mysql_query("INSERT INTO address (address, postcode, town, housenumber) VALUES('$adress','$postcode,'$town','$housenumber'") or die (mysql_error()); $id = mysql_insert_id() } else { // if the form is not posted with variables, place default empty variables so no warnings or errors show $errorMsg = ""; $username = ""; $firstname = ""; $lastname = ""; $phone = ""; $address = ""; $postcode = ""; $town = ""; $housenumber = ""; $b_m = ""; $b_d = ""; $b_y = ""; $email1 = ""; $email2 = ""; $pass1 = ""; $pass2 = ""; } Hey guys i have a few question with this login script im trying to make. Ok so first im using php myadmin and i've created a simple login here that works fine but i want to tweak it so when i login i can login to a specific site where i've created tables and stuff. Is there anyone out there that can help me im a little stumped on how to do this. Thanks in regards. Here are my two scripts im using show_login.html Code: [Select] <html> <head> <title>Login Form</title> <h1>Login to Authorized Area</h1> <form method= "post" action= "login.php"> <br> Username: <input type= "text" name= "username"> <br> <br> Password: <input type= "password" name= "password"> <br> <p> <input type= "submit" name= "submit" value= "Login" </p><br> </html> </form> login.php Code: [Select] <? if ((!$_POST['username']) || (!$_POST['password'])) { header("Location: show_login.html"); exit; } $db_name="ryan"; $table_name="auth_users4"; $connection=@mysql_connect("localhost","RyanH","test1234")or die(mysql_error()); $db =@mysql_select_db($db_name, $connection)or die(mysql_error()); $sql= "SELECT * FROM $table_name WHERE username ='$_POST[username]' AND password = password('$_POST[password]')"; $result = @mysql_query($sql,$connection) or die(mysql_error()); $num=mysql_num_rows($result); if ($num != 0) { echo "<P>Congratulations, you're authorized!</p>"; }else{ echo "<P>You are not authorized to use this site</p>"; echo'<br/><a href="show_login.html">Try Again</a>'; exit; } ?> I have a page that shows entries in a guestbook I'm making, and below the entries there is supposed to be a form to write an entry. Except, none of the HTML after the script to show the entries shows up on the page. I have no clue what's wrong. Here is the script to show the entries. $n is name, $d is date, $s is site (optional), and $m is message. $file = fopen("posts.txt", 'rb'); flock($file, LOCK_SH); while(!feof($file)){ $entry = fgetcsv($file, 0, '|'); if(empty($entry)){exit;} $d = $entry[1]; $n = $entry[2]; $s = $entry[3]; $m = $entry[4]; echo ' <table style="border: #3399AA 1px solid;"><tr style="background: #3399AA; font: bold 10px verdana,sans-serif; color: #FFFFFF;"> <td width="170">'.$n.'</td> <td align="right" width="170">'.$d.'</td> </tr> '; if($s != 'none'){ echo ' <tr><td colspan="2" style="font: 10px verdana,sans-serif; color: #3399AA;"> <b>Site: </b><a href="'.$s.'">'.$s.'</a> <center><div style="width: 250; height: 1px; background: #3399AA; margin: 10px;"></div></center></td></tr> '; } echo ' <tr> <td colspan="2" style="font: 10px verdana,sans-serif; color: #3399AA;">'.$m.'</td> </tr></table><br> '; } flock($file, LOCK_UN); fclose($file); The file it is reading looks like this: Code: [Select] |11:51 am, 3rd Nov 2010|Memoria|none|Hello. :) |11:51 am, 3rd Nov 2010|Memoria|http://sitehere|Hello again. |11:51 am, 3rd Nov 2010|Memoria|none|How are you doing? Thanks! Hi Everyone, I wonder if somebody could help me. I have been at this for hours and am really struggling. I have a timer which I have set up for a quiz. The quiz opens in a javascript shadow box. When the quiz is opened a session variable for the timer is set up to keep track of the time. What I need is for this session variable to end when the shadow box is closed. I have a onClose hook to peform actions when the shadow box is closed which is in javascript. Obviously I cannot end the session variable in the javascript function due to js being client side and php being server side. Has anyone any suggestions how I can resolve this issue. I need to end this session variable as if the user exits the quiz and then selects another quiz to do the timer uses the current time session rather than assigning the new time value for that particular quiz. Thanks in advance. Edd |