简体   繁体   中英

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 , echo es, HTML code, print s 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM