Search code examples
phphtmlsessiondoctype

Problem with <!DOCTYPE html> in PHP with session_start() ... Apache configuration


I have faced an issue when I uploaded my source code to a hosting.

In my HTML/PHP pages, I have some code like the following one:

<!DOCTYPE html>
<html lang="es">

<?php
session_start();
....
....
?>

If I run the page in my localhost, with display_errors=On ... I do not get any error for the session, but if I run in the hosting (with same PHP version), I get this error:

Warning: session_start(): Session cannot be started after headers have already been sent in

This error doesn't allow me to get $_SESSION variable, so I can't continue.

I'm trying to replicate in my local environment, but I can't configure the server to behave in the same way.

I have identified how to solve it (moving <!DOC....> after the session_start() command), but I would like to understand how to replicate this issue in my environment.

Is there any PHP.ini or Apache configuration that I'm missing in my local environment?

Thanks in advance.

I tried to change parameters in PHP.ini but I was not able to replicate the behaviour of the hosting environment.


Solution

  • <?php
    session_start();
    ?>
    <!DOCTYPE html>
    <html lang="es">
    <head>
        <meta charset="UTF-8">
        <title>My Page</title>
        <!-- Other head elements -->
    </head>
    <body>
        <!-- Your content here -->
    </body>
    </html>
    

    try this code.

    Note:

    1. The session can not be started after headers have been sent. It occurs when the session_start() function is called after any output has been sent to the browser. This includes HTML, white space, or echo statements sent before calling session_start().
    2. Ensure no spaces or lines exist before the <?php tag at the top of the file. Even a single space or line break can cause headers to be sent prematurely.
    3. Ensure no closing PHP tags (?>) at the end of your PHP files. Leaving the PHP tag open at the end of the file can help prevent accidental whitespace or newlines from being sent to the output.