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

This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Closed 3 years ago.
I want to pass a variable to a page, but cannot modify header... is always in the way
if(isset($_POST['send']))
{
$sender = $_SESSION['Email'];
$receiver = $_POST['email'];
$message = $_POST['textmessages'];
$date = date("Y-m-d h:i:sa");
$q = 'INSERT INTO `tblmessage`(`id`,`sender_name`,`receiver_name`,`message_text`,`date_time`,`userid`)
VALUES("","'.$sender.'","'.$receiver.'","'.$message.'","'.$date.'","'.$user_id.'")';
$r = mysqli_query($con, $q);
if($r)
{
header("location.href='messages.php?user=".$receiver);
}
else
{
echo $q;
}
}
I tried passing the user to the page, but:
output started at C:\xampp\htdocs\MBPH(Beta)\messages.php:79) in `C:\xampp\htdocs\MBPH(Beta)\newmessage.php on line 38
always pops up, that line 38 is
'header("location.href='messages.php?user=".$receiver);'

You could add ob_end_flush() before your header() function. It will clear out the current output buffer and your header() should be sent.
Reference: ob_end_flush() documentation

You can try this code
ob_start();
Your output here
ob_get_contents();

Related

Form doesn't send properly [duplicate]

This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Closed 4 years ago.
I've been trying to make a form in Wordpress to post data to the database and check if the data matches and if so then it proceeds to the next form but I can't seem to get it to work properly, been testing having the form placed in the themes folder to allow straighter testing, the php looks like this:
<?php
if(isset($_POST['submit'])) {
global $wpdb;
$ordernumber = $_POST['ordernmbr'];
$orderfirstname = $_POST['firstname'];
$orderpostnumber = $_POST['postnmbr'];
// Sanitizing
$ordernumber = stripslashes_deep($ordernumber);
$orderfirstname = stripslashes_deep($orderfirstname);
$orderpostnumber = stripslashes_deep($orderpostnumber);
$sql = "SELECT * FROM wp_postmeta WHERE 'post_id' = %d";
$sql = $wpdb->prepare($sql, array($ordernumber));
$res = $wpdb->get_results($sql);
if ($res > 0) {
wp_redirect(admin_url('http://localhost/wordpress/index.php/shop/'));
die();
} else {
$error = "Not like this";
echo $error;
}
print_r($res);
}
?>
<?php
get_footer();
?>
}
The problem is that when I try to post data it gives me an error saying
Warning: Cannot modify header information - headers already sent by (output started at /Applications/XAMPP/xamppfiles/htdocs/wordpress/wp-includes/class.wp-styles.php:225) in /Applications/XAMPP/xamppfiles/htdocs/wordpress/wp-includes/pluggable.php on line 1219
how do I go on about fixing this?
You can't redirect the browser after the content has already begun being served.
That piece of code needs to be included before the theme starts loading, so it needs to be in a plugin.
When setting up the plugin, be sure to give it a high priority, and choose the right filter/action to have it load early (before any content is rendered): WP Action Reference

PHP - Check if user is an admin or not [duplicate]

This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
How to include php file in a php file
(1 answer)
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 5 years ago.
So i have a page where there is a button when clicked it takes u to an admin page.
if u click it first takes u to a admincheck code before bringing u to the adminpage. In that admincheck page it should let admins go through and normal users redirected back. It doesnt work i dont know why
here is the admincheck code:
<?php
include "dbconnection.php";
include "login.php;"
$query = "SELECT * FROM gebruikers WHERE gebruikerID = $userid";
$result = mysqli_query($conn, $query);
$count = $conn->affected_rows;
if($row['admin']=='Ja'){
header("location: contactregister.php");
}
else{
$message = "You shall not pass!";
echo "<script type='text/javascript'>alert('$message');</script>";
header("location: home.php");
}
?>
Did i do anything wrong in that code??

Updating data Php pdo [duplicate]

This question already has answers here:
Why does this PDO statement silently fail?
(2 answers)
Closed 6 years ago.
Im trying to update my data using php but it doesnt work, any ideas?
This is the code, this isnt the full code (its not done) but even the username cant be updated.
<?php
session_start();
include "dbconfig.php";
require "check.php";
if(!empty($_POST['user_name']) || !empty($_POST['user_email'])){
$user_name = trim($_POST['user_name']);
$user_email = trim($_POST['user_email']);
$count=$db_con->prepare("SELECT * FROM users WHERE user_id=:userid");
$count->bindParam(":userid",$_SESSION['user_session'],PDO::PARAM_STR,15);
$count->execute();
$row = $count->fetch(PDO::FETCH_OBJ);
$sql=$db_con->prepare("update users set user_name=:username where user_id='$row->user_id'");
$sql->bindParam(':username',$user_name,PDO::PARAM_STR, 32);
if($sql->execute()){
echo "Successfully updated Profile";
}
else{
print_r($sql->errorInfo());
}
else {
echo "No data inserted!"
}
include "home.php";
?>
I guess a syntax error in this Line
$sql=$db_con->prepare("update users set user_name=:username where user_id='$row->user_id'");
Corrected
$sql=$db_con->prepare("update users set user_name=:username where user_id="$row->user_id);

PHP contact form won't send email, echoes back [duplicate]

This question already has answers here:
PHP parse/syntax errors; and how to solve them
(20 answers)
Closed 7 years ago.
I'm having some issue with my PHP. I'm new to it, so it's all kind of confusing. But the big issue is trying to send email thru a contact form and failing miserably.
I get this error:
Parse error: syntax error, unexpected '$name' (T_VARIABLE) in C:\wamp\www\mtltechevents\contact_form.php on line 7
Line 7:
$name = $_POST['name1'];
I can't see a syntax error. When I remove the error message, it echoes back when I try to fill in the info, as well:
$name = $_POST['name1'];
$email = $_POST['email1'];
$message = $_POST['message1'];
$contact = $_POST['contact1'];
$email = filter_var($email, FILTER_SANITIZE_EMAIL); // Sanitizing E-mail.
// After sanitization Validation is performed
if (filter_var($email1, FILTER_VALIDATE_EMAIL)) {
if (!preg_match("/^\s*(?:\+?(\d{1,3}))?[-. (]*(\d{3})[-. )]*(\d{3})[-. ]* (\d{4})(?: ​*x(\d+))?\s*​$/", $contact)) {
echo "<span>* Please Fill Valid Contact No. *</span>";
Any thoughts? I checked out some of the other issues with contact forms and none really answered what my problem was.
Your error would usually show up if you are missing a semi-colon or bracket above the stated line as it is expecting you to do something else. An example of this would be
$anothervariable = $_POST['anotherpost'] // No semi-colon
$name = $_POST['name1'];
$email = $_POST['email1'];
$message = $_POST['message1'];
$contact = $_POST['contact1'];
Is session started?? Can you post complete code. It sounds like kind of syntax error

Cannot modify header information - related to MySQL query [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Headers already sent by PHP
I fixed this problem, but since I don't understand what caused it, I can't be sure it's really fixed.
My PHP site displays the latest activity on the home page, before you log in. I recently modified the logic to include more types of activity. It looked like it worked, but I got the following error upon logging in:
Warning: Cannot modify header information - headers already sent by
(output started at header.php:75)
in index.php on line 26
I think this error message is misleading, because the way I fixed it was by changing "LIMIT 10" to "LIMIT 9" in the MySQL query that gets the activity to be displayed on the home page.
public function getLatestActivity()
{
$sql = "SELECT 'Debate' AS Type, d.Debate_ID AS ID, CONCAT('debate.php?debate_id=', d.Debate_ID) AS URL, d.Title, d.Add_Date
FROM debates d
UNION SELECT 'Discussion' AS Type, d.Discussion_ID AS ID, CONCAT('discussion.php?discussion_id=', d.Discussion_ID) AS URL, d.Title, d.Add_Date
FROM discussions d
UNION SELECT 'Petition' AS Type, p.Petition_ID AS ID, CONCAT('petition.php?petition_id=', p.Petition_ID) AS URL, p.Petition_Title AS Title, p.Add_Date
FROM petitions p
ORDER BY Add_Date DESC
LIMIT 9";
try
{
$stmt = $this->_db->prepare($sql);
$stmt->execute();
$activity = array();
while ($row = $stmt->fetch())
{
$activity[] = '<span style="font-size: x-large"><strong>Latest activity</strong></span><br /><span style="font-size: large">' . $row['Type'] . ': <span style="color: #900">' . $row['Title'] . '</span></span>';
}
$stmt->closeCursor();
return $activity;
}
catch(PDOException $e)
{
return FALSE;
}
}
And here's what I'm doing with the data returned by that function. It loops through the array and shows a new item every 4 seconds.
<?php $latest_activity = $pdb->getLatestActivity(); ?>
<script type="text/javascript">
var activity = <?php echo json_encode($latest_activity); ?>;
var index = -1;
$(function()
{
getLatestActivity();
});
function getLatestActivity()
{
index = (index + 1) % activity.length;
var div = document.getElementById('divLatestActivity');
if (index < activity.length)
{
div.innerHTML = activity[index];
}
setTimeout("getLatestActivity()", 4000);
}
</script>
Why did changing "LIMIT 10" to "LIMIT 9" fix the "cannot modify header information" problem?
In PHP, if you use the header() function (i.e. header("Location:login.php"); to redirect to the login.php page), you must do it before any other code that might output text to the browser.
//this will CAUSE a warning
echo "Login now";
session_start()
header("content-type:text/html");
header("cache-control:max-age=3600");
However...
//this will NOT CAUSES a warning
header("content-type:text/html");
header("cache-control:max-age=3600");
session_start();
echo "Login now";
So comb through your code that executes any session_start() or header() directives and make sure there are no echo ""; before them. If you have any MySQL warnings that are thrown out onto the page before your session_start() or header() that will also cause this warning.
You need to check if some output has been done in the form of echo, print or HTML. If this has been done, then header("LOCATION: login.php") will throw an error.
A way to over come this is using output buffering.
ob_start();

Categories