Warning while submitting form in PHP [duplicate] - php

This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Closed 8 years ago.
I am developing an mobile application using jquery mobile and PHP. I encounter a warning when i submit the form for checking the credentials.
Warning: Cannot modify header information - headers already sent by (output started at /home/u387779804/public_html/walcliff/index.php:6) in /home/u387779804/public_html/walcliff/index.php on line 48
The php code
<?php session_start();?>
<?php
if(isset($_POST['sec']))
{
$s=$_POST['sec'];
$user="u387779804_a";
$password="arunvenu123";
$server="mysql.1freehosting.com";
$con=mysql_connect($server,$user,$password);
mysql_select_db("u387779804_a",$con);
$query=mysql_query("select * from details where secretnum='$s'");
if (!$query) { // add this check.
die('Invalid query: ' . mysql_error());
}
$info=mysql_fetch_array($query);
if($_POST['sec'] == $info['secretnum'])
{
$_SESSION['fid']=$info['fid'];
$_SESSION['phone']=$info['phone'];
$_SESSION['name']=$info['name'];
$_SESSION['email']=$info['email'];
$_SESSION['address']=$info['address'];
$_SESSION['city']=$info['city'];
header('Location:list.php');
}
else
{
echo '<script> alert("Wrong User name password")</script>';
}
}
?>
I have attached the screen shoot also.Any possible solutions for this problem is welcomed! Thanks in advance!

The second line is actually your problem here. That's a linebreak, which is considered starting of the body and thus means no-more headers can be sent.
Change the first three lines to the following:
<?php ob_start(); session_start(); ?>
<?php
if(isset($_POST['sec']))
Or, better yet:
<?php
ob_start();
session_start();
if(isset($_POST['sec']))

Related

trying to redirect a user to a different link after an input was insert [duplicate]

This question already has answers here:
How do I make a redirect in PHP?
(34 answers)
Closed 6 years ago.
I am learning PHP and HTML (sorry for being noob) trying to redirect a customers to a different link after an input was insert. which means after he press verify he will be redirect to my website www.example.com/home.php This is my current code:
<div class="tclpad" style="width:90px;"> </div>
<div class="tclpad"><input class="bstd" value="Verify" type="submit"></div>
Also, when someone inserts a wrong information, i can see in the code:
<?php
if(isset($_SESSION['wrong'])) {
echo "<p class='error'>Authentication failed.</p>";
session_destroy();
}
?>
I want the user after he press verify will get a message 'Verified'.
Thank you so much guys for your help.
Check the accepted answer here: How to make a redirect in PHP?
I'm not sure exactly what you're looking for with the 'Verified' statement, but the answer above shows how to redirect the web page with the PHP header() function.
Edit:
I realized the header() function limits how the current page provides feedback. Instead, you could use javascript to redirect:
function redirectOnVerify(myVar) {
if(myVar === 'success'){
window.alert('You have verified successfully');
window.location = 'http://newlocation.com' ;
}
else if (myVar === 'failure') {
window.alert('Failed to verify');
}
else {
console.log('PHP auth error, neither success nor failure')
}
}
And then in your html:
<input onClick="redirectOnVerify('
<?php if(isset($_SESSION['right'])){
echo 'success'
}
else if (isset($_SESSION['wrong']){
echo 'failure'
}
else {}
?>
')">
/j
Use header() like
header("refersh: 2; url=page2url");
Refersh is a delay time here the page will redirect after 2 seconds if u don't want delay then either set refersh to 0 or do this
header("location=pag2url");

PHP - setcookie(); not working ( Cannot modify header information - headers already sent ) [duplicate]

This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Closed 8 years ago.
I am getting this error:
Warning: Cannot modify header information - headers already sent by (output started at /removed/loginform.php:2) in /removed/loginform.php on line 24
I understand that I am getting the error when I try to set a cookie, and it's because setcookie can't have any output before it... the problem is, there is no output before it (At least from what I can see). It is saying that "< ?php" is a header, and I don't understand that. If setcookie can only be used in PHP and < ?php is a header, how is it even possible to use setcookie without getting this header error?
My code:
<!--Database Connections-->
<?php include "../../includes/dbpractice_con.php"; ?>
<?php
//Declare variables
$username = "";
$password = "";
$message = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") { //Retrieve from form when submit is clicked.
//Escape to prevent SQL injection.
$username = mysqli_real_escape_string($connection, $_POST['username']);
$password = mysqli_real_escape_string($connection, $_POST['password']);
$check = mysqli_query($connection, "SELECT * FROM users WHERE username='$username' AND password='$password'");
$rowCount = mysqli_num_rows($check);
if ($rowCount == 1) {
$cookieExpiration = time() + 757368000; //1 year
setcookie("username", $username, $cookieExpiration);
} else {
$message = "Invalid username or password. <br/>Don't have an account? Click here to register.<br/><br/>";
}
}
?>
<html>
<!--Database Connections--> is HTML output, even if it is just a comment. Remove that and try again.
EDIT:
There is also a space between the PHP blocks. Try putting the include in the main PHP block.
Generally that means you have sent something to client prior to setcookie() call.
Do simple test:
<?php
ob_start();
include "../../includes/dbpractice_con.php"; ?>
# ... rest of your code... #
and before setcookie() call add line
ob_get_clean();
just to be sure that no output was made earlier.
Anything outside of <?php ?> is HTML and is sent to user. So this
<!--Database Connections-->
<?php include "../../includes/dbpractice_con.php"; ?>
outputs <!--Database Connections--> as HTML comment. Another possible output is here
<?php include "../../includes/dbpractice_con.php"; ?>
<?php ...
at least you have new line character between two PHP tags, which is also unwanted output.
You can't have anything to echo, print_r, var_dump data before cookieset() call, check manually for these functions.
Always check all included scripts (with include, require, etc).
BE SURE THEY START WITH <?php WITH NOTHING BEFORE and END WITH ?> FOLLOWING NOTHING.
this is good example:
<?php
// some lines
?>
these aren't
something<?php ?>
or
<?php ?>something
or
<?php ?>
(if file has been saved as UTF-8).
Look at your dbpractice_con.php, check is it saved as ANSI (from notepad check with save as dialog), be sure that everything is between and no one character is before and after the tags. Don't use multiple tags in same script because it increases risk of unwanted output.
Try this:
<?php
// Database connections
include "../../includes/dbpractice_con.php";
//Declare variables
// ... proceed with code ...
If this doesn't work then the problem is probably in dbpractice_con.php

Issues with header while redirecting it to the current page [duplicate]

This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
PHP error: Cannot modify header information – headers already sent [duplicate]
(5 answers)
Closed 8 years ago.
I have wriiten as
<?php
if (isset($_POST['delete'])):
$size = count($_POST['checkbox']);
for ($i=0; $i<=$size-1; $i++) {
$id = $_POST['checkbox'][$i];
$wpdb->query("DELETE FROM wp_submitted_form WHERE id =".$id);
}
header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
endif;
?>
When submit button is clicked it throws error message as:
Cannot modify header information - headers already sent by (output started at /home/wizcorea/public_html/wp-admin/includes/template.php:1657) in /home/wizcorea/public_html/wp-content/plugins/submitted-form/view.php on line 54
I want that page should get refreshed after submit button is clicked
Use the ob_flush function of PHP. add this function at the top of the code.
<?php
ob_flush();
And this will work.
EDITED:
INstead of this code:
header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
Use this code:
echo '<script>location.href="http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'].'"</script>';

PHP Headers Already Sent Error [duplicate]

This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Closed 9 years ago.
The following code is not working even after having inserted ob_start(), and ob_flush();
I keep getting the PHP headers already sent error
<?php
ob_start();
include("/home/www/pheincl/config.php");
include("/home/www/pheincl/common_functions.php");
$num = $_SERVER['HTTP_X_UP_CALLING_LINE_ID'];
if($num == null)
{
$num = $_SERVER['HTTP_X_MSISDN'];
if($num == null)
{
$num = $_GET["msisdn"];
}
}
if(strlen($num) > 3)
{
$sql="select count(*) from members where msisdn='$num'";
$r=fetch($sql);
if($r[0] > 0)
{
$r1=fetch("select pin from members where msisdn='$num'");
if(strlen($r1[pin]) > 2)
{
header("Location:http://location1.com?msisdn=$num&pin=$r1[pin]");
}
}
else
{
header("Location:http://location2.com&msisdn=$num");
}
}
else
{
header("Location:location3.com/phe/log.php");
}
ob_end_flush();
?>
UPDATE: After some further testing it looks like this problem is specific to my servier. Someone I know put this on their server and it worked fine
use notepad++ and set encoding to UTF8 without BOM
your BOM (Byte Order Mark) is probably what's causing it
EDIT:
Make sure you do it on all included files
Before any header function, the script shouldn't print anything. That means no echo, no html code outside php tags etc.
So either that sql echoes some error, or your include files do something similar.
Something is sending some output to the browser before your header code executes. Look for any errors output to the screen or any print or echo statements.
You can try to delete the final ?> to avoid the problem. Sometimes this fixes the problem.

Warning: Cannot modify header information - headers already sent by [duplicate]

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.
Please save me. I know that this question has been asked many times, however, I can't seem to find solutions that are relevant to my situation.
The problem: Warning: Cannot modify header information - headers already sent by (output started at /.../Sites/st.ambulance/resources/views/login.view.php:32) in /.../Sites/st.ambulance/resources/controllers/tables_.php on line 47
This is the code block with line 32:
<label>Month</label>
<select name="dob_month">
<?php for($i=0,$j=1;$i<sizeof($month);$i++,$j++){ ?>
<option value="<?php h($j) ?>"><?php h($month[$i]) ?></option> //line 32
<?php } ?>
</select>
The definition of the h function:
function h($s){
echo(htmlspecialchars($s,ENT_QUOTES));
}
This is tables_.php:
<?php
$error = "";
if(isset($_POST['guest_tables'])){
if(isset($_SESSION['logged_in']) && $_SESSION['logged_in']){
$guest = array();
$volunteer = array();
$guest = isset($_POST['guest']) ? $_POST['guest'] : null;
$volunteer = isset($_POST['volunteer']) ? $_POST['volunteer'] : null;
$seat_array = array($volunteer['seat_no'].$volunteer['table']);
$seat_count = 0;
$table_seat_error = "";
if($form->is_seatOccupied($volunteer['table'],$volunteer['seat_no']) != "")
$table_seat_error .= "Seat (".$volunteer['seat_no'].")
at table (".$volunteer['table'].") is currently occupied";
if($_SESSION['no_guests'] >= 1){
if($guest && $volunteer){
foreach($guest as $gue){
$seat_table = $gue['seat_no'].$gue['table'];
for($h=0;$h<sizeof($seat_array);$h++){
if($seat_table == $seat_array[$h] )
$seat_count = $seat_count + 1;
}
if($form->is_seatOccupied($gue['table'], $gue['seat_no']) != "")
$table_seat_error .= "Seat (".$gue['seat_no'].")
at table (".$gue['table'].") is currently occupied";
$seat_array[] = $seat_table;
}
if($seat_count == 0){
if($table_seat_error == ""){
for($d=0;$d<$_SESSION['no_guests'];$d++){
$_SESSION['guests'][$d]['table'] = $guest[$d]['table'];
$_SESSION['guests'][$d]['seat'] = $guest[$d]['seat_no'];
}
$_SESSION['volunteer']['table'] = $volunteer['table'];
$_SESSION['volunteer']['seat'] = $volunteer['seat_no'];
$form->set_guests($_SESSION['guests']);
$form->set_volunteer($_SESSION['volunteer']);
header('location: /branch/menus.php'); //line 47
exit();
}
else{
$error = $table_seat_error;
}
}
else{
$error = "You have selected the same seat for two or more
people: one person, per seat, per table. Only.";
}
}
}
else{
$_SESSION['volunteer']['table'] = $volunteer['table'];
$_SESSION['volunteer']['seat'] = $volunteer['seat_no'];
if(!$form->is_seatOccupied($_SESSION['volunteer']['table'],
$_SESSION['volunteer']['seat']) != ""){
$form->set_volunteer($_SESSION['volunteer']);
header('location: /branch/menus.php');
exit();
}
}
}
}
?>
EDIT: would it help to know that I'm trying to handle multiple forms on a single page?
Line 47 modifies the response headers:
header('location: /branch/menus.php'); //line 47
Line 47 cannot be executed because the headers have already been sent, which happened to occur on line 32. All that happened on line 32 was that PHP decided it had enough content in the response to start sending it back to the browser.
Generally, if you want to modify the headers (whatever you're doing on line 47), you need to do it at the very beginning of the file.
This is a good time to learn about the MVC design pattern - it would eliminate the possibility of this issue in the future. In MVC, the Controller executes first, and prepares everything for the View. So, you can modify your headers all you want in the Controller, and they won't be sent until during or after the View is processed.
EDIT: It looks like you are using MVC, but somehow your view is executing before the controller has started (or perhaps finished)... that shouldn't happen! Unfortunately, the code you've posted doesn't illustrate how either the controller or view are being accessed... but they're being accessed out of order.
As TRiG point out in the comments below, you probably want to insert an exit() statement after line 47 as follows:
header('location: /branch/menus.php'); //line 47
exit();
This will cause the server to immediately send the Location redirect to the browser, and the request/response cycle is complete. All your header('Location: ...'); calls should be immediately followed by exit();. This doesn't fix the issue at hand, but it is very important.
switch on output buffering, locate php.ini and look for / uncomment / change / add the following line:
output_buffering = On
edit: and include a line saying ob_start(); in some initial include, like some common init.php or database.php
edit^2: the ob_start is not needed (anymore?); this works, save as test.php and request. Seeing is believing.
Output has started
<?php
header("Content-Type: text/plain");
?>
The point is that in HTTP the response of the server consists of 2 parts: the headers and the body.
The headers contain information about the content, the connection etc, like what type of content, e.g.
Content-Type: text/html
or
Content-Type: image/jpeg
indicating it's html or jpg. Without it, the browser wouldn't be sure what to do with the content. Of course once PHP has to start outputting the body part of the response, there's no way to change the header. So you can either do anything header-related first before emitting any byte of the body, or you could instruct php to hold it's breath and emit the body only when the script is done, or when you say so. And that's what they call output buffering.

Categories