简体   繁体   中英

PHP built-in server hosting web fonts

I'm using PHP's built-in web server for local development of a project, like so:

$ php -S localhost:8000 -t web/

Inside the web directory is FontAwesome (an icon webfont) and a web page with correct includes and classes. The font doesn't display correctly when served locally.

The 'Network' developer tab in a browser shows the font correctly loading from the server:

200 GET http://localhost:8000/fonts/fontawesome-webfont.woff2?v=4.6.3

However the response headers include Content-type: application/octet-stream when (I believe) they should be returning Content-type: application/font-woff etc.

Is there a way to serve web fonts with PHP's built-in web server? Adding custom MIME types perhaps?

From the docs :

If a PHP file is given on the command line when the web server is started it is treated as a "router" script. The script is run at the start of each HTTP request. If this script returns FALSE, then the requested resource is returned as-is. Otherwise the script's output is returned to the browser.

$ php -S localhost:8000 router.php

Sample router.php for adding additional mime types, not natively supported by the php cli webserver looks like:

<?php
// router.php
$path = pathinfo($_SERVER["SCRIPT_FILENAME"]);
if ($path["extension"] == "el") {
    header("Content-Type: text/x-script.elisp");
    readfile($_SERVER["SCRIPT_FILENAME"]);
} else {
    return FALSE;
}
?>

My own router.php file from including Font-Awesome looks like this:

<?php
// router.php
$path = pathinfo($_SERVER["SCRIPT_FILENAME"]);
switch ($path["extension"]) {
    case "ttf":
        header("Content-Type: application/x-font-ttf");
        break;
    case "woff":
        header("Content-Type: application/x-font-woff");
        break;
    case "woff2":
        header("Content-Type: font/woff2");
        break;
    default:
        return FALSE;
}
readfile($_SERVER["SCRIPT_FILENAME"]);

Keep in mind that you won't need to deploy the router script, it's only required for local development.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM