IT, Snippets

Passing Variables to an Include in PHP

If we have ever had the need to pass variables in an include to make it dynamic, this is very common when we reuse components.

I’ll leave you with a feature that will save you the work.

// Include con Variables
function includeWithVariables($filePath, $variables = array(), $print = true)
{
    $output = NULL;
    if(file_exists($filePath)){
        // Extrae las variables en un entorno local
        extract($variables);

        // Empieza el buffering de salida
        ob_start();

        // Include el archivo
        include $filePath;

        // Termina el buffering y devuelve su contenido
        $output = ob_get_clean();
    }
    if ($print) {
        print $output;
    }
    return $output;

}

After placing our function, we can use it wherever we want by passing it the variables.

<?php includeWithVariables('detalles.php', array('detalle' => 'Hola')); ?>

And inside our PHP file called details.php we could call any variable simply with

<? echo $detalle; ?>

As you’ve seen, the solution for passing variables or parameters to an include is very simple. We hope to continue helping, and if you have any questions, don’t hesitate to leave a comment.

Safety tip

If the variables you pass to the include come from forms or URLs ($_POST, $_GET, etc.), it is good practice to sanitize them before passing them, to avoid security problems such as XSS or injections.

author-avatar

About Danilo Ulloa

Diseñador Web Freelance en Madrid y Tenerife. Desarrollador Fullstack (Debian, Nginx, PHP, Laravel, MySQL, JS, VUE, HTML, CSS, Python).