Search code examples
phpincludeshell-execoutput-buffering

Why shouldn't I use shell_exec rather than output buffering to 'include' a file into a variable?


I have a template that handles all the various stuff that's repeated on every page. The problem is, all the stuff that's different goes into the middle of the template. Most people are familiar with this, but here are some pseudotags as a visual aid:

<begin_template>
    <top_part_of_template_with_repeated_stuff>
        <!--different stuff goes here-->
    <bottom_part_of_template_with_more_repeated_stuff>
<end_template>

I know there are various different ways to deal with this. I don't like to do it this way:

include 'top_part_of_template.html';
// output the different part
include 'bottom_part_of_template.html';

because it bothers me for opening and closing tags to be in separate documents. What I'm doing currently is a template like this:

<template>
    <?php if (isset($different_stuff)) echo $different_stuff ?>
<more_template>

and getting the different stuff using output buffering like this:

ob_start();
include 'different_stuff.php';
$different_stuff = ob_get_clean();

include 'template.php';

I came across this answer, which suggests using shell_exec. While I generally understand what shell_exec does, I am not really familiar with using it. I tried it like this:

$different_stuff = shell_exec('php different_stuff.php');
include 'template.php';

It does work, and I like it simply because it's one statement instead of three. It feels like a bad idea, though (mainly because I think if it was a good idea I would see it used more often and this is the first time I've seen it) but I'm not familiar enough with shell_exec to know why.

I think this may be sounding kind of like an opinion-based question, but I'm really not looking for opinions. I would like to know about objective, demonstrable reasons not to use this approach.


Solution

  • You're spinning up a new shell environment and a new instance of PHP that way instead of leveraging the PHP instance your code is running in already. So there's performance and memory implications.

    Many servers have separate php.ini files for command-line PHP (which your shell_exec calls) and FPM based PHP (which most modern web servers call).

    And, shell_exec doesn't pass back any error information, so you'll have a harder time detecting issues and troubleshooting them.