PHP - Setcookie Working Only After Refresh
I am working on a login script and I am using cookies for the first time. I have it something like this:
<?php if (correct user/pass entered) - set user/pass cookies ?> <html> <?php if (user/pass cookies are set) {echo 'you are logged in';} else {echo 'you are NOT logged in';} ?> </html> The problem is that if I enter a valid username and password, and the cookies are set, then I get the message 'you are NOT logged in' unless I leave the page then return to it, or if I refresh, in which case I get the message 'you are logged in'. Its almost as though I cannot use the cookies until I navigate away from the page on which they were set. Am I doing something wrong, or is this the way it works? Similar Tutorialswhen a user logs in the cookie isnt being set. am i doing it wrong? if(empty($error)) { $query = $link->query("SELECT * FROM ".TBL_PREFIX."users WHERE u_username = '$username' AND u_password = '".asf_hash($password)."'") or die(print_link_error()); $row = $query->fetchAll(); $num_rows = $query->rowCount(); if($num_rows == 1) { if($row[0]['u_confirmed'] == 1) { setcookie('uid', $row[0]['u_uid'], time() + $session_length); // this cookie isnt being set echo 1; } else { $error = 'You Need To Activate Your Account'; } } else { if(!$error) { echo $lang->incorrect_login_details; } } } im doing a print_r on all cookies and it doesnt appear in the list. $session_length is set at 99999999 I just did a huge import from an app I have been working on. No issues except for this. I uploaded & imported all files & databases from my wampserver (localhost, local server) to my main online server. Before I continue with the problem, I have to give you info on how the files work. I am using a "controller" to view the files. Meaning, from index.php, I call all the files. For example, instead of mysite.com/register.php, its mysite.com/index.php?page=register. The index defines the doctype & html tags etc. The other files that are called through index.php are just pure php code, it does not contain the head & body tags etc. So, the issue is , when the surfer submits a form, i need to set a cookie. this cookie is VERY important. I cannot get it to work. I am getting the header warnings after submit Of course, this is to be expected. But I tried it on my local server, & it worked. I am not very familiar with cookies, this is a side of PHP i never really even touched. I know almost everything but that. So the php code is before the html code on the page, so I figured it was worth a shot. Im guessing the problem here is, since the code being outputted as index.php code + the form page code. So the cookie is being set after the html tags. How can I fix this? I need it to work thru the controller. I cannot just make it a single file, all files on the site needs to be thru this controller, otherwise it will mess everything up. Ino I could just add the code from index.php plus the form page code & just run the php code before all of the html tags, but like I said it has to be called thru index.php. I appreciate your replies, & I hope you guys dont think im an idiot & can understand my question, im terrible with words! For some reason I can not get this to work. Any thoughts? if( $row['password'] == $pass && $row['name'] == $user ) { $username = $row['name']; $uid = $row['id']; setcookie("id", $uid, 1400); //creates the first session var setcookie("username", $username, 1400); // second session var setcookie("loggedin", "1", 1400); echo "<script type=\"text/javascript\">alert(\"".$row['name']."Logged in as ".$_COOKIE['username'].".\"); window.location=\"index.php?OMG=loggedin\"</script>"; } I get a message box saying: "[username] Logged in as ." I've searched php.ini for corrupt cookie settings, nothing unusual. Hey Guys, I am trying to set a cookie so that when I registered user returns it Auto Logins them in. I am able to accomplish this on my Local server but as Soon as I upload to a web server to test it, it doesn't work. Is anyone able to shed some light on this for me. $usass = $mem['userid']; if (isset($_POST['rem'])) { $year = 3600*24*365; setcookie ("id" , "$usass", time()+$year); } if the code for setting the cookie, and the code for checking the cookie is Below if(isset($_COOKIE['id'])) { $_SESSION['userid'] = $_COOKIE['id']; print "<script>"; print " self.location='loggedin.php';"; // Comment this line if you don't want to redirect print "</script>"; } Hi, I'm working on a mac with MAMP, phpMyadmin. on localhost, also the mysql server is on my localhost. I've tested in either Safari and Firefox. I'm trying to set my cookie, and it doesn't work, and pulling my hair out. I'm trying out following script which should work, but it doesn't and it's driving me mad. I wanna check the cookie for when a person is or isn't logged in, so that i can show additional data on the .php page <html> <body> <?php $value = "my cookie value"; // send a cookie that expires in 24 hours setcookie("TestCookie",$value, time()+3600*24); // Print individual cookies echo $_COOKIE["TestCookie"]; // Print all cookies print_r($_COOKIE); ?> </body> </html> i have never been able to get this to work but i am at it agian in this code the php is not making the cookie can any one tell me why <?php function getRandomString($length = 5) { $validCharacters = "abcdefghijklmnopqrstuxyvwzABCDEFGHIJKLMNOPQRSTUXYVWZ+-*#&@!?1234567890"; $validCharNumber = strlen($validCharacters); $result = ""; for ($i = 0; $i < $length; $i++) { $index = mt_rand(0, $validCharNumber - 1); $result .= $validCharacters[$index]; } return $result; } setcookie("code", "getRandomString()", 3600000); echo getRandomString(); ?> I know PHP setcookie can set for all subdomains - by setting parameter 5 to something like ".domain.com". However, I have quite a lot of code that just leaves param 5 blank (so sets for the current subdomain of that server). Hopefully there'd be an easy way how to do this (a server setting?). I know you can use ini_set('session.cookie_domain','http://domain.com'); but that only seems to set the session cookie value, not ones set in PHP. I only really want it to ensure if someone accesses the site through both www.domain.com and domain.com that they use the same cookies. Hello. I currently have a site that registered members can login in to and view the member only pages. Eventually I will be adding paypal code to purchase products. I use Session with an IF statement for all my members pages. Would it be beneficial at all to have cookies created for the users with setcookie? Or is this just a security risk waiting to happen? I am aiming to use setcookie to refresh the expiry of a cookie on EVERY page request. Is this slow? I'm sure I can design things so i don't need to reset it on every page request, but if it isn't a big deal then I'll do it. Is setcookie slow? hello i use the fallowing code for my login page but it gives me the fallowing error i was wondering what is the problem? (line 179 is the setcookie) by the way it doesn't set the cookie any help would be appreciated error: Quote Warning: Cannot modify header information - headers already sent by (output started at /home2/sportsh9/public_html/test/login_acc.php:6) in /home2/sportsh9/public_html/test/login_acc.php on line 179 my code: <? include_once('functions.php'); function cleanQuery($string) { if(get_magic_quotes_gpc()) // prevents duplicate backslashes { $string = stripslashes($string); } $badWords = "(delete)|(update)|(union)|(insert)|(drop)|(http)|(--)"; $string = eregi_replace($badWords, "", $string); if (phpversion() >= '4.3.0') { $string = mysql_real_escape_string($string); } else { $string = mysql_escape_string($string); } return $string; } if (isset($_COOKIE['scmuser'])) { echo "<META HTTP-EQUIV=\"Refresh\" CONTENT=\"1; URL=index.php\">"; }else{ if ($_POST['username']) { //did they supply a password and username $username=cleanQuery($_POST['username']); $password=cleanQuery($_POST['password']); if ($password==NULL || $username==NULL) { ?> <p align="center"> <font color="#FF0000">Username or password wasn't supplied!</font><form action="login_acc.php" method="POST"> <table style="border:1px solid #FFFFFF;" width="90%" align="center"> <tr> <td align="center">Username: </td> <td align="center"> <input type="text" size="20" maxlength="25" name="username" /></td> </tr> <tr> <td align="center">Password: </td> <td align="center"> <input type="password" size="20" maxlength="25" name="password" /></td> </tr> <tr> <td align="center" colspan="2"> <input type="submit" value="Login"/> </td> </tr> <tr> <td align="center" colspan="2"> <a href="register.php">Register</a> - <a href="forgetpass.php">Forgot Your Password?</a> </td> </tr> </table> </form> <? }else{ $query = mysql_query("SELECT username,password FROM users WHERE username = '$username'") or die(mysql_error()); $data = mysql_fetch_array($query); if($data['password'] != $password) { ?> <p align="center"> <font color="#FF0000">The supplied login was incorrect</font><form action="login_acc.php" method="POST"> <table style="border:1px solid #FFFFFF;" width="90%" align="center"> <tr> <td align="center">Username: </td> <td align="center"> <input type="text" size="20" maxlength="25" name="username" /></td> </tr> <tr> <td align="center">Password: </td> <td align="center"> <input type="password" size="20" maxlength="25" name="password" /></td> </tr> <tr> <td align="center" colspan="2"> <input type="submit" value="Login"/> </td> </tr> <tr> <td align="center" colspan="2"> <a href="register.php">Register</a> - <a href="forgetpass.php">Forgot Your Password?</a> </td> </tr> </table> </form> <? }else{ $query = mysql_query("SELECT username,password FROM users WHERE username = '$username'") or die(mysql_error()); $row = mysql_fetch_array($query); setcookie("scmuser", "$username", time()+3600); echo "<META HTTP-EQUIV=\"Refresh\" CONTENT=\"1; URL=index.php\">"; } } } } ?> thank you I hate header errors... I can never figure them out, im getting this error; Warning: Cannot modify header information - headers already sent by (output started at /home/damnpeti/public_html/restrict2.php:6) in /home/damnpeti/public_html/restrict2.php on line 62 Code: <?php $testDB = mysql_connect('localhost', $db_user, $db_pwd); mysql_select_db ($db_name); if (!$testDB) { die('Could not connect: ' . mysql_error()); } $surfer_ip = $_SERVER["REMOTE_ADDR"]; $str_sql = "select * from ".$db_table." where ipaddress='".$surfer_ip."'"; $result = mysql_query($str_sql); if ($row = mysql_fetch_assoc($result)) { $blocked_time = strtotime($row['blocked_time']); if($blocked_time != 0) { $current_time = time(); if($current_time - $blocked_time > 3600*24) //24 hours past { $str_sql = "delete from ".$db_table." where ipaddress='".$surfer_ip."'"; mysql_query($str_sql); $str_sql = "insert into ".$db_table." (ipaddress, surf_index) values('".$surfer_ip."', 1)"; mysql_query($str_sql); } else { die ("<center><div class='errors'>You have accessed this page too many times. To regain access, purchase a license or wait 24 hours.</div></center>"); } } else { if($row['surf_index'] < 2) { $str_sql = "update ".$db_table." set surf_index=surf_index+1 where ipaddress='".$surfer_ip."'"; mysql_query($str_sql); } else { $str_sql = "update ".$db_table." set blocked_time='".date ("Y-m-d H:i:s")."' where ipaddress='".$surfer_ip."'"; mysql_query($str_sql); die ("<center><div class='errors'>You have accessed this page too many times. To regain access, purchase a license or wait 24 hours.</div></center>"); } } } else { $str_sql = "insert into ".$db_table." (ipaddress, surf_index) values('".$surfer_ip."', 1)"; mysql_query($str_sql); } if(!isset($_COOKIE['surf_no'])) setCookie('surf_no', '1'); else setCookie('surf_no', $_COOKIE['surf_no']+1); if ($_COOKIE['surf_no'] > 2) die("<center><div class='errors'>You have accessed this page too many times. To regain access, purchase a license or wait 24 hours.</div></center>"); include 'http://damnitpetitions.com/cut/index3.php'; ?> Line 62 is if ($_COOKIE['surf_no'] > 2) I know it has something to do with the cookie... but Idk? I need the include there. If there include isnt where its at, the script is worthless. I'm stumped on this one. New to sessions and cookies. When somebody logs out, the browser goes to logout.php. It logs them out, but the page shows this error: Warning: setcookie() expects parameter 3 to be long, string given in /data/21/2/40/160/2040975/user/2235577/htdocs/logout.php on line 23 you are now logged out. Code: [Select] <?php session_start(); if(!($_SESSION[id])){ $url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_server['PHP_SELF']); // check for trailing slash if ((subst($url, -1) == '/') OR (substr($url, -1) == '\\') ){ $url = substr($url, 0, -1); } $url .= '/index.php'; header("Location: $url"); exit(); } else { $_SESSION = array(); session_destroy(); setcookie ('PHPSESSID'. '', time()-300, '/', '', 0); } $page_title ='logged out!'; echo ' you are now logged out'; Hi all, Thanks for reading. I'm running a script using jQuery that auto-refreshes a <div> on the index page from an external PHP script to get all the rows in a database and display them on the index page. The script works great - here it is as follows: Code: [Select] <script type="text/javascript"> $(document).ready(function() { $("#responsecontainer").fadeOut("fast").load("getrows.php").fadeIn("slow"); var refreshId = setInterval(function() { $("#responsecontainer").fadeOut("fast").load('getrows.php').fadeIn("slow"); }, 5000); $.ajaxSetup({ cache: false }); }); </script> The getrows.php script I'm working with looks like this: Code: [Select] <?php $rowsQuery = mysql_query("SELECT * FROM Happenings WHERE HappeningDate='$today'"); if (mysql_num_rows($rowsQuery) == 0) { $happeningsToday = "There are no happenings today."; } else { $allHappeningsToday = 1; while ($getHappeningsToday = mysql_fetch_array($rowsQuery)) { $happeningName = stripslashes($getHappeningsToday['HappeningName']); $happeningDate = $getHappeningsToday['HappeningDate']; $happeningDescription = $getHappeningsToday['HappeningDescription']; if ($allHappeningsToday == 1) { $happeningsToday .= " <div class=\"box\"> <p>".$happeningName." | ".$happeningDate." | ".$happeningDescription." </div>"; $allHappeningsToday = 2; } else { $happeningsToday .= " <div class=\"box\"> <p>".$happeningName." | ".$happeningDate." | ".$happeningDescription." </div>"; $allHappeningsToday = 1; } } } echo $happeningsToday; ?> This script works great as well. Currently, the auto-refresh jQuery script as you can see if getting and fading in/out all of the rows. Off of the above getrows.php script, is there a way after I could get only the newly created rows since the last refresh and only fade those in and out while leaving the others already loaded by the auto-refresh script to not fade in/out? Any ideas, thoughts or suggestions would be unbelievably helpful. Thank you very much. will refresh a page every second will cause some crash or error ?? cause when i try this, it sometimes display this error "Warning: mysql_connect() [function.mysql-connect]: Can't connect to MySQL " this is occur when i run it in my local server. I am so worried if this might also happen when i run it online. thanks So basically, My Bulletfactory page is playing up. Every 30 minutes the bulletfactory should produce bullets, it is producing the bullets fine, but only when someone views the page (after 30 minutes is up). If there any kind of PHP refresh for this? Or do i just use normal refresh? Thanks I'm having trouble getting my script to refresh the page. If the username, password match it falls into this if statement. Sometimes it works and other times and won't refresh the page automatically. I'm trying to use this line to refresh the page Code: [Select] echo "<meta http-equiv='refresh' content='=2;index.php' />"; Here is the if statement Code: [Select] if(mysql_num_rows($checklogin) == 1) { // store the row returned from query $row = mysql_fetch_array($checklogin); // get email address from row returned $email = $row['EmailAddress']; // store user variables in session array $_SESSION['Username'] = $username; $_SESSION['EmailAddress'] = $email; $_SESSION['LoggedIn'] = 1; // boolean echo "<h1>Success</h1>"; echo "<p>We are now redirecting you to the member area.</p>"; echo "<meta http-equiv='refresh' content='=2;index.php' />"; } here is the entire index.php file Code: [Select] <?php include "base.php";?> <!-- base.php contains session_start() --> <!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>User Management System (Tom Cameron for NetTuts)</title> <link rel="stylesheet" href="style.css" type="text/css" /> </head> <body> <div id="main"> <?php // check if user is already logged in if(!empty($_SESSION['LoggedIn']) && !empty($_SESSION['Username'])) { ?> <h1>Pitch Shark Member Area</h1> <p>Thanks for logging in! You are <b><?=$_SESSION['Username']?><b> and your email address is <b><?=$_SESSION['EmailAddress']?></b>.</p> <ul> <!-- link that runs logout.php script --> <li><a href="logout.php">Logout.</a></li> </ul> <?php } // check login form elseif(!empty($_POST['username']) && !empty($_POST['password'])) { // strip away malicious code $username = mysql_real_escape_string($_POST['username']); // encrypt password $password = md5(mysql_real_escape_string($_POST['password'])); // return all matches to username and password $checklogin = mysql_query("SELECT * FROM haas12_test.users WHERE Username = '".$username."' AND Password = '".$password."'"); // if there is a match if(mysql_num_rows($checklogin) == 1) { // store the row returned from query $row = mysql_fetch_array($checklogin); // get email address from row returned $email = $row['EmailAddress']; // store user variables in session array $_SESSION['Username'] = $username; $_SESSION['EmailAddress'] = $email; $_SESSION['LoggedIn'] = 1; // boolean echo "<h1>Success</h1>"; echo "<p>We are now redirecting you to the member area.</p>"; echo "<meta http-equiv='refresh' content='=2;index.php' />"; } // if there information entered could not be found else { echo "<h1>Error</h1>"; echo "<p>Sorry, your account could not be found. Please <a href=\"index.php\">click here to try again</a>.</p>"; } } // display login form with link to register form else { ?> <h1>Member Login</h1> <p>Thanks for visiting! Please either login below, or <a href="register.php">click here to register</a>.</p> <form method="post" action="index.php" name="loginform" id="loginform"> <fieldset> <label for="username">Username:</label><input type="text" name="username" id="username" /><br /> <label for="password">Password:</label><input type="password" name="password" id="password" /><br /> <input type="submit" name="login" id="login" value="Login" /> </fieldset> </form> <?php } ?> </div> </body> </html> After I submit form data how can I force the page to refresh so I can see the changes take effect? I know this is probably a very basic question. I have a php page that is maid up of three pieces. header.php main.php footer.php I can't figure out how to refresh the header.php and footer.php without refreshing the main.php. Anyone have an example of how I can do this. Thanks hits I've been doing some searching, but I can't figure this out, as I don't know enough about JS.
I have found a tutorial that does this
<HTML> <HEAD> <TITLE>Crunchify - Refresh Div without Reloading Page</TITLE> <style type="text/css"> body { background-image: url('http://cdn3.crunchify.com/wp-content/uploads/2013/03/Crunchify.bg_.300.png'); } </style> <script type="text/javascript" src="http://code.jquery.com/jquery-1.10.1.min.js"></script> <script> $(document).ready( function() { setInterval(function() { var randomnumber = Math.floor(Math.random() * 100); $('#show').text( 'I am getting refreshed every 3 seconds..! Random Number ==> ' + randomnumber); }, 3000); }); </script> </HEAD> <BODY> <br> <br> <div id="show" align="center"></div> <div align="center"> <p> by <a href="http://crunchify.com">Crunchify.com</a> </p> </div> </BODY> </HTML>But I don't know what exactly I can remove, what needs to stay (as far as the js), and where exactly I insert my ad code that is in a <script> tag of its own... but that also has a <noscript> tag as a fallback. While I understand I need to change the refresh from 3 secs, can someone help me take out the example JS code, and tell me where I would put my JS ad code? And do I simply remove the <script tags from my ad code, when inserting it into an area that is already between <script> tags? Any help on this would be appreciated, thanks! |