1

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.

Szymon Toda
  • 4,454
  • 11
  • 43
  • 62

4 Answers4

3

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>';
Alex Quintero
  • 1,160
  • 10
  • 21
1

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

Community
  • 1
  • 1
Szymon Toda
  • 4,454
  • 11
  • 43
  • 62
0

It's happening because output has been sent already. You can't edit Header Information when you have echo'd anything!

Frederik Spang
  • 3,379
  • 1
  • 25
  • 43
0

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.

Community
  • 1
  • 1
Abdessabour Mtk
  • 3,895
  • 2
  • 14
  • 21