This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Warning: Cannot modify header information - headers already sent
Headers already sent by PHP
Error: Cannot modify header information - headers already sent by (output started at C:\xampp\htdocs\GameHutWebsite\data\connection.php:1) in C:\xampp\htdocs\GameHutWebsite\login.php on line 21
I am getting this error when the user enters the correct username and password in the login screen to send the user in the home page. This is the code:
<?php
if ($_POST)
{
$dsLogin = $dataobj->validateLogin($_POST["txtUsername"],$_POST["txtPassword"]);
if (mysql_num_rows($dsLogin))
{
$dsUserDetails = mysql_fetch_array($dsLogin);
$_SESSION["UserEmail"] = $dsUserDetails["UserEmail"];
$_SESSION["Username"] = $dsUserDetails["Username"];
$_SESSION["UserTypeId"] = $dsUserDetails["UserTypeId"];
header ("Location: index.php");
}
else
{
$msg = "Invalid Username and Password!";
}
}
?>
Connection Class:
<?php
class connection
{
function connect($sql)
{
$server = 'localhost';
$myDB = 'gamehutdb';
//connection to the database
$dbhandle = mysql_connect($server, 'root', "")
or die("Couldn't connect to SQL Server $server");
//select a database to work with
$selected = mysql_select_db($myDB)
or die("Couldn't open database $myDB");
//execute the SQL query and return records
$result = mysql_query($sql);
//return result set
return $result;
//close the connection
mysql_close($dbhandle);
}
}
?>
You have used
header ("Location: index.php");
AFTER sending something to the client (ie, using echo or print), make sure that there is nothing sent to the client before that code.
Another reason might be a BOM problem.
This is probably due to the fact that your connection class is emitting some kind of output
Comment out the "header" line and run your script. If you get some output, then that's the reason.
You should conditionally launch the "header" line based on whether you get an error or not, at least while you troubleshoot your problem.
Related
I am trying to redirect to the logout page when the database connection fails. How do I do it? It always shows the error message but not the one I specify. Help appreciated, thanks in advance.
Richard
code:
function ms_connect() {
// Create connection
// Microsoft Access
$db_source = DB_SERVER;
$db_system = DB_SYSTEM_SEC;
$odbc_driver = "driver={microsoft access driver (*.mdb)};dbq=" . $db_source . ";systemdb=" . $db_system;
$conn = odbc_connect($odbc_driver, DB_SERVER_USERNAME,DB_SERVER_PASSWORD); // Error returned here!
if ($conn) {
return $conn;
} else{
exit("Connection could not be established.");
header ("Location: /logout.php");
}
}
it does not show "Connection could..."
error shown
PHP Warning: odbc_connect(): SQL error: [Microsoft][ODBC Microsoft Access Driver] Not a valid account name or password., SQL state 08004 in SQLConnect in C:\inetpub\wwwroot\functions\functions.php on line 11
You are doing an exit, which will terminate the script before the redirect.
You can pass your error message as a get param and show it on your page if you need.
Your code should look like this :
if ($conn) {
return $conn;
} else{
header ("Location: /logout.php?error=Connection+could+not+be+established.");
}
Also if you want to hide the warning just add:
error_reporting(0);
ini_set('display_errors', 'Off');
The warning you see is triggered by the odbc_connect function, while it is strange that the exit string is not printed, it is not strange that your redirect does not work since the exit prevents it from being executed.
Try:
if ($conn !== false) {
return $conn;
} else{
header ("Location: /logout.php");
exit();//just in case
}
You can ignore the warning (and you should) by the connection using the '#' sign in front of the connect function. (which is more elegant than to ignore all errors).
$conn = #odbc_connect($odbc_driver, DB_SERVER_USERNAME,DB_SERVER_PASSWORD); // Error returned here!
edit:
A nice way to do it and still show a message to the user plus redirect is using html meta redirects:
if ($conn !== false) {
return $conn;
} else{
echo '<html><head><meta http-equiv="refresh" content="5;url=/logout.php" /></head><body>Could not create a connection, redirecting in 5 seconds.</body></html>';
exit();
}
This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Closed 7 years ago.
I'm having a small issue with a header redirect on a login form. I have debugged the If & While statement and they both work fine, which surely can only be the header. I have tried redirecting it too numerous sites and pages but still nothing. Would really appreciate any help. Thanks!!!
<center>
<?php
include './index.php';// This is a login form
include './connection.php';// SQl connection page
include './session.php'; // Sessions page
error_reporting(E_ALL);
$mysqli = new mysqli ("c3433870.co.uk.mysql", "c3433870_co_uk", "BFUWGpn3", "c3433870_co_uk");
if($mysqli->connect_errno > 0) {
die('Unable to connect to database [' . $mysqli->connect_error . ']');
}
session_start();
if(isset($_POST['submit'])){
$stmt = $mysqli->prepare("SELECT username, password FROM users WHERE username=? AND password=? LIMIT 1");
$username = $_POST['username'];
$password = $_POST['password'];
$stmt->bind_param('ss', $username, $password);
$stmt->execute();
$stmt->bind_result($username, $password);
$stmt->store_result();
if($stmt->num_rows == 1) //To check if the row exists
{
while($stmt->fetch()) //fetching the contents of the row
{
$_SESSION['Login_sessions'] = true;
$_SESSION['login_user'] = $username;
header('Location: ./profile.php');
}
}
else {
echo "Wrong Username or Password!";
}
$stmt->close();
$stmt->free_result();
}
else
{
echo "Not Found";
}
$mysqli->close();
?>
</center>
Server headers are sent after the first echo. when you echo your center tag you thwart yourself.
Since the headers are already sent, you cannot change the location inside.
For this same reason, it is considered best practice not to close your php tags, as the php parser doesn't care either way.
I would remove the ?>
I've seen the use of header in the php to redirect to a page.
I've used the method in the code below and the a redirect error as given below the code.
I need to know what went wrong with the code.
Here is the code (php) :
<?php
/**
* Created by PhpStorm.
* User: Priyabrata
* Date: 3/18/14
* Time: 8:58 PM
*/
function connect_to_db($uid, $pass){
$con=mysqli_connect("localhost", "root", "12345", "MyDB");
if (mysqli_connect_errno()){
echo "Failed to establish link!!";
}else{
echo mysqli_connect_error();
}
$result=mysqli_query($con, "SELECT `pwd` from `login_table` where `uid` = "."'".$uid."'");
if (!$result){
echo "Error!!";
exit();
}
while($xx = mysqli_fetch_array($result)){
if ($xx['pwd'] == hash("MD5", $pass)){
header("location:../Html/Login-Existing-Users1_success.htm");
exit();
}else{
echo "Invalid Login Credentials!!";
exit();
}
}
mysqli_close($con);
}
function validate_credentials(){
if ((isset($_POST["username"]))&&(isset($_POST["password"]))){
$uid = $_POST["username"];
$pwd = $_POST["password"];
if (($uid == "")||($pwd == "")){
echo "Please enter User name and password";
}else{
//Check user name and password
connect_to_db($uid, $pwd);
}
}else{
echo "Please enter User name and password";
}
}
validate_credentials();
Here is the error I get, instead of a redirect when uploaded to the server:
Warning: Cannot modify header information - headers already sent by (output started at /home/opticfhb/public_html/helpvssupport.net/login.php:19) in /home/opticfhb/public_html/helpvssupport.net/login.php on line 27
Additional Info : This works perfectly in my local machine and creates the problem in the server.
You can't call header() after you've already echoed any output. HTTP requests contain header information and data. Any output is part of the data, and data comes after all the headers have already been sent.
PHP has a function called headers_sent to check whether or not the headers have already been sent or not. You might consider writing a function that issues the Location header if they haven't been, or echo out some simple redirect HTML if they have -- perhaps by including this tag in the <head>:
<meta http-equiv="refresh" content="0;http://www.website.com/redirect/url" />
I am trying to put a function that I will commonly use in its own file. Then, I want to include that file so I have access to the function (or so I think).
activity.php (this is the function I want to be able to use)
<?php
function activity() {
$inactive = 600;
// check to see if $_SESSION["timeout"] is set
if (isset($_SESSION["timeout"])) {
// calculate the session's "time to live"
$sessionTTL = time() - $_SESSION["timeout"];
if ($sessionTTL > $inactive) {
$_SESSION["loggedIn"] = false;
session_destroy();
echo "session destroyed";
}
}
else {
echo "You need to log in.";
}
}
?>
Here is showuser.php (the file where the error occurs):
<?php
include ('activity.php');
session_start();
// check to see if $_SESSION["timeout"] is set
activity();
$host="localhost"; // Host name
$uname="root"; // Mysql username
$password="xxx"; // Mysql password
$db_name="itit"; // Database name
$tbl_name="users"; // Table name
// Connect to server and select database.
$mysqli = mysqli_connect($host, $uname, $password, $db_name);
if($_SESSION["loggedIn"]) {
$stmt = $mysqli->prepare("SELECT email FROM users WHERE username = ?");
$stmt->bind_param("s", $_SESSION["username"]);
$stmt->execute();
$stmt->bind_result($em);
$stmt->fetch();
}
else {
echo "You are not logged in.";
}
?>
<h2>Username - Email</h2>
<div id="userinfo"><? echo $_SESSION["username"] ?> - <? echo $em ?></div>
<?
$stmt->close();
mysqli_close($mysqli);
?>
The function should check to see if the session has timed out, unless I am doing something wrong with that code...
I get these errors when running the scripts which include the file:
Warning: include(activity.php) [function.include]: failed to open stream: No such file or directory in /Users/Eamon/Sites/templates/showuser.php on line 2
Warning: include() [function.include]: Failed opening '/activity.php' for inclusion (include_path='.:/Applications/XAMPP/xamppfiles/lib/php:/Applications/XAMPP/xamppfiles/lib/php/pear') in /Users/Eamon/Sites/templates/showuser.php on line 2
Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /Users/Eamon/Sites/templates/showuser.php:2) in /Users/Eamon/Sites/templates/showuser.php on line 3
Fatal error: Call to undefined function activity() in /Users/Eamon/Sites/templates/showuser.php on line 6
UPDATE
I did this instead
include ('../activity.php');
This got rid of all the errors except for the "Warning: session_start" error.
Looks like a problem with the directory where PHP is looking for the file.
Try changing it to include ('./activity.php');
If activity.php is in /Users/Eamon/Sites/templates/ you can change your include to
include (__DIR__'."/activity.php');
and it should work for you.
This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Reference - What does this error mean in PHP?
(38 answers)
Closed 9 years ago.
<?php session_start();
include_once("include/Connection.php");
$userid=$_POST['userid'];
$password=$_POST['password'];
$loginSql = "SELECT * FROM admin2 WHERE admin_name='$userid' and admin_psw='$password'";
$loginQuery=mysql_query($loginSql);
$num_row = mysql_num_rows($loginQuery);
$login = mysql_fetch_array($loginQuery);
$user = $login['admin_name'];
$password = $login['admin_psw'];
echo $user;
echo $password;
if($num_row >0)
{
if($user == $userid)
{
$_SESSION['id_gosi'] = $login['id'];
$_SESSION['userid_gosi'] = $login['admin_name'];
header("Location: CustomerMaster.php");
}
else{
header("Location: index.php?msg=2");
exit();}}
else{
header("Location: index.php?msg=1");
}?>
Warning: Cannot modify header information - headers already sent by (output started at C:\wamp\www\php_mahavirbhadra\Admin\validate_login.php:17) in C:\wamp\www\php_mahavirbhadra\Admin\validate_login.php on line 26
Warning: Unknown: 1 result set(s) not freed. Use mysql_free_result to free result sets which were requested using mysql_query() in Unknown on line 0
when i write above code for admin login in php than connection successfully done but give me above error what can i do for this error ...Please give me solution....
print/echo before HEADER is WRONG !!!
/* echo $user;
echo $password;*/
if($num_row >0)
{
if($user == $userid)
{
....
header("Location: CustomerMaster.php");
}
else
{
header("Location: index.php?msg=2");
exit();
}
}
else
header("Location: index.php?msg=1");
?>
never echo ANYTHING before HEADER, so remove those ECHO $USER, $PASSWORD
Tip 1-> Use mysqli instead of mysql
Tip 2-> Use prepared statement
Tip 3-> Use mysql_real_escape_string()