PHP - Keeping Users Logged In
What are the different ways you can keep a User "logged in"?
From what I *vaguely* recall from a year or two ago when I read a whole hoard of PHP books, you commonly use cookies and sessions. But I'm asking this more from an OOP standpoint than a PHP standpoint. Let's say I have a User record in my database, and a User comes along and attempts to log in. In OOP terms, I would think you'd call some class to help log them in, and upon successfully logging in, you would "load" the User object into memory and set the "LoggedIn" field to "True". Then as long as that field was set in their object, they could surf all over the place and do things like change their account and buy things. Is that how you would do it in OOP? TomTees Similar TutorialsHi all, Does anyone know of an effective way of find out whether a user is still logged in and they haven't left? Sam Sites such as this one often show the logged on users and guests.
I have no reason to need to do so, but am curious on how this is accomplished.
For users, yes, you've authenticated them and logged them on regardless of IP address, but how do you know they didn't just close their browser?
For guests, are they just using IP address? And still, how do you know when they leave?
PS. How should I include an image in a post like I did? What I did was first attach a file, and then edit the post to include that file as an image. Couldn't seem to include an image off my local PC. Not a better way?
Attached Files
Capture.PNG 4.13KB
0 downloads Hello all...fairly new to this php/mysql thing... working on my final project thats due in about 24 hours... and i hit a rut... im making a pretty basic, online classifieds site. users can sign up, login, post new listings and view others listings by clicking on different categories. the problem i am having right now is this...When the user clicks on "My listings" i need it to pull only the listings that were created by that users user_id, which is the primary key in my user_info table...my professor suggested storing it in hidden field through the login submit button...very confused and frustrated... any help is much appreciated... I am trying to build my own custom login script. What I am trying to achieve is once a user has logged in depending on wether they have checked the keep me logged in checkbox they have two options. If they haven't checked it then it creates session variables only, and if they have checked it it also creates cookie variable as well as the session variables. If they then close their browser / tab without logging out and then revisit the site they will get redirected to login page because the active session variable is no longer there. As soon as they land on the loggin page, it automatically checks for the cookie variable and if it exists, it uses it to login and redirect them automatically. However the problem that I am facing is that the session variable is still being trashed after a default amount of idle time and forcing a login. My goal is that the user shouldn't have to re-login unless they have either clicked the logout button. Can someone please have a look through my solution and advise me as to wether this is the correct method that I am implementing, if there is an easier way to achieve what I want, and is this a secure way to handle user logins. Thanks in advance. Andrew Here is the check code I have placed at the top of each admin page. Code: [Select] <?php session_start(); $url = (!empty($_SERVER['HTTPS'])) ? "https://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'] : "http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']; $uid = $_SESSION['uid']; if (!isset($uid)) { header('location:login.php?redirect='.$url); exit(); } ?> Next we have the code for the login.php file. Code: [Select] <?php include ('functions.php'); ?> <?php get_header('login'); ?> <div id="login-result"> <?php connect(); $redirect = htmlspecialchars(mysql_real_escape_string(addslashes($_GET['redirect']))); if(isset($_COOKIE['remembered'])){ $username = htmlspecialchars(mysql_real_escape_string(addslashes($_COOKIE['remembered']['username']))); $password = htmlspecialchars(mysql_real_escape_string(addslashes($_COOKIE['remembered']['password']))); $sql = "SELECT * FROM usersT WHERE username='$username' AND password='$password'"; $result = mysql_query($sql); $count = mysql_num_rows($result); $row = mysql_fetch_array($result); $uid = $row['uid']; $fname = $row['firstname']; $lname = $row['lastname']; $role = $row['role']; if($count==1){ $sql2 = "UPDATE usersT SET status = '1' WHERE uid = '$uid'"; $result2 = mysql_query($sql2); if($result2){ session_register("uid"); session_register("uname"); session_register("ulevel"); $_SESSION["uid"] = $uid; $_SESSION["uname"] = $fname; $_SESSION["ufullname"] = $fname . " " .$lname; $_SESSION["urole"] = $role; $home = get_option('home'); if(!empty($redirect)) { header( 'Location: '. $redirect ) ; exit(); } else { header( $home ) ; exit(); } } } else { echo "<div class=\"error rounded5 shadow\">Invalid username or password!</div>"; } } else if (isset($_POST['admin_login'])){ if(isset($_POST["username"]) && isset($_POST["password"])){ $username_p = htmlspecialchars(mysql_real_escape_string(addslashes($_POST["username"]))); $password_p = htmlspecialchars(mysql_real_escape_string(addslashes($_POST["password"]))); $psw = md5($password_p); $sql3 = "SELECT * FROM usersT WHERE username='$username_p' AND password='$psw'"; $result3 = mysql_query($sql3); $count3 = mysql_num_rows($result3); $row3 = mysql_fetch_array($result3); $uid = $row3['uid']; $fname = $row3['firstname']; $lname = $row3['lastname']; $role = $row3['role']; if($count3==1){ $sql4 = "UPDATE usersT SET status = '1' WHERE uid = '$uid'"; $result4 = mysql_query($sql4); if($result4){ session_register("uid"); session_register("uname"); session_register("ulevel"); $_SESSION["uid"] = $uid; $_SESSION["uname"] = $fname; $_SESSION["ufullname"] = $fname . " " .$lname; $_SESSION["urole"] = $role; $home = get_option('home'); if(isset($_POST['remember'])) { setcookie("remembered[username]", $username, time() + 86400 * 365 * 2); setcookie("remembered[password]", $psw, time() + 86400 * 365 * 2); } if(!empty($redirect)) { header( 'Location: '. $redirect ) ; exit(); } else { header( $home ) ; exit(); } } } else { echo "<div class=\"error rounded5 shadow\">Invalid username or password!</div>"; } } } ?> </div><!-- / login-results --> <div id="login" class="rounded5 shadow"> <form name="loginform" id="loginform" action="<?php $_SERVER['PHP_SELF']; ?>" method="post"> <p> <label for="username">Username<br> <input type="text" name="username" id="username" class="rounded5" value="<?php echo $username_p; ?>" size="20" tabindex="10" /></label> </p> <p> <label for="password">Password<br> <input type="password" name="password" id="password" class="rounded5" value="<?php echo $password_p; ?>" size="20" tabindex="20" /></label> </p> <p class="submit"> Keep me logged in<input type="checkbox" name="remember" id="remember" /><br /><br /><a href="" class="left">Lost your password?</a> <input type="submit" name="admin_login" id="admin_login" class="btn rounded10 right" value="Log In" tabindex="100" /> </p> <div class="cleaner"></div><!-- / cleaner --> </form> </div><!-- / login--> <?php get_footer('login'); ?> Finally here is the code I am using for the logout.php page. Code: [Select] <?php session_start(); include ('functions.php'); connect(); $uid = mysql_real_escape_string($_SESSION['uid']); $sql = "UPDATE usersT SET status = '0' WHERE uid = '$uid'"; $result = mysql_query($sql); if($result) { session_unset(); session_destroy(); if(isset($_COOKIE['remembered'])){ setcookie("remembered[username]", $username, time() - 3600); setcookie("remembered[password]", $psw, time() - 3600); header("location: login.php"); } exit(); } else { echo "You couldn't be logged out at this time."; } ?> Hai..
currently i am developing client dashboard using php/mysql.Here is my problem i need to create a tab named as notes.Using this tab the logged in users can add a new note or edit his existing note and save as text file.. I have dynamic images that have the "Like" button, it's basically like a wishlist. The way I want it to work is that when a user is not logged in, the 'Like' button will navigate them to a login popup (which I already made). Hello
I am trying to work out how many regular users I have to my site and how long those users tend to be users..
So, I have a table that logs every time a user visits my site and logs in, it stores the date / time as a unix timestamp and it logs their user id.
I started by getting the id's of any user who logs in more than 5 times in a specified period, but now I want to extend that...
SELECT userID as user, count(userID) as logins FROM login_history where timestamp > UNIX_TIMESTAMP('2014-06-01 00:00:00') and timestamp < UNIX_TIMESTAMP('2014-07-01 00:00:00') group by user having logins > 5; I just discovered that I have a major security flaw with my website. Anyone who logs in to the website can easily access other users information as well as delete and edit other users information just by changing the ID variable in the address bar. I have user ID Session started on these pages but still people can do anything they like with other users information just by editing the address bar. For example if your logged in in the address bar of www.mywebsite.com/delete_mystuff.php?id=5 and change the "5" say to a "9" then you will have access to user#9 information. Every important page that I have has this code: Code: [Select] session_start(); if (!isset($_SESSION['user_id'])) { // Start defining the URL. $url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']); // Check for a trailing slash. if ((substr($url, -1) == '/') OR (substr($url, -1) == '\\') ) { $url = substr ($url, 0, -1); // Chop off the slash. } // Add the page. $url .= '/index.php'; ob_end_clean(); // Delete the buffer. header("Location: $url"); exit(); // Quit the script. } else { //Else If Logged In Run The Script if((isset($_GET['id'])) && (is_numeric($_GET['id']))) { $id = (int) $_GET['id']; } elseif ((isset($_POST['id'])) && (is_numeric($_POST['id']))) { $id = (int) $_POST['id']; } else { echo ' No valid ID found, passed in url or form element'; exit(); } What am I doing wrong? Please help if you know how to correct this. Many thanks in advance. Alright, so I'm fairly new to PHP coding and I still have a ton to learn, so it's not surprising that I ran into a problem pretty quickly. I've setup a database and even managed to scrap together a SIMPLE member management system. All of it works, but I still need one thing. A lot of sites I visit which allow users to signup have this at the top; Login or Register. Nothing huge, just in the corner, know what I mean? I was wondering how I do this? Also, after someone logs in, how do I change that to show "You are logged in as [username] and then a logout option? I am making a login system and I have done it before. ryanweekly.com is the site I am trying to put it on. Here is the script to the home page. Here is the code I am having a problem with: Code: [Select] <?php if (empty($username)) include ("loginbar.php"); if (!empty($username)) include ("logged.php"); ?> Code: [Select] <?PHP $username = $_SESSION['MM_Username']; ?> <?php require_once('Connections/ryanweeklyusers.php'); ?> <?php if (!function_exists("GetSQLValueString")) { function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") { if (PHP_VERSION < 6) { $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue; } $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue); switch ($theType) { case "text": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "long": case "int": $theValue = ($theValue != "") ? intval($theValue) : "NULL"; break; case "double": $theValue = ($theValue != "") ? doubleval($theValue) : "NULL"; break; case "date": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "defined": $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue; break; } return $theValue; } } ?> <?php // *** Validate request to login to this site. if (!isset($_SESSION)) { session_start(); } $loginFormAction = $_SERVER['PHP_SELF']; if (isset($_GET['accesscheck'])) { $_SESSION['PrevUrl'] = $_GET['accesscheck']; } if (isset($_POST['username'])) { $loginUsername=$_POST['username']; $password=$_POST['password']; $MM_fldUserAuthorization = ""; $MM_redirectLoginSuccess = "index.php"; $MM_redirectLoginFailed = "index.php?reg=loger"; $MM_redirecttoReferrer = false; mysql_select_db($database_ryanweeklyusers, $ryanweeklyusers); $LoginRS__query=sprintf("SELECT username, password FROM users WHERE username=%s AND password=%s", GetSQLValueString($loginUsername, "text"), GetSQLValueString($password, "text")); $LoginRS = mysql_query($LoginRS__query, $ryanweeklyusers) or die(mysql_error()); $loginFoundUser = mysql_num_rows($LoginRS); if ($loginFoundUser) { $loginStrGroup = ""; if (PHP_VERSION >= 5.1) {session_regenerate_id(true);} else {session_regenerate_id();} //declare two session variables and assign them $_SESSION['MM_Username'] = $loginUsername; $_SESSION['MM_UserGroup'] = $loginStrGroup; if (isset($_SESSION['PrevUrl']) && false) { $MM_redirectLoginSuccess = $_SESSION['PrevUrl']; } header("Location: " . $MM_redirectLoginSuccess ); } else { header("Location: ". $MM_redirectLoginFailed ); } } $ruser = $_REQUEST['Y2User-53201']; ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Ryan Weekly</title> <style type="text/css"> body { background-color: #E3E5E2; } </style> <script src="SpryAssets/SpryValidationTextField.js" type="text/javascript"></script> <link href="SpryAssets/SpryValidationTextField.css" rel="stylesheet" type="text/css" /> </head> <style type="text/css"> <!-- body { font-size:12px; font-family:Verdana, Arial, Helvetica, sans-serif; } div#wrapper { width: 80%; background-color:#FFFFFF; margin-top: 50px; margin-bottom: 50px; margin-left: auto; margin-right: auto; padding: 0px; border: thin solid #000000; } div#header { padding: 15px; margin: 0px; text-align: center; } div#nav { width: 25%; padding: 10px; margin-top: 1px; float: left; border: thin solid #000000; } div#main { margin-left: 30%; margin-top: 1px; padding: 10px; border: thin solid #000000; } div#underhead { padding: 15px; margin: 0px; border-top: thin solid #000000; } { ul.nav a:hover, ul.nav a:active, ul.nav a:focus { /* this changes the background and text color for both mouse and keyboard navigators */ background: #6F7D94; color: #FFF; } .content ul, .content ol { padding: 0 15px 15px 40px; /* this padding mirrors the right padding in the headings and paragraph rule above. Padding was placed on the bottom for space between other elements on the lists and on the left to create the indention. These may be adjusted as you wish. */ } /* ~~ The navigation list styles (can be removed if you choose to use a premade flyout menu like Spry) ~~ */ ul.nav { list-style: none; /* this removes the list marker */ border-top: 1px solid #666; /* this creates the top border for the links - all others are placed using a bottom border on the LI */ margin-bottom: 15px; /* this creates the space between the navigation on the content below */ } ul.nav li { border-bottom: 1px solid #666; /* this creates the button separation */ } ul.nav a, ul.nav a:visited { /* grouping these selectors makes sure that your links retain their button look even after being visited */ padding: 5px 5px 5px 15px; display: block; /* this gives the link block properties causing it to fill the whole LI containing it. This causes the entire area to react to a mouse click. */ text-decoration: none; background: #8090AB; color: #000; } ul.nav a:hover, ul.nav a:active, ul.nav a:focus { /* this changes the background and text color for both mouse and keyboard navigators */ background: #6F7D94; color: #FFF; } /* ~~ The footer ~~ */ .footer { padding: 10px 0; background: #6F7D94; position: relative;/* this gives IE6 hasLayout to properly clear */ clear: both; /* this clear property forces the .container to understand where the columns end and contain them */ } /* ~~ miscellaneous float/clear classes ~~ */ .fltrt { /* this class can be used to float an element right in your page. The floated element must precede the element it should be next to on the page. */ float: right; margin-left: 8px; } .fltlft { /* this class can be used to float an element left in your page. The floated element must precede the element it should be next to on the page. */ float: left; margin-right: 8px; } .clearfloat { /* this class can be placed on a <br /> or empty div as the final element following the last floated div (within the #container) if the #footer is removed or taken out of the #container */ clear:both; height:0; font-size: 1px; line-height: 0px; } --> </style> <body> <div align="Left"> <p><img src="indexp.png" width="728" height="90" /></p> </div> <div id="underhead"> <?php if (empty($username)) include ("loginbar.php"); if (!empty($username)) include ("logged.php"); ?> <?PHP $justreg = $_REQUEST['reg']; if ($justreg == yes) echo 'Thanks For Registering!'; if ($justreg == loger) echo 'There was an error while tring to log you in.'; if ($justreg == out) echo 'You were logged out!'; ?> </div> <?php include("menu.php"); ?> <div id="main"> <p>Welcome To Ryan Weekly! The all new and improved site!</p> <p>I have a song on itunes!</p> <p> <object width="400" height="160"> <param name="movie" value="http://widget.tunecore.com/swf/tc_run_h_v2.swf?widget_id=62316" /> <param name="allowFullScreen" value="true" /> <param name="allowscriptaccess" value="always" /> <embed src="http://widget.tunecore.com/swf/tc_run_h_v2.swf?widget_id=62316" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="400" height="160"></embed> </object> </p> </div> Ryan Weekly 2009 - 2011 (May 11, 2011 at 6:00PM Is our 3 Year anniversary!) <script type="text/javascript"> var sprytextfield1 = new Spry.Widget.ValidationTextField("sprytextfield1"); var sprytextfield2 = new Spry.Widget.ValidationTextField("sprytextfield2"); </script> </body> </html> Hi guys, Have a wierd scenario where my brain is simply refusing to think. I have small script which let's a user log in through a login screen. Thats ok. I can check whether the user is already logged in the same machine through sessions. My requirement is : I need to restrict the same username logging in from multiple computers at any one given time. In other words, a user can not use two machines to login at the same time. Can someone please suggest a method to solve this scenario. Your help is very much appreciated. Cheers Elabuwa Hello all, This has probably been asked before but I couldn't find through search. And I'm pretty sure is not possible, but... Is there a way of displaying the windows logged on user? or get the name of the compter? as I know I can get the ip address. The reason I ask. Each user has their own network account but on occasion we need to log on a user as a generic account we have. And I want to check if it's this user accessing the page so different options etc can be displayed. I could use the computer name to check this as we log all activity. I could then query the log using the comp name to find logged on user. Unfortunately the log does not hold ip, which would seem obvious but it doesn't Many Thanks Hi guys, Im building a website for a company http://www.eminence-logistics.co.uk and the client wants a log in system which im having problems with. The registration system is all working fine. If you go to the website you can see where the login form is. Now when the user isn't logged in i need the form to show, but when the user IS logged in i would like a message replacing the form saying welcome, along with a log out button. How do i do this? Thankyou very much Enlighten Hi i am wondering how i can redirect someone that's not logged in?
hello i am stuck and hoping you can help, i have created this function and its not working correctly, what i am trying to do is when someone is logged in they get this line of code echo "<a href=\"update-content.php?id=5\">Edit</a> | <a href=\"delete-content.php?id=5\">Delete</a>"; which is ok as i dont want that to work yet and if your not logged in you dont get it. i have added //show when logged in and show not logged in so you know which code i want it to load when at the moment its only loading the not logged in one even if you are. i have looked on google read up on php sites but cant figure out how to do it, so hoping you guys will tell me were i gone wrong and how to correct it, thanks again heres the code. function get_left() { if (isset($_GET['page'])) { $page = $_GET['page']; //Show Page not logged in $sql = "SELECT title,body FROM content WHERE page = '$page' AND location = 'left' AND disabled = 'no' ORDER BY id"; $res = mysql_query($sql) or die (mysql_error()); while($row = mysql_fetch_assoc($res)){ echo '<h1>' . $row['title'] . '</h1>'; echo '<p>' . $row['body'] . '</p>'; } } //show when logged in elseif ($_SESSION['username']&&(isset($_GET['page']))){ $sql = "SELECT title,body FROM content WHERE page = '$page' AND location = 'left' AND disabled = 'no' ORDER BY id"; $res = mysql_query($sql) or die (mysql_error()); while($row = mysql_fetch_assoc($res)){ echo '<h1>' . $row['title'] . '</h1>'; echo '<p>' . $row['body'] . '</p>'; echo "<a href=\"update-content.php?id=5\">Edit</a> | <a href=\"delete-content.php?id=5\">Delete</a>"; } } } Hi. I'm new to php. I created a register, log in, welcome, and log out page for my site. They are all working accordingly. I'm having one problem that I can't seem to fix. I would like to stay logged in as I navigate other pages of my site. Everytime i click on a link to another page within my site I get logged out. I know this issue might pertain to using session but thats all I was able to find using google search. Can anyone help? Much appreciated. 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 on my site: http://www.retroandvintage.co.uk whne you login ast test/test teh search does not work?! search page code Code: [Select] <?php session_start(); include_once("config.php"); $ebits = ini_get('error_reporting'); error_reporting($ebits ^ E_NOTICE); // Check user logged in already: checkLoggedIn("yes"); ?> <!doctype html> <html> <head> <title>Pubs and bars in <? echo $Townsearch;?></title> <meta name="description" content="Pubs, bars and restuarants in <? echo $Townsearch;?>" /> <meta name="keywords" content="<? echo $Townsearch;?>, pubs, bars, food, drink, nightlife" /> <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/style.css" title="default" /> <link rel="alternate stylesheet" type="text/css" href="css/style1.css" title="1" /> <link rel="alternate stylesheet" type="text/css" href="css/style2.css" title="2" /> <script type="text/javascript" src="js/stylechanger.js"></script> <script type="text/javascript" src="js/jquery-1.2.1.pack.js"></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?rsTown=<? echo $Town ?>&rsCounty=<? echo $County ?>"> Town/City: <input type="text" size="26" class="searchbox" value="" name="rsTown" id="inputString" onKeyUp="lookup(this.value);" onBlur="fill();" /> <input type="hidden" value="<? echo $County ?>" name="rsCounty" 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="#">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</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 in <? echo $Town;?>, <? $_SESSION['county'];?></h2> <p>Posted on <time datetime="2009-06-29T23:31+01:00">June 29th 2009</time> by <a href="#">Mads Kjaer</a> - <a href="#comments">3 comments</a></p> </header> <?php $tableName="pubs"; $targetpage = "search.php"; $limit = 20; $query = "SELECT COUNT(*) as num FROM $tableName WHERE rsTown LIKE '$Town%'"; $total_pages = mysql_fetch_array(mysql_query($query)); $total_pages = $total_pages['num']; $stages = 3; $page = $_GET['page']; if($page){ $start = ($page - 1) * $limit; }else{ $start = 0; } // Get page data $query1 = "SELECT * FROM $tableName WHERE rsTown LIKE '$Town%' 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&rsTown=$Town'>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&rsTown=$Town&rsCounty=$County'>$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&rsTown=$Town&rsCounty=$County'>$counter</a>";} } $paginate.= "..."; $paginate.= "<a href='$targetpage?page=$LastPagem1&rsTown=$Town&rsCounty=$County'>$LastPagem1</a>"; $paginate.= "<a href='$targetpage?page=$lastpage&rsTown=$Town&rsCounty=$County'>$lastpage</a>"; } // Middle hide some front and some back elseif($lastpage - ($stages * 2) > $page && $page > ($stages * 2)) { $paginate.= "<a href='$targetpage?page=1&rsTown=$Town&rsCounty=$County'>1</a>"; $paginate.= "<a href='$targetpage?page=2&rsTown=$Town&rsCounty=$County'>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&rsTown=$Town&rsCounty=$County'>$counter</a>";} } $paginate.= "..."; $paginate.= "<a href='$targetpage?page=$LastPagem1&rsTown=$Town&rsCounty=$County'>$LastPagem1</a>"; $paginate.= "<a href='$targetpage?page=$lastpage&rsTown=$Town&rsCounty=$County'>$lastpage</a>"; } // End only hide early pages else { $paginate.= "<a href='$targetpage?page=1&rsCounty=$County'>1</a>"; $paginate.= "<a href='$targetpage?page=2&rsCounty=$County'>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&rsTown=$Town&rsCounty=$County'>$counter</a>";} } } } // Next if ($page < $counter - 1){ $paginate.= "<a href='$targetpage?page=$next&rsTown=$Town&rsCounty=$County'>next</a>"; }else{ $paginate.= "<span class='disabled'>next</span>"; } $paginate.= "</div>"; } echo $total_pages.' Results'; // pagination echo $paginate; ?> <ul> <?php while($row = mysql_fetch_array($result)) { echo '<li>'.$row['rsPubName'].', '.$row['rsTown'].', '.$row['rsCounty'].'</li>'; } $_SESSION['county'] = $row['rsCounty']; ?> </ul> </article> </section> <section id="comments"> <h3>Comments</h3> <article> <header> <a href="#">George Washington</a> on <time datetime="2009-06-29T23:35:20+01:00">June 29th 2009 at 23:35</time> </header> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut.</p> </article> <article> <header> <a href="#">Benjamin Franklin</a> on <time datetime="2009-06-29T23:40:09+01:00">June 29th 2009 at 23:40</time> </header> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut.</p> </article> <article> <header> <a href="#">Barack Obama</a> on <time datetime="2009-06-29T23:59:00+01:00">June 29th 2009 at 23:59</time> </header> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut.</p> </article> </section> <form action="" method="POST" method="post"> <h3>Post a comment</h3> <p> <label for="name">Name</label> <input name="name" id="name" type="text" required /> </p> <p> <label for="email">E-mail</label> <input name="email" id="email" type="email" required /> </p> <p> <label for="website">Website</label> <input name="website" id="website" type="url" /> </p> <p> <label for="comment">Comment</label> <textarea name="comment" id="comment" required></textarea> </p> <p> <input type="submit" value="Post comment" /> </p> </form> </div> <aside> <section> <header> <h3>Members Login Area</h3> </header> <h4>Welcome <? print($_SESSION["rsUser"]); ?></h4> <ul> <li><a href="#">Sign up</a></li> <li><a href="#">Forgot Password</a></li> </ul> </section> <section> <header> <h3>Archives</h3> </header> <ul> <li><a href="#">December 2008</a></li> <li><a href="#">January 2009</a></li> <li><a href="#">February 2009</a></li> <li><a href="#">March 2009</a></li> <li><a href="#">April 2009</a></li> <li><a href="#">May 2009</a></li> <li><a href="#">June 2009</a></li> </ul> </section> </aside> </div> <footer> <div> <section id="about"> <header> <h3>About</h3> </header> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco <a href="#">laboris nisi ut aliquip</a> ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> </section> <section id="blogroll"> <header> <h3>Blogroll</h3> </header> <ul> <li><a href="#">NETTUTS+</a></li> <li><a href="#">FreelanceSwitch</a></li> <li><a href="#">In The Woods</a></li> <li><a href="#">Netsetter</a></li> <li><a href="#">PSDTUTS+</a></li> </ul> </section> <section id="popular"> <header> <h3>Popular</h3> </header> <ul> <li><a href="#">This is the title of a blog post</a></li> <li><a href="#">Lorem ipsum dolor sit amet</a></li> <li><a href="#">Consectetur adipisicing elit, sed do eiusmod</a></li> <li><a href="#">Duis aute irure dolor</a></li> <li><a href="#">Excepteur sint occaecat cupidatat</a></li> <li><a href="#">Reprehenderit in voluptate velit</a></li> <li><a href="#">Officia deserunt mollit anim id est laborum</a></li> <li><a href="#">Lorem ipsum dolor sit amet</a></li> </ul> </section> </div> </footer> </body> </html> Hi all,
My company has a php site on wordpress that i’m trying to add google AD tracking to. Now, on the live site, when i’m logged into word-press and run the page, I can see the triggers firing fine on Tag assistant, if i un-comment the alerts, they also fire. When i log out of word-press and hit the page, nothing happens at all. No alerts, no google triggers, nothing in the php is running? Any ideas whats going on ?
<script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'AW-1234567897'); <?php $url = $_SERVER['REQUEST_URI']; if ($url =="/thankyou/") { print " gtag('event', 'conversion', {'send_to': 'AW-1234567897/1234567897', 'value': 1.0, 'currency': 'GBP' }); "; print " gtag('event', 'conversion', {'send_to': 'AW-1234567897/1234567897'}); "; //Print "alert('OK');"; //Print "alert('" . $url . "');"; } ?> </script> tia Dave Please help with my register page: http://www.retroandvintage.co.uk/register.php after someone has registered they are stuck on reg_script.php and don't get redirected back to main.php being already logged in?! here is my code: Code: [Select] <?php session_start(); include_once("config.php"); //include_once("functions.php"); require_once('captcha/recaptchalib.php'); $privatekey = "6Ldhhr4SAAAAAKFoL2INOZV0_VuF6_z3OwDjVFNn"; $resp = recaptcha_check_answer ($privatekey, $_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]); if (!$resp->is_valid) { // What happens when the CAPTCHA was entered incorrectly die ("The reCAPTCHA wasn't entered correctly. Go back and try it again." . "(reCAPTCHA said: " . $resp->error . ")"); } else { // Your code here to handle a successful verification $rsPostCode = $_POST['rsPostCode']; $rsGender = $_POST['rsGender']; $rsUser = $_POST['rsUser']; $rsPass = $_POST['rsPass']; $rsEmail = $_POST['rsEmail']; $rsMobile = $_POST['rsMobile']; $rsAge = $_POST['rsAge']; $sql = "INSERT INTO members_copy (RSPOSTCODE, RSGENDER, RSUSER, RSPASS, RSEMAIL, RSMOBILE, RSAGE) VALUES ('$rsPostCode', '$rsGender', '$rsUser', '$rsPass', '$rsEmail', '$rsMobile', '$rsAge');"; //echo $sql; mysql_query($sql); $ebits = ini_get('error_reporting'); error_reporting($ebits ^ E_NOTICE); /* Login script: This script does the following: Checks that the user is NOT already logged in - if they are they are redirected to the members page by the 'checkLoggedIn()' function. Checks if the login form has been submitted - if so, the 'login' and 'password' fields are checked to ensure they are of the correct format and length. If there are any problems here an error is added to the $messages array and then the script executes the 'doIndex()' function - this function basically outputs the main 'index' page for this script - ie the login form. If there are no problems with the previous step, the 'login' and 'password' field data is passed to the 'checkPass' function to check that an entry exists in the 'users' table for that login/password pair. If nothing is returned from the 'checkPass()' function, an error is added to the $messages array and the 'doIndex()' function is called as above. If a row of data is returned from the 'users' table, the data is passed to the 'cleanMemberSession()' function - which initializes session variables and logs the user in. The user is then forwarded to the members page. If the form hasn't yet been submitted, then the 'doIndex()' function is called and the login page is displayed. */ // Check user not logged in already: checkLoggedIn("no"); // Page title: $title="Member Login Page"; // if $submit variable set, login info submitted: if(isset($_POST["Register"])) { // // Check fields were filled in // // login must be between 4 and 15 chars containing alphanumeric chars only: field_validator("rsUser", $_POST["rsUser"], "alphanumeric", 4, 15); // password must be between 4 and 15 chars - any characters can be used: field_validator("rsPass", $_POST["rsPass"], "string", 4, 15); // if there are $messages, errors were found in validating form data // show the index page (where the messages will be displayed): if($messages){ doIndex(); // note we have to explicity 'exit' from the script, otherwise // the lines below will be processed: exit; } // OK if we got this far the form field data was of the right format; // now check the user/pass pair match those stored in the db: /* If checkPass() is successful (ie the login and password are ok), then $row contains an array of data containing the login name and password of the user. If checkPass() is unsuccessful however, $row will simply contain the value 'false' - and so in that case an error message is stored in the $messages array which will be displayed to the user. */ if( !($row = checkPass($_POST["rsUser"], $_POST["rsPass"])) ) { // login/passwd string not correct, create an error message: $messages[]="Incorrect login/password, try again"; } /* If there are error $messages, errors were found in validating form data above. Call the 'doIndex()' function (which displays the login form) and exit. */ if($messages){ doIndex(); exit; } /* If we got to this point, there were no errors - start a session using the info returned from the db: */ cleanMemberSession($row["rsUser"], $row["rsPass"]); // and finally forward user to members page (populating the session id in the URL): header("Location: main.php"); /* This function displays the default 'index' page for this script. This consists of just a simple login form for the user to submit their username and password. */ } } ?> |