avoid output buffering error in serevr - php

I am developing w web site. Here I have included a thumnail page. It’s working well in my localhost. But when I uploaded its show me an error see
Warning: Cannot modify header information - headers already sent by (output started at /mydomain/demo1/admin/thumbnail.php:50) in /mydomain/demo1/admin/act-addVehicle.php on line 191
my code
if(move_uploaded_file ($tmpName,$path.$actual_image_name)){
$succ=1;
chmod("$add",0777);
$imgSucc=1;
//strt image thumbnail
include("./thumbnail.php");
// ends
}else{ echo "Failed to upload file Contact Site admin to fix the problem";
exit;}
How I avoid this error
is there any settings in php ini ?
does anyone know ?
please reply

Without seeing thumbnail.php's code its hard to tell exactly what's happening, but basically its outputting something before act-addVehicle.php on line 191 is setting another header.
Most likely a single space at the end of the script. Check after ?> perhaps line 50 if just after.
You could wrap the include('thumbnail.php') into an ob_start() and ob_end_clean() but that will not solve the underlying issue of outputting before setting a new header.

This kind of error typically comes from having a closing php tag in one of your file that is followed by some white space. This white space is sent to the browser when the script is executed BEFORE it executes a "header()" function.
For example, I would not be surprised that your thumbnail.php or act-addverhicule.php ends with a "?>" tag and that there is some white space after it.
As a good practice, it is always better to remove all closing php tag (the "?>") at the end of your files to avoid these kind of problems...

of course. use ob_start funciton somewhere in the beginning of your code

Related

Find the root cause of already sent headers in php when entire class is referenced

fellow members and visitors.
Please imbue me of your knowledge and allow me to be enlightened by your expertise by answering this question or providing me a path of exploration.
My simple mind cannot has exhausted the possibilities it was aware and would really like to begin to understand what to do in such a situation should it arise again.
Everything begins with a :
Warning: session_start(): Cannot send session cache limiter - headers
already sent (output started at
/path/to/site/wp-content/themes/theme_name/inc/general/class-Upbootwp_Walker_Nav_Menu.php:125)
in
/path/to/site/wp-content/plugins/wp-php-console/includes/class-wp-php-console.php
on line 142
Here is the exact ubootwp_Walker_Nav_menu.php class for reference.
I am used to having a precise line number in these kind of error but this time, I get no such indicator (I just get the last line, but there's nothing there except the end of the class.
From my understanding, something in that class instantiate a session and when the Worpdress php console plugin try to do it, it crashes as headers were already sent by that class.
I did add the following
error_reporting(E_ALL);
ini_set('display_errors', 'On');
to get the error statement, as I would previously only get a 'error 500'.
I cannot see anything wrong with that class (no obvious echo, print, ob_start).
Does some of you have any clue on how I would go in trying to find the root cause of it ?
Any insight will be appreciated.
edit:
ubootwp_Walker_Nav_menu.php is a UTF-8 file (No BOM)
No hidden characters or anything before php opening tag.
No php closing tag at the end of the file
No echo,ob_start,print or anything obvious that I can see that would initiate a session.
Thoughts:
The error message explicitly states that the error occurs in the php console plugin (which effectively wants to start a session) because the ubootwp_Walker_Nav_menu.php has created the session. Is it possible that the error message is not accurate or does that unequivocaly means that this class is the error ?
Edit 2:
Actually, I thought it was not relevant but I had another notice before the header sent which was:
Strict Standards: Declaration of Upbootwp_Walker_Nav_Menu::start_lvl() should be compatible with Walker_Nav_Menu::start_lvl(&$output, $depth = 0, $args = Array) in /home3/i8h1o2r7/public_html/dev/wp-content/themes/axial/inc/general/class-Upbootwp_Walker_Nav_Menu.php on line 130
This was very relevant to the problem as this was the cause of the "header sent". I fixed the declaration from the class which was not causing an issue before and it fixed the PHP console plugin "session already created" issue from the initial message.
The session has to start before ANY html has been sent to the browser. You can turn on output buffering but, it's going to cause problems if run on a server without output buffering enabled ... Doesn't WP start a session anyway?
I found the solution to this problem from Magnus comment reference to another similar question. In my particular case, the header were sent by another notice that was caused by a signature mismatch and outputting headers early.
Strict Standards: Declaration of Upbootwp_Walker_Nav_Menu::start_lvl()
should be compatible with Walker_Nav_Menu::start_lvl(&$output, $depth
= 0, $args = Array) in /home3/i8h1o2r7/public_html/dev/wp-content/themes/axial/inc/general/class-Upbootwp_Walker_Nav_Menu.php
on line 130
Once that specific error was fixed, headers were not outputted anymore and the second error (initial question) vanished completely.

Why am I getting Warning: Cannot modify header information - headers already sent by (output started at ...)?

I'm reusing a search PHP script, but I get this error:
Warning: Cannot modify header information - headers already sent by
(output started at /Volumes/Work/MAMP/PC
Flag/php_scripts/conection.php:2) in /Volumes/Work/MAMP/PC
Flag/includes/search.php on line 63
line #2 conection.php:
$con = mysqli_connect("localhost", "root", "root", "cms");
line #63 search.php:
header('Location: search-page.php?keywords=' . urlencode($keywords));
What is the problem?
Also I need to mention that the script doesn't redirect me anymore to search-page.php as it should.
When you use header() it shouldn't be any output before, not even a space, you have two solution:
Dirty one
Use ob_clean() before the header to clean the output buffer
ob_clean();
header('Location: search-page.php?keywords=' . urlencode($keywords));
Correct one
Search in your script and your request route for any output, content before <?php, echoes, HTML code, prints or spaces after the ?> are usually the cause of this ;)
Debug
This snippet may help you to find out where is the output in your code:
var_dump(ob_get_contents());die()
Put this before line 63
Javascript workaround
In the case that everything fails, you have another option, use javascript to redirect, although I recommend you to keep trying without get to this point :)
Replace the header(...) with this:
echo '<script>window.location.href="search-page.php?keywords=' . urlencode($keywords)) . '";</script>';
You have send a header already as error states. Please investigate when and how headers are sent.
That usually happens when something is printed before that line to output buffer.
Make sure that you are using UTF-8 without BOM document encoding - BOM sign is invisible in most text editors yet can be interpreted as content which forces sending HTTP headers.
You can debug your output with Output Control function
It's happening because output has been sent already. You can't edit Header Information when you have echo'd anything!
It seems like the error you're getting is because an output have been occured.you can fix it with this code :
if (headers_sent()) {
ob_clean();
}
Just found this detailed answer.

Headers already sent error in CakePHP app [duplicate]

This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Closed 9 years ago.
function new_photo()
{
if( !empty($this->data))
{
$this->data['Photo']['showcase_id'] = $this->Session->read('CurrShowcase.id');
$this->data['Photo']['added'] = date("Y-m-d H:i:s");
$this->Showcase->Photo->save($this->data);
$flasher = 'Photo uploaded successfully';
$flasher .= '<br/><img src="' . $this->data['Photo']['thumbnail_url'] . '"/>';
$this->Session->setFlash($flasher);
//$this->redirect(array('action'=>'sc',));
}
}
I have a Showcase Controller in my CakePHP app, and a new photo form to submit new photos. Whenever I uncomment the last line that redirects after the data is saved, I get this error:
Warning (2): Cannot modify header information - headers already
sent by (output started at D:\.....
Even if I get this error, $this->data still gets saved properly in the database. However, if I comment the redirect line as shown above, everything works fine and error-free. I HAVE checked for blank spaces around the tags, so I'm pretty sure it's not that.
Any ideas?
Edit:
commenting out the setFlash statement does not fix the problem.
Change your debug mode to 0 to make sure it's not a notice/warning being generated prior to the redirect. Also, you might want to tighten up your processing section to (be paranoid and) ensure that it's not using invalid indexes, as well as anywhere else throughout the application flow for that action to make sure you're not getting any ouput (if it works when you change debug to 0).
Is there a debug statement somewhere that you're not showing us?
You may be up against an invisible UTF-8 BOM character somewhere. Check your text editor settings whether it saves your files with BOM or without.
I'd check for whitespace in the models. Anyone of them. That was one of the gotchas I hit.
Either this code outputs something to the browser, or you have a whitespace after ?> in the end of the file (or any other included file). The whitespace is sent to the user thus sending http header.
I'm assuming setFlash outputs something to the browser?
If whitespace before or after your <?php ?> tags isn't your issue you might have to try passing 'null' for the 'layout' parameter of setFlash();
i.e.
$this->Session->setFlash($flasher, null);

Unbelievable PHP script won't echo out string

I have a test.php script which contains this:
<?php echo 'test'; ?>
When I point to it via my browser, it works and prints out "test" as expected.
I have another script which I am trying to test but however, it is ignoring all my echos! I thought I would put an echo right at the top as this will surely work, but when I get to this script via POST request from a form. It does not even echo out what is at the top of the line:
<?php echo 'START START START';
error_reporting(E_ALL);
I even point to from my browser and still no output?
What the hell is going on?
Update
The error log shows this :
PHP Parse error: syntax error, unexpected T_ECHO in /var/www/tester/convertor.php
But the echo is at the top of the line. I am going to set diaplay errors.
You have a parse error, so the script isn't even executed. So it's expected that it won't output anything.
The parse error can be for any echo in the script. It may be because of an "echo" statement after a line missing a semicolon, for example.
Things to try:
Check your error log
Check the headers (is it coming back 404?)
Make sure you view-source: don't just look in the browser
Delete everything except the echo. If it works, add things back a bit at a time until it breaks.
Load your script in a hex editor and make sure there aren't any weird characters in there
Are you including this file from another file? If so, check the other file too. Watch out for output buffering.
Put exit; after the echo start start start and see if that works. Look in the apache error log for clues. Comment out the rest of the PHP code in the file and see if it works then...
UPDATE
I have had this when copy pasting white space from a browser sometimes - e.g. copy/pasting some code from a web page. Sometimes weird control characters get embedded invisibly in the white space, and I find that deleting the whitespace and re-entering it fixes it. Did you copy paste anything into this file?
Are you hosting this page on a server with PHP installed?
If you just have a .php file on your hard drive somewhere and open it in a web browser, it won't work. You need to be running a web server with PHP extensions and access the file using the HTTP or HTTPS protocols.
On a similar note to this i have seen alot of scripts throw errors like this when they have come from developers on windows (i'm on linux).
I have to go to the start of the php file and hit delete a couple of times to get rid of some invisible characters before the script will run.
You're missing the ending ?>
<?php
echo 'START START START';
error_reporting(E_ALL);
?>

PHP fails to setcookie

I'm a PHP virgin (first day), so please type slowly.
I have a number of images, bg_001.jpg, bg_002.jpg, etc., which I want to rotate through each time the page is refreshed. I tried this:
if (isset($_COOKIE["bg1"])) {
$img_no = $_COOKIE["bg1"] + 1;
} else {
$img_no = 1;
}
$filename = 'bg_' . sprintf("%03d", $img_no) . '.jpg';
if (!file_exists("/img/" . $filename)) {
$img_no = 1;
$filename = 'bg_' . sprintf("%03d", $img_no) . '.jpg';
}
setcookie("bg1", $img_no, time() + 86400);
print '<img src="img/' . $filename . '" alt="" height="175" width="800"> ';
Instead of a cookie I get a
Warning: Cannot modify header information - headers already sent by (output
started at /home2/.../about.php:7) in /home2/.../about.php on line 31
Line 31 being the line with the setcookie. I already found pointers about PHP having trouble with Unicode's BOM, but I have no idea how to fix it (if it is the problem here in the first place).
So, to make it official (and avoid a "not a real question" label), how do I fix this? :-)
Constructive criticism on my code is welcome too.
epilogue:
Seemed like a common newbie error: several answers toward the same solution within fifteen minutes. Thanks guyz/galz.
So I moved everything except the print to the start of the file, and indeed: fixed.
cookies can only be sent, if there are no information sent prior. This means that the first thing in your PHP file has to be <?php, and nothing can get before that part (not even the dreaded UTF-8 BOM), because if something is before the first <?php (like <html>), then php will send those data for the browser and after data is sent you can't use setcookie. Refactor your code to look something like this:
<?php
(...)
setcookie(...)
(...)
?>
<HTML>
(...)
</HTML>
And double check that editors like notepad didn't put any UTF-8 BOM signatures before the first <?php in the file.
With HTTP your header (request/response info) and Content (actual textor binary content) are set separately and Header must precede the Content.
Setting a cookie actually adds a command to the header response, so any modifications to the cookie need to happen before you start outputting any content.
Move all your code that references your cookie before the opening html element on your page and you should be ok.
You might also find it easier to use sessions instead of manipulating the cookies themselves. the session_start() still needs to come before any other content but it makes it easier to store data structures, etc.
have a look at http://php.net/session_start
To get around this without major code changes, use Output Buffering like so,--
<?php
ob_start();
// ... my code here
?>
<html></html>
<?php
// ... end of the file
ob_end_flush();
?>
The error/warning you got says it all: headers are already sent
This means that output has been already sent to the browser before the setcookie() method was called.
As you can understand cookies "should be set" before any output is send to the browser.
So check line 7 at about.php. You should have html code there or you might have a call to print or echo.

Categories