PHP - Php Session Duplication
I've recently had a problem with my admin site where PHP sessions, which are stored in a MySQL database, are duplicating and causing the page to return to the login screen. Usually the site works fine in Firefox, but stops working in IE and Safari. This problem suddenly appeared over night with no change to the files.
Due to the amount of code, I'm reluctant to post it all, but does anyone have a suggestion on why this could be happening and how to solve it? Similar TutorialsAs part of an image gallery I am trying to INSERT data into a table to make accessible the relevant info of individual images - the problem I have encountered is that each query seems to be being inserted twice, and I can't figure out why. The code = Code: [Select] <?php /*============================================== Connect to MySQL and select the correct database ==============================================*/ mysql_connect("localhost", "uname", "pwd") or die(mysql_error()); echo "Connected to MySQL<br />"; mysql_select_db("gallery_db") or die(mysql_error()); echo "Connected to Database gallery_db.<br />"; /*============================================= Include the files needed to undertake this task =============================================*/ include("functions.php"); /*========================= Set up arrays and variables =========================*/ $store = array(); $exif = array(); $folder = "./images/"; $insrt = 'INSERT INTO images VALUES (img_id, '; $file_name = ''; $file_location =''; $copyright =''; $caption = ''; $file_date = ''; $file_time = ''; $camera = ''; $speed = ''; $fNo = ''; $ISO = ''; /*================================= Open folder and read relevant files =================================*/ if ($handle = opendir('./images')) { while (false !== ($file = readdir($handle))) { if ($file != "." && $file != "..") { $file_name = $file; //>>> File Name <<< $file_location = $folder . $file; //>>> File Location <<< $exif = exif_read_data($file_location, 'EXIF'); //>>> Read exif data <<< /*============================================================== Check if the 'Copyright' info existe in the exif data, and if it doesn't set the $copyright variable to the relevant value. ==============================================================*/ if (array_key_exists('Copyright', $exif)) { $copyright = $exif['Copyright']; } else { $copyright = "copy name"; } $caption = $exif['COMMENT'][0]; //>>> Get the Caption <<< //>>> Re-format DateTime into separate date and time var's $file_date & $file_time <<< $temp = substr($exif['DateTime'], 0, 10); $file_date = substr($temp, 8, 2) . substr($temp, 4, 4) . substr($temp, 0, 4); $file_time = substr($exif['DateTime'], 11, 8); //>>> Set the rest of the variables <<< $camera = $exif['Model']; //>>> Get the camera make and model <<< $speed = $exif['ExposureTime']; //>>> Get the shutter speed <<< $fNo = $exif['COMPUTED']['ApertureFNumber']; //>>> Get the f No. <<< $ISO = $exif['ISOSpeedRatings']; //>>> Get the ISO rating <<< //>>> Fill the $store[] array with the relevant bits for each seperate query <<< $store[] = $insrt . "'" . $file_name . "', " . "'" . $file_location . "', " . "'" . $copyright . "', " . "'" . $caption . "', " . "'" . $file_date . "', " . "'" . $file_time . "', " . "'" . $camera . "', " . "'" . $speed . "', " . "'" . $fNo . "', " . "'" . $ISO . "')"; } } closedir($handle); } /*============================================================================= Get individual queries from $store[] and INSERT INTO images the relevant VALUES =============================================================================*/ $num_queries = count($store); //>>> Check the number of queries in the array $store $loop = 0; //>>> Starting point for query No. bearing in mind that array keys are numbered from zero while ($loop <= $num_queries - 1) { $query = $store[$loop]; if (!mysql_query($query)){ die('Error: ' . mysql_error()); } mysql_query($query); $loop++; } ?> I know it's not pretty, but that can be attended to once working properly. I am quite sure that it will be a very simple solution, probably so simple that I haven't even thought of it. Hi
I am reading in data from a csv file
if (($handle = fopen("data.csv", "r")) !== FALSE) { while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { echo "User Name: $data[0]"; echo "Booking IDs: $data[1]"; } echo "<hr>";The problem is some of the usernames are duplicated so get outputted the same user name 20 times but with different IDs, obviously but I am unsure how to group them together. I can't seem to figure out how to write if the next username is the same as current then just add another ID not go through the entire loop. Any ideas? Thanks Hello there, I'm looking for a PHP method to duplicate a line, for example if I wanted to duplicate this line: mail($to,$subject,$message,$headers); How could I specify a value of how many are displayed instead of doing this to send it 3 times: mail($to,$subject,$message,$headers); mail($to,$subject,$message,$headers); mail($to,$subject,$message,$headers); Many thanks <?php // Daniel URL duplicator. // Input links list. $linksList = "links.txt"; // How many times to duplicate the url? $manyTimes = 1000; // Read in the list. for ($x = 0; $x <= $manyTimes; $x++) { $handle = fopen($linksList, "r"); $line = fgets($handle); echo $line; fclose($handle); } ?>Hey Guys, I'm stuck on this simple bit of code lol what I'm trying to do is load in a list of urls: site1.com site2.com site3.com etc For each site that is read, I'm trying to duplicate it X times, above would print to screen the same url 1000 times, then move onto the next print it 1000 times etc until the list is done (or how ever many times I select) I can't think of the best way to do it! any help would be appreciated guys! Graham Hi everyone, I don't know whether this is a PHP or MySql problem, but I think it is the former. The following code queries the database correctly, (and before you ask, there are no duplicate database entries), but the output duplicates every row. e.g., hammer (jpg image) hammer hammer (jpg image) hammer saw (jpg image) saw saw (jpg image) saw screwdriver (jpg image) screwdriver screwdriver (jpg image) screwdriver and so on. I cannot see why the code causes the row to repeat. Code: [Select] <?php session_start(); if (isset($_SESSION['id'])) { // Put stored session variables into local php variable $id = $_SESSION['id']; $userId = $_SESSION['userId']; $userGroup = $_SESSION['userGroup']; $managerId = $_SESSION['managerId']; } include_once("demo_conn.php"); $sql = mysql_query("SELECT * FROM users WHERE id='$id'"); while($row = mysql_fetch_array($sql)) { // Get member data into a session variable $egroup = $row["egroup"]; session_register('egroup'); $_SESSION['egroup'] = $egroup; } $query = mysql_query("SELECT topics.url_big, topics.url_small, topics.title, topics.$egroup, quiz.passState, quiz.userDate FROM topics INNER JOIN quiz ON (topics.managerId = quiz.managerId) WHERE topics.$egroup = 1 ORDER BY title ASC"); while ($row1 = mysql_fetch_array($query)) { echo "<a href='../../wood/wood_tool_images/{$row1['url_big']}' target='_blank'><img src='../../wood/wood_tool_images/{$row1['url_small']}' /><br />\n"; echo "{$row1['title']} <br />\n"; } ?> Hi I have this simple code $one = rand(1,9); $two = rand(1,9); $three = rand(1,9); but I need to change it so that they are all unique and the same number is not used more than once can anyone help? thanks Please help and amend the code Save without repetition required $read[0] I hope that my example is clear to you I apologize for bothering you. I am not good in English <?php $fileLocation = getenv("DOCUMENT_ROOT") . "/rt.txt"; $file = fopen($fileLocation,"a"); $n1 = $_POST['n1']; $n2 = $_POST['n2']; for($i = 0; $i < count($file); $i++){ $read = explode("|", $file[$i]); if($n1 == $read[0]){ echo 'Repetition'; } else { fwrite($file,$n1.'|'.$n2."\r\n"); }
in this page http://maximaart.com/newscp/ i have this problem Code: [Select] Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /home/maximasy/public_html/newscp/index.php:1) in /home/maximasy/public_html/newscp/index.php on line 2 my source code is <?php session_start(); include_once("config.php"); include_once("functions.php"); $errorMessage = ''; if (isset($_POST['txtUserId']) && isset($_POST['txtPassword'])) { if ($_POST['txtUserId'] === "$user" && $_POST['txtPassword'] === "$pass") { // the user id and password match, $_SESSION['basic_is_logged_in'] = true; require("main.php"); exit;?> I am trying to create an index page which contains registration and login field the problem that i get is on successful login a warning is displayed session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at C:\xampp\htdocs\Eventz.com\index.php:116) in C:\xampp\htdocs\Eventz.com\index.php on line 235 This is the login part of my index.php this tag is inside an html table below the login form I also have a registration form and its php code above the login form Code: [Select] <?php if (isset($_REQUEST['pass'])) { $id=$_POST['id']; $pass=$_POST['pass']; $conn =mysql_connect("localhost","root",""); if (!$conn) { die('Could not connect: ' . mysql_error()); } /* checking connection....success! */ $e=mysql_select_db('test', $conn); if(!$e) { die(''.mysql_error()); } else { echo 'database selected successfully'; } if (isset($_REQUEST['id']) || (isset($_REQUEST['pass']))) { if($_REQUEST['id'] == "" || $_REQUEST['pass']=="") { echo "login fields cannot be empty"; } else { $sql=mysql_query("Select email,password from login where email='$id' AND password='$pass'"); $count=mysql_num_rows($sql); if($count==1) /* $count checks if username and password are in same row */ { session_start(); $_SESSION['id']=$id; echo "</br>Login Successful</br>"; } else { echo "</br>invalid</br>"; echo "please try to login again</br>"; } } } } ?> Any help or suggestion would be appreciated I am having trouble resolving an error. Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /home/s519970/public_html/header.php:27) in /home/s519970/public_html/admin/login.php on line 2 What I can gather is I can't use "header (Location: 'admin.php')" after i've used session_start(). I have tried to replace the header (Location: 'admin.php') with this: echo "<script>document.location.href='admin.php'</script>"; echo "<script>'Content-type: application/octet-stream'</script>"; I've been trying to read up on solutions but haven't been able to get it sorted. If anyone can offer some advice that would be greatly appreciated as im new to php. Code: [Select] <?php session_start(); if(isset($_SESSION['user'])) echo "<script>document.location.href='admin.php'</script>"; echo "<script>'Content-type: application/octet-stream'</script>"; ?> <div id="loginform"> <form action="dologin.php" method="post"> <table> <tr> <td><span>Username:</span></td> <td><input type="text" name="username" /></td> </tr> <tr> <td><span>Password:</span></td> <td><input type="password" name="password" /></td> </tr> <tr> <td colspan="2" align="right"><input type="submit" name="login" value="Login" /></td> </tr> </table> </form> </div> I have tried using require_once('yourpage.php'); before my <head></head> tags in the header document where I've specified the html information but this doesn't seem to work. I've been advised to use ob_start("ob_gzhandler"); but I am not sure how to implement this. Any advice is greatly appreciated! I'm making a simple login system with MySQL and PHP (very simple, I'm just starting with PHP). The MySQL portion is done, but I need to ensure only people who are logged in can see certain content. To check if people are logged in, my website checks that they have the $_SESSION['user'] variable set. If it is set, then it lets them continue through the website, if not, it tells them to login. Is that enough security, or can people simply inject a session cookie into their browser to spoof that they are logged in? My idea was to generate a session key cookie when they login (just a random string of letters and numbers) and store that in the database, then on every page, check to make sure their session key is the same thing that's in the database. Is this necessary? It seems expensive. hi everyone. i'm wondering what the best way is to create a session variable and pass it to an iframe. i need to do something along these lines, but it doesn't seem to pass the ID. Any hints on how i should accomplish this? Code: [Select] session_start(); $_SESSION['ID']=$_GET['ID']; // id from previous page $ID=session_id(); <iframe src="iframepage.php?ID=<?php echo $ID; ?>" style="width:680px; height:200px;" noresize="noresize" frameborder="0" border="0" scrolling="Yes" allowtransparency="true" /> </iframe> Just curious how other people feel about this. I am working on an application where a lot of info is pulled from MySQL and needed on multiple pages.
Would it make more sense to...
1. Pull all data ONCE and store it in SESSION variables to use on other pages
2. Pull the data from the database on each new page that needs it
I assume the preferred method is #1, but maybe there is some downside to using SESSION variables "too much"?
Side question that's kind of related: As far as URLs, is it preferable to have data stored in them (i.e. domain.com/somepage.php?somedata=something&otherdata=thisdata) or use SESSION variables to store that data so the URLs can stay general/clean (i.e. domain.com/somepage.php)?
Both are probably loaded questions but any possible insight would be appreciated.
Thanks!
Greg
Edited by galvin, 04 November 2014 - 10:30 AM. Evening! I've been iffing and ahhing over this and well im not too sure, hence the post. Code: [Select] // Redirects if there is no session id selected and echos the error on the previous page if(!isset($_GET['get']) || ($_GET['getget'])){ header("Location: #.php?error"); } So it should simply check if get is set if it isnt then see if getget is set? If not redirect and show the error. Now ive tried it and even when get/getget is set it still redirects, probably something silly. Care to share anyone? Harry. Hello, I am interested in how the php can recognise a certain session when everytime i start session new id is created. For example i made this small script: session_start(); if( isset( $_SESSION['test'] ) ) { echo "test is set"; } else { $_SESSION['test'] = 'test'; echo "test is not set"; } My browser is closed. All files from /tmp folder where php default sessions files are stored in wamp are deleted. So i start the browser and it of course echoes "test is not set", then i check the folder and new session file is created. I then refresh the page and it normally echoes "test is set" but no new session files are created in /tmp folder. So now i close the browser and start it again. New file is created in /tmp although i used same browser. Now this new file has a different name than one previously created. So this time again it says "test it not set" and when i refresh the page it says "test is set" so my question is what logic is used by php to determine from which session file in /tmp folder to load session on page refresh when it creates a new id every time session is started ( browser opened ) even though the browser and ip are same. Thanks Firstly, I am new to the forum, so hello I am trying to code a login script for my website. I have got the login to work but how do I get it to create a session so the user stays logged in until they log out? Also how can I prevent access to success.php and fail.php so they cannot be accessed directly. I am new to PHP so please explain in detail for me. Here is my code... Code: [Select] <?php ob_start(); $host=""; // Host name $username=""; // Mysql username $password=""; // Mysql password $db_name=""; // Database name $tbl_name=""; // Table name mysql_connect("$host", "$username", "$password")or die("cannot connect"); mysql_select_db("$db_name")or die("cannot select DB"); $myusername=$_POST['myusername']; $mypassword=$_POST['mypassword']; $mypassword=md5($mypassword); $myusername = stripslashes($myusername); $mypassword = stripslashes($mypassword); $myusername = mysql_real_escape_string($myusername); $mypassword = mysql_real_escape_string($mypassword); $sql="SELECT * FROM $tbl_name WHERE email='$myusername' and password='$mypassword'"; $result=mysql_query($sql); $count=mysql_num_rows($result); if($count==1){ session_register("myusername"); session_register("mypassword"); header("location:success.php"); } else { header("location:fail.php"); } ob_end_flush(); ?> I am building an app (PHP and MySQL)and I had been using a lot of GET calls to get info from URLs, but the more I thought about it, the more I didn't like the possibility of people being able to mess with the URLs. So I am in the process of changing everything to use SESSION variables to store data across pages, rather than GET. The way I see it, SESSION variables are completely behind the scenes so they seem to be the better option. Am I right, or is GET better than SESSION for some reason? This is weird. I thought session_destroy erased your session id: echo "session is ".session_id(); session_destroy(); echo "<br>session now is ".session_id(); When I run it i get: Code: [Select] session is mkqb0m49ktbtt1g34r6e67g012 session now is But when I reload the page I get the same thing! Code: [Select] session is mkqb0m49ktbtt1g34r6e67g012 session now is If session_id was destroyed (it echoed blank to prove this) why does it get repopultaed with the same session id when I reload the browser? giving me Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING in /home/enriquec/public_html/admincenter.php on line 6 this is my code Code: [Select] <?php require "header.php";?> <?php if ($_SESSION['username']) echo "Welcome, "."$_SESSION['username']."; else die("You must be logged in!"); ?> <?php require "footer.php":?> Hello I keep having this issue with sessions. I have an login feature on my website that uses sessions. When i do like this: 1. Login 2. close browser 3. open browser again 4. try to log in It fails, actually nothing happens, so I manually need to go to logout.php to reset and then I can log in again. Why is this happening and how do i solve it? |