PHP - Header And Session
Does starting a Session send data to the Header?
Debbie Similar TutorialsTrying to make it so people need a active session in order to access the page after the log in page and if they dont then it redirects them back to the log in page. My session works fine. I tested and made sure. it saves the user_id lets me display the page but how do I keep someone from simply going to the webpage with out loging in? Just a simple if statment checking if lastactive is empty or not? is that secure? Code: [Select] <?php include_once("connect.php"); if(isset($_SESSION['user_id'])) { // Login OK, update last active $sql = "UPDATE users SET lastactive=NOW() WHERE id='".mysql_real_escape_string($_SESSION['user_id'])."'"; mysql_query($sql); }else{ header("Location: index.php"); exit(); } ?> I have four session variables, two I am valueing using $_POST elements from a previous page's form, the other two I am valueing using items retrieved from a database. Here is the code - ---------------------------------------------------- <?php session_start(); $_SESSION['UserLastName'] = strtolower(trim($_POST['txtLastName'])); $_SESSION['BadgeID'] = trim($_POST['txtBadgeID']); //get list for supervisor drop down $q1 = sprintf("select * from emps where emp_last = '".$_SESSION['UserLastName']."' and emp_badge = '".$_SESSION['BadgeID']."'"); $rs_emp_info = hitMSSQL($q1,"intra_sql","employees","xxxx","xxxx",1); $_SESSION['SSN'] = $rs_emp_info->fields("emp_ssn"); $_SESSION['CostCenter'] = $rs_emp_info->fields("emp_costcenter"); if ($_POST['rdoAction'] == 0) { header("Location: http://webapps/injury/empForm.php"); } ?> ---------------------------- When I get to the next page, empForm.php, the Last name and badge ID session vars are populated but the SSN and Cost Center session vars are not. I have tried several things including putting an exit(); after my header statement and first putting the database items into plain old $vars and then trying to populate the session vars with the value of the regular $vars, but nothing seems to work. I have a session_start() at the top of all of my scripts. Any idea why I am losing these values? (and why this box that I am typing into on this site is bouncing around so badly that I can't see what I am typing here???) Hey guys, i always get the error: Warning: Cannot modify header information - headers already sent by (output started at /home/worldw44/public_html/Newsletter/Admin/Admin.php:1) in /home/worldw44/public_html/Newsletter/Admin/Admin.php on line 6 when im tyring to run: <?php if(isset($_SESSION['adminlogin'])) { $run=yes; } else { header( 'Location: http://www.worldwidelighthouses.com/Newsletter/Admin/Log-In.php'); }?> <!DOCTYPE HTML> <html lang="en-GB"> <head> <meta charset="utf-8"> <!--Search Engine Meta Tags--> <meta name="author" content="Worldwide Lighthouses"> <meta name="keywords" content="Lighthouses,Lightships,Trinity House,Fog Signals,Fog Horns,Fresnel"> <meta name="description" content="Worldwide Lighthouses is the number 1 source of information, pictures and videos on the Subject of Lighthouses and Lightships"> <!--Stylesheets/Javascript--> <link rel="stylesheet" href="../../Page-Layout.css" media="screen and (min-width: 481px)"> <link rel="stylesheet" href="../../Mobile-Page-Layout.css" media="only screen and (max-width:480px)"> <!--Mobile Browser Support--> <meta name="viewport" content="width=320; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;"> <!--IE Support--> <!--[if lt IE 9]><script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script> <link rel="stylesheet" href="../Page-Layout.css"><![endif]--> <meta name="application-name" content="Worldwide Lighthouses"> <meta name="msapplication-starturl" content="http://worldwidelighthouses.com/"> <meta name="msapplication-tooltip" content="Worldwide Lighthouses: Your number one source of Lighthouse Information, Videos and Pictures"> <meta name="msapplication-task" content="name=Lighthouses;action-uri=http://worldwidelighthouses.com/Lighthouses.php;icon-uri=http://worldwidelighthouses.com/IE9/Lighthouses.ico"> <meta name="msapplication-task" content="name=Lightships;action-uri=http://worldwidelighthouses.com/Lightships.php;icon-uri=http://worldwidelighthouses.com/IE9/Lightships.ico"> <meta name="msapplication-task" content="name=Fog Signals;action-uri=http://worldwidelighthouses.com/Fog-Signals.php;icon-uri=http://worldwidelighthouses.com/IE9/Fog-Signals.ico"> <meta name="msapplication-task" content="name=Glossary;action-uri=http://worldwidelighthouses.com/Glossary.php;icon-uri=http://worldwidelighthouses.com/IE9/Glossary.ico"> <title>Mailing List Administration | Worldwide Lighthouses</title> </head> <body> <header> <h1 id="WWLH">Worldwide Lighthouses</h1> <form method="get" action="http://www.worldwidelighthouses.com/Search/search.php" id="Search-Box"> <input type="search" placeholder="Search Worldwide Lighthouses" name="query" id="query" size="30" value="" autocomplete="off"> <input type="submit" value="Search"> <input type="hidden" name="search" value="1"> </form> </header> <nav> <ul id="Nav"> <li class="MenuButton" id="Index"><a href="../Index.php"><p class="Nav">Home</p></a></li> <li class="MenuButton" id="Lighthouses"><a href="../Lighthouses.php"><p class="Nav">Lighthouses</p></a></li> <li class="MenuButton" id="Lightships"><a href="../Lightships.php"><p class="Nav">Lightships</p></a></li> <li class="MenuButton" id="FogSignals"><a href="../Fog-Signals.php"><p class="Nav">Fog Signals</p></a></li> <li class="MenuButton" id="Daymarks"><a href="../Daymarks.php"><p class="Nav">Daymarks</p></a></li> <li class="MenuButton" id="Buoys"><a href="../Buoys.php"><p class="Nav">Buoys</p></a></li> <li id="MenuButtonLast"><a href="../Glossary.php"><p class="Nav">Glossary</p></a></li> </ul> </nav> <article> <h1 class="Title">Contact Admin Centre</h1> <div class="Textbox"> <div id="Social"> <a href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal" data-via="WWlighthouses">Tweet</a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script> <object id="Facebook" data="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fworldwidelighthouses.com/&layout=button_count&show_faces=false&width=450&action=like&colorscheme=light&height=21"></object> </div> </div> </article> <footer> <ul> <li><a href="../About.php">About</a></li> <li><a href="../Contact-us.php">Contact</a></li> <li><a href="../Use-Our-Media.php">Use our media</a></li> <li><a href="../Search/search.php">Search</a></li> <li><a href="../Social-Networking.php">Social</a></li> <li><a href="#Top">Back to top</a></li> </ul> <br> <br> &#169; Worldwide Lighthouses <?php echo date("Y"); ?> </footer> </body> Cany anyone offer some suggestions as to why? Note i have no ability to change phpconfig. I have several pages on my site using the exact same code at the very top, which works fine except for one page: <?php include_once("../members/dbinfo.php"); The top of dbinfo looks like this: <?php session_start(); And then the connection strings for the database However it is giving me this error on this one page: Quote Warning: session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at C:\Inetpub\WebSites\premierathome_com\products\FrenchTalkingDictionary.php:1) in C:\Inetpub\WebSites\premierathome_com\members\dbinfo.php on line 1 Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at C:\Inetpub\WebSites\premierathome_com\products\FrenchTalkingDictionary.php:1) in C:\Inetpub\WebSites\premierathome_com\members\dbinfo.php on line 1 Now the session does actually start and doesn't prevent anything from working, I just get those messages. I'm at a loss as to why a different page with the exact same code, save for searching the database for a different product version would have this problem. I have had this code in place as well which works fine on other pages but doesn't help my problem at all: if(!isset($_SESSION['OK'])){ session_start(); } OK being a variable I set up during log in. I'm at a loss, is anyone able to help me out with this? Hi Everyone I am having a few issues with my website. I have developed in on my xampp local host and it works ok but when I upload the files and try to renew a membership using stripe I get the following messages. Warning: session_start(): Cannot start session when headers already sent in /customers/a/d/f/mywebsite.co.uk/httpd.www/mywebsite/inc/settings.php on line 2 Warning: Cannot modify header information - headers already sent by (output started at /customers/a/d/f/mywebsite.co.uk/httpd.www/mywebsite/procedures/payments/charge.php:1) in /customers/a/d/f/mywebsite.co.uk/httpd.www/mywebsite/procedures/payments/charge.php on line 141 I have some includes that appear on every page. This is the bootstrap.php file. This file holds the settings.php which connects to my database and other function files. In this settings page I call the session_start() php function and then connect to my database. I call the bootstrap.php file on every page to there for call the session_start() on every page. I am using sessions alot so is this the right thing to do? I have attached the renew_membership payment page which holds the form. The user fills out the payment page and the form data gets sent to a script called charge.php which uses the stripe objects to make the payment. I then want to do a redirect to the paymentSuccess.php page to output to the user that the payment was made successfully. This is where the issues arrise. I have split the charge file into 3 screen shots so it is more readable. Hope someone can help me. Thanks a lot David
Edited April 26 by Irish_Dave 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! 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;?> Hello everyone, I'm just starting out with PHP as I need to create an online bookstore for a school project. I'm working by a magazine which should teach you exactly how to do this using PHP, but I've had a bunch of problems with the code they use and I don't really know what's going on. Anyway, this looks really simple and basically what it does is allows you to post a comment on a book, then returns you to the book's page. Problem is, I'm getting the Header may not contain more than a single header, new line detected. error and I can't figure out why. I've tried researching into the matter but all the cases I found had to do with returning to an url, which is not my case. Anyway, here's the snippet of code: The form: Code: [Select] <div style="width:400px; border:1px solid #ffffff; background-color:#F9F1E7; padding:5px"> <b>Adauga opinia ta:</b> <hr size="1"> <form action="adauga_comentariu.php" method="POST"> Nume: <input type="text" name="nume_utilizator"><br><br> Email: <input type="text" name="adresa_email"><br><br> Comentariu: <br> <textarea name="comentariu" cols="45"></textarea><br><br> <input type="hidden" name="id_carte" value="<?=id_carte?>"> <center><input type="submit" value="Adauga"</center> </form> </div> The script adaugare_comentariu.php: Code: [Select] <?php ob_start(); include("conectare.php"); $numeFaraTags=strip_tags($_POST['nume_utilizator']); $emailFaraTags=strip_tags($_POST['adresa_email']); $comentariuFaraTags=strip_tags($_POST['comentariu']); $sql="insert into comentarii (id_carte, nume_utilizator, adresa_email, comentariu) values(".$_POST['id_carte'].", '".$numeFaraTags."','".$emailFaraTags."','".$comentariuFaraTags."')"; mysql_query($sql); $inapoi="carte.php?id_carte=".$_POST['id_carte']; header("location:urldecode($inapoi)"); ob_end_flush(); ?> conectare.php connects to the mysql database. $inapoi is the variable which returns the user to carte.php (the book he posted a comment on), where id_carte is the book's unique id. I'm getting Header may not contain more than a single header, new line detected on line ten, which is the header line. Can anyone help me? I've been stumped on this for a few days now and I've just let it pass and started working on other bits, but it's bugging me too much and I'd like to fix it. This topic has been moved to PHP Applications. http://www.phpfreaks.com/forums/index.php?topic=350027.0 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> 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. 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. 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. Can some one help please i always get this wrong dont now why keep saying header already been sent any help please and how to fix it Code: [Select] <?php session_start(); $conn = mysql_connect(""); $db = mysql_select_db("", $conn); if(isset($_POST['submit'])){ $user = mysql_escape_string($_POST['user']); $pass = mysql_escape_string($_POST['pass']); } if(empty($user) && empty($pass)){ exit; }else{ } ?> <?php $sql = mysql_query("SELECT * FROM useradmin WHERE dbusername= '".$user."' AND dbuserpass= '".$pass."'")or die(mysql_error()); $row = mysql_fetch_assoc($sql); $count = count($sql); $u = $row['dbusername']; $p = $row['dbuserpass']; if($u == $user && $p == $pass){ $_SESSION['access'] = "$u"; header("location: index.php"); }else { echo "Sorry there as been a problem!"; exit; } ?> Hi is there a way that i can set header not go anywhere like the problem with this is that it still goes to the second header is there a way i can set if none do nothing exit? and else do the second header?? Code: [Select] <?php if ($_POST['agents']=="none") { header("location:#"); exit; // header("Location: {$_SERVER['PHP_SELF']}"); } else { header("location:http://www.xxxxxx.co.uk/tv/".$_POST['agents']."/index.php"); } ?> Hi there, I have a form which displays a "successful" message if the form is completed correctly. However, I want the form to go to another url if it is successful. I have tried this, but I get the "headers already sent..." message // Add New Subscriber Success Message $successMsg = header('Location: http://www.example.com/'); is there another way to forward onto another page? Thanks Hi everyone, I have a login area, and i also have set up for me is a view page... the view page is each user's sort of profile, it gets id and displays relevant content. i was wondering if i could get the id or post rather through a re-direct on log in? for example user logs in with username and password, user is re-directed to the view page like this: header( "refresh:5;url=view00=id.php " ); echo '<h1>You will be re-directed in 5 seconds...</h1>'; user is taken to view page where they can edit bit on it. So far though i'm getting page not found error? first of all is this possible? if not whats the correct way/better way? Thanks How do I get this to put in the pilotID? Code: [Select] header("Location: logbook.php?id=" . $pilotid); Thanks! Hey guys, I have a problem, i'm using ob_start to send multiples headers and it works but the problem is that my metada is not being sent, when i remove the ob_start it gets sent. Is there a way i can allow more info to be sent with ob_start? or should i use other methods to redirect to pages? i dont want to use javascript or meta http because they are not very reliable is there any other way? Thanks for help. |