Why is 'require' PHP function rearranging my HTML? - php

I have implemented a verification system for my website, where every time the user requests a page, a PHP script is run that checks if the user is currently logged in. If not, then the user is redirected to a login page. This is done by having a single "redirect.php" file which is 'required' by each page, using the syntax <?php require 'redirect.php' ?>.
Every page that has the above statement has all the code in the <head> element removed and put at the beginning of the <body>. Also, a HTML entity is inserted in quotes: " ".
The result is that in DevTools my HTML looks like this:
Whereas, in my editor, it looks like this:
<?php require 'redirect.php' ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<h1>Stuff</h1>
</body>
</html>
I know that the code inside the 'redirect.php' file is irrelevant because even if I empty that file I get the same odd behaviour. I've checked for invisible unicode characters that somehow made it into my code; there aren't any.
Does anyone know what this is and how to fix it?
If it helps, I'm with InfinityFree hosting.

 is a Byte Order Mark.
The file you are requiring must be saved in a format that starts with one (typically UTF-8 With BOM).
It gets inserted into your output stream as a character. Since it isn't a character allowed before the start of the body element it implicitly starts the body element (as well as the html and head elements) and gets inserted at the start of it.
The DOM inspector then normalises it as an HTML entity because it isn't a visible character.
When the rest of the document is parsed, some of what you intended to be put in the head is backfilled through the HTML 5 error recovery rules.
Check your editor and make sure the file format you save the PHP files in doesn't include a BOM.

As it has been answered,  represents a Byte-Order-Mark (BOM). Quentin was so kind to clear this up early.
And as you have found out already, <?php require 'redirect.php' ?> is inserting it.
However with what you experience there is more. You've not shared your browser version, but a single BOM alone at the top of redirect.php would not result in the problem you were able to demonstrate (with a common browser).
Here's the differentiation:
It is true that there is an insertion of the BOM. However if it would be at the very beginning of the HTTP response body (the top of the document), it would not be shown in the browser nor via the devtools / in the DOM.
Next to the BOM there must be as well at least one additional character. And it must be positioned before a BOM.
That could be for example another BOM character (or some other whitespace or any other character).
This is important to note when you're looking forward to troubleshoot the issue, as it is most likely not redirect.php (alone), or it must not be at its very beginning, but somewhere there-in, e.g. another require/include.
This could result in a cleaning strategy that orders things differently:
Fix the other files first and then when the browser shows clean, fix the first file (so redirect.php second-last and then the file that has the <?php require 'redirect.php' ?> statement last).
(only an example, this depends on the concrete files in use which I don't know. point in case is it might appear clean by accident)
It might be fine in your usage scenario to keep the one BOM. Personally I would not suggest that, but with the browses and interoperability requirements you have, this can vary.
https://www.w3.org/International/questions/qa-utf8-bom.en.html
http://www.unicode.org/faq/utf_bom.html#bom5
https://www.w3.org/International/questions/qa-byte-order-mark#problems

When I open open this code sample in VSCode and use DevTools the format never changes. Try wrapping your required file in quotes and parenthesis like the example below.
<?php require("redirect.php")?>

DevTools shows the interpreted code. It's possible that your free host inject some ADs into your code. Look at your real source code with CTRL+U in your browser. This should show whats going on

Related

Immovable Meta tag inside background image style

I've run into an interesting problem that I've found no information about. I'm using cPanel's text editor for edits.
I had a header tag for months, unchanged, working perfectly, that looked like this:
<header class="cat-header" style="background-image:url('<?= $bgImg ?>')"></header>
Suddely, without making any change in the tag, the header images were replaced by the characters ')"
Looking into it I found the following:
<header class="cat-header" style="background-image:url('<?= $bgImg ?><meta http-equiv="Content-Type" content="text/html; charset=utf-8">')"></header>
Since I'm not the only one with access to the website's code, I suspected someone else added the <meta> tag for optimization purposes, or something else. I moved it outside of the <header>, saved the file, checked the website - it works again.
But just as I close the file, the meta tag moves back inside the <header>. The thing is unstoppable, changing it has no effect (tried replacing literal quote characters with "), copy-pasting it removes the duplicate. Everything else is saved correctly, the only way to remove it is to remove the <header> entirely.

Which naming convention is correct for included HTML code fragment files?

I do have an index.php file which includes different parts of the page via PHP.
For example this includes the <head> section of the HTML page into the index.php file:
<!doctype html>
<html>
<head>
<?php include($_SERVER['DOCUMENT_ROOT']."/PATH-TO-FILE/head.php"); ?>
</head>
<body>
...
</body>
</html>
The content of "head.php" may be something like this:
<meta charset="utf-8">
<title>Title of page</title>
<meta name="description" content="Description text...">
...
<link rel="stylesheet" href="stylesheet.css">
...
and so on...
Technically "head.php" is not a PHP file because it does not contain any PHP code. Neither is it a valid HTML document. It is just a HTML code fragment.
Until now I have always named these HTML code fragment files either *.html or *.php.
My question is whether this is correct or not?
Is it advisable to not give it a file extension at all? Instead of "head.php" simply "head"?
Please keep in mind that certain directives can be set in the server's .htaccess file concerning the caching and expiration of *.html and *.php files. Removing the file extension and renaming it from "head.php" to "head" may exclude it from the mentioned directives in the .htaccess file.
While searching I found this question here on StackOverflow:
What extension should I use for files containing fragments of HTML
But that question was asked 6 years ago and there are so many different file extensions mentioned there, it's difficult to say which one to use.
Can anyone give an updated answer concerning this issue?
If you use include, I'd strongly recommend using *.php. include executes the code in it, even if it's raw HTML. (in that case it's just output without much further processing)
Hence, use *.php for files output that way. (Else you might get also bad highlighting in editors when using <?php one day in it for some reason; also, if someone opens the *.html file directly, he'll see the raw code then)
In case you are using e.g. readfile(), then use *.html to highlight that it is raw HTML code only, nothing ever will be executed.
It basically depends on how you include the file.
P.s.: To no extension at all. Not really advisable, that's usually what you use for binary files and directories. Note that extensions really just are to give you oversight what happens.
I would leave as php. Your are including that file with php. Itself head file is useless as its own.
What if you add some php to that file, for further development? Add php extension back not an efficient lifecycle.
More importan is where you store those files. Putting them under a templates folder will tell to anyone, that those files are templates.

codeigniter letter at start of every page

I'm working on a website, which I have temporarily hosted here.
You'll notice the mystery letter 'a' I'm getting at the start of every page. I've gone through all the php files (controllers, views, models) and cannot locate where this letter is coming from. Another curiosity is that all the head content is not residing in the head tags when inspected with Firebug. It appears in the body tags, however it still functions correctly. Are these two issues related?
The only thing I have found from searching the internet is that perhaps some files have been saved as ANSI instead of UTF-8. I've tried 'saving as' all my php files as UTF-8 using my editor, but it is a very slow process. Any help debugging this situation would be appreciated.
EDIT- thanks for your response, #erman-belegu. It doesn't seem to be in any controller. For instance, I've set up a 404 redirect, with its own controller and view. The view looks like this:
<!DOCTYPE html>
<html>
<head>
<meta name="description" content="No Page">
</head>
<body>
<h1>No page dude.</h1>
</body>
</html>
But when inspected with firebug, it looks like this:
<html>
<head></head>
<body>
a
<meta content="No Page" name="description">
<h1>No page dude.</h1>
</body>
</html>
I have encoded everything using UTFCast, and am still experiencing the same issue. Any help welcomed.
You see the head inside the body tag because the mysterious "a" is the first character of your output. It's put inside the body tag by the rendering engine of your browser, or by firebug.
If you find the cause of your "a" - almost certainly some content outside PHP tags - the head will return to normal in firebug.
Searching for the "a" is tricky.. I'm not sure how large your codebase is, but I'd say start by exiting the process right before output is sent. You should see only the "a". Then move the exit step by step untill your "a" disappears, and you'll find it.
Check your controllers at start or maybe any print somewhere. Check all your code on these pages because you print these "a ".
Also use UTF-8 without BOM. But, I think that you print it accidentally and dont think that this happens for any other reasons.

php file only works if file begins with php code

I am new to php and wonder what am I missing about the rules for interleaving html and php code.
This is now the second time I run into a situation where a php file only works if my php tag is at the beginning of the file. This is not the case for all my files. I wonder why that might be.
Here is an example:
My file structured as follows works just fine:
<?php
... my php code
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>Authentication</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<div id="container">
</div>
</body>
</html>
But when I move that html block at the top (which is what I want ultimately since I use some echo statements in my php code), and leave only the following at the bottom:
</div>
</body>
</html>
then some portion of the php code do not work. For example, my setcookie function no longer sets a cookie (though it does not error out) while I can still run sql queries or echo statements just fine. I ran into a similar issue with a complete different code taken straight out of a tutorial site: the example would only work if the code started with
Some operations (like writing a cookie) must be performed by PHP before any output is sent to the browser, because those operations involve setting response headers (which are always sent before any other content). That seems to be the problem here.
Per the documentation:
setcookie() defines a cookie to be sent along with the rest of the
HTTP headers. Like other headers, cookies must be sent before any
output from your script (this is a protocol restriction). This
requires that you place calls to this function prior to any output,
including <html> and <head> tags as well as any whitespace.
Give those links a look, they will explain something, and never forget to ask here on stackOverflow
http://www.w3schools.com/php/php_cookies.asp
http://php.net/manual/en/features.cookies.php
http://www.w3schools.com/php/php_sessions.asp
http://it.php.net/manual/en/session.examples.basic.php
Answering your question, you can place the tag practically anywhere in the html code, as long as it's structured correctly.
However, there are some functions in php requires that no output is made before it is executed, like setcookie, setsession, header .. etc.
The output here is either;
a. an echo statement in php code.
b. an html code before the tag that the function is in.
and as for that some code in php doesn't work.
Usually, if you have any problem in your code, that php code doesn't work. So, it's better to check if it syntax correct or not before that.

DOCTYPE is not rendered if declared in PHP include?

So far i've declared for example
>test.php
<!DOCTYPE HTML>
<html>
...
and in index.php
>index.php
include 'test.php';
...
Works fine on all except IE8, as far as I know, will render the document in quirksmode. Any idea why?
Use the following process:
Check if <!doctype html> is not the first line; this will trigger quirks mode
Check if the encoding is UTF-16; this requires a byte order mark
Check the file encodings of the HTML documents to make sure they match
Flush the buffer to output the doctype
References
Quick Guide to UTF-8
Speed Up Your Website With PHP Buffer Flushing
PHP5 Changelog
The Notepad file encoding problem, redux

Categories