Home > Mobile >  Is it possible to configure the "PHP built-in web server" to process PHP codes that are in
Is it possible to configure the "PHP built-in web server" to process PHP codes that are in

Time:01-04

Since the PHP built-in web server does not consider ".htaccess" files "AddType application/x-httpd-php .php .htm .html" (or anything like that), how can I configure it to process PHP codes, embedded in the HTML inside its curly braces (<?php ... ? >)?

Thank you so much.

CodePudding user response:

It would be so much easier to use LAMP stack. It is not recommended to use PHP built-in web server for production. You can find the warning below in PHP manual

"Warning This web server is designed to aid application development. It may also be useful for testing purposes or for application demonstrations that are run in controlled environments. It is not intended to be a full-featured web server. It should not be used on a public network."

You can't use PHP in HTML files. Or not atleast without any major configuration. However you can write HTML in PHP files.

CodePudding user response:

Renaming your HTML files to have a ".php" extension is what makes most sense. However, if you really do not want to do this, or can't, there is a way.

You could use a router script (see: https://www.php.net/manual/en/features.commandline.webserver.php) in which you process the file as PHP. For example create a file called router.php:

<?php
$extensions = array("html", "htm");

$path = parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
$ext = pathinfo($path, PATHINFO_EXTENSION);

if (in_array($ext, $extensions)) {
    $file = __DIR__ . $path;
    $data = file_get_contents($file);
    return eval('?> ' . $data); // this is where the data is processed. 
}
return false; // return false if the file does not have a .html or .htm extension.

Then run your built in web server using this file: php -S localhost:8000 router.php.

Next, go to your browser and visit an HTML file, for example index.html on: localhost:8000/index.html. If your HTML file contains any PHP code, this will now be executed by the eval() function in your router.php.

BE CAREFUL: This is not something you should use in production as this can pose a serious security threat!

  •  Tags:  
  • Related