PHP - Headers Already Sent Caused By session_start();? [duplicate] - php

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Headers already sent by PHP
EDIT** I have now fixed the headers already sent up to the point where, line 53 ie. Last line in my common.php, which starts the session, is causing headers already sent. So now where am I supposed to put my session_start?
My index.php -
<?php
require("common.php");
if(empty($_SESSION['user']))
{
header("Location: login.php");
die("Redirecting to login.php");
}
?>
<!DOCTYPE html>
<!-- paulirish.com/2008/conditional-stylesheets-vs-css-hacks-answer-neither/ -->
<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7" lang="en"> <![endif]-->
<!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8" lang="en"> <![endif]-->
<!--[if IE 8]> <html class="no-js lt-ie9" lang="en"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en"> <!--<![endif]-->
<head>
<meta charset="utf-8" />
<!-- Set the viewport width to device width for mobile -->
<meta name="viewport" content="width=device-width" />
<title>nCMS | Simplicity, Reimagined.</title>
<!-- Included CSS Files (Uncompressed) -->
<!--
<link rel="stylesheet" href="stylesheets/foundation.css">
-->
<!-- Included CSS Files (Compressed) -->
<link rel="stylesheet" href="stylesheets/foundation.min.css">
<link rel="stylesheet" href="stylesheets/app.css">
<script src="javascripts/modernizr.foundation.js"></script>
<!-- IE Fix for HTML5 Tags -->
<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<!--INCLUDE HEADER -->
<?PHP include('header.php'); ?>
<!--/INCLUDE HEADER -->
<!--INCLUDE PAGE -->
<div class="row">
Hello <?php echo htmlentities($_SESSION['user']['username'], ENT_QUOTES, 'UTF-8'); ?>, secret content!<br />
<h3>Hi, I'm Index!</h3>
</div>
<!--/INCLUDE PAGE-->
<!--INCLUDE FOOTER-->
<?PHP include('footer.php'); ?>
<!--/INCLUDE FOOTER-->
<!-- Included JS Files (Compressed) -->
<script src="javascripts/jquery.js"></script>
<script src="javascripts/foundation.min.js"></script>
<!-- Initialize JS Plugins -->
<script src="javascripts/app.js"></script>
</body>
</html>
This is the live page - http://www.cogameservers.com/ncms
Thank you for any help - Necro
common.php -
<?php
$username = "";
$password = "";
$host = "";
$dbname = "";
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
try
{
$db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
}
catch(PDOException $ex)
{
die("Failed to connect to the database: " . $ex->getMessage());
}
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc())
{
function undo_magic_quotes_gpc(&$array)
{
foreach($array as &$value)
{
if(is_array($value))
{
undo_magic_quotes_gpc($value);
}
else
{
$value = stripslashes($value);
}
}
}
undo_magic_quotes_gpc($_POST);
undo_magic_quotes_gpc($_GET);
undo_magic_quotes_gpc($_COOKIE);
}
header('Content-Type: text/html; charset=utf-8');
session_start();

I know that you resolved your issue from my comments.but here it is as answer.
As you asked where you put session_start to remove header already sent error.
As general practice, put session_start() at the starting of your php file. also need to clear previous bufffer.
ob_start(); // this will clear output buffer
session_start();

It appears the error is caused by header("Location: login.php"); - the error says common.php is sending headers already on line 77. It will keep doing this as long as common.php is sending the headers.
Warning: Cannot modify header information - headers already sent by (output started at /home/megatron/public_html/ncms/index.php:9) in /home/megatron/public_html/ncms/common.php on line 77
Without knowing the contents of that file I can't help you. I'd suggest just looking through that file for something sending some headers and see if it necessary or approach this problem differently.

Related

Special characters showing up on content retrieved from mysql using php

I have content stored in a mysql database. When I am trying to retrieve the content using PHP and display it using html and CSS, some of it displays these special characters ������.
I have declared the encoding type in my HTML, used to render the PHP content as follows.
I have also added this to the head off the html document
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta charset="utf-8">
<!-- [portable options] -->
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0;" />
<meta name="apple-mobile-web-app-capable" content="yes" />
What mistake am I making that the retrieved content shows the special characters?
This is the document that contains the PHP script that retrieves the data from mysql
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta charset="utf-8">
<!-- [loading stylesheets] -->
<link type="text/css" rel="stylesheet" href="css/style.css" />
<!-- [loading stylesheets] -->
<link type="text/css" rel="stylesheet" href="css/style.css" />
<link type="text/css" rel="stylesheet" href="css/flexslider.css" />
<!-- [loading scripts] -->
<script type="text/javascript" src="js/jquery-2.0.3.min.js"></script>
<script type="text/javascript" src="js/main.js"></script>
</head>
<body>
<div class="blog-post">
<div class="wrapper">
<!--
<iframe frameborder="0" scrolling="yes" width="100%" height="500px"
src="debug/includes/news_index.php" name="" id="">
</iframe>
-->
<?php
// connection string constants
define('DSN', 'mysql:dbname=mydb;host=localhost');
define('USER', 'myadmin');
define('PASSWORD', 'mypwd2015');
// pdo instance creation
$pdo = new PDO(DSN, USER, PASSWORD);
// query preparation
$stmt = $pdo->query("
SELECT title, introtext, id, created, created_by, catid
FROM mytbl_items
");
// fetching results
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
// if this returns 0 then it means no records are present
echo count($result) . "\n";
// the loop should print valid table
foreach ($result as $index => $row) {
if ($index == 0) echo '<div>';
echo <<<HTM
<span class="post-date">{$row['created']}</span>
<h2 class="blog-post-title">{$row['title']}</h2>
<p>
{$row['introtext']}
</p>
<p>
<a href='read_serverside.php?id={$row['id']}'><input type="button" value="Read More" /></a>
</p>
<div class="blog-meta">
<img src="img/avatar.png" alt="Avatar" />
<h4 class="blog-meta-author">{$row['created_by']}</h4>
<span>Category: {$row['catid']}</span>
</div>
HTM;
if ($index == (count($result)-1)) echo '</div>';
}
?>
</div> <!-- .blog-meta -->
</div> <!-- .blog-post #2 -->
</body>
</html>
What else should I do to avoid the special chars from showing up?
Try setting the utf8 charset at the PDO Connection like this:
$pdo = new PDO(DSN, USER, PASSWORD,array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
This works for me.
Try this one before the start of HTML.
I hope it will also work for you.
<?php header('Content-Type: text/html; charset=iso-8859-15'); ?>
<!DOCTYPE html>
<html lang="en-US">
<head>
There are characters in your database that does not exist in Unicode UTF 8. The data are not recognized by this format so thew are displayed as weird characters. I suggest you change the <meta charset="utf-8"> into #charset 'iso-8859-15' or to delete the line. If this does not work you have to go to the data that are causing the error and determine the type of encoding that is used.
If you have main or front controller you should put
header('Content-Type: text/html; charset=utf-8');
somewhere there.
If you haven't put that call at the very beginning of your file before you start output html:
<?php header('Content-Type: text/html; charset=utf-8'); ?>
<!DOCTYPE html>
<html>
<head>
......

Chrome loading the contents of a PHP file into a CSS file

My website loads perfectly on Firefox, but the CSS disappears completely on Chrome (although the html loads).
According to the console, this seems to be because Chrome is loading the contents of index.php into main.css and bannerTest.css like so:
On Firefox, however, it loads the CSS as expected:
Things I have tried that did not work:
clearing my history/cache/cookies
adding text/css to the tags. All this did was make the text render a
little weirdly on Firefox.
css and html validation. I fixed all the semi-colons and such. Still doesn't work.
What's the problem? I can't even figure out what steps to take to investigate what's going on more deeply, let alone figure out the problem itself. No errors are printed to the console as far as I can tell.
Here is index.php:
<!DOCTYPE html>
<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]-->
<head>
<meta charset="utf-8">
<title>Study</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<link href="css/bannerTest.css" rel="stylesheet">
<link href='http://fonts.googleapis.com/css?family=Montserrat:400,700' rel='stylesheet' type='text/css'>
<link href="css/main.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.js"></script>
<style>
/**
* The banner assumes a margin of 0px, but is not included
* in banner.css to avoid collisions with other themes and
* admin bars.
*/
body {
margin:0px;
}
</style>
<link rel="icon" type="image/ico" href="favicon.ico">
</head>
<body>
<?php
//Connect to MySQL database.
$host = "127.0.0.1";
$user = "root";
$password = "password";
$database = "database";
$r = mysql_connect($host, $user, $password);
if (!$r) {
echo "Could not connect to server.\n";
trigger_error(mysql_error(), E_USER_ERROR);
}
$query = "CREATE DATABASE IF NOT EXISTS " . $database;
mysql_query($query);
#mysql_select_db($database) or die("Unable to select database.");
$query="CREATE TABLE IF NOT EXISTS `groupcodes` (`groupcode` int(10) PRIMARY KEY, `usercode` int(10))";
mysql_query($query);
$userid = "";
?>
<div id="banner">
<div id="u-header-container">
<div class="container">
<div class="row-fluid">
<div id="home-link-container">
<a id="home-link" href="http://csue.edu/">
<span id="wordmark">U</span>
<span id="university">UNIVERSITY</span>
</a>
</div>
</div>
</div>
</div>
<div id="database-container">
<header>
<a href="index.php">
<h4 id="logo">Computing Systems</h4>
<h1 id="study_logo">Study</h1>
</a>
</header>
<div id="study">
<form method="post" id="consent-form" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="wide-column">
<p>
By clicking the 'Acccept' button below, you hereby acknowledge the following:
</p>
<p>
I am 18 years of age or older, live in the United States, and have a Google Drive or Dropbox account.
I have read this form and decided that I will participate in the project described above.
Its general purposes, the particulars of involvement, and possible risks and inconveniences have
been explained to my satisfaction. I understand that I can withdraw at any time.
</p>
</div>
<input type="text" name="email_input">
<br>
<input type="submit" value="Begin Study">
</form>
</div>
</div>
</div>
</body>
</html>
You misdiagnosed the problem. It is due to visiting different URLs to load the HTML document rather then using different browsers. You just switched browsers at the same time as you switched URLs.
Look at the URL that is being loaded in your first image:
http://localhost/peergroup/index.php/css/main.css
In Chrome you must be visiting http://localhost/peergroup/index.php/ while in Firefox you are visiting http://localhost/peergroup/index.php (without a / at the end).
This is causing relative URLs to be computed differently.
A workaround is to use URLs that are relative to the site root (i.e. starting with a /).

Why is PHP page not displaying in browser? [duplicate]

This question already has answers here:
The character encoding of the HTML document was not declared
(6 answers)
Closed 9 years ago.
When I visit my page I get a blank display and the following message:
"The character encoding of the HTML document was not declared. The document will render with garbled text in some browser configurations if the document contains characters from outside the US-ASCII range. The character encoding of the page must be declared in the document or in the transfer protocol."
Here's the relevant code:
<?php
$errors = array();
$missing = array();
//check if the form has been submitted
if (isset($_POST['send']))
{
//email processing script
$to = '$_POST['email']';
$subject = 'Your Quote';
$expected = array('email',);
$required = array('email');
$headers .= 'Content-Type: text/plain; charset=utf-8';
require('./includes/processmail.inc.php');
if ($mailSent) {
header('Location: http://www.dailyspiro.com/email.php');
exit;
}
}
?>
<!DOCTYPE html>
<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]-->
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
Use following PHP header at the top of the PHP Code
header('Content-type: text/html; charset=utf-8');
ie.
<?php
header('Content-type: text/html; charset=utf-8');
$errors = array();
$missing = array();
//check if the form has been submitted
if (isset($_POST['send']))
{
//email processing script
$to = '$_POST['email']';
Instead of using a meta tag to declare encoding, try using a standard doctype like
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

new DomDocument() do not work with getElementsByTagName('section'); [duplicate]

This question already has answers here:
PHP DOMDocument error handling
(5 answers)
Closed 9 years ago.
I would like to have different outputs if the file is called by Ajax or not.
For that I have this code witch works fine:
/* AJAX check */
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$content = get_content();
die($content);
}
my function for filtering the contend is this:
function get_content(){
//$file = file_get_contents('index.html'); //works better but i get only errors
$dom = new DomDocument();
$dom->loadHTML($_SERVER['REQUEST_URI']); //or $file
$section= $dom->getElementsByTagName('section');
return $section->item(0)->nodeValue;
}
my output is always empty.
Whats wrong here?
!!!I'am not looking for DOMDocument error handling!!!!
What I do for now is:
/* decide what the content should be up here .... */
/* AJAX check */
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
/* if ajax, show only content of the section tag */
$file = file_get_contents($_SERVER['SCRIPT_FILENAME']);
$section = preg_replace("/.*<section[^>]*>|<\/section>.*/si", "", $file);
die($section);
}
/* not ajax, show page.... */
and it seems to work. I do not know it is the best solution because somewhere in this forum I read that its better to realise that with DomDocument().
Any suggestions are welcome?
Here is the html-file:
<!doctype html>
<!-- Determine browser JS free -->
<!-- HTML5 Mobile Boilerplate -->
<!--[if IEMobile 7]><html class="no-js iem7"><![endif]-->
<!--[if (gt IEMobile 7)|!(IEMobile)]><!--><html class="no-js" lang="en"><!--<![endif]-->
<!-- HTML5 Boilerplate -->
<!--[if lt IE 7]><html class="no-js lt-ie9 lt-ie8 lt-ie7" lang="en"> <![endif]-->
<!--[if (IE 7)&!(IEMobile)]><html class="no-js lt-ie9 lt-ie8" lang="en"><![endif]-->
<!--[if (IE 8)&!(IEMobile)]><html class="no-js lt-ie9" lang="en"><![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en"><!--<![endif]-->
<head>
<meta charset="utf-8">
<title>title</title>
<link rel="stylesheet" type="text/css" href="../css/style.css">
<link rel="shortcut icon" href="img/base/favicon.html" />
<link rel="apple-touch-icon-precomposed" href="img/base/apple-touch-icon-57x57-precomposed.html" />
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="img/base/apple-touch-icon-72x72-precomposed.html" />
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="img/base/apple-touch-icon-114x114-precomposed.html" />
<script src="/js/libs/modernizr.custom.js"></script>
<!--[if (IE 7)]>
<link rel="stylesheet" href="/css/fallback/icons-ie7.css">
<![endif]-->
</head>
<body >
<section role="main">
<header class="hero-banner">
<img class="resize" src="/img/base/spacer-hero.png" rel="/img/designers/banners/cloe-banner3.jpg" alt="Cloe" />
<noscript><img src="/img/designers/banners/cloe-banner3.jpg" alt="Cloe" /></noscript>
<hgroup>
<h1>Claudia</h1>
<h2 class="text-hl">Designerin</h2>
</hgroup>
</header>
</section>
<footer role="contentinfo">
<p><small>©2013 joe</small></p>
<p><small>Our website uses delicious cookies to improve your experience. We'll assume you're ok with that.</small></p>
</footer>
<!-- jQuery from Google's CDN with local fallback -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="/js/libs/jquery-1.8.3.min.js"><\/script>')</script>
<script src="/js/libs/wfl.js"></script>
<!-- Initialises scripts from plugins.js and helper.js -->
<script src="/js/script.js"></script>
<!-- Google Goggles -->
</body>
</html>
You can turn the errors of by setting internal errors to true:
$doc = new DOMDocument;
$before = libxml_use_internal_errors(true);
$doc->loadHTML($html);
libxml_use_internal_errors($before);
You then won't have the errors logged any longer. In your case most likely you've got display errors enabled which might be okay for development, but on your production server, please switch to error logging otherwise your website would reveal too much data to the outside.
See as well:
PHP DOMDocument error handling

Php title for web page

I have this code on my header.php. Its for creating title on the fly. The problem is that it only creates a title when user is on the article.php(page for reading the article) but produce a 'undefined variable i' error on other pages. What should I change or who know a better code for the title of web page? i is id.
if(isset($i=$_GET['i']) && $i = true ) {
$i=$_GET['i'];
$tbl_name="yote";
$sql=mysql_query("SELECT * FROM $tbl_name WHERE i='$i'") or die(mysql_error());
while($rows=mysql_fetch_array($sql)){
$title = $rows['title']. "";
}
mysql_close();
} else {
$title = 'Malloooo - News, Reviews, Analysis and Market Watch From Around The World';
}
?>
<!-- Header
================================================== -->
<!DOCTYPE html>
<!--[if lt IE 7 ]><html class="ie ie6" lang="en"> <![endif]-->
<!--[if IE 7 ]><html class="ie ie7" lang="en"> <![endif]-->
<!--[if IE 8 ]><html class="ie ie8" lang="en"> <![endif]-->
<!--[if (gte IE 9)|!(IE)]><!--><html lang="en"> <!--<![endif]-->
<head>
<!-- Basic Page Needs
================================================== -->
<meta charset="utf-8">
<title><?php echo $title; ?></title>
Honestly, there's quite a bit wrong with your code.
if (isset($i=$_GET['i']) ... : Not sure what you're trying to do with that, but it's not valid.
... && $i = true) : This is setting a value, not checking it.
You're horribly vulnerable to SQL injection. Look into PDO: http://php.net/PDO

Categories