Home > Blockchain >  how to require a php file passing parameters
how to require a php file passing parameters

Time:11-28

I have a function that does something (and it is included in my files php). That function should require a php file passing parameters, but it fails and I'm not able to go ahead...

following the initial code of the function:

<?php
    function write_pdf($orientation, $initrow, $rowsperpage)
    {
        ob_start();

        require "./mypage.php?orient=$orientation&init=$initrow&nrrows=$rowsperpage"; 

        $html = ob_get_clean();

        $dompdf = new Dompdf();
        
        $dompdf->loadHtml($html);

...
...

the "mypage.php" returns the errors:

Notice:Undefined variable: orientation in C:\wamp\www\htdocs\site\mypage.php on line 8

Notice:Undefined variable: initrow in C:\wamp\www\htdocs\site\mypage.php on line 8

Notice:Undefined variable: rowsperpage in C:\wamp\www\htdocs\site\mypage.php on line 8

is there a way to do something like that? thanks!

CodePudding user response:

you can do so.

to_include.php

<?php
$orient = isset($_GET["orient"]) ? $_GET["orient"] : "portrait";
$init = isset($_GET["init"]) ? $_GET["init"] : 1;

echo "<pre>";
var_dump(
[
    "orient"=>$orient,
    "init"=>$init
]
);
echo "</pre>";

main.php

<?php
function include_get_params($file) {
  $main = explode('?', $file);
  $parts = explode('&', $main[1]);
  foreach($parts as $part) {
    parse_str($part, $output);
    foreach ($output as $key => $value) {
      $_GET[$key] = $value;
    }
  }
  include($main[0]);
}

include_get_params("to_include.php?orient=landscape&init=100");

The method include_get_params, first separates the main part of the string, separates the file from the parameters, through the ? After that he sets the parameters into pieces and puts all of this within the $_GET In to_include, we retrieved the parameters from the $_GET

I hope I helped you.

CodePudding user response:

You don't need to pass the parameters, as when you require the file is like its code where inside the function, so any variable defined in the function before the require, it will exists and be defined as well in your required file. So, you can directly use inside your required file the variables $orientation, $initrow, $rowsperpage.

Another way, quite ugly, is to add those vars to $_GET before require the file, assuming you're expecting to get them from $_GET:

$_GET['orient'] = $orientation;
$_GET['init'] = $initrow;
$_GET['nrrows'] = $rowsperpage;

require './mypage.php';

And my recommended way is to encapsulate your included file code in a function, so you can call it passing params. Even make a class, if included code is large and can be sliced in methods.

  • Related