PHP - Cannot Send Session Cookie - Headers Already Sent
I am confused why I am getting the following error and was wondering if I could get a 2nd pair of eyes..
error: [29-Jul-2010 20:58:01] PHP Warning: session_start() [<a href='function.session-start'>function.session-start</a>]: Cannot send session cookie - headers already sent in /home/curren11/public_html/mysite***.com/file_monitor.php on line 2 [29-Jul-2010 20:58:01] PHP Warning: session_start() [<a href='function.session-start'>function.session-start</a>]: Cannot send session cache limiter - headers already sent (output started at /home/curren11/public_html/mysite***.com/file_monitor.php:2) in /home/curren11/public_html/mysite***.com/file_monitor.php on line 2 Here is the code: <?php session_start(); $root_path = realpath(getcwd()); $error_monitor_file = $root_path.'/file_modify.txt'; $hour = date("H"); $today = date("m-d-Y"); $myFile2 = "file_monitor.php.log"; $fh3 = fopen($myFile2, 'a'); $log_msg = "Last ran on: ".$today." at: ".$hour." \n"; fwrite($fh3, $log_msg); function scan_dir($path) { $out = array(); $files = opendir($path); while ($f = readdir($files)) { $extension = substr($f,-3); if ($f=='.' or $f=='..' or $extension=='jpg' or $extension=='JPG' or $extension=='png' or $extension=='gif' or $f=='file_monitor.php' or $f=='file_modify.txt' or $f=='file_monitor.php.log' or $f =='error_log' ) { continue; } if (is_dir($path.'/'.$f)) { $out = array_merge($out, scan_dir($path.'/'.$f)); } //if (((!is_dir($path.'/'.$f)) && ($f!='.' or $f!='..' or $extension!='jpg' or $extension!='JPG' or $extension!='png' or $extension!='gif')) else // { $out[] = $path. '/'. $f; //} } $_SESSION['all_files'] = $out; return $out; } $a = scan_dir(getcwd()); $count_array = count($_SESSION['all_files']); $loop_count=0; while($loop_count < $count_array) { // file in directory when was it last changed ? $filechange1 = date("m-d-Y-H", filemtime($_SESSION['all_files'][$loop_count])); // was it chnaged today and have I sent out an alert yet? if($filechange1 == $today."-".$hour) { $fh2 = fopen($error_monitor_file, 'a'); fwrite($fh2, "\n alert, file: ".$_SESSION['all_files'][$loop_count]." was changed today within the last hour ! \n"); fclose($fh2); } $loop_count ++; // log file? was it changed this past hour? if (file_exists($error_monitor_file)) { $filechange_log = date("m-d-Y-H", filemtime($error_monitor_file)); if ( ($loop_count == $count_array ) && ($filechange_log == $today."-".$hour ) ) { email(); } } } // function for email... function email() { require_once ('class.phpmailer.php'); $mail = new PHPMailer(); $mail->IsSMTP(); // send via SMTP $mail->Host = "localhost"; // SMTP servers $mail->SMTPAuth = true; // turn on SMTP authentication $mail->Username = "**c66@***ar.com"; // SMTP username $mail->Password = "*****"; // SMTP password $mail->From = "***@***.com"; $mail->FromName = "Colonial Cottage File Changed"; $mail->AddAddress("email@*****.com"); $mail->WordWrap = 50; // set word wrap //$mail->AddAttachment("/var/tmp/file.tar.gz"); // attachment //$mail->AddAttachment("/tmp/image.jpg", "new.jpg"); $mail->IsHTML(true); // send as HTML $mail->Subject ="Unauthorized file changed today!"; $mail->Body = "" ; $mail->AltBody = "This is the text-only body"; if(!$mail->Send()) { exit(); } } if ((file_exists($error_monitor_file)) && $hour == "00") { unlink($error_monitor_file); } fclose($fh3); exit(); ?> Similar TutorialsI 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 Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /home/hedgehog/public_html/class/class.phpmailer.php:3005) in /home/hedgehog/public_html/admin/class/authenticate.class.php on line 15 I own a website, www.gpstudios.com Some time ago I started recieiving this error after posting comments on the playgame page/news page. Try posting comments yourself on this game: http://www.gpstudios.com/playgame.php?gameid=324 I have attached a picture of the error. Unfortunately, I have no idea when this bug appeared. It must have happened a while ago, but I never noticed. Anyone know how or why I am getting this bug? Because I'm unsure as to where/when the error occurred, I cannot supply the code. Sorry for the lack of details, but I'm hoping someone will understand this error a little better than me :S Thanks, -Tom Hi, I am just recently getting this error message:Warning: session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at /home/XXX/chordsandguitar.com/index.php:46) in /home/jchords/chordsandguitar.com/index.php on line 48 this is no doubt related to the fact that my site has been hacked along with 1000's of others that are on dreamhost. I don't know if it's related to php file permissions some of my files may have had had their permission set for read-write when they should not have been. They have all been changed to the more restrictive 755 or 644. So here is how I am using the session_start to store some variables: Code: [Select] session_start(); if (!isset($_SESSION["count"])) { $_SESSION["count"]=0; } else $_SESSION["count"]++; if ($_SESSION["count"] == 0) { $scale_menu = 'C'; $variation_menu = 'maj'; $code_id = '1'; } else { //allows retreiving the value of the drop-downs after the Select button has been pushed // has to be skipped on the first access or overwrites starting vars. to null if (isset($_GET['s_menu'])) $scale_menu = $_GET['s_menu']; else $scale_menu = $_GET['scale_menu']; } So any ideas why I am getting this error? Thanks, Jacques Warning: session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at /home/bakerde1/public_html/oceangamer.com/login.php:1) in /home/bakerde1/public_html/oceangamer.com/login.php on line 2 Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /home/bakerde1/public_html/oceangamer.com/login.php:1) in /home/bakerde1/public_html/oceangamer.com/login.php on line 2 These are my error messages, here is my code. I don't know if it is the UTF-8 code at the start, but if it is can anyone recommend a binary editor to remove this. If it isn't what is the problem? <?php session_start(); $username = $_POST['username']; $password = base64_decode($_POST['password']); $errors = array(); if($username == 'User Name' || $username == ''){ $errors[] = 'Please enter a valid username'; } if($password == 'Password' || $password == ''){ $errors[] = 'Please enter a valid password'; } $link = mysql_connect("localhost","*****","******") or die ("Could not connect!"); mysql_select_db("chef"); $query = mysql_query("SELECT * FROM `users` WHERE `username`='$username'"); $numrows = mysql_num_rows($query); if ($numrows!=0) { while($row = mysql_fetch_assoc($query)) { $dbusername = $row['username']; $dbpassword = $row['password']; } if ($username==$dbusername&&$password==$dbpassword) { $_SESSION['user'] = $username; while ($row = mysql_fetch_array($res)) { $type = $row['Type']; } if ($type == "0") { header("location: chefpanel.php"); }else{ header("location: restpanel.php"); } } else $errors[] = 'Username or Password Incorrect'; } else $errors[] = 'Username or Password Incorrect'; ?> <html xmlns="http://www.w3.org/1999/xhtml"> <head> 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;?> Hi Chaps, I'm working on a PHP script to mysqldump database to file. Using this as a base: http://www.edmondscommerce.co.uk/mysql/php-mysql-dump-script/, I've managed to strip it down to this: Code: [Select] set_time_limit(0); $mysql_host='localhost'; $mysql_database='database'; $mysql_username='username'; $mysql_password='pasword'; _mysql_test($mysql_host,$mysql_database, $mysql_username, $mysql_password); $print_form = 0; header('Content-type: text/plain'); header('Content-Disposition: attachment; filename="'.$mysql_database."_".date('Y-m-d').'.sql"'); $filename = $mysql_database."_".date('Y-m-d').'.sql'; _mysqldump($mysql_database); function _mysqldump($mysql_database) { $sql="show tables;"; $result= mysql_query($sql); if( $result) { while( $row= mysql_fetch_row($result)) { _mysqldump_table_structure($row[0]); _mysqldump_table_data($row[0]); } } else { echo "/* no tables in $mysql_database */\n"; } mysql_free_result($result); } function _mysqldump_table_structure($table) { echo "/* Table structure for table `$table` */\n"; echo "DROP TABLE IF EXISTS `$table`;\n\n"; $sql="show create table `$table`; "; $result=mysql_query($sql); if( $result) { if($row= mysql_fetch_assoc($result)) { echo $row['Create Table'].";\n\n"; } } mysql_free_result($result); } function _mysqldump_table_data($table) { $sql="select * from `$table`;"; $result=mysql_query($sql); if( $result) { $num_rows= mysql_num_rows($result); $num_fields= mysql_num_fields($result); if( $num_rows> 0) { echo "/* dumping data for table `$table` */\n"; $field_type=array(); $i=0; while( $i <$num_fields) { $meta= mysql_fetch_field($result, $i); array_push($field_type, $meta->type); $i++; } echo "insert into `$table` values\n"; $index=0; while( $row= mysql_fetch_row($result)) { echo "("; for( $i=0; $i <$num_fields; $i++) { if( is_null( $row[$i])) echo "null"; else { switch( $field_type[$i]) { case 'int': echo $row[$i]; break; case 'string': case 'blob' : default: echo "'".mysql_real_escape_string($row[$i])."'"; } } if( $i <$num_fields-1) echo ","; } echo ")"; if( $index <$num_rows-1) echo ","; else echo ";"; echo "\n"; $index++; } } } mysql_free_result($result); echo "\n"; } function _mysql_test($mysql_host,$mysql_database, $mysql_username, $mysql_password) { global $output_messages; $link = mysql_connect($mysql_host, $mysql_username, $mysql_password); if (!$link) { array_push($output_messages, 'Could not connect: ' . mysql_error()); } else { array_push ($output_messages,"Connected with MySQL server:$mysql_username@$mysql_host successfully"); $db_selected = mysql_select_db($mysql_database, $link); if (!$db_selected) { array_push ($output_messages,'Can\'t use $mysql_database : ' . mysql_error()); } else array_push ($output_messages,"Connected with MySQL database:$mysql_database successfully"); } } The problem is, I want the file to save to a specific network location, rather than the output being sent to headers. I've tried to play around with: Code: [Select] ob_start();.... $page = ob_get_contents(); ob_end_flush(); $fp = fopen("output.html","w"); fwrite($fp,$page); fclose($fp); But this outputs to the browser, then saves the file...I would like to load the page, and have the script create and save the file where I want it (without the output in the browser, or prompt to save/download file). Note: I need something like this as I'm running PHP/MySQL on IIS, so can use shell/system/etc. Any help will be hi-5-tastic! Quick question for you guys. I am collecting payment data for a product. Is it possible to send data from my form via http directly into another payment form via the post http headers? So say if i had all the details payment info and address info and i matched my form exactly to theirs. Is it possible to write a php script to send the data from my form directly to another websites form to make an order, say amazon or a big site like this? ?first_name=samuel&last_name=east&action=Submit Any Help? Thanks How do I send multiple headers with this code? Code: [Select] <?php $postdata = http_build_query( array( 'var1' => 'some content', 'var2' => 'doh' ) ); $opts = array('http' => array( 'method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $postdata ) ); $context = stream_context_create($opts); $result = file_get_contents('http://example.com/submit.php', false, $context); ?> *this header: Code: [Select] User-Agent: Mozilla/5.0 (iPhone; U; CPU iPhone OS 3_0 like Mac OS X; en-us) AppleWebKit/528.18 (KHTML, like Gecko) Version/4.0 Mobile/7A341 Safari/528.16 Simple question. How do I redirect the header location on a session page. I thought I could go a different direction, but now I'm back to this one. I tried just adding header("Location: newpage.php") at the end of a query insert, but it gave me the warning that it can't modify the head. But I need the page to redirect after the query is done. Thoughts?
I'm trying to start a session in a simple php file.
Here's *all* the code:
Here's the URL: Hi All, I have a secure website which always checks the cookies is not expired and the session id is set. When someone doesn't browse for the period of the cookie it will expire however the session id stays valid until he logout. A lot of people don't logout so the pages will still be accessable for them or others who use their pc. Is there a way to destroy the session id when the cookies expires? Marco hey guys im using a session cookie to store a user_id, only if user has clicked to remember me on the login form...that way when autenticating it checks id in db and if matching a user it logs in automatically.
now the problem i want to just remove user_id from a session cookie. if i use the code below to delete the user_id session then it will remove all session cookies.
is there a way just to remove 1 session cookie? thank you
// create session cookie session_start(); session_set_cookie_params('3600', 'C:\Users\Ricky\Desktop\www\BiSi\private\tmp\session', 'http://127.0.0.1/', true, true); ini_set('session.gc_probability', 1); session['user_id'] = 1; //delete session cookies setcookie (session_name(), null, time() - 3600); session_regenerate_id(true);any help/advise would be greatful...cheers guys I don't know why but I'm failing hard at GoogleFu today. I can't find a tutorial on how to store a session id in a cookie and then call it on the server. session_id says it replaces the cookie it makes if you set the id via session_id, even if it's the same id...but I'm not sure if that really matters. Can anyone help point me in the right direction to a good tutorial/give me some insight on this subject? I want to store the session id in a cookie to keep a user logged in for 2 weeks or so (unless they log out of course). I did find some tutorials on how to re-route the session handlers for open/close/read/write session functions which allow me to store the session in a database. Is this what I want? Sorry for the newbie question, Thanks, Justin Hi, I'd like to know the security of assuming session variables and using them for secure membership systems. Could a malicious user not create a session, then change the session username to another user and effectively login as that user? As I see it, no. Because session data is stored on the server and only a session id is stored on the client by way of a cookie. But what if we used cookies? What is the solution to this? Because I know I could easily change ANY variables within a cookie. I guess storing cookie data via db would help. But what is the best practice solution? I see a lot of code which simply checks for a cookie with the variable 'logged_in' to true. It then manages the user by username or userid which are stored within the cookie but which can be changed with ease by a malicious user. The default PHP Session name on my webspace server is PHPSESSID. Does that mean that the session cookie will be called PHPSESSID? The reason i ask is that in a couple of places i can't use PHP to update the information in the session cookie (because PHP is parsed before the webpage loads) and so i need to use Javascript to update a cookie which i would prefer to be the session cookie used by PHP. I guess i'm asking what the name of the cookie is, how i would refer to it in Javascript (if that is even possible) so that i can update it and whether this would cause any issues with the info already stored in the session cookie by PHP. Cheers NM hello all, I have a client that wants to protect their web page with a password protected landing page. Once the password is entered the user is directed to a "disclaimer" page that they have to agree to first before going into the site. I have put both the landing page and the disclaimer page in my root directory and then the site I put in a sub directory /cms/ in the main site index.php I check for the post password and then set a $_COOKIE for the user that will expire in 1 month <?php // this goes on the very top of the index.php file in the template you are using //check if user has entered password and needs cookie set if(isset($_POST['fpass']) && !isset($_COOKIE['fpass'])) setcookielive('fpass', $_POST['fpass'], strtotime( '+1 month' )); function setcookielive($name, $value='', $expire=0, $path='', $domain='', $secure=false, $httponly=false) { //set a cookie as usual, but ALSO add it to $_COOKIE so the current page load has access $_COOKIE[$name] = $value; return setcookie($name,$value,$expire,$path,$domain,$secure,$httponly); } The next thing I do is check if a user is trying to access the main site with having the COOKIE - if so I redirect the user to the landing page //check if user has not entered password if (!isset($_COOKIE['fpass']) || $_COOKIE['fpass'] == "") header('location: http://www.mypage.com'); This works fine up to this point. Now my problem is that I also need to check if a user has the month long cookie set but is trying to access the main page without viewing the disclaimer page first. I thought this would work: //check if the user has a cookie set but is on a new session if (isset($_COOKIE['fpass']) && !isset($_SESSION['fpass'])) header('location: http://www.mypage.com/disclaimer.php'); But this only throws the user into a loop of "disclaimer" -> "landing page" -> "disclaimer" etc. They can never get into the main site. How do I check for the cookie and whether the user has visited the disclaimer page - but then allow the user to continue once they go to the disclaimer page? NB: the $_SESSION is not set until the main site. Hi to everyone, I'm new to the forum and I'm posting here because I ended up in a logical problem for my next script development.
I need to get some data of external websites (with vbulletin board), perfectly legal.
Using file_get_contents i can print the page content on my server and then use jquery's powerful selectors to get my data.
The problem is that these data are shown only to logged in users so i would need this script (maybe using cURL?) to either login to the external website and then persists the connection or maybe if the user who is executing my script is already logged in that website then use his login? (most likely impossible I think..)
This is my code so far (found on some sites and merged into this)
$data = array('vb_login_username' => 'Scanu', 'vb_login_password' => 'grgfgrgrfbtgbt'); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "http://www.vbulletin.org/forum/login.php?do=login"); curl_setopt($ch, CURLOPT_AUTOREFERER, true); curl_setopt($ch, CURLOPT_COOKIESESSION, true); curl_setopt($ch, CURLOPT_FAILONERROR, false); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false); curl_setopt($ch, CURLOPT_FRESH_CONNECT, true); curl_setopt($ch, CURLOPT_HEADER, true); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); $result = curl_exec($ch); curl_close($ch); $pattern = "#Set-Cookie: (.*?; path=.*?;.*?)\n#"; preg_match_all($pattern, $result, $matches); array_shift($matches); $cookie = implode("\n", $matches[0]); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "http://www.vbulletin.org/forum/"); curl_setopt($ch, CURLOPT_COOKIE, $cookie); curl_setopt($ch, CURLOPT_AUTOREFERER, true); curl_setopt($ch, CURLOPT_COOKIESESSION, true); curl_setopt($ch, CURLOPT_FAILONERROR, false); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false); curl_setopt($ch, CURLOPT_FRESH_CONNECT, true); curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch, CURLOPT_POST, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30); $result = curl_exec($ch); curl_close($ch); echo $result; ?>It just shows the same page for unregistered users. Any help or advice is appreciated, i'm very new to this type of script.. Hi girls and boys I am trying to set a variable if a session OR a cookie has been set, but am unsure on how to write the statement... if (isset($_SESSION['name'])||isset($_COOKIE['name'])) {$variable = $_SESSION['name']||$_COOKIE['name'];} Obviously not working there, but just need a pointer here. any help is appreciated... what would be the best way to automate/force session destroy and cookie erase i have a facebook iframe, with facebook login which gets the activation token now the user is not logged out from the login script after he logs out of facebook. any ideas how to force cookie timeout without a logout button? im playing with Code: [Select] <?php session_start(); //Global User Object Var //loggedInUser can be used globally if constructed if (isset($_SESSION['userCakeUser'])) { $obj = casttoclass('stdClass', $_SESSION['userCakeUser']); $_SESSION['userCakeUser'] = $obj; $_SESSION['start'] = time(); // taking now logged in time $_SESSION['expire'] = $_SESSION['start'] + (1 * 60) ; // ending a session in 1 minute } if(isset($_SESSION["userCakeUser"]) && is_object($_SESSION["userCakeUser"])) { $loggedInUser = $_SESSION["userCakeUser"]; } ?> |