Home » Php » html – How to merge multiple php files into one php file

html – How to merge multiple php files into one php file

Posted by: admin February 25, 2020 Leave a comment

Questions:

I am trying to create a script that will get multiple PHP files and make a one PHP file with that. E.g home.php, about.php, new.php Will be combined to form Index.php.

I’ve tried this code:

$code = '';
foreach (glob("*.php") as $filename) {
   $code.=file_get_contents("./$filename");
}
file_put_contents("./combined.php",$code);

but it won’t output.

How could I merge multiple PHP files?

How to&Answers:

I’ve checked your code on my machine and it seems it’s working well. But can’t understand why it’s not working for you.

By the way, if you need more solutions, then you can also try the following ways.

If your files are coming from form then you can do it as follow:

$files = [];
$combine_files = $_POST['combine_files'];
foreach ($combine_files as $single_file)
{
    $files .= $single_file;
}

$combined_contents;
foreach ($files as $single_file)
{
    $combined_contents .= file_get_contents("./".$single_file);
}

file_put_contents("./combined.php",$combined_contents);

If not from form, then simply it can also be done by following way:

$files = ["home.php", "about.php", "new.php"]; // create an array of files
$combined_contents;
foreach ($files as $single_file)
{
    $combined_contents .= file_get_contents("./".$single_file);
}
file_put_contents("./combined.php",$combined_contents); // puts all contents into one file