PHP - How Do I Navigate Users To The Login Popup When They Click On A 'like' Button And Not Logged In At The Same Time?
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).
Similar TutorialsSites 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 Hi all, Does anyone know of an effective way of find out whether a user is still logged in and they haven't left? Sam 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 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.. 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'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 all, I have a problem I am not sure how to sort, hopefully someone here can help. I have a sliding login panel on a website that I am making. Its quite discreet. I have a stripped down version here that you can see: http://mgdesign.hostultra.com/login_test/login_test.php On the page I am making, users with a log in enter their details and will be taken to the restricted page. I would like this sliding panel to be on every page when the user is not logged in. Once they log in from the sliding panel they can still surf around all the main site pages. When they log out the session dies and it reverts to the home page. However, when they are logged in I would like the sliding login panel to disappear from the top of each page. Is there any way I can do this simply? Any help or advice would be greatly appreciated. Hi, i have a site www.gnetuk.net where people can register and login,. thats all fine but what code can i use on my php pages to see whos logged in im sure its going to be a simple line of code or smthink but i am new to this stuff. PLEASE HELP <G> Hi, I am creating an admin page that allows me to view requests for sheet music that is not currently on my website. (View image to get an idea of what we're talking about). On this page are 6 columns. ID (autoincremented) This is the # the request is Userid - the user's id artist - the name of the artist the user requested title - the name of the title the user requested added - after I have manually added the sheet music to my site, i click added which will set the "added" column in my sql table to "yes". Also, once added is clicked, an email will be sent to the user that originally requested the sheet. delete - This deletes the row in the sql database, and removes it from view on my page. At the bottom of the page, there is also a button called "Added All", which goes through and sets the "added" status to "yes" for all rows on the page. So, the problem I'm having right now, is emailing the user after I have selected Added. After I figure this out, I need to implement it into the "Added All" button, which will email all the corresponding users. Here is what I have come up with. Any input appreciated. I'm not getting any errors at this point. I tested my variables and all are echoing out correctly. The area that I have specified to email the user is in this if statement: if ($confirm=="true" && isset($_GET['id'])) Here's my code. Thanks <?php session_start(); include_once('../inc/connect.php'); include_once('../inc/admin.php'); if (isset($_SESSION['username'])){ $loginstatus = "logout"; if(!isset($_SESSION['sort_counter'])) {$_SESSION['sort_counter'] = 1;} if(($_SESSION['sort_counter']%2) == 0){ //test even value $sortcount = "DESC"; }else{ //odd value $sortcount = ""; } $result = mysql_query("SELECT * FROM requests WHERE added='no' ORDER BY id"); $requestedquery = mysql_query("SELECT added FROM requests WHERE added='no'"); $requestedcount = mysql_num_rows($requestedquery); $addedquery = mysql_query("SELECT added FROM requests WHERE added='yes'"); $addedcount = mysql_num_rows($addedquery); $getuserinfo = mysql_query("SELECT * FROM users"); $row2 = mysql_fetch_assoc($getuserinfo); $sort = $_GET['sort']; $delete = $_GET['delete']; $confirm = $_GET['confirm']; ///////////////////////////////// if ($sort=='id'){ // $result = mysql_query("SELECT * FROM users ORDER BY id"); $result = mysql_query("SELECT * FROM requests WHERE added='no' ORDER BY id $sortcount"); $_SESSION['sort_counter'] = $_SESSION['sort_counter'] + 1; //increment after every run } if ($sort=='userid'){ // $result = mysql_query("SELECT * FROM users ORDER BY username"); $result = mysql_query("SELECT * FROM requests WHERE added='no' ORDER BY userid $sortcount"); $_SESSION['sort_counter'] = $_SESSION['sort_counter'] + 1; //increment after every run } if ($sort=='artist'){ // $result = mysql_query("SELECT * FROM users ORDER BY email"); $result = mysql_query("SELECT * FROM requests WHERE added='no' ORDER BY artist $sortcount"); $_SESSION['sort_counter'] = $_SESSION['sort_counter'] + 1; //increment after every run } if ($sort=='title'){ // $result = mysql_query("SELECT * FROM users ORDER BY email"); $result = mysql_query("SELECT * FROM requests WHERE added='no' ORDER BY title $sortcount"); $_SESSION['sort_counter'] = $_SESSION['sort_counter'] + 1; //increment after every run } if ($sort=='file'){ // $result = mysql_query("SELECT * FROM users ORDER BY email"); $result = mysql_query("SELECT * FROM requests WHERE added='no' ORDER BY file $sortcount"); $_SESSION['sort_counter'] = $_SESSION['sort_counter'] + 1; //increment after every run } /// FIX THIS AREA if ($confirm=="true" && isset($_GET['id'])) { mysql_query('UPDATE `requests` SET `added`="yes" WHERE id = ' . (int)$_GET['id']); $useremailquery = mysql_query("SELECT email FROM users WHERE id=".$row2['id'].""); $emailrow = mysql_fetch_assoc($useremailquery); $useremail = $emailrow['email']; $to = $useremail; $subject = "Sheet requested ready for download!"; $Email = "admin@mysite.com"; mail("$to", "$subject", " Hello, <br />The sheet that you requested on Sheet Music site is now ready for download.<br /> Thank you<br /><strong>Sheet Music site</strong>", "$Email"); echo "<SCRIPT language='JavaScript'><!-- window.location='requestedsheets.php';//--> </SCRIPT>"; } if ($delete=="true" && isset($_GET['id'])) { mysql_query('DELETE FROM `requests` WHERE id = ' . (int)$_GET['id']); echo "<SCRIPT language='JavaScript'><!-- window.location='requestedsheets.php';//--> </SCRIPT>"; } if ($delete=="false" && isset($_GET['id'])) { echo "<SCRIPT language='JavaScript'><!-- window.location='requestedsheets.php';//--> </SCRIPT>"; } ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html lang="en-US" xml:lang="en-US" xmlns="http://www.w3.org/1999/xhtml"> <head> <link rel="stylesheet" type="text/css" href="../styles/style.css" /> <link rel="stylesheet" type="text/css" href="../styles/requestedsheets.css" /> <script type="text/javascript"> function make_blank() { if(document.login.username.value =="Username"){ document.login.username.value =""; document.login.username.style.color ="#000000"; } } function make_blank1() { if(document.login.password.value =="Password"){ document.login.password.value =""; document.login.password.type ="password"; document.login.password.style.color ="#000000"; } } function undoBlank() { if(document.login.username.value == ""){ document.login.username.value ="Username"; document.login.username.style.color="#ccc"; } } function undoBlankpass() { if(document.login.password.value == ""){ document.login.password.value ="Username"; document.login.password.style.color="#cccccc"; } } </script> </head> <body bgcolor="#343331"> <!-- Header --> <div id="header"> <div id="headerleft"></div> <div id="headermiddle"><a href="../index.php"><img src="../img/logo.png"></a></div> <div id="headerright"> <?php echo "<form name='login' action='../inc/$loginstatus.php' method='POST'>";?> <div class="loginboxdiv" id="username"> <input type="text" class="loginbox" name="username" value="Username" onFocus="make_blank();" onBlur="undoBlank();"> </div> <div class="loginboxdiv" id="password"> <input class="loginbox" type="text" name="password" type="text" value="Password" onFocus="make_blank1();" onBlur="undoBlankpass();"> </div> <div id="login"> <?php echo "<input type='image' src='../img/$loginstatus.png' alt='".ucfirst($loginstatus)."'>";?> </div> </form> <div id="register"> <a href="../register.php"><img src="../img/register.png"></a> </div> <div id="forgotpassword"> <a href="../resetpassword.php" class="forgot">Forgot Password?</a> </div> </div> </div> <!-- Content Top --> <div id="contenttop"> <div id="links"> <table cols="7"> <tr> <td align="center" valign="middle" width="100px" height="48px"><a href="../index.php"><img src="../img/home.png"></a></td> <td align="center" valign="middle" width="100px" height="48px"><a href="../member.php"><img src="../img/member.png"></a></td> <td align="center" valign="middle" width="100px" height="48px"><a href="../addsheet.php"><img src="../img/addsheet.png"></a></td> <td align="center" valign="middle" width="100px" height="48px"><a href="../advertise.php"><img src="../img/advertise1.png"></a></td> <td align="center" valign="middle" width="100px" height="48px"><a href="../faq.php"><img src="../img/faq.png"></a></td> <td align="center" valign="middle" width="100px" height="48px"><a href="../terms.php"><img src="../img/terms.png"></a></td> <td align="center" valign="middle" width="100px" height="48px"><a href="../contact.php"><img src="../img/contact.png"></a></td> </tr> </table> <!-- 92x30 --> </div> </div> <!-- Content Middle --> <div id="contentmiddle"> <div id="content"> <?php include('inc/navadmin.php'); echo "<br /><div style='font-size: 28px; text-align: center;'>Requested Sheets</div> <div id='headcont'> <div id='requested'>Requested Sheets: ".$requestedcount."</div> <div id='added'>Added Sheets: ".$addedcount."</div> </div><br /> <table border='1' align='center'> <tr> <th bgcolor='#cccccc'><a href='requestedsheets.php?sort=id'>ID</a></th> <th bgcolor='#cccccc'><a href='requestedsheets.php?sort=userid'>UserID</a></th> <th bgcolor='#cccccc'><a href='requestedsheets.php?sort=artist'>Artist</a></th> <th bgcolor='#cccccc'><a href='requestedsheets.php?sort=title'>Title</a></th> <th bgcolor='#cccccc'><a href='requestedsheets.php'>Added</a></th> <th bgcolor='#cccccc'><a href='requestedsheets.php'>Delete</a></th> </tr>"; echo "<script type='text/javascript'> function show_delete() { var r=confirm('Delete?'); if (r==true) { // Delete return true; } else { // Don't Delete return false; } } "; echo " function show_undelete() { var r=confirm('Undelete?'); if (r==true) { // Undelete return true; } else { // Don't Undelete return false; } } </script>"; $usersids = ""; $i = 0; while($row = mysql_fetch_array($result)) { // $active = $row['active']; $color = "#ffffff"; $deleted = "Delete"; if ($active=='no'){ $color = "#f43636"; $deleted = "Undelete"; $active = "false"; $alert = "show_undelete"; } else{ $active = "true"; $alert = "show_delete"; } // echo "<tr>"; echo "<td align='center' width='40' bgcolor='$color'>" .$row['id']. "</td>"; echo "<td align='center' width='40'>" .$row['userid']. "</td>"; echo "<td align='center' width='230'>".ucwords($row['artist'])."</td>"; echo "<td align='center' width='230'>".ucwords($row['title'])."</td>"; echo "<td align='center' width='10'><a href='requestedsheets.php?confirm=true&id=" .$row['id'] . "'>Added</a></td>"; echo "<td align='center' width='10'><a href='requestedsheets.php?delete=$active&id=" .$row['id']. "' onclick='return $alert()'>$deleted</a></td>"; echo "</tr>"; $usersids[$i] = $row['id']; $i++; } echo " <tr> <td align='center' width='10' colspan='6'><a href='requestedsheets.php?confirm=all'>Added All</a></td> </tr>"; if ($confirm=="all") { $i = 0; mysql_data_seek($result,0); while($row = mysql_fetch_array($result)) { mysql_query('UPDATE `requests` SET `added`="yes" WHERE id = ' . $usersids[$i]); $i++; } echo "<SCRIPT language='JavaScript'><!-- window.location='requestedsheets.php';//--> </SCRIPT>"; } echo "</table>"; } else{ $loginstatus = "login"; } ?> </div> </div> <!-- Content Bottom --> <div id="contentbottom"> </div> </body> </html> Hi guys I am new to PHP and need som help. I have set up a site that allows a user to log in through a simple form where the data is then send to checklogin.php. Here the data is checked up against my sql database and if the login is correct the user is transfered to the "secret" members only site. All this works fine. My question is then, how do I get the members site to greet the member with "Hello 'username'"; of course where the username changes depending on the login. This is the part where the username and password is checked: <?php $host="mydbb10.surftown.dk"; // Host name $username="****"; // Mysql username $password="****"; // Mysql password $db_name="****"; // Database name $tbl_name="members"; // Table name // Connect to server and select databse. mysql_connect("$host", "$username", "$password")or die("cannot connect"); mysql_select_db("$db_name")or die("cannot select DB"); // username and password sent from form $myusername=$_POST['myusername']; $mypassword=$_POST['mypassword']; // To protect MySQL injection (more detail about MySQL injection) $myusername = stripslashes($myusername); $mypassword = stripslashes($mypassword); $myusername = mysql_real_escape_string($myusername); $mypassword = mysql_real_escape_string($mypassword); $sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'"; $result=mysql_query($sql); // Mysql_num_row is counting table row $count=mysql_num_rows($result); // If result matched $myusername and $mypassword, table row must be 1 row if($count==1){ // Register $myusername, $mypassword and redirect to file "korrekt.php" session_register("myusername"); session_register("mypassword"); echo "Tak fordi du loggede ind<br>Redirecter..."; header("location: ../forhandlerservice.php"); } else { echo "Forkert brugernavn eller password"; header("location: ../loginfejl.html"); } ?> and this is the first line of code on the members site: <? session_start(); if(!session_is_registered(myusername)){ header("location:login.html"); } ?> Sorry if I provided to much code, just want to make sure that I don't forget anything. Any help is appreciated. Thank you Hi, I have a restricted area for my work's company. This is an area where registered users with their own user name and password can access to download technical documents etc. I am hearing some reports that users will have to login twice to get to the area - This happens in Chrome, IE 7/8 and some Firefox's. It has only happened to me once or twice. Does anyone know why this may be? Here is the HTML code from the login form on the index page: Code: [Select] <form name="login_form" method="post" action="log.php?action=login"> <p>Login:<br /> <input type="text" name="user" /> </p> <p>Password: <br /><input type="password" name="pwd" /> </p> <p class="submit"> <input type="submit" value="Submit" name="submit" class="submit" /> </p> </form> Here is the log.php File: (personal connection details edited) Code: [Select] <?php $hostname = "IP:3306"; $username = "user"; $password = "password"; $database = "db_name"; $link = MYSQL_CONNECT($hostname,$username,$password); mysql_select_db($database); ?> <?php session_name("MyWebsiteLogin"); session_start(); if($_GET['action'] == "login") { $conn = mysql_connect("IP:3306","user","password"); $db = mysql_select_db("db_name"); //Your database name goes in this field. $name = $_POST['user']; $ip=$_SERVER['REMOTE_ADDR']; $country = file_get_contents('http://api.hostip.info/country.php?ip='.$ip); $q_user = mysql_query("SELECT * FROM customer WHERE username='$name'"); ?> <?php $insert_query = ("INSERT INTO login(username, ip, country) VALUES ('$name','$ip','$country');"); mysql_query($insert_query) or die('Error, insert query failed'); ?> <?php if(mysql_num_rows($q_user) == 1) { $query = mysql_query("SELECT * FROM customer WHERE username='$name'"); $data = mysql_fetch_array($query); if($_POST['pwd'] == $data['password']) { session_register("name"); header("Location: http://#/download/index.php?un=$name"); // This is the page that you want to open if the user successfully logs in to your website. exit; } else { header("Location: login.php?login=failed&cause=".urlencode('Wrong Password')); exit; } } else { header("Location: login.php?login=failed&cause=".urlencode('Invalid User')); exit; } } ?> Any help or ideas would be greatly appreciated. I am trying to make a login and direct for my clients. I have all the login stuff working but can't figure out how to redirect specific clients to their pages only. Any help anyone can offer would be great. Code: [Select] <?php //Start session session_start(); //Include database connection details require_once('config.php'); //Array to store validation errors $errmsg_arr = array(); //Validation error flag $errflag = false; //Connect to mysql server $link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD); if(!$link) { die('Failed to connect to server: ' . mysql_error()); } //Select database $db = mysql_select_db(DB_DATABASE); if(!$db) { die("Unable to select database"); } //Function to sanitize values received from the form. Prevents SQL injection function clean($str) { $str = @trim($str); if(get_magic_quotes_gpc()) { $str = stripslashes($str); } return mysql_real_escape_string($str); } //Sanitize the POST values $login = clean($_POST['login']); $password = clean($_POST['password']); //Input Validations if($login == '') { $errmsg_arr[] = 'Login ID missing'; $errflag = true; } if($password == '') { $errmsg_arr[] = 'Password missing'; $errflag = true; } //If there are input validations, redirect back to the login form if($errflag) { $_SESSION['ERRMSG_ARR'] = $errmsg_arr; session_write_close(); header("location: login-form.php"); exit(); } //Create query $qry="SELECT * FROM members WHERE login='$login' AND passwd='".md5($_POST['password'])."'"; $result=mysql_query($qry); //Check whether the query was successful or not if($result) { if(mysql_num_rows($result) == 1) { //Login Successful 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 { //Login failed header("location: login-failed.php"); exit(); } }else { die("Query failed"); } ?> hi... I have a site that allows user to download some files. at present if i type http://www.abc.com/files/xyz.zip it allows all the users to access and download files. I want only the login users can access these files....... pls help how to do this. thanks in advance I have a Yahtzee system Code: [Select] session_start(); $_SESSION['Yahtzee']['totaltime'] =time(); echo $_SESSION['Yahtzee']['totaltime']; Now, Long STORY Short when somone finishes playing the Yahtzee, I update there username with the score they had, and I want to update how long they have been playing, and it will be for "Total Time Playing globally" no matter how many games. If I do this session and echo it out, it echo's out the time, but I need it to echo out seconds instead so I can just add that to my totaltime field in my database each time they finished a game. Hello Guys, I would really appreciate some feedback on this one. Here's the basic simplified code for my bidding system site (querys for when a user sends a new valid bid): Its working fine but if 2 users send a bid at exactly the same precise moment (even same milliseconds), I have 2 problems (described below code, for better understanding) Please picture this code as if its happening 2 times at the same time (from 2 different users) Code: [Select] $time = microtime(true) * 10000; $result = mysql_query("UPDATE `AUCTIONS` SET Current_Price = Current_Price + '$increase_price', Bids = Bids + 1, Bidder = '$bidder', Bidder_Time = '$bidder_time' WHERE PId = '$id'"); //grab the current price to save on bidding history DB if($result) { $resultPrice = mysql_query("SELECT Current_Price FROM AUCTIONS WHERE PId = '$id'"); while($row=mysql_fetch_array($resultPrice)) { $current_price = $row['Current_Price']; } if($resultPrice) { $result = mysql_query("INSERT INTO `BIDDING_HISTORY_DB` (Id, Bidder, Bidder_Time, Raw_Time, Ip, Type, Bid_Amount) VALUES ('$id', '$last_bidder', '$last_bidder_time', '$time', '$client_ip', '$credit_type', '$current_price')"); } } If 2 users bid at exactly the same SAME moment, its possible that on BIDDING_HISTORY_DB... I get the Bid_Amount field with the same value (when it should be always 1 number higher than the previous) ( Bid_Amount is coming from $current_price) $current_price grabs the new updated value from the AUCTIONS DB on the first query (Current_Price = Current_Price + '$increase_price'). So its impossible to have 2 values that are the same (at least I am not expecting that), but I realized that if the query from 2 users are being processed at the same time and the UPDATE AUCTIONS query is processed 2 times and AFTER THAT then the SELECT Current_Price FROM AUCTIONS WHERE PId = '$id' is processed on both bids...that is when the Current_Price is grabbed with the same value for both USERS!! Any ideas on how I can find a solution to this ??? The other problem is that I am knowing which bid was made (by which user) before/after because of the $time variable. But sometimes when 2 bids are made at the SAME precise time with the same milliseconds (yes it happens) ... this is when problems arise (because 1 user could have as Current_Price 10.11 and the other one 10.12 and then on DB the user with 10.12 could be shown as if he made the bid first, any ideas/suggestions on how I can find a solution to this? Hi! I have read like crazy to find a tutorial on a login page without My_SQL. Anyway I am working on a easy login/logged out page with sessions. Here is the login page with tree users in an array.
The things that I need some hints to solve is, when clicking on login the error message don't show. Instead the script goes to the logged in page right away. And when you write the wrong password you get loged in anyway.
I am not sure how or if it's possible to write a varible to a file this way. But I tried and recived a parse error with the txt varible.
When searching for topics I get more confused with the My_SQL varibles. I am near a breaking point at cracking the first step on PHP, but need some advice.
<?php $page_title = 'Logged in'; //Dynamic title include('C:/wamp/www/PHP/includes/header.html'); ?> <?php session_start(); //A array for the sites users with passwords $users = array( 'Dexter'=>'meow1', 'Garfield'=>'meow2', 'Miro'=>'meow3' ); //A handle to save the varible users to file on a new line from the last entry $handle = fopen("newusers.txt, \n\r") $txt = $users; fclose($handle); if(isset($_GET['logout'])) { $_SESSION['username'] = ''; header('Location: ' . $_SERVER['PHP_SELF']); } if(isset($_POST['username'])) { if($users[$_POST['username']] == $_POST['password']) { $_SESSION['username'] = $_POST['username']; }else { echo "Something went wrong, Please try again"; } } ?> <?php echo "<h3>Login</h3>"; echo "<br />"; ?> <!--A legend form to login--> <fieldset><legend>Fill in your username and password</legend> <form name="login" action="777log.php" method="post"> Username: <br /> <input type="text" name="username" value="" /><br /> Password: <br /> <input type="password" name="password" value="" /><br /> <br /> <input type="submit" name="submit" value="Login" /> </fieldset> </form> <?php //Footer include file include('C:/wamp/www/PHP/includes/footer.html'); ?>The logged in page <?php //Header $page_title = 'Reading a file'; include('C:/wamp/www/PHP/includes/header.html'); ?> <?php session_start(); //Use an array forthe sites users $users = array( 'Dexter'=>'meow1', 'Garfield'=>'meow2', 'Miro'=>'meow3' ); // if(isset($_GET['logout'])) { $_SESSION['username'] = ''; echo "You are now loged out"; //The user is loged out and returned to the login page header('Location: ' . $_SERVER['PHP_SELF']); } if(isset($_POST['username'])) { //Something goes wrong here when login without any boxes filled if($users[$_POST['username']] == $_POST['password']) { $_SESSION['username'] = $_POST['username']; }else { echo "Something went wrong, Please try again"; $redirect = "Location: 777.php"; } } ?> <?php if($_SESSION['username']): ?> <p><h2>Welcome <?=$_SESSION['username']?></h2></p> <p align="right"><a href="777.php">Logga ut</a></p><?php endif; ?> <p>Today Ben&Jerrys Chunky Monkey is my favorite!</p> <?php //Footer include('C:/wamp/www/PHP/includes/footer.html'); ?> When i press login i get Fatal error: Call to a member function query() on a non-object in /home/a5347792/public_html/login.php on line 15
<?php $dbConnection['username'] = "root"; $dbConnection['password'] = ""; $dbConnection['host'] = "localhost"; $dbConnection['db'] = "joke"; if(isset($_POST['rbLgn'])) { $login = true; if(isset($_POST['username'])) { $username = $_POST['username']; } if(isset($_POST['password'])) { $password = $_POST['password']; } if(isset($username) && isset($password)) { $query = $db->query("SELECT * FROM `users` WHERE `username`='{$username}' AND `password`='{$password}' LIMIT 1"); if($query->num_rows > 0) { echo "User found - logging in."; } else { echo "User not found, credentials: " . $username . " | " . $password; } } } ?> Edited by mac_gyver, 25 October 2014 - 10:21 AM. code tags when posting code please |