Jump to content

Is there any problem if I require_once a file at top of every php page?


colap

Recommended Posts

    <head>
        <meta charset="UTF-8">
        <title>myproject</title>
        <link rel="stylesheet" type="text/css" href="style.css" />
        <script type="text/javascript" src="jquery-1.11.3.js"></script>
        <script type="text/javascript" src="javascript.js"></script>
    </head>

That above head is common to every page. I want to put that in a separate head.php file. Then I want to require_once('head.php'); at top of every page. Is there any problem with this? I don't want to copy and paste that same head in every page.

Link to comment
Share on other sites

Another option is you create your typical entire HTML page, but you include placeholders to insert custom HTML.  You "could" then create custom PHP script to insert your custom content, but don't, and instead look into http://twig.sensiolabs.org/http://www.smarty.net/, etc, etc.


<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>myproject</title>
        <link rel="stylesheet" type="text/css" href="style.css" />
        <script type="text/javascript" src="jquery-1.11.3.js"></script>
        <script type="text/javascript" src="javascript.js"></script>
    </head>
    <body>
        {{ content }}
        <div>Your footer on every page</div>
    </body> 
</html> 
Link to comment
Share on other sites

If you do the inclusion on top of the script, that's a problem, because PHP cannot start/resume a session or send cookies once there's output (unless buffering is enabled).

 

And as NotionCommotion already said, you should really use a template engine. Assembling HTML documents from various PHP scripts is 90s technology. Yeah, it kinda works, but it's cumbersome, inflexible, insecure and just hopelessly outdated.

 

Modern template engines are far more powerful. You can define a base document and then override the page-specific parts. You can even change the title or add new CSS/JavaScript links to the head, which is not possible with a plain require_once.

Link to comment
Share on other sites

...insecure...

 

Out of curiosity, what is inherently insecure about putting HTML tags, like the OP posted, and importing it with require_once()?

 

 

You can even change the title or add new CSS/JavaScript links to the head, which is not possible with a plain require_once.

 

A file imported through require_once() can be dynamic. For example, the imported file could contain a template class. The class can be set to customize the <head> tag content or any other part of the template.

 

Note that I'm not arguing for or against third-party template engines. I'm just addressing some generalizations.

Link to comment
Share on other sites

Reading through your (Jacques1) response again, I likely agree with most of your points.

 

 

Based on the following:

 

...with a plain require_once.

 

I imagine you are talking about importing a text file that only outputs the HTML tags. That isn't the most flexible way of doing things.  :happy-04:

 

 

I am still curious about the potential security issues.

 

Link to comment
Share on other sites

 

Another option is you create your typical entire HTML page, but you include placeholders to insert custom HTML.  You "could" then create custom PHP script to insert your custom content, but don't, and instead look into http://twig.sensiolabs.org/http://www.smarty.net/, etc, etc.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>myproject</title>
        <link rel="stylesheet" type="text/css" href="style.css" />
        <script type="text/javascript" src="jquery-1.11.3.js"></script>
        <script type="text/javascript" src="javascript.js"></script>
    </head>
    <body>
        {{ content }}
        <div>Your footer on every page</div>
    </body> 
</html> 

 

 

If you do the inclusion on top of the script, that's a problem, because PHP cannot start/resume a session or send cookies once there's output (unless buffering is enabled).

 

And as NotionCommotion already said, you should really use a template engine. Assembling HTML documents from various PHP scripts is 90s technology. Yeah, it kinda works, but it's cumbersome, inflexible, insecure and just hopelessly outdated.

 

Modern template engines are far more powerful. You can define a base document and then override the page-specific parts. You can even change the title or add new CSS/JavaScript links to the head, which is not possible with a plain require_once.

 

 

Is depending on third party library good? Isn't twig written in php? So why can't we make something like twig with plain php? {{ content }} , isn't it similar to require_once('content.php');? How did twig make this? What's the php code behind {{ content }} by twig?

 

If you do the inclusion on top of the script, that's a problem, because PHP cannot start/resume a session or send cookies once there's output (unless buffering is enabled).

Can you explain this with example code? I'm also curious to know about security issues of require_once('content.php');

Edited by php-coder
Link to comment
Share on other sites

Twig is a completely separate language designed specifically for templating. Compared to PHP, it has a much more compact syntax, several security features (like auto-escaping and sandboxing) and intelligent templating techniques like inheritance and macros.

 

For example, a base template would look like this:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>{{ title }}</title>
        {% block head_items %}
            <link rel="stylesheet" href="res/style/main.css">
            <script src="res/js/lib/jquery-1.11.3.js"></script>
            {% block additional_head_items %}{% endblock %}
        {% endblock %}
    </head>
    <body>
        {% block content %}{% endblock %}
    </body>
</html>

This allows you to

  • safely insert data (all variables like the title are automatically HTML-escaped)
  • append new scripts or styles to the ones you already have by default
  • completely override the default head elements in case you have a page that doesn't need jQuery or has a special style
  • simply insert the page content into the body element (no need to assemble the various document parts yourself)

A concrete page template might look like this:

{% extends "base.twig" %}

{% block additional_head_items %}
    <script src="res/js/lib/uploader.js"></script>
{% endblock %}

{% block content %}
    <p>This is the content of the example page</p>
{% endblock %}

This appends an uploader script to the document head and then inserts the page content into the body.

 

PHP has none of those features. Yes, Twig happens to be implemented with PHP, but that doesn't mean it's “just PHP”. This is like saying that we might as well use C instead of PHP, because PHP happens to be implemented with C.

 

(Ab)using PHP as a template engine is inherently insecure for two reasons. First, even the tiniest HTML fragment is technically a full-blown PHP application which can do just about anything: read and change files on the server, access the database, load arbitrary code (possibly even from a remote location), perform network operations. This is completely unnecessary and a huge risk, because if any of those mini-applications gets compromised, you're screwed.

 

Secondly, PHP has no concept for systematically escaping data. It assumes that the programmer escapes everything by hand and never makes a mistake. We all know this is unrealistic. In the real world, many programmers have never even heard of escaping, and those who do know it constantly screw up. Just look at the security history of any PHP application, and you'll see the same cross-site scripting vulnerabilities over and over again.

 

Twig has a far more realistic and robust approach: If you use sandboxing, your templates can only do what they're supposed to do (i. e. generate HTML markup). And if you use auto-escaping, you can eliminate the vast majority of XSS vulnerabilities.

  • Like 1
Link to comment
Share on other sites

Is depending on third party library good? Isn't twig written in php? So why can't we make something like twig with plain php? {{ content }} , isn't it similar to require_once('content.php');? How did twig make this? What's the php code behind {{ content }} by twig?

Can you explain this with example code? I'm also curious to know about security issues of require_once('content.php');

 

Yea, that is what I said for WAY too long.  Yes, you could create your own PHP based library and mimic a really good 3rd party library.  And you can even review the twig (or whatever) source code for inspiration.  But do you have the time and will you do so?  If you are like me, you will make a decent (at least in my head) template engine which addresses your specific needs.  But then those needs may change.  If you have a very niche need, maybe spin your own.  But if you are just rendering a webpage (and a good template engine can do more), then look into a 3rd party library.

 

PS.  I feel that PHP should add modern template functionality using a lower level language in the future.

Link to comment
Share on other sites

@Jacques1,

 

You also told about cookies and sessions problem with require_once('content.php'); Can you please explain this also with example code? And what is that php-sandbox? Isn't depending on external third party library like twig a problem when you upgrade your project? Is it possible to avoid using template library or is it possible to do the same functionality with only plain php instead of using twig?

Edited by php-coder
Link to comment
Share on other sites

You also told about cookies and sessions problem with require_once('content.php'); Can you please explain this also with example code?

 

You can try it yourself.

<?php

echo 'Output from required file';

session_start();

Unless you have output buffering enabled, the session_start() call will fail due to the previous output. HTTP messages (which is what PHP sends to the browser) have headers on top and the content below. As soon as you send the content, it's no longer possible to go back and add headers for cookies or other purposes.

 

 

 

And what is that php-sandbox?

 

I'm talking about Twig sandboxing. It allows you to specify exactly what a template can and cannot do.

 

 

 

Isn't depending on external third party library like twig a problem when you upgrade your project?

 

Programming is all about using libraries! If your application doesn't use any library, then it's either trivial, or you're spending way too much time reinventing the wheel.

 

PHP has several package manager (like Composer) which make it very easy to include third-party libraries.

 

 

 

Is it possible to avoid using template library or is it possible to do the same functionality with only plain php instead of using twig?

 

You can avoid a lot of things. Like I said, you could replace your PHP scripts with thousands of lines of C code. But why would you?

 

Being a good programmer means choosing the right tools for the job, not limiting yourself to the most basic tools. I understand that a library like Twig can be scary at first, simply because it's something new. But it pays off. You've already decided to use jQuery instead of plain JavaScript, so why not do the same with PHP?

Link to comment
Share on other sites

The only problem I have found with Twig is its reliance at times on Symfony components, Twig is a standalone bundle but it's still a layer of Symfony framework, once you dive deeper into it beyond rendering simple stuff it can be a lot to get ones head around, particularly where forms are concerned, so then we get to the stage of the Documentation on Twigs website which tbh is ok for front end devs but needs more clarity for backend devs I feel. All that said it's good stuff though and blazing fast rendering and you can mix Twig syntax and plain old HTML in the templates and it's no issue.

Link to comment
Share on other sites

The only problem I have found with Twig is its reliance at times on Symfony components, Twig is a standalone bundle but it's still a layer of Symfony framework, once you dive deeper into it beyond rendering simple stuff it can be a lot to get ones head around, particularly where forms are concerned

I think you might be confusing how Symfony uses twig and twig itself. Twig does not require any of the symfony stack to use it for your own stuff. Twig also has nothing special with regards to how forms work. All the form stuff is part of the Symfony framework and irrelevant if you're not using it.

 

To use twig for your own non-symfony project all you have to do is download it (or add it via composer) and start using it per the getting started documentation.

Link to comment
Share on other sites

I think I've answered this question at least three times now. No, Twig is not just PHP. It's far, far more powerful than PHP when it comes to templating (see #9 for a detailed description), simply because it's a dedicated template engine.

 

Yes, both PHP and Twig can assemble HTML from files, just like both a Porsche and your old bicycle have wheels. We care about the extra features which make one tool more useful than the other. Does PHP have template inheritance? No. Does PHP have auto-escaping? No. Does PHP have sandboxing? No. It has nothing but a bunch of low-level insertion routines.

 

If you want to stick with PHP, that's OK. But if you're open to learning, I suggest you stop the silly comparisons and simply try Twig. I think the benefits are very obvious when you actually have to generate a non-trivial HTML document.

Link to comment
Share on other sites

  • 3 months later...

It's been three months since our discussion, and you still haven't made up your mind?

 

Talking about vague rumors isn't very helpful. If you want a performance discussion, there should be a) a real problem (i. e. you're working on a performance-critical application which is already highly optimized) and b) hard facts (benchmarks, results of profiling etc.). It doesn't make sense to worry about a few nanoseconds if this is your personal homepage running on a cheap shared hosts with 10 visitors per month.

 

As the Stackoverflow thread already explained, Twig templates are compiled to PHP code which is then cached. So there's effectively no overhead.

Link to comment
Share on other sites

We can use htmlspecialchars() for escaping and can skip using twig for escaping.

 

Yeah, because escaping every friggin' variable by hand is so much easier than letting the application do it. And of course programmers never screw up – the 10,000 XSS vulnerabilities in the CVE database must be fake.

 

PHP programmers really are strange. I've offered you a solution which is simultaneously better for you, better for your users and better for everybody else. But you rather keep programming like it was 1995.

Link to comment
Share on other sites

We can use htmlspecialchars() for escaping and can skip using twig for escaping.

 

Yeah, because escaping every friggin' variable by hand is so much easier than letting the application do it. And of course programmers never screw up – the 10,000 XSS vulnerabilities in the CVE database must be fake.

 

PHP programmers really are strange. I've offered you a solution which is simultaneously better for you, better for your users and better for everybody else. But you rather keep programming like it was 1995.

 

I'm doing work for a place with a tradition of NIH Syndrome and no time to reinvent any wheels.

 

When I show a view I pass an array containing only the few values that will actually be used by the view.

 

That array has htmlspecialchars run on it recursively. So every value sent to the view is escaped and stored in $cooked.

 

If I need a value to not be escaped for any reason, I have to pass it to the view as part of a second array that is stored in $raw.

 

Is this still inferior to twig's escaping?

 

Is there some other aspect of xss I'm missing?

 

Can you point me to the code in twig that actually does their escaping? I assume it's probably doing much more than just htmlspecialchars.

Link to comment
Share on other sites

It's been three months since our discussion, and you still haven't made up your mind?

 

In their defense, I do this too because I'd typically be struggling with php 4 quality code for 10 hours a day 6 days a week for months at a time and then I'd have maybe 3 days of nothing to do so I go look up some aspect of modern php, suffer from library comparison burnout, make plans to try out 3 libraries, only try out one, and then my free time is gone and I'm back to legacy work before I'm anywhere close to making a decision.

Link to comment
Share on other sites

Is this still inferior to twig's escaping?

 

Yes, because it's cumbersome, confusing and fragile.

 

Twig automatically escapes the variables when the output is rendered, which is logical (escaping is an output feature) and almost completely eliminates the need for human intervention. Most of the time, the template author doesn't even have to think about XSS vulnerabilities. You, on the other hand, escape the variables as they enter the template, so the author has to constantly decide if they use the raw value or the escaped value. If they get it wrong just once, chances are you'll end up with a nasty bug or a security vulnerability.

 

And then again: Twig is a lot more than auto-escaping.

Link to comment
Share on other sites

Yes, because it's cumbersome, confusing and fragile.

 

Twig automatically escapes the variables when the output is rendered, which is logical (escaping is an output feature) and almost completely eliminates the need for human intervention. Most of the time, the template author doesn't even have to think about XSS vulnerabilities. You, on the other hand, escape the variables as they enter the template, so the author has to constantly decide if they use the raw value or the escaped value. If they get it wrong just once, chances are you'll end up with a nasty bug or a security vulnerability.

 

And then again: Twig is a lot more than auto-escaping.

 

But considering my situation... not allowed to use twig or anything else, I'm the ONLY person editing the code, the one other person who might edit the code also knows php and is smart enough to look at all the other <?=$cooked->foo?> and follow convention, and in the rare case they need something intentionally unescaped they'll either consult me or consult my documentation on how the views work or explicitly use html_entity_decode() to reverse the escaping.

 

I'm not knocking twig. I'm just stuck in a bad situation and could use some advice on the escaping aspect. Yes, there's a ton of great things twig does but when it comes to just the escaping part of it, is there anything other than htmlspecialchars that I should be doing when escaping output. Do you have any idea what twig does when it's escaping other than just htmlspecialchars?

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.