Konstantin Schubert
Konstantin Schubert

Reputation: 3356

How to to add php-statements in an html file?

I tried to add the command <?php session_start(); ?> before the first line of an index.html - file. Aside from that, the file only contains html statements. When I noticed that the php-code was not getting interpreted, I changed the ending of the file to index.php, which solved that issue.

Now I am wondering whether what I did is an ugly hack or actually an accepted practice? Is it ok to add a php-prefix to a file that is otherwise html?

Also, I am sadly still getting the following error: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent . In case my above practice is fine, what causes this error?

Upvotes: 0

Views: 116

Answers (2)

GFargo
GFargo

Reputation: 383

Keep in mind that .php Files should parse through both PHP & HTML Tags. Placing a tag at the begining of the document is a common practice.

Also like @markus-tharkun mentioned - it really depends on what you are trying to do with the PHP code. If you just wanted to put a Timestamp in a Header of your HTML Doc it could be as simple as the following:

<h2>
  <?php echo date('l jS \of F Y h:i:s A'); //Prints Date inside the H2 Tag ?> 
</h2>

Once again, i could put this code anywhere inside my Tag and it would print out the current date using PHP. PHP can play interesting tricks with scope therefore it should always be paid close attention to.

Upvotes: 1

Dai
Dai

Reputation: 155728

What you did is what you're meant to do.

Filesystem-based webservers, such as Apache and IIS (for the most part) interpret a requested file based on its file extension and process it accordingly. When a user requests a .html file then the server will return the raw bytes of the file, whereas if the user requested a .php file then it will run it through the PHP module or CGI program which generates the desired output.

You can configure your webserver (assuming you're not on a shared hosting service) to always process .html files with PHP, but it's better to hide implementation details in your URIs and use URL Rewriting instead (something Apache and IIS7+ have full support for).

With respect to the session_start() error you're getting - that's because session_start has to be called before anything is output to the client, which means that the <?php session_start() ?> part has to be at the very start of your document with no plaintext or blank-lines before it. You can have some PHP code before the call, but be sure that the PHP code is not sending any responses or headers.

Upvotes: 1

Related Questions