PHP - Am Having A Small Display Problem With Sessions When Logging Out
hi phpfreaks
Recently I tryed to create a login for my website and a logout using sessions. The problem I have is: Whenever I log in I will be going to the homepage of the website. My session will be set and everything works fine. Now when I log out my session will be unset and destroyed. The problem is, is that whenever I go back in history I can still see my homepage. When I refresh that page the browser asks the user to resend it's information (probably because it has to do with using post in my login template). b.t.w. is it a bad thing to use request and a .htaccess file for my login form? So whenever a user logs in -> logs out -> goes back in history -> refreshes -> resend information the user is not asked to answer any account and password information to get itself logged in again. This troubles me for quite a while now ! Here are the pages I use to login, logout and show the homepage: Login.php: Code: [Select] <?php class Handler_Login extends Action_Handler { function __construct($action_handle) { parent::construct($action_handle); $this->action = $action_handle; } function secured_handler() { if ($this->session->check_session() == false) { $password = $_POST['password']; $username = $_POST['username']; $login = $this->dbh->Login($username, $password); if ($login == true) { $this->session->set('username', $username); $this->view->displayHome(); $this->view->display(); } else { echo "you are not logged in"; } } else { $this->view->displayHome(); $this->view->display(); } } } ?> Logout.php: Code: [Select] <?php class Handler_Loguit extends Action_Handler { function __construct($action_handle) { parent::construct($action_handle); $this->action = $action_handle; } function secured_handler() { $this->session->stopSession(); $this->view->displayLogin(); $this->view->display(); } } ?> Home.php: Code: [Select] <?php class Handler_home extends Action_Handler { public function __construct($action_handle) { parent::construct($action_handle); $this->action = $action_handle; } function secured_handler() { if ($this->session->check_session() == false) { $this->view->displayLogin(); $this->view->display(); } else { $this->view->displayHome(); $this->view->display(); } } } ?> Session.php: Code: [Select] <?php class Session { function __construct() { if(!isset($_SESSION)) { session_start(); } } function set($name, $value) { $_SESSION[$name] = $value; } function get($name) { return $_SESSION[$name]; } function stopSession() { unset($_SESSION); session_destroy(); } function check_session() { if(isset($_SESSION['username']) && !empty($_SESSION['username'])) { return true; } else { return false; } } } ?> view.php: Code: [Select] <?php class view { private $tpl; function __construct() { } function displayStatus() { $status = file_get_contents("templates/status.tpl"); $this->tpl = str_replace("%content%", $status, $this->tpl); } function displayLogin() { $this->tpl = file_get_contents("templates/login.tpl"); } function displayHome() { $this->tpl = file_get_contents("templates/home.tpl"); } function display() { echo $this->tpl; } } ?> now what I'm trying to do is: whenever the user goes back in history after being logged out, the page should be redirected to the login page. I have no idea how I would accomplish this. I know it has got something to do with my login.php but I can't really make it redirect to itself since it will then most possibly start an endless loop of redirecting. I'm using templates to display my pages, if neccesary I will post them too, Thanks for your support and I hope this issue will get solved Similar TutorialsHi guys, I got a little bit of an issue. I have a register page, which works fine and submits to itsself, however i also have a login page which currently has no errors but doesnt allow any1 to log in. If some1 can see why that will be great, as this is causing so many issues. This is the last step i cant get past. Here is the code Code: [Select] <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <title>Forensics E-learning Package</title> <script type="text/javascript" src="start.js"></script> <link rel="stylesheet" type="text/css" href="style.css" /> </head> <body> <div id="wrapper"> <div id="header"> <div id="toplinks"> </div> </div> <div id="menu"> <ul> <li><a class="selected" href="index.html">Home</a></li> <li><a href="index.php">Initial Quiz</a></li> <li><a href="about.php">About</a></li> <li><a href="member.php">Member Section</a></li> </ul> </div> <div id="content"> <div id="main"> <h1>Forensics E-Learning Package</h1><BR /></head> Login to the User Profiled E-Learning Course which is specifically aimed to raise awareness in computer forensics. <?php $submit =&$_POST['submit']; if(isset($submit)) { if($username && sha1($password)) { $username =&$_POST['username']; $password =&$_POST['password']; $_SESSION['$username'] = $username; $_SESSION['$password'] = sha1($password); $connect = mysql_connect("localhost","root", "") or die ("Couldn't Connect!"); mysql_select_db("userlogin", $connect) or die("Couldn't find db"); //$con = mysql_connect('userscores.db.7767668.hostedresource.com','userscores','L3tt3r09'); //mysql_select_db('userscores', $con); $query = mysql_query("SELECT * FROM users WHERE username=' $username'"); $numrows = mysql_num_rows($query); if ($numrows!=0) { //code to login while ($row = mysql_fetch_assoc($query)) { $dbusername = $row['username']; $dbpassword = $row['password']; $dbscore = $row['score']; $dbdclty = $row['dclty']; $dbid = $row['id']; $dbnewdclty = $row['newdclty']; } $_SESSION['id'] = $dbid; $_SESSION['PreviousScore'] = $dbscore; $_SESSION['dclty'] = $dbdclty; $_SESSION['newdclty'] = $dbnewdclty; if ($username==$dbusername&&sha1($password)==$dbpassword) { $username==$dbusername; } else { echo ("Incorrect Password!"); } } else { echo("That user doesn't exist!"); } } else { echo("Please enter a username and password!"); } echo ("You Successfully Logged In!"); } else { ?><BR /><BR /><?php echo("Please Log In!"); } if ($submit) echo "Logged In Successfully!"; ?> <BR /><BR /> <form action='index.php' method='POST'> Username: <input type='text' name='username'><BR /> Password: <input type='password' name='password'><BR /> <input type='submit' value='Log In'> </form> <p><BR /><BR /> <a class="button" href='register.php'><span><button class="button" id="save">Register</button></span></a> </div> <div id="right"> <h2>Right Menu</h2> <div class="rightitem"> <ul> <li><a class="selected" href="index.html">Home</a></li> <li><a href="index.php">Initial Quiz</a></li> <li><a href="about.php">About</a></li> <li><a href="member.php">Members Area</a></li> <li><a href="contact.php">Leave Feedback</a></li> </ul> </div> </div> </div> <div class="clearbottom"></div> <div id="footer"></div></div> </body> </html> Thanks for any help Lance Hey, i have a small problem with the logout part of my account system. When i click the logout link, it directs me to the index page with an error (custom error stuff i made). Heres my logout code <?php echo 'Behandler ...<br />'; if(isset($_SESSION['logged']) && isset($_SESSION['email']) && $_SESSION['logged'] == 1) { echo 'Logger ud, vent venligst...'; unset($_SESSION['logged']); unset($_SESSION['email']); header('location: index.php?p=success&ploca=login&pid=1'); exit(); } else { header('location: index.php?p=error&ploca=login&pid=5'); // This is where it jumps to directly. exit(); } ?> The weird thing is, that the sessions email and logged is set, as you can see here; //Printed with print_r($_SESSION); Array ( [psite] => index [logged] => 1 [email] => a@b.c ) Anyone sees my problem? Hi, I have sessions and cookies for my website with PHP 7.2 version. But now and again, it logs me out quickly. Sometimes after 10 minutes inactivity, other times it doesn't, or even sometimes on clicking a link on the site. I can't tell if it is the browsers settings which I changed, but made no difference. Can anybody see a problem with my sessions, if that is set up wrong and if it is the reason as to why I am getting logged out of my site a lot without logging out? htaccess Header always edit Set-Cookie (.*) "$1; SameSite=Strict" php.ini session.name = __MySession session.save_path = /path-to-sessions session.hash_function = sha512 session.gc_maxlifetime = 3600 session.gc_probability = 1 ; session.gc_divisor = 100 session.cookie_lifetime = 0 session.use_only_cookies = 1 session.use_trans_sid = 0 session.cookie_secure = 1 session.use_strict_mode = 1 session.cookie_httponly = 1 session.use_cookies = 1 session.referer_check = http://www.my-domain.com/ session.cache_limiter = nocache sessions function <?php function mySiteSession() { $session_name = '__MySession'; $cookie_domain = "www.my-domain.com"; if (strpos($_SERVER['REQUEST_URI'], 'secured-area')) { $cookie_path = "/secured-area/"; $saved_path_location = '/path-to-sessions'; ini_set('session.save_path', $saved_path_location); } else { if (strpos($_SERVER['REQUEST_URI'], 'contact-us-now') && !strpos($_SERVER['REQUEST_URI'], 'secured-area')) { $cookie_path = "/contact-us-now/"; $saved_path_location = '/path-to-sessions'; ini_set('session.save_path', $saved_path_location); $max_life_time_seconds = 3600; $_SESSION['created'] = time(); $session_life_time_seconds = time() - $_SESSION['created']; if ($session_life_time_seconds > $max_life_time_seconds) { session_destroy(); session_unset(); } } else { $cookie_path = "/secured-area/"; $saved_path_location = '/path-to-sessions'; ini_set('session.save_path', $saved_path_location); } } $cookie_secure = false; // website is not live and no https yet $cookie_httponly = true; $cookieParams = session_get_cookie_params(); session_set_cookie_params($cookieParams["lifetime"], $cookie_path, $cookie_domain, $cookie_secure, $cookie_httponly); session_name($session_name); secureSession(); session_write_close(); $cleanSession = @secureSession(); if (!$cleanSession) { session_regenerate_id(true); secureSession(); } session_regenerate_id(true); } function secureSession() { if (isset($_COOKIE[session_name()]) && preg_match('/^[-,a-zA-Z0-9]{1,128}$/', $_COOKIE[session_name()])) { session_start(); } else if (isset($_COOKIE[session_name()])) { unset($_COOKIE[session_name()]); session_start(); } else { session_start(); } } ?> Web Page Layout <?php ob_start(); // some pages have this but not all mySiteSession(); // my sites code and html ob_flush(); // some pages have this but not all ?> I hope that this is enough information, as I am not sure how to get to the bottom of this. Edited February 10, 2019 by Cobra23It appears that my '/tmp' folder on my shared hosting (GoDaddy) account is full with session files and it seems I have to wait (up to 72hrs) for their hopeless admins to clear out the folder. The strange things is everything was working fine a couple of days ago. Now sometimes I get errors on my PHP page saying disk is full and session cache error. Sometimes don't even get these errors. I can't seem to get back these errors now. Is there anyway to generate session or disk errors in PHP? Also, the login page doesn't work. It just doesn't login and reloads itself each time. I think it might be due to either the '/tmp' folder being full or it's getting confused with session variables that haven't been destroyed. I'm really not sure? Any help or insight would be much appreciated. Class creating the session variables and verifying login: Code: [Select] <?php session_start(); //global $loginTime; /** * LoginSystem * * Simple Login system with sessions and MySQL User DB * * @version 1.0 * @author A.Surrey (www.surneo.com) * * */ class LoginSystem { var $db_host, $db_name, $db_user, $db_password, $connection, //$userid, //added by IH 18-January-2011 $username, $password, $userip, $loginTime, $timeout; /** * Constructor */ function LoginSystem() { require_once('../../config/settings.php'); $this->db_host = $dbhost; $this->db_name = $dbname; $this->db_user = $dbuser; $this->db_password = $dbpassword; } /** * Check if the user is logged in * * @return true or false */ function isLoggedIn() { if($_SESSION['LoggedIn']) { return true; } else return false; } /** * Check username and password against DB * * @return true/false */ //function doLogin($username, $password) function doLogin($username, $password, $userip) { $timezone = 0; //(GMT -5:00) EST (U.S. & Canada) $loginTime = gmdate("Y-m-j H:i:s", time() + 3600*($timezone+date("I"))); $this->connect(); $this->username = $username; $this->password = $password; $this->userip = $userip; // check db for user and pass here. //$sql = sprintf("SELECT UserID, UserName, Password FROM Users WHERE UserName = '%s' and Password = '%s'", $sql = sprintf("SELECT UserID, UserName, FullName, Password FROM Users WHERE UserName = '%s' and Password = '%s' AND ActiveUser = '1'", $this->clean($this->username), md5($this->clean($this->password))); $result = mysql_query($sql, $this->connection); // If no user/password combo exists return false if(mysql_affected_rows($this->connection) != 1) { $this->disconnect(); return false; } else // matching login ok { $row = mysql_fetch_assoc($result); $userid = $row['UserID']; // more secure to regenerate a new id. session_regenerate_id(); //set session vars up $_SESSION['LoggedIn'] = true; $_SESSION['userName'] = $this->username; $_SESSION['userID'] = $row['UserID']; $_SESSION['fullName'] = $row['FullName']; //$this->getLoginTime(); //return $this->loginTime; //#### WORKING QUERY - MANUAL DATE VALUE #### //$sql2 = 'UPDATE Users SET LastLogin = "2011-01-18 23:55:32" WHERE UserID = "' . $userid.'"'; //#######################// //$sql2 = 'UPDATE Users SET LastLogin = "'.$loginTime.'" WHERE UserID = "'.$userid.'"'; $sql2 = 'UPDATE Users SET LastLogin = "'.$loginTime.'", UserIP = INET_ATON("'.$this->userip.'") WHERE UserID = "'.$userid.'"'; $result2 = mysql_query($sql2, $this->connection); //echo '<script>alert("'.$sql2.'");</script>'; } $this->disconnect(); return true; } function sessionTimer() { //unset($_SESSION['timeout']); session_start(); $this->inactivesession = $inactivesession; // set timeout period in seconds (14400 = 4 hours) $this->inactivesession = 1400; $this->session_life = $session_life; // check to see if $_SESSION['timeout'] is set if(isset($_SESSION['timeout']) ) { $this->session_life = time() - $_SESSION['timeout']; if($this->session_life > $this->inactivesession) { session_destroy(); //header("Location: logout.php?msg=2"); return true; } else { return false; } } //$_SESSION['timeout'] = time() + $this->session_life; $_SESSION['timeout'] = time() + $this->inactivesession; //$_SESSION['timeout'] = time(); //return false; } /** * Destroy session data/Logout. */ function logout() { unset($_SESSION['LoggedIn']); unset($_SESSION['fullName']); unset($_SESSION['userName']); unset($_SESSION['userID']); unset($_SESSION['timeout']); session_destroy(); } /** * Connect to the Database * * @return true/false */ function connect() { $this->connection = mysql_connect($this->db_host, $this->db_user, $this->db_password) or die("Unable to connect to MySQL"); mysql_select_db($this->db_name, $this->connection) or die("Unable to select DB!"); // Valid connection object? everything ok? if($this->connection) { return true; } else return false; } /** * Disconnect from the db */ function disconnect() { mysql_close($this->connection); } /** * Cleans a string for input into a MySQL Database. * Gets rid of unwanted characters/SQL injection etc. * * @return string */ function clean($str) { // Only remove slashes if it's already been slashed by PHP if(get_magic_quotes_gpc()) { $str = stripslashes($str); } // Let MySQL remove nasty characters. $str = mysql_real_escape_string($str); return $str; } /** * create a random password * * @param int $length - length of the returned password * @return string - password * */ function randomPassword($length = 8) { $pass = ""; // possible password chars. $chars = array("a","A","b","B","c","C","d","D","e","E","f","F","g","G","h","H","i","I","j","J", "k","K","l","L","m","M","n","N","o","O","p","P","q","Q","r","R","s","S","t","T", "u","U","v","V","w","W","x","X","y","Y","z","Z","1","2","3","4","5","6","7","8","9"); for($i=0 ; $i < $length ; $i++) { $pass .= $chars[mt_rand(0, count($chars) -1)]; } return $pass; } } ?> Login page: Code: [Select] <?php session_start(); require ('class/MathGuard.class.php'); require_once('class/LoginSystem.class.php'); $userip = $_SERVER['REMOTE_ADDR']; if(isset($_POST['Submit'])) { if((!$_POST['Username']) || (!$_POST['Password'])) { // display error message header('location: login.php?msg=1');// show error exit; } // ######## MatchGuard check ######## if (!MathGuard :: checkResult($_REQUEST['mathguard_answer'], $_REQUEST['mathguard_code'])) { //show_error ("Incorrect Security Code entered"); header('location: login.php?msg=3'); exit; } $loginSystem = new LoginSystem(); if($loginSystem->doLogin($_POST['Username'],$_POST['Password'],$userip)) { /** * Redirect here to your secure page */ header('location: view_articles.php'); } else { header('location: login.php?msg=2'); exit; } } /** * show Error messages * */ function showMessage() { if(is_numeric($_GET['msg'])) { switch($_GET['msg']) { //case 1: echo "Please fill both fields."; case 1: echo '<div class="msg"><img src="images/icons/error.png" alt=""/><p>Please fill in all fields!</p></div>'; break; //case 2: echo "Incorrect Username or Password!"; case 2: echo '<div class="msg"><img src="images/icons/error.png" alt=""/><p>Incorrect Username or Password!</p></div>'; break; //case 3: echo "Incorrect Security Code"; case 3: echo '<div class="msg"><img src="images/icons/error.png" alt=""/><p>Incorrect Security answer!</p></div>'; break; } } } /* function show_error($myError) { echo $myError; //stop executing script and display the form exit(); }*/ ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Login</title> <meta name="robots" content="noindex, nofollow" /> <link rel="stylesheet" type="text/css" href="css/login.css" /> <script type="text/javascript" src="js/jquery-1.3.2.min.js"></script> <script type="text/javascript" src="js/supersleight.js"></script> <script type="text/javascript"> $(document).ready(function(){ $(".block").fadeIn(1000); $(".msg").fadeIn(1000); $('.msg').supersleight(); }); </script> </head> <body> <div id="wrap"> <?php showMessage();?> <div class="block"> <div class="head"> <h3>Login</h3><!--<a href="#">Forgot Password?</a>--> </div> <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post"> <div class="body"> <div class="div-row"> <label for="username">Username</label><input type="text" id="Username" name="Username" maxlength="30" /> </div> <div class="div-row"> <label for="password">Password</label><input type="Password" id="Password" name="Password" maxlength="30" /> </div> <div class="div-row"> <?php MathGuard::insertQuestion(); ?> </div> <div class="send-row"> <button id="login" value="Login" type="submit" name="Submit"></button> </div> </div> </form> </div> </div> </body> </html> Make pages secure include: Code: [Select] <?php session_cache_expire(240); session_start(); require('./class/LoginSystem.class.php'); $loginSys = new LoginSystem(); /** * if not logged in goto login form, otherwise we can view our page */ if(!$loginSys->isLoggedIn()) { header("Location: ./login.php"); exit; } $sessionTime = new LoginSystem(); if($sessionTime->sessionTimer()) { header("Location: ./logout.php?msg=2"); exit; } ?> Logout page: Code: [Select] <?php session_start(); require('class/LoginSystem.class.php'); $loginSys = new LoginSystem(); $loginSys->logout(); function showMessage() { if(is_numeric($_GET['msg'])) { switch($_GET['msg']) { case 1: echo '<div class="msg" style="border:1px; border-color:#8be57e; background:#b4efab; color:#337129;"><img src="images/icons/succes.png" alt=""/><p>You have logged out successfully.</p></div>'; break; case 2: echo '<div class="msg"><img src="images/icons/error.png" alt=""/><p>Due to inactivity your session has expired.</div>'; break; } } } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Login</title> <meta name="robots" content="noindex, nofollow" /> <link rel="stylesheet" type="text/css" href="css/login.css" /> <link rel="stylesheet" type="text/css" href="css/ui.dialog.css" /> <style type="text/css"> body{ background-image: none; } </style> <script type="text/javascript" src="js/jquery-1.3.2.min.js"></script> <script type="text/javascript" src="js/supersleight.js"></script> <script type="text/javascript"> $(document).ready(function(){ $(".block").fadeIn(1000); $(".msg").fadeIn(1000); $('.msg').supersleight(); }); </script> </head> <body> <div id="wrap"> <?php showMessage();?> <div class="block"> <div class="head"> <h3>Logged Out</h3> </div> <div class="body"> <p align="center"><font color="#000000"><b>Redirecting to the 'Login' page in <span id="seconds" style="color:#ff0000;">10</span> seconds.</b></font></p> <script language="JavaScript"> var seconds = 10; setInterval( function(){ if (seconds <= 1) { window.location = 'http://domain.tld/cms/login.php'; } else { document.getElementById('seconds').innerHTML = --seconds; } }, 1000 ); </script> <br><br> <p align="center">If you are not redirected, go straight to the <a href="login.php"><font size="3" color="blue"><b>Login</b></font></a> page.</p> </div> </div> </div> </body> </html> MathGuard class (works fine and I have not changed anything in this file) Code: [Select] <? class MathGuard { /** A main hashing function: concat of user's answer, hour and the additional prime number (default 37) */ function encode($input, $prime) { return md5($input.date("H").$prime); } /** This function generates the hash code from the two numbers * @param $a first number * @param $b second sumber * @param $prime additional number to encode with * */ function generateCode($a, $b, $prime) { $code = MathGuard::encode($a + $b, $prime); return $code; } /** This function checks whether the answer and generated security code match * @param $mathguard_answer answer the user has entered * @param $mathguard_code hashcode the mathguard has generated */ function checkResult($mathguard_answer, $mathguard_code, $prime = 37) { // echo("prime; $prime, $mathguard_answer"); $result_encoded = MathGuard::encode($mathguard_answer, $prime); if ($result_encoded == $mathguard_code) return true; else return false; } /** this function inserts the two math term into your form, the parameter is optional */ function insertQuestion($prime = 37) { //default prime is 37, you can change it when specifying the different parameter $a = rand() % 10; // generates the random number $b = rand() % 10; // generates the random number $code = MathGuard :: generateCode($a, $b, $prime); echo ("<label for=mathcheck>Security: $a + $b =</label> <input type='input' name='mathguard_answer' size='2' maxlength='4' /><input type='hidden' name='mathguard_code' value='$code' />"); } /** this function returns math expression into your form, the parameter is optional * quite simmilar to insertQuestion, but returns the output as a text instead of echoing */ function returnQuestion($prime = 37) { //default prime is 37, you can change it when specifying the different parameter $a = rand() % 10; // generates the random number $b = rand() % 10; // generates the random number $code = MathGuard :: generateCode($a, $b, $prime); return ("<label for=mathcheck>Security: $a + $b =</label> <input type='input' name='mathguard_answer' size='2' maxlength='4' /><input type='hidden' name='mathguard_code' value='$code' />"); } } ?> edit: removed domain name I have made a php cart : check it out on http://fhcs.be/cart-demo4/ My question is: when I order something by clicking on the "voeg toe" button, I'm redirected to the shopping cart. But I don't want to be redirected to the shopping cart, I want to stay on de menu list. What is an easy way to fix this? thanks people index.php Code: [Select] <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>PHP Shopping Cart Demo · Bookshop</title> <link rel="stylesheet" href="css/styles.css" /> </head> <body> <div id="shoppingcart"> <h1>Welkom, plaats uw order</h1> </div> <div id="booklist"> <h1>Warme dranken</h1> <?php $sql = 'SELECT * FROM products WHERE cat=2'; $result1 = $db->query($sql); $output1[] = '<ul>'; while ($row = $result1->fetch()) { $output1[] = '<li>'.$row['name'].': €'.$row['price'].'<br /><a href="cart.php?action=add&id='.$row['id'].'">Voeg Toe</a></li>'; } $output1[] = '</ul>'; echo join('',$output1); ?> <h1>Cocktails</h1> <?php $sql = 'SELECT * FROM products WHERE cat=3'; $result2 = $db->query($sql); $output2[] = '<ul>'; while ($row = $result2->fetch()) { $output2[] = '<li>'.$row['name'].': €'.$row['price'].'<br /><a href="cart.php?action=add&id='.$row['id'].'">Voeg Toe</a></li>'; } $output2[] = '</ul>'; echo join('',$output2); ?> </div> </body> cart.php Code: [Select] <?php // Include MySQL class require_once('inc/mysql.class.php'); // Include database connection require_once('inc/global.inc.php'); // Include functions require_once('inc/functions.inc.php'); // Start the session session_start(); // Process actions $cart = $_SESSION['cart']; $action = $_GET['action']; switch ($action) { case 'add': if ($cart) { $cart .= ','.$_GET['id']; } else { $cart = $_GET['id']; } break; case 'delete': if ($cart) { $items = explode(',',$cart); $newcart = ''; foreach ($items as $item) { if ($_GET['id'] != $item) { if ($newcart != '') { $newcart .= ','.$item; } else { $newcart = $item; } } } $cart = $newcart; } break; case 'update': if ($cart) { $newcart = ''; foreach ($_POST as $key=>$value) { if (stristr($key,'qty')) { $id = str_replace('qty','',$key); $items = ($newcart != '') ? explode(',',$newcart) : explode(',',$cart); $newcart = ''; foreach ($items as $item) { if ($id != $item) { if ($newcart != '') { $newcart .= ','.$item; } else { $newcart = $item; } } } for ($i=1;$i<=$value;$i++) { if ($newcart != '') { $newcart .= ','.$id; } else { $newcart = $id; } } } } } $cart = $newcart; break; } $_SESSION['cart'] = $cart; ?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>PHP Shopping Cart Demo · Cart</title> <link rel="stylesheet" href="css/styles.css" /> </head> <body> <div id="shoppingcart"> <h1>Uw bestelling</h1> <?php echo writeShoppingCart(); ?> </div> <div id="contents"> <h2>Gelieve na te kijken voordat u bestelt</h2> <?php echo showCart(); ?> <p><a href="index.php">Terug naar lijst</a></p> <form action="mail.php" method="post"> <input type="submit" name="sendemail" value="Bestel" /> <input type="hidden" name="cart" value="<?= $cart; ?>" /> </form> </div> </body> </html> echo "<tr> <td class='trow2' align='center' valign='center' width='1'></td> <td class='trow2' valign='center'> <strong><a href='server.php?view=details&id=" . $list['id'] . "'>" . capitalizeFirstCharacter($list['servername']) . "</a></strong> <div class=\"stat2\"> <div class=\"stat\"> if(!$sock=@fsockopen($list_f['serverip'],$list_f['serverport'], $num, $error, 1)) { echo "<font color='red'><b>Offline</b></font>"; } else { echo "<font color='green'><b>Online</b></font>"; } </div> </div> <div class='smalltext'>" . $list['shortdescription'] . "</div> </td> <td class='trow1' valign='middle' align='left' style='white-space: nowrap'><span class='smalltext'>" . $list['revision'] . "</span></td> <td class='trow2' valign='middle' align='right' style='white-space: nowrap'><font size='4px'>" . $voteAmount . " Votes</font></td> </tr>"; How can I make this echo code work? <?php // SQL Connection $username="root"; $password=""; $database="mydb"; $connection = mysql_connect("localhost", $username, $password) or die("Connection Failure to Database"); // Select Database mysql_select_db($database, $connection) or die ($database . "No Database" . $username); $id = $_GET['id']; $MyQuery = "SELECT * FROM bookings WHERE id = '$id'"; $retrieve = mysql_query($MyQuery) or die(mysql_error()); if(mysql_num_rows($retrieve) != 0): $row = mysql_fetch_assoc($retrieve); endif; $idX = ($row['id']); echo $idX; if(mysql_num_rows($retrieve) == 0) { echo '<blink><font color="red"><strong>No Booking Found</strong></font></blink>'; } else { echo '<form action="' . $_SERVER['PHP_SELF'] . '" method="post">'; echo '<table width="350">'; echo ' <tr>'; echo ' <td width="100">Full Name</td>'; echo ' <td width="100"><input style="width: 235px" value="' . ($row['fullname']) . '" type="text" name="fullname"></td>'; echo ' </tr>'; echo ' <tr>'; echo ' <td width="100">Address</td>'; echo ' <td width="100"><input style="width: 235px" value="' . ($row['address']) . '" type="text" name="address"></td>'; echo ' </tr>'; echo ' <tr>'; echo ' <td width="100">City</td>'; echo ' <td width="100"><input style="width: 235px" value="' . ($row['city']) . '" type="text" name="city"></td>'; echo ' <tr>'; echo ' <td width="100">Postcode</td>'; echo ' <td width="100"><input style="width: 235px" value="' . ($row['postcode']) . '" type="text" name="postcode"></td>'; echo ' </tr>'; echo ' <tr>'; echo ' <td width="100">Country</td>'; echo ' <td width="100"><select style="width: 235px" name="country">'; echo ' <option value="' . ($row['country']) . '">' . ($row['country']) . '</option>'; echo ' <option></option><option value="Abkhazia">Abkhazia</option><option value="Afghanistan">Afghanistan</option><option value="Aland">Aland</option><option value="Albania">Albania</option><option value="Algeria">Algeria</option><option value="American Samoa">American Samoa</option><option value="Andorra">Andorra</option><option value="Angola">Angola</option><option value="Anguilla">Anguilla</option><option value="Antarctica">Antarctica</option><option value="Antigua and Barbuda">Antigua and Barbuda</option><option value="Argentina">Argentina</option><option value="Armenia">Armenia</option><option value="Aruba">Aruba</option><option value="Ascension">Ascension</option><option value="Ashmore and Cartier Islands">Ashmore and Cartier Islands</option><option value="Australia">Australia</option><option value="Australian Antarctic Territory">Australian Antarctic Territory</option><option value="Austria">Austria</option><option value="Azerbaijan">Azerbaijan</option><option value="Bahamas, The">Bahamas, The</option><option value="Bahrain">Bahrain</option><option value="Baker Island">Baker Island</option><option value="Bangladesh">Bangladesh</option><option value="Barbados">Barbados</option><option value="Belarus">Belarus</option><option value="Belgium">Belgium</option><option value="Belize">Belize</option><option value="Benin">Benin</option><option value="Bermuda">Bermuda</option><option value="Bhutan">Bhutan</option><option value="Bolivia">Bolivia</option><option value="Bosnia and Herzegovina">Bosnia and Herzegovina</option><option value="Botswana">Botswana</option><option value="Bouvet Island">Bouvet Island</option><option value="Brazil">Brazil</option><option value="British Antarctic Territory">British Antarctic Territory</option><option value="British Indian Ocean Territory">British Indian Ocean Territory</option><option value="British Sovereign Base Areas">British Sovereign Base Areas</option><option value="British Virgin Islands">British Virgin Islands</option><option value="Brunei">Brunei</option><option value="Bulgaria">Bulgaria</option><option value="Burkina Faso">Burkina Faso</option><option value="Burundi">Burundi</option><option value="Cambodia">Cambodia</option><option value="Cameroon">Cameroon</option><option value="Canada">Canada</option><option value="Cape Verde">Cape Verde</option><option value="Cayman Islands">Cayman Islands</option><option value="Central African Republic">Central African Republic</option><option value="Chad">Chad</option><option value="Chile">Chile</option><option value="China, Peoples Republic of">China, Peoples Republic of</option><option value="China, Republic of (Taiwan)">China, Republic of (Taiwan)</option><option value="Christmas Island">Christmas Island</option><option value="Clipperton Island">Clipperton Island</option><option value="Cocos (Keeling) Islands">Cocos (Keeling) Islands</option><option value="Colombia">Colombia</option><option value="Comoros">Comoros</option><option value="Congo, Democratic Republic of the (Congo Kinshasa)">Congo, Democratic Republic of the (Congo Kinshasa)</option><option value="Congo, Republic of the (Congo Brazzaville)">Congo, Republic of the (Congo Brazzaville)</option><option value="Cook Islands">Cook Islands</option><option value="Coral Sea Islands">Coral Sea Islands</option><option value="Costa Rica">Costa Rica</option><option value="Cote dIvoire (Ivory Coast)">Cote dIvoire (Ivory Coast)</option><option value="Croatia">Croatia</option><option value="Cuba">Cuba</option><option value="Cyprus">Cyprus</option><option value="Czech Republic">Czech Republic</option><option value="Denmark">Denmark</option><option value="Djibouti">Djibouti</option><option value="Dominica">Dominica</option><option value="Dominican Republic">Dominican Republic</option><option value="Ecuador">Ecuador</option><option value="Egypt">Egypt</option><option value="El Salvador">El Salvador</option><option value="Equatorial Guinea">Equatorial Guinea</option><option value="Eritrea">Eritrea</option><option value="Estonia">Estonia</option><option value="Ethiopia">Ethiopia</option><option value="Falkland Islands (Islas Malvinas)">Falkland Islands (Islas Malvinas)</option><option value="Faroe Islands">Faroe Islands</option><option value="Fiji">Fiji</option><option value="Finland">Finland</option><option value="France">France</option><option value="French Guiana">French Guiana</option><option value="French Polynesia">French Polynesia</option><option value="French Scattered Islands in the Indian Ocean">French Scattered Islands in the Indian Ocean</option><option value="French Southern and Antarctic Lands">French Southern and Antarctic Lands</option><option value="Gabon">Gabon</option><option value="Gambia, The">Gambia, The</option><option value="Georgia">Georgia</option><option value="Germany">Germany</option><option value="Ghana">Ghana</option><option value="Gibraltar">Gibraltar</option><option value="Greece">Greece</option><option value="Greenland">Greenland</option><option value="Grenada">Grenada</option><option value="Guadeloupe">Guadeloupe</option><option value="Guam">Guam</option><option value="Guatemala">Guatemala</option><option value="Guernsey">Guernsey</option><option value="Guinea">Guinea</option><option value="Guinea-Bissau">Guinea-Bissau</option><option value="Guyana">Guyana</option><option value="Haiti">Haiti</option><option value="Heard Island and McDonald Islands">Heard Island and McDonald Islands</option><option value="Honduras">Honduras</option><option value="Hong Kong">Hong Kong</option><option value="Howland Island">Howland Island</option><option value="Hungary">Hungary</option><option value="Iceland">Iceland</option><option value="India">India</option><option value="Indonesia">Indonesia</option><option value="Iran">Iran</option><option value="Iraq">Iraq</option><option value="Ireland">Ireland</option><option value="Isle of Man">Isle of Man</option><option value="Israel">Israel</option><option value="Italy">Italy</option><option value="Jamaica">Jamaica</option><option value="Japan">Japan</option><option value="Jarvis Island">Jarvis Island</option><option value="Jersey">Jersey</option><option value="Johnston Atoll">Johnston Atoll</option><option value="Jordan">Jordan</option><option value="Kazakhstan">Kazakhstan</option><option value="Kenya">Kenya</option><option value="Kingman Reef">Kingman Reef</option><option value="Kiribati">Kiribati</option><option value="Korea, Democratic Peoples Republic of (North Korea)">Korea, Democratic Peoples Republic of (North Korea)</option><option value="Korea, Republic of (South Korea)">Korea, Republic of (South Korea)</option><option value="Kosovo">Kosovo</option><option value="Kuwait">Kuwait</option><option value="Kyrgyzstan">Kyrgyzstan</option><option value="Laos">Laos</option><option value="Latvia">Latvia</option><option value="Lebanon">Lebanon</option><option value="Lesotho">Lesotho</option><option value="Liberia">Liberia</option><option value="Libya">Libya</option><option value="Liechtenstein">Liechtenstein</option><option value="Lithuania">Lithuania</option><option value="Luxembourg">Luxembourg</option><option value="Macau">Macau</option><option value="Macedonia">Macedonia</option><option value="Madagascar">Madagascar</option><option value="Malawi">Malawi</option><option value="Malaysia">Malaysia</option><option value="Maldives">Maldives</option><option value="Mali">Mali</option><option value="Malta">Malta</option><option value="Marshall Islands">Marshall Islands</option><option value="Martinique">Martinique</option><option value="Mauritania">Mauritania</option><option value="Mauritius">Mauritius</option><option value="Mayotte">Mayotte</option><option value="Mexico">Mexico</option><option value="Micronesia">Micronesia</option><option value="Midway Islands">Midway Islands</option><option value="Moldova">Moldova</option><option value="Monaco">Monaco</option><option value="Mongolia">Mongolia</option><option value="Montenegro">Montenegro</option><option value="Montserrat">Montserrat</option><option value="Morocco">Morocco</option><option value="Mozambique">Mozambique</option><option value="Myanmar (Burma)">Myanmar (Burma)</option><option value="Nagorno-Karabakh">Nagorno-Karabakh</option><option value="Namibia">Namibia</option><option value="Nauru">Nauru</option><option value="Navassa Island">Navassa Island</option><option value="Nepal">Nepal</option><option value="Netherlands">Netherlands</option><option value="Netherlands Antilles">Netherlands Antilles</option><option value="New Caledonia">New Caledonia</option><option value="New Zealand">New Zealand</option><option value="Nicaragua">Nicaragua</option><option value="Niger">Niger</option><option value="Nigeria">Nigeria</option><option value="Niue">Niue</option><option value="Norfolk Island">Norfolk Island</option><option value="Northern Cyprus">Northern Cyprus</option><option value="Northern Mariana Islands">Northern Mariana Islands</option><option value="Norway">Norway</option><option value="Oman">Oman</option><option value="Pakistan">Pakistan</option><option value="Palau">Palau</option><option value="Palestine">Palestine</option><option value="Palmyra Atoll">Palmyra Atoll</option><option value="Panama">Panama</option><option value="Papua New Guinea">Papua New Guinea</option><option value="Paraguay">Paraguay</option><option value="Peru">Peru</option><option value="Peter I Island">Peter I Island</option><option value="Philippines">Philippines</option><option value="Pitcairn Islands">Pitcairn Islands</option><option value="Poland">Poland</option><option value="Portugal">Portugal</option><option value="Pridnestrovie (Transnistria)">Pridnestrovie (Transnistria)</option><option value="Puerto Rico">Puerto Rico</option><option value="Qatar">Qatar</option><option value="Queen Maud Land">Queen Maud Land</option><option value="Reunion">Reunion</option><option value="Romania">Romania</option><option value="Ross Dependency">Ross Dependency</option><option value="Russia">Russia</option><option value="Rwanda">Rwanda</option><option value="Saint Helena">Saint Helena</option><option value="Saint Kitts and Nevis">Saint Kitts and Nevis</option><option value="Saint Lucia">Saint Lucia</option><option value="Saint Pierre and Miquelon">Saint Pierre and Miquelon</option><option value="Saint Vincent and the Grenadines">Saint Vincent and the Grenadines</option><option value="Samoa">Samoa</option><option value="San Marino">San Marino</option><option value="Sao Tome and Principe">Sao Tome and Principe</option><option value="Saudi Arabia">Saudi Arabia</option><option value="Senegal">Senegal</option><option value="Serbia">Serbia</option><option value="Seychelles">Seychelles</option><option value="Sierra Leone">Sierra Leone</option><option value="Singapore">Singapore</option><option value="Slovakia">Slovakia</option><option value="Slovenia">Slovenia</option><option value="Solomon Islands">Solomon Islands</option><option value="Somalia">Somalia</option><option value="Somaliland">Somaliland</option><option value="South Africa">South Africa</option><option value="South Georgia and the South Sandwich Islands">South Georgia and the South Sandwich Islands</option><option value="South Ossetia">South Ossetia</option><option value="Spain">Spain</option><option value="Sri Lanka">Sri Lanka</option><option value="Sudan">Sudan</option><option value="Suriname">Suriname</option><option value="Svalbard">Svalbard</option><option value="Swaziland">Swaziland</option><option value="Sweden">Sweden</option><option value="Switzerland">Switzerland</option><option value="Syria">Syria</option><option value="Tajikistan">Tajikistan</option><option value="Tanzania">Tanzania</option><option value="Thailand">Thailand</option><option value="Timor-Leste (East Timor)">Timor-Leste (East Timor)</option><option value="Togo">Togo</option><option value="Tokelau">Tokelau</option><option value="Tonga">Tonga</option><option value="Trinidad and Tobago">Trinidad and Tobago</option><option value="Tristan da Cunha">Tristan da Cunha</option><option value="Tunisia">Tunisia</option><option value="Turkey">Turkey</option><option value="Turkmenistan">Turkmenistan</option><option value="Turks and Caicos Islands">Turks and Caicos Islands</option><option value="Tuvalu">Tuvalu</option><option value="U.S. Virgin Islands">U.S. Virgin Islands</option><option value="Uganda">Uganda</option><option value="Ukraine">Ukraine</option><option value="United Arab Emirates">United Arab Emirates</option><option value="United Kingdom">United Kingdom</option><option value="United States">United States</option><option value="Uruguay">Uruguay</option><option value="Uzbekistan">Uzbekistan</option><option value="Vanuatu">Vanuatu</option><option value="Vatican City">Vatican City</option><option value="Venezuela">Venezuela</option><option value="Viet Nam">Viet Nam</option><option value="Wake Island">Wake Island</option><option value="Wallis and Futuna">Wallis and Futuna</option><option value="Western Sahara">Western Sahara</option><option value="Yemen">Yemen</option><option value="Zambia">Zambia</option><option value="Zimbabwe">Zimbabwe</option></SELECT></td>'; echo ' </tr>'; echo ' <tr>'; echo ' <td width="100">Tel</td>'; echo ' <td width="100"><input style="width: 235px" value="' . ($row['tel']) . '" type="text" name="tel"></td>'; echo ' </tr>'; echo ' <tr>'; echo ' <td width="100">Email</td>'; echo ' <td width="100"><input style="width: 235px" value="' . ($row['email']) . '" type="text" name="email"></td>'; echo ' </tr>'; echo ' <tr>'; echo ' <td width="100">Info</td>'; echo ' <td width="100"><input style="width: 235px" value="' . ($row['info']) . '" type="text" name="info"></td>'; echo ' </tr>'; echo ' <tr>'; echo ' <td width="100">Checkin Date</td>'; echo ' <td width="100"><input style="width: 70px" value="' . ($row['checkin']) . '" type="text" name="checkin"></td>'; echo ' </tr>'; echo ' <tr>'; echo ' <td width="100">Checkout Date</td>'; echo ' <td width="100"><input style="width: 70px" value="' . ($row['checkout']) . '" type="text" name="checkout"></td>'; echo ' </tr>'; echo ' <tr>'; echo ' <td width="100"></td>'; echo ' <td width="100"><input type="submit" name="editbooking" value="Update Booking"></td>'; echo ' </tr>'; echo '</table>'; echo '<input type="hidden" name="source">'; echo '</form>'; } if (isset($_POST['editbooking'])) { $fullname = $_POST['fullname']; $address = $_POST['address']; $city = $_POST['city']; $postcode = $_POST['postcode']; $country = $_POST['country']; $tel = $_POST['tel']; $email = $_POST['email']; $info = $_POST['info']; $checkin = $_POST['checkin']; $checkout = $_POST['checkout']; $source = 'Manual Add'; $id_update = ($row['id']); $SQL = "UPDATE bookings SET fullname = '$fullname', address = '$address', city = '$city', postcode = '$postcode', country = '$country', tel = '$tel', email = '$email', info = '$info', checkin = '$checkin', checkout = '$checkout', source = '$source' WHERE id = '$id_update'"; error_reporting(0); $result = mysql_db_query($database,"$SQL"); header("location:index.php#bookings"); } ?> Where am I going wrong here? It simply won't update the query but if I change $id to 27 for example it will edit it?? Okay, I am writing a new form validation script that also keeps the data so it can re-populate the fields the user already filled out if there is an error on the page so they do not have to fill it out again. Here is an example of the code I am using in the HTML part of the form input elements. <input name="name" type="text" id="name" value="<?php=$fields['name']?>"> Now, the problem I am getting is the <?php=$fields['name']?> code is being physically displayed within the form field at all times. How would I go about having it not display this line of code in the field? Thanks!! the problem im getting is with this line in the bootstrap Code: [Select] $this->view->head_title('test'); the view property is only initiated in the league_controller and $this->view doesnt exsist within the bootstap but i call the bootstrap header in the league controller and it wont let me execute the head title...if anyone can help me on why or how i can over come this please....thank you (code below) bootstrap Code: [Select] public static function header() { $this->view->head_title('test'); } leaugue_controller method Code: [Select] public function league($game_name, $league_name) { Bootstrap::header(); $rows = $this->leagues->fetch_league($game_name, $league_name); $this->view->head_title()->set_separator()->prepend('hello'); $this->view->rows = $rows; Bootstrap::footer(); } I have this $string=<span style=\"font-weight: bold;"> how can i replace the \" with " only i try this but didnt work str_replace("\\\"","\"",$string) I just want to compare this two functions <?php function myfunction($x) { if($_GET['x']==$x) { return "SELECTED"; } } echo "<option value='test'".myfunction('test').">TEST</option>"; ?> ======================================================= <?php function myfunction($x) { if($_GET['x']==$x) { echo "SELECTED"; } } ?> <option value="test" <?php myfunction("test");?>>TEST</option> * Assume that $_GET['x']=="test" My question: I try to use echo for the first case and option didnt SELECTED until i use return Same thing with the second one, where i have to use return instead of echo can anyone simply explain this thanks Hmm i can't figure this out... Below you see my code. I have 8 results from the query and i have the pegination set to max 2 values. It has 8 result so it devides them into 4 pages. But all the results are on the first page so the second third and fourth page are empty. Why is that? <?php if (isset($_POST['model_zoeken'])) { $con = mysql_connect("localhost","admin",""); if (!$con) { die('Could not connect: ' . mysql_error()); } if (!(isset($pagenum))) { $pagenum = 1; } mysql_select_db("produkten", $con); $data = mysql_query("SELECT * FROM eigenschappen") or die(mysql_error()); $rows = mysql_num_rows($qry); $page_rows = 2; $last = ceil($rows/$page_rows); if ($pagenum < 1) { $pagenum = 1; } elseif ($pagenum > $last) { $pagenum = $last; } $max = 'limit ' .($pagenum - 1) * $page_rows .',' .$page_rows; $data_p = mysql_query("SELECT * FROM eigenschappen $max") or die(mysql_error()); $qry = "SELECT * FROM eigenschappen WHERE 1=1"; if (isset($_POST['prod_name']) && trim($_POST['prod_name']) != "") { $qry .= " AND prod_name='" . mysql_real_escape_string($_POST['prod_name']). "'"; } "'"; } $result = mysql_query($qry) or die(mysql_error()); $teller = 0; $rijen = 0; echo '<table border="0"><tr>'; while($row = mysql_fetch_array($result)) { echo' <td width="160" align="center"> <a href="'.$row['website'].'"></a><img src="'.$row['prod_img'].'"> </td> <td width="165" valign="top"><br /><br />Name: '.$row['prod_name'].'<br/><br/>Website: <a href="'.$row['website'].'" target="_blank">'.$row['website_naam'].'</a> </td>' ; $teller = $teller + 1; $rijen = $rijen + 1; if ($teller == 3 || $rijen == 3){ echo "</tr><tr>"; $rijen = 0; $teller = 0; } } echo '</tr></table>'; echo '<br />'; echo " --Page $pagenum of $last-- <p>"; if ($pagenum == 1) { } else { echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=1'> <<-First</a> "; echo " "; $previous = $pagenum-1; echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=$previous'> <-Previous</a> "; } echo " ---- "; if ($pagenum == $last) { } else { $next = $pagenum+1; echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=$next'>Next -></a> "; echo " "; echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=$last'>Last ->></a> "; } } ?> hello guys, this is my first post on this forum and I really need your help on this. What I have is: I created a login page a home page and a index page. The index page checks if the session is set. If it's not the login page will be shown. If it is the homepage will be shown. Whenever the user logs in, the session gets set. The problem is is that whenever I login and the user presses the back button on his browser my session will always be returned false which means that whenever a user has logged in, the index page doesn't show home but shows the login page again even though the user has already logged in. Here is my code to make you understand a little bit better: session.php: Code: [Select] <?php class Session { function __construct() { } function set($name, $value) { $_SESSION[$name] = $value; } function get($name) { return $_SESSION[$name]; } function stopSession() { unset($_SESSION); session_destroy(); } function startSession() { if(!isset($_SESSION)) { session_start(); } } function check_session() { if(isset($_SESSION['username']) && !empty($_SESSION['username'])) { return true; } else { return false; } } } ?> login.php: Code: [Select] <?php class Handler_Login extends Action_Handler { function __construct($action_handle) { parent::construct($action_handle); $this->action = $action_handle; } function secured_handler() { $password = $_POST['password']; $username = $_POST['username']; $login = $this->dbh->Login($username, $password); if ($login == true) { $this->session->startSession(); $this->session->set('username', $username); $this->view->displayHome(); $this->view->display(); } else { //This is going to get more advanced later on, I'm currently working on resolving my session issue before I continue on this. echo "you are not logged in"; } } } ?> index.php: Code: [Select] <?php class Handler_home extends Action_Handler { public function __construct($action_handle) { parent::construct($action_handle); $this->action = $action_handle; } function secured_handler() { // for some reason this always returns false when the user goes back in history :( if ($this->session->check_session() == false) { $this->view->displayLogin(); $this->view->display(); } else { $this->view->displayHome(); $this->view->display(); } } } ?> anyone has an idea why the login page is always shown ? Hi guys, i'm trying to increment a variable / session value whenever 'submit' comes in the POST. I can't seem to get around the logic of this. Code looks like this: Code: [Select] $var = 0 if($_POST('submit'){ $_SESSION['var2'] = $var++; } What I want it to do is increment the value of the session index everytime a user clicks 'submit'. But because i've reset $var to 0 everytime, it's always just going to stay at 1. I just can't think of a way to achieve this, does anyone have any clue on how I can? been trying to get a code up and working for a update database form, couldnt really get any working i found from google and then after a bit of help from here i got a crazy idea and stopped dead and my tracks and switched gears. so i thought, why not just use the form i used to insert my database and change it around a little. same concept, how should this not be possible ? for reference here are my tables and structure Movies ID(PK) Title Category(FK) URL 0 Name 1 http://www. Categories ID(PK) Category 1 Drama note: i know i should change Category from movies to CategoryID for less confusion. to make long story short when i tried i got errors, to much time to go back over everything so i will just stick with what i got for now. ok so my insert form inserts a movie title,category and url into my movies table. the dropdown for category is populated with a list of categories in my categories table, the way the code is writen it shows the actual category name instead of the id inside the dropdown. the form goes like: Title: textfield1 Category:dropdown URL:textfield2 so what i did was took the code from it, replaced title textfield1 with the same dropdown for category and just edited the select and echo to pull and show movie titles. i also added a WHERE to it so i can only select titles in a certian category. so it should look like, Title: dropdown Category:dropdown so here is the code below (ignore leftovers from URL or anything else i plan on taken them out pending the outcome) Code: [Select] <html> <form id="form1" name="Update" method="post" action="ad3.php"> <label> Title: <input type="text" name="Title" id="Title" /> </label> <br /> <select name='dropdownt' id='dropdownt'> <?php $con = mysql_connect("localhost", "root", ""); if (!$con) { die('Could not connect to DB: ' . mysql_error() ); } mysql_select_db ("5", $con); $query = "SELECT Title FROM movies WHERE Category='1'"; $result = mysql_query($query) OR DIE ("There was an error" .mysql_error()); while($row=mysql_fetch_array($result)) { echo " <option value=\"{$row['Title']}\">{$row['Title']}</option>"; } php?> </select> <select name='dropdown' id='dropdown'> <?php $con = mysql_connect("localhost", "root", ""); if (!$con) { die('Could not connect to DB: ' . mysql_error() ); } mysql_select_db ("5", $con); $query = "SELECT ID, Category from categories"; $result = mysql_query($query) OR DIE ("There was an error" .mysql_error()); while($row=mysql_fetch_array($result)) { echo " <option value=\"{$row['ID']}\">{$row['Category']}</option>"; } php?> </select> <input name="" type="submit" value="send" /> </form> </html> one thing that i could not figure out (due to my lack of php knownledge) is that after my SELECT i have the Code: [Select] echo " <option value=\"{$row['Title']}\">{$row['Title']}</option>"; before i had edited this code there was ID where the first 'Title' is. after trying to take one part of that out i got a error so i just left it. so what i thought i would do for the process page (ad3.php) i would just turn the INSERT into a UPDATE. Code: [Select] <?php $con = mysql_connect("localhost", "root", ""); if (!$con) { die('Could not connect to DB: ' . mysql_error() ); } mysql_select_db ("5", $con); $sql="UPDATE movies SET Category = '$_POST[dropdown]', Title = '$_POST[dropdownt]' LIMIT 1"; if (!mysql_query($sql,$con)) { die ('Error: ' . mysql_error()); } echo "<a href=\"form2.php\">Record added. Click here to make a new entry</a>"; the surprising thing (to me anyways) is that it actually worked! well.. ALMOST it should work by letting me select a certian title thats in a certian category and change its current category into a different one and then submit. after a few hours i finaly got it to do what i need BUT the problem i am having is that when looking into my phpmyadmin, it just changes the name and category to the first record in my movies table which is id "0". one of the too. i almost done it on my own.. almost... sorry for the extended post but i didnt want to leave anyone confused. so my question is, did i forget to add anything, take anything out, miss a change i needed to make ? maybe its the echos after my SELECT in my form > Hi all, I have a simple script that does not work! I think it may be to do with $num = mysqli_num_rows($result) and $row = mysqli_assoc_result($result). I have tried echoing the value which works if I put it above the include("cxn.php");. The code is: <?php include("cxn.php"); $sql = "SELECT * FROM table WHERE email='$_POST[email]'"; $result = mysqli_query($cxn,$sql) or die("Cant execute query!"); $num = mysqli_num_rows($result); $row = mysqli_fetch_assoc($result); if ($num > 0) { $to = "$_POST[email]"; $subj = "from the website"; $mess = "Your value is".$row['value']; $mailsend = mail($to,$subj,$mess,$headers); echo "email sent to $_POST['email']"; } else { echo "email not found!";} ?> I followed tutorial from youtube Code: [Select] http://www.youtube.com/watch?v=5b3TcoeY7Bsand made shopping cart. Everything is working fine, but there is one part I want to add. I want user to be able to set the quantity of products without going to the cart (user have to be able to enter quantity himself). At the moment I have no idea how to do this, i am still researching this topic, but wanted to try to ask for help from the pros . This is the complete code (a bit large): index.php: Code: [Select] <?php session_start(); require("includes/connection.php"); if(isset($_GET['page'])){ $pages=array("products", "cart"); if(in_array($_GET['page'], $pages)) { $_page=$_GET['page']; }else{ $_page="products"; } }else{ $_page="products"; } ?> <!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" /> <link rel="stylesheet" href="css/reset.css" /> <link rel="stylesheet" href="css/style.css" /> <title>Shopping Cart</title> </head> <body> <div id="container"> <div id="main"> <?php require($_page.".php"); ?> </div><!--end of main--> <div id="sidebar"> <h1>Cart</h1> <?php if(isset($_SESSION['cart'])){ $sql="SELECT * FROM products WHERE id_product IN ("; foreach($_SESSION['cart'] as $id => $value) { $sql.=$id.","; } $sql=substr($sql, 0, -1).") ORDER BY name ASC"; $query=mysql_query($sql); while($row=mysql_fetch_array($query)){ ?> <p><?php echo $row['name'] ?> x <?php echo $_SESSION['cart'][$row['id_product']]['quantity'] ?></p> <?php } ?> <hr /> <a href="index.php?page=cart">Go to cart</a> <?php }else{ echo "<p>Your Cart is empty. Please add some products.</p>"; } ?> </div><!--end of sidebar--> </div><!--end container--> </body> </html> cart.php: Code: [Select] <?php if(isset($_POST['submit'])){ foreach($_POST['quantity'] as $key => $val) { if($val==0) { unset($_SESSION['cart'][$key]); }else{ $_SESSION['cart'][$key]['quantity']=$val; } } } ?> <h1>View cart</h1> <a href="index.php?page=products">Go back to products page</a> <form method="post" action="index.php?page=cart"> <table> <tr> <th>Name</th> <th>Quantity</th> <th>Price</th> <th>Items Price</th> </tr> <?php $sql="SELECT * FROM products WHERE id_product IN ("; foreach($_SESSION['cart'] as $id => $value) { $sql.=$id.","; } $sql=substr($sql, 0, -1).") ORDER BY name ASC"; $query=mysql_query($sql); $totalprice=0; while($row=mysql_fetch_array($query)){ $subtotal=$_SESSION['cart'][$row['id_product']]['quantity']*$row['price']; $totalprice+=$subtotal; ?> <tr> <td><?php echo $row['name'] ?></td> <td><input type="text" name="quantity[<?php echo $row['id_product'] ?>]" size="5" value="<?php echo $_SESSION['cart'][$row['id_product']]['quantity'] ?>" /></td> <td><?php echo $row['price'] ?>$</td> <td><?php echo $_SESSION['cart'][$row['id_product']]['quantity']*$row['price'] ?>$</td> </tr> <?php } ?> <tr> <td>Total Price: <?php echo $totalprice ?></td> </tr> </table> <br /> <button type="submit" name="submit">Update Cart</button> </form> <br /> <p>To remove an item set it's quantity to 0. </p> products.php: Code: [Select] <?php if(isset($_GET['action']) && $_GET['action']=="add"){ $id=intval($_GET['id']); if(isset($_SESSION['cart'][$id])){ $_SESSION['cart'][$id]['quantity']++; }else{ $sql_s="SELECT * FROM products WHERE id_product={$id}"; $query_s=mysql_query($sql_s); if(mysql_num_rows($query_s)!=0){ $row_s=mysql_fetch_array($query_s); $_SESSION['cart'][$row_s['id_product']]=array( "quantity" => 1, "price" => $row_s['price'] ); }else{ $message="This product id it's invalid!"; } } } ?> <h1>Product List</h1> <?php if(isset($message)){ echo "<h2>$message</h2>"; } ?> <table> <tr> <th>Name</th> <th>Description</th> <th>Price</th> <th>Action</th> </tr> <?php $sql="SELECT * FROM products ORDER BY name ASC"; $query=mysql_query($sql); while ($row=mysql_fetch_array($query)) { ?> <tr> <td><?php echo $row['name'] ?></td> <td><?php echo $row['description'] ?></td> <td><?php echo $row['price'] ?>$</td> <td><a href="index.php?page=products&action=add&id=<?php echo $row['id_product'] ?>">Add to cart</a></td> </tr> <?php } ?> </table> So i have this page that pretty much displays all the members in the database, and its split into pages using a pagination php script. The problem is that i want the ID number displayed next to it, however the database record id jumps since some records have been deleted. So while there were a total of 1000 records 10 have been removed so instead of showing the accurate ID number of 995 on the last record it displays the number 1000 .... I've tried just assigning a number to each record using the following code... $get_members = "SELECT * FROM members ORDER BY ID ASC LIMIT $rowsperpage OFFSET $offset"; $run_mem_query = mysql_query($get_members) or die(mysql_error()); $club_id = 1; while($member = mysql_fetch_assoc($run_mem_query)){ ?> <li><strong><?php echo $club_id++ ;?>.</strong><?php echo $member['username'] ;?> - <span><?php echo $member['state'] ;?></span></li> <?php } The problem with that is that every time i click to go to the next page the number sequence refreshed back to 1 and starts over.... i've been trying to find a way around his, but can't....does anyone have any solutions to this??? Here's the script that controls the pagination <?php if ($totalpages > 1){ /*********** Start the pagination links ********/ echo "<p>"; // range of num links to show $range = 6; // if not on page 1, don't show back links if ($currentpage > 1) { // show << link to go back to page 1 echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=1'>First</a> "; // get previous page num $prevpage = $currentpage - 1; // show < link to go back to 1 page echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$prevpage'>Previous</a> "; } // end if if($result > 0){ // loop to show links to range of pages around current page for ($x = ($currentpage - $range); $x < (($currentpage + $range) + 1); $x++) { // if it's a valid page number... if (($x > 0) && ($x <= $totalpages)) { // if we're on current page... if ($x == $currentpage) { // 'highlight' it but don't make a link echo " <b>$x</b> "; // if not current page... } else { // make it a link echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$x'>$x</a> "; } // end else } // end if } // end for }else{ echo "<a href='{$_SERVER['PHP_SELF']}?currentpage=$x'>1</a>"; } // if not on last page, show forward and last page links if ($currentpage != $totalpages) { // get next page $nextpage = $currentpage + 1; // echo forward link for next page echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$nextpage'> Next </a> "; // echo forward link for lastpage echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$totalpages'> Last </a> "; } // end if echo "</p>\n"; /****** end build pagination links ******/ } ?> I have created a login form. I am sending values through Ajax for form validation. However, I am having problem with the code that I am unable to store values in Sessions & Cookies.
I have added a "Remember me" checkbox into login form. I want to validate Boolean value using Javascript Checked property and send the data to PHP for validation.
If user clicks on remember me checkbox then the data should be stored in either Sessions & Cookies. If it is not checked then data should be stored only in Sessions. I am posting here my login form code, Ajax code & PHP code.
Could you guys help me to point out my mistake what I am doing wrong in this code?
Login Form:
<input type="checkbox" id="cb" name="cb"> <label for="cb">Remember me</label>Ajax Code: function login(){var e = _("email").value; var pass = _("password").value; var cb = _("cb").value; if(e == "" || pass == ""){ _("status").innerHTML = "Please fill out the form"; } else { _("loginbtn").style.display = "none"; _("status").innerHTML = 'please wait ...'; var ajax = ajaxObj("POST", "handlers/login_handler.php"); ajax.onreadystatechange = function() { if(ajaxReturn(ajax) == true) { if(ajax.responseText == "login_failed"){ _("status").innerHTML = "Login failed, please try again."; _("loginbtn").style.display = "block"; } else { window.location = "message.php?msg=Hello "+ajax.responseText; } } } ajax.send("e="+e+"&pass="+pass+"&cb="+cb); } }PHP Code: $cb = cleanstr($_POST['cb']); if(isset($cb) && ($cb == true)) { // IF USER CLICKED ON REMEMBER ME CHECKBOX CREATE THEIR SESSIONS AND COOKIES $_SESSION['userid'] = $db_id; $_SESSION['username'] = $db_username; $_SESSION['password'] = $db_pass; setcookie("id", $db_id, strtotime( '+30 days' ), "/", "", "", TRUE); setcookie("user", $db_username, strtotime( '+30 days' ), "/", "", "", TRUE); setcookie("pass", $db_pass, strtotime( '+30 days' ), "/", "", "", TRUE); // UPDATE THEIR "IP" AND "LASTLOGIN" FIELDS $sql = "UPDATE users SET ip='$ip', lastlogin=now() WHERE id='$db_id' LIMIT 1"; $query = mysqli_query($con, $sql); echo $db_username; exit(); } else { // IF USER HAS NOT CLICKED ON REMEMBER ME CHECKBOX CREATE THEIR SESSIONS ONLY $_SESSION['userid'] = $db_id; $_SESSION['username'] = $db_username; $_SESSION['password'] = $db_pass; // UPDATE THEIR "IP" AND "LASTLOGIN" FIELDS $sql = "UPDATE users SET ip='$ip', lastlogin=now() WHERE id='$db_id' LIMIT 1"; $query = mysqli_query($con, $sql); echo $db_username; exit(); } I have this code and its working awsomely fine if i provide a direct link of an uploaded image. Just and just only one problem i am not able to pass my uploaded image to facebook->api (whether its valid or not) and the following always echo echo 'Only jpg, png and gif image types are supported!'; i even remove the check on image type and try to get the image from $img = realpath($_FILES["pic"]["tmp_name"]); but $img gets nothing in it and uploads a by default empty image on facebook as my page Kindly check my following code and let me know what is wrong with my code and what should i do instead to upload images Online link of the following CODE: http://radiations3.com/facebook/1.php Code: [Select] <? require 'src/facebook.php'; $app_id = "364900470214655"; $app_secret = "xxxxxxxx"; $facebook = new Facebook(array( 'appId' => $app_id, 'secret' => $app_secret, 'cookie' => true, 'fileUpload' => true, )); $user = $facebook->getUser(); //echo $user; if(($facebook->getUser())==0) { header("Location:{$facebook->getLoginUrl(array('req_perms' => 'user_status,publish_stream,user_photos,offline_access,manage_pages'))}"); exit; } else { $accounts_list = $facebook->api('/me/accounts'); echo "i am connected"; } $valid_files = array('image/jpeg', 'image/png', 'image/gif'); //to get the page access token to post as a page foreach($accounts_list['data'] as $account){ if($account['id'] == 194458563914948){ // my page id =123456789 $access_token = $account['access_token']; echo "<p>Page Access Token: $access_token</p>"; } } //posting to the page wall if (isset($_FILES) && !empty($_FILES)) { if( !in_array($_FILES['pic']['type'], $valid_files ) ) { echo 'Only jpg, png and gif image types are supported!'; } else{ #Upload photo here $img = realpath($_FILES["pic"]["tmp_name"]); $attachment = array('message' => 'this is my message', 'access_token' => $access_token, 'name' => 'This is my demo Facebook application!', 'caption' => "Caption of the Post", 'link' => 'example.org', 'description' => 'this is a description', 'picture' => '@' . $img, 'actions' => array(array('name' => 'Get Search', 'link' => 'http://www.google.com')) ); $status = $facebook->api('/194458563914948/feed', 'POST', $attachment); // my page id =123456789 var_dump($status); } } ?> <body> <!-- Form for uploading the photo --> <div class="main"> <p>Select a photo to upload on Facebook Fan Page</p> <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data"> <p>Select the image: <input type="file" name="pic" /></p> <p><input class="post_but" type="submit" value="Upload to my album" /></p> </form> </div> </body> |