开发者

What’s the right way to embed PHP code in my CSS and JavaScript files?

Like everyone else I'm storing my site`s display information in style sheet files. And I want to create back-end cms so users will be able to, for example, change < h1 > color, size etc.

So, what's the right way to embed PHP code in my CSS file(s)?

Is adding this header:

<?php header("Content-type: text/css"); ?>

And changing file extension in link:

<link rel="stylesheet" type="text/css" media="screen" href="style.php">

Valid?

And what about JavaScript? At this moment I'm echoing <script type="text/javascript"> tags, but ma开发者_如何学Cybe there's also a way to embed everything in the .js files?

Thanks!


Yes, this is perfectly valid.

The same can be done for Javascript too by sending

<?php header("Content-type: application/javascript"); ?>

However, this is not optimal from a performance point of view because a PHP process has to be started for serving those resources.

If you have only very few dynamically changing CSS properties or JS variables, I would consider putting them into the document's head and continuing to serve the external files statically.

Remember that usually, there are no caching headers sent for PHP files. You'll have to take care of sending the correct headers inside your PHP script! Cheers @oracle certified professional for the reminder.


What you're doing is absolutely valid.

However if you're running a bigger site with many visitors, you should concern to just let PHP "build" a "real" CSS file when your user updates his or her design to save your servers performance to better needed things:

<?php

header("Content-type: text/css");

// Your database magic here to fetch the user-specific designs 

// open the cached css
$cachefile = "cachedCSS/mycss.css";

if (file_exists($cachefile)) {
    // the page has been cached from an earlier request
    // output the contents of the cache file
    include($cachefile); 
    // exit the script, so that the rest isnt executed
    exit;
}

$fp = fopen($cachefile, 'w');
// save the contents of output buffer to the file
fwrite($fp, ob_get_contents());
// close the file
fclose($fp);
// Send the output to the browser
ob_end_flush(); 

Read more about it here: http://www.theukwebdesigncompany.com/articles/php-caching.php


Make sure you are parsing the php in those files.

In .htaccess :

AddType application/x-httpd-php .php .css .js

This will ensure that any <?php ?> tags in file types other than .php will be parsed by the server and the php code isn't readable by users.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜