Viewed   284 times

I keep reading it is poor practice to use the PHP close tag ?> at the end of the file. The header problem seems irrelevant in the following context (and this is the only good argument so far):

Modern versions of PHP set the output_buffering flag in php.ini If output buffering is enabled, you can set HTTP headers and cookies after outputting HTML because the returned code is not sent to the browser immediately.

Every good practice book and wiki starts with this 'rule' but nobody offers good reasons. Is there another good reason to skip the ending PHP tag?

 Answers

2

Sending headers earlier than the normal course may have far reaching consequences. Below are just a few of them that happened to come to my mind at the moment:

  1. While current PHP releases may have output buffering on, the actual production servers you will be deploying your code on are far more important than any development or testing machines. And they do not always tend to follow latest PHP trends immediately.

  2. You may have headaches over inexplicable functionality loss. Say, you are implementing some kind payment gateway, and redirect user to a specific URL after successful confirmation by the payment processor. If some kind of PHP error, even a warning, or an excess line ending happens, the payment may remain unprocessed and the user may still seem unbilled. This is also one of the reasons why needless redirection is evil and if redirection is to be used, it must be used with caution.

  3. You may get "Page loading canceled" type of errors in Internet Explorer, even in the most recent versions. This is because an AJAX response/json include contains something that it shouldn't contain, because of the excess line endings in some PHP files, just as I've encountered a few days ago.

  4. If you have some file downloads in your app, they can break too, because of this. And you may not notice it, even after years, since the specific breaking habit of a download depends on the server, the browser, the type and content of the file (and possibly some other factors I don't want to bore you with).

  5. Finally, many PHP frameworks including Symfony, Zend and Laravel (there is no mention of this in the coding guidelines but it follows the suit) and the PSR-2 standard (item 2.2) require omission of the closing tag. PHP manual itself (1,2), Wordpress, Drupal and many other PHP software I guess, advise to do so. If you simply make a habit of following the standard (and setup PHP-CS-Fixer for your code) you can forget the issue. Otherwise you will always need to keep the issue in your mind.

Bonus: a few gotchas (actually currently one) related to these 2 characters:

  1. Even some well-known libraries may contain excess line endings after ?>. An example is Smarty, even the most recent versions of both 2.* and 3.* branch have this. So, as always, watch for third party code. Bonus in bonus: A regex for deleting needless PHP endings: replace (s*?>s*)$ with empty text in all files that contain PHP code.
Tuesday, October 11, 2022
1

Quoting the doc:

(since 4.4.2 and 5.1.2) This function now prevents more than one header to be sent at once as a protection against header injection attacks.

So I suppose even that CRLF replacement you've already did is not necessary.

Sunday, October 2, 2022
 
3

X-Powered-By is a custom header in IIS. Since IIS 7, you can remove it by adding the following to your web.config:

<system.webServer>
  <httpProtocol>
    <customHeaders>
      <remove name="X-Powered-By" />
    </customHeaders>
  </httpProtocol>
</system.webServer>

This header can also be modified to your needs, for more information refer to http://www.iis.net/ConfigReference/system.webServer/httpProtocol/customHeaders


Add this to web.config to get rid of the X-AspNet-Version header:

<system.web>
  <httpRuntime enableVersionHeader="false" />
</system.web>

Finally, to remove X-AspNetMvc-Version, edit Global.asax.cs and add the following in the Application_Start event:

protected void Application_Start()
{
    MvcHandler.DisableMvcResponseHeader = true;
}

You can also modify headers at runtime via the Application_PreSendRequestHeaders event in Global.asax.cs. This is useful if your header values are dynamic:

protected void Application_PreSendRequestHeaders(object source, EventArgs e)
{
      Response.Headers.Remove("foo");
      Response.Headers.Add("bar", "quux");
}
Saturday, November 26, 2022
 
3

It’s all about loose coupling and single responsibility, which goes hand to hand with MV* (MVC/MVP/MVVM) patterns in JavaScript which are very modern in the last few years.

Loose coupling is an Object-oriented principle in which each component of the system knows its responsibility and doesn’t care about the other components (or at least tries to not care about them as much as possible). Loose coupling is a good thing because you can easily reuse the different modules. You’re not coupled with the interfaces of other modules. Using publish/subscribe you’re only coupled with the publish/subscribe interface which is not a big deal – just two methods. So if you decide to reuse a module in a different project you can just copy and paste it and it’ll probably work or at least you won’t need much effort to make it work.

When talking about loose coupling we should mention the separation of concerns. If you’re building an application using an MV* architectural pattern you always have a Model(s) and a View(s). The Model is the business part of the application. You can reuse it in different applications, so it’s not a good idea to couple it with the View of a single application, where you want to show it, because usually in the different applications you have different views. So it’s a good idea to use publish/subscribe for the Model-View communication. When your Model changes it publishes an event, the View catches it and updates itself. You don’t have any overhead from the publish/subscribe, it helps you for the decoupling. In the same manner you can keep your application logic in the Controller for example (MVVM, MVP it’s not exactly a Controller) and keep the View as simple as possible. When your View changes (or the user clicks on something, for example) it just publishes a new event, the Controller catches it and decides what to do. If you are familiar with the MVC pattern or with MVVM in Microsoft technologies (WPF/Silverlight) you can think of the publish/subscribe like the Observer pattern. This approach is used in frameworks like Backbone.js, Knockout.js (MVVM).

Here is an example:

//Model
function Book(name, isbn) {
    this.name = name;
    this.isbn = isbn;
}

function BookCollection(books) {
    this.books = books;
}

BookCollection.prototype.addBook = function (book) {
    this.books.push(book);
    $.publish('book-added', book);
    return book;
}

BookCollection.prototype.removeBook = function (book) {
   var removed;
   if (typeof book === 'number') {
       removed = this.books.splice(book, 1);
   }
   for (var i = 0; i < this.books.length; i += 1) {
      if (this.books[i] === book) {
          removed = this.books.splice(i, 1);
      }
   }
   $.publish('book-removed', removed);
   return removed;
}

//View
var BookListView = (function () {

   function removeBook(book) {
      $('#' + book.isbn).remove();
   }

   function addBook(book) {
      $('#bookList').append('<div id="' + book.isbn + '">' + book.name + '</div>');
   }

   return {
      init: function () {
         $.subscribe('book-removed', removeBook);
         $.subscribe('book-aded', addBook);
      }
   }
}());

Another example. If you don’t like the MV* approach you can use something a little different (there’s an intersection between the one I’ll describe next and the last mentioned). Just structure your application in different modules. For example look at Twitter.

If you look at the interface you simply have different boxes. You can think of each box as a different module. For example you can post a tweet. This action requires the update of a few modules. Firstly it has to update your profile data (upper left box) but it also has to update your timeline. Of course, you can keep references to both modules and update them separately using their public interface but it’s easier (and better) to just publish an event. This will make the modification of your application easier because of looser coupling. If you develop new module which depends on new tweets you can just subscribe to the “publish-tweet” event and handle it. This approach is very useful and can make your application very decoupled. You can reuse your modules very easily.

Here is a basic example of the last approach (this is not original twitter code it’s just a sample by me):

var Twitter.Timeline = (function () {
   var tweets = [];
   function publishTweet(tweet) {
      tweets.push(tweet);
      //publishing the tweet
   };
   return {
      init: function () {
         $.subscribe('tweet-posted', function (data) {
             publishTweet(data);
         });
      }
   };
}());


var Twitter.TweetPoster = (function () {
   return {
       init: function () {
           $('#postTweet').bind('click', function () {
               var tweet = $('#tweetInput').val();
               $.publish('tweet-posted', tweet);
           });
       }
   };
}());

For this approach there's an excellent talk by Nicholas Zakas. For the MV* approach the best articles and books I know of are published by Addy Osmani.

Drawbacks: You have to be careful about the excessive use of publish/subscribe. If you’ve got hundreds of events it can become very confusing to manage all of them. You may also have collisions if you’re not using namespacing (or not using it in the right way). An advanced implementation of Mediator which looks much like an publish/subscribe can be found here https://github.com/ajacksified/Mediator.js. It has namespacing and features like event “bubbling” which, of course, can be interrupted. Another drawback of publish/subscribe is the hard unit testing, it may become difficult to isolate the different functions in the modules and test them independently.

Thursday, August 4, 2022
4

Read the answers in the duplicate questions for the meaning and usage of &:.... In this case, entries is an array, and there are three methods map, sort_by, and map chained. sort_by(&:last) is equivalent to sort_by{|x| x.last}. map(&:first) is the same as map{|x| x.first}. The reason the first map does not use &:... is because (i) the receiver of accept_entry is not e, and (ii) it takes an argument e.

Thursday, August 18, 2022
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :