Key Takeaways
- The PHP script demonstrated in the text allows for automatic generation of CSS3 properties with browser-specific prefixes, and compression of CSS files for improved page load times, without the need for additional tools.
- The script works by replacing underscore-prefixed properties in CSS files with a set of browser-specific prefixed properties, and then concatenating and compressing the CSS files to reduce server requests and unnecessary white space.
- The script can be used with other CSS preprocessors like Sass or Less, and its benefits include improved website performance and compatibility across different browsers, as well as saving the time and effort of manually adding vendor prefixes and compressing CSS files.
- Generate CSS3 properties with browser-specific prefixes so that we don’t have them all by hand
- Concatenate all the CSS files and strip out comments and unnecessary white space to reduce the number of server requests and decrease the page’s load time
- Perform the process on-the-fly when the web page is requested
<span>_border-radius: 10px;</span>The code will generate a complete list of properties like this:
<span>-o-border-radius: 10px; </span><span>-moz-border-radius: 10px; </span><span>-webkit-border-radius: 10px; </span><span>border-radius: 10px;</span>Then, in the HTML, a link is written like this to import the styles:
<span><span><span><link> rel<span>="stylesheet"</span> href<span>="css/css.php?f=css_file1|css_file2|css_file3"</span>></span></span></span>With the single link element, three CSS files will be loaded as one. The css.php script will read in the files that are listed (css_file1.css, css_file2.css, and css_file3.css), combine them, and return them as a single file. It looks pretty easy to use, right? So with out further ado, let’s start writing some code!
Writing the Code
Go ahead and create the file css.php with the following code:<?php $files = explode("|", $_GET["f"]); $contents = ""; foreach ($files as $file) { $contents .= file_get_contents($file . ".css"); } preg_match_all('/_[a-zA-Z-]+:s.+;|[a-zA-Z-]+:s_[a-zA-Z].+;/', $contents, $matches, PREG_PATTERN_ORDER); $prefixes = array("-o-", "-moz-", "-webkit-", ""); foreach ($matches[0] as $property) { $result = ""; foreach ($prefixes as $prefix) { $result .= str_replace("_", $prefix, $property); } $contents = str_replace($property, $result, $contents); } $contents = preg_replace('/(/*).*?(*/)/s', '', $contents); $contents = preg_replace(array('/s+([^w'"]+)s+/', '/([^w'"])s+/'), '', $contents); header("Content-Type: text/css"); header("Expires: " . gmdate('D, d M Y H:i:s GMT', time() + 3600)); echo $contents;The code first receives the list of CSS files to be processed as a string from the URL parameter (accessible in PHP as $_GET["f"]). Each file is separated with a pipe-character. The explode() function splits the string on the pipes returning an array of filenames. The function file_get_contents() gets the contents of each file which is appended, one by one, to the variable $contents. After the contents of the CSS files has been retrieved, the next step is to find any CSS properties that start with an underscore and replace them with the browser-specific prefixed properties. The function preg_match_all() finds all the parts in the text that match the regular expression and places the matches into $matches[0] as an array. I won’t explain why $matches has the array index 0 because you can read a clear explanation about the function in the PHP Manual. Rather I’d like to focus on explaining the flow of our program. This image explains the pattern of the regular expression:
Using the Script
I’d like to give you a simple usage example for script that we’ve just made. Put the css.php into your css directory, along with these three CSS files. The first file is header.css:<span>_border-radius: 10px;</span>The second file is center.css:
<span>-o-border-radius: 10px; </span><span>-moz-border-radius: 10px; </span><span>-webkit-border-radius: 10px; </span><span>border-radius: 10px;</span>The third file is footer.css:
<span><span><span><link> rel<span>="stylesheet"</span> href<span>="css/css.php?f=css_file1|css_file2|css_file3"</span>></span></span></span>Look at how the CSS3 properties have been written; the ones that would have a browser-specific prefix are given only once and have an underscore in front of them. Next, create the file index.html that will use the styles.
<?php $files = explode("|", $_GET["f"]); $contents = ""; foreach ($files as $file) { $contents .= file_get_contents($file . ".css"); } preg_match_all('/_[a-zA-Z-]+:s.+;|[a-zA-Z-]+:s_[a-zA-Z].+;/', $contents, $matches, PREG_PATTERN_ORDER); $prefixes = array("-o-", "-moz-", "-webkit-", ""); foreach ($matches[0] as $property) { $result = ""; foreach ($prefixes as $prefix) { $result .= str_replace("_", $prefix, $property); } $contents = str_replace($property, $result, $contents); } $contents = preg_replace('/(/*).*?(*/)/s', '', $contents); $contents = preg_replace(array('/s+([^w'"]+)s+/', '/([^w'"])s+/'), '', $contents); header("Content-Type: text/css"); header("Expires: " . gmdate('D, d M Y H:i:s GMT', time() + 3600)); echo $contents;Look at the href attribute in the link tag. Every CSS filename is separated by a pipe.
Conclusion
In this article I showed you how to automate some common manipulations of CSS using PHP. The script relies heavily on regular expressions, a very powerful language that allows us to manipulate string however we see fit. Overall, the script is very simple but it offers many benefits. Try using it in your next project. Image via 1xpert / ShutterstockFrequently Asked Questions about CSS3 Prefixer and Compressor
What is the purpose of a CSS3 prefixer and compressor?
A CSS3 prefixer and compressor is a tool that helps in optimizing CSS files for better performance and compatibility. It automatically adds vendor prefixes to CSS properties to ensure they work across different browsers. The compressor function reduces the size of the CSS files by eliminating unnecessary characters, thus improving the loading speed of your website.
How does a CSS3 prefixer and compressor work?
A CSS3 prefixer and compressor works by scanning your CSS files for properties that require vendor prefixes. It then adds these prefixes automatically, saving you the time and effort of doing it manually. The compressor function works by removing unnecessary characters like spaces, comments, and line breaks from your CSS files, thus reducing their size.
Why should I use a CSS3 prefixer and compressor?
Using a CSS3 prefixer and compressor can greatly improve the performance and compatibility of your website. It ensures that your CSS properties work across different browsers and reduces the size of your CSS files, thus improving the loading speed of your website. It also saves you the time and effort of manually adding vendor prefixes and compressing your CSS files.
Are there any downsides to using a CSS3 prefixer and compressor?
While a CSS3 prefixer and compressor offers many benefits, it’s important to note that it may not always be necessary. Some modern browsers no longer require vendor prefixes for certain CSS properties. Also, over-compressing your CSS files can make them difficult to read and maintain.
How do I use a CSS3 prefixer and compressor?
To use a CSS3 prefixer and compressor, you simply need to input your CSS files into the tool. It will then automatically add the necessary vendor prefixes and compress your files. Some tools also offer additional features like minification and optimization.
Can I use a CSS3 prefixer and compressor with other CSS preprocessors?
Yes, you can use a CSS3 prefixer and compressor with other CSS preprocessors like Sass or Less. The tool will simply add the necessary vendor prefixes and compress the outputted CSS files.
What are some good CSS3 prefixer and compressor tools?
There are many good CSS3 prefixer and compressor tools available, including Autoprefixer, PostCSS, and CSS Drive. These tools offer a range of features and can be used with various CSS preprocessors.
How do I choose the right CSS3 prefixer and compressor tool?
When choosing a CSS3 prefixer and compressor tool, consider factors like ease of use, compatibility with your CSS preprocessor, and the range of features offered. You should also consider the tool’s performance and reliability.
Can I use a CSS3 prefixer and compressor for large CSS files?
Yes, you can use a CSS3 prefixer and compressor for large CSS files. However, keep in mind that the processing time may be longer for larger files.
Is it necessary to use a CSS3 prefixer and compressor for every project?
Whether or not you should use a CSS3 prefixer and compressor for every project depends on the specific requirements of the project. If browser compatibility and performance are important considerations, then using a CSS3 prefixer and compressor can be beneficial.
The above is the detailed content of Automatic CSS3 Prefixer and Compressor. For more information, please follow other related articles on the PHP Chinese website!

Absolute session timeout starts at the time of session creation, while an idle session timeout starts at the time of user's no operation. Absolute session timeout is suitable for scenarios where strict control of the session life cycle is required, such as financial applications; idle session timeout is suitable for applications that want users to keep their session active for a long time, such as social media.

The server session failure can be solved through the following steps: 1. Check the server configuration to ensure that the session is set correctly. 2. Verify client cookies, confirm that the browser supports it and send it correctly. 3. Check session storage services, such as Redis, to ensure that they are running normally. 4. Review the application code to ensure the correct session logic. Through these steps, conversation problems can be effectively diagnosed and repaired and user experience can be improved.

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

Setting the httponly flag is crucial for session cookies because it can effectively prevent XSS attacks and protect user session information. Specifically, 1) the httponly flag prevents JavaScript from accessing cookies, 2) the flag can be set through setcookies and make_response in PHP and Flask, 3) Although it cannot be prevented from all attacks, it should be part of the overall security policy.

PHPsessionssolvetheproblemofmaintainingstateacrossmultipleHTTPrequestsbystoringdataontheserverandassociatingitwithauniquesessionID.1)Theystoredataserver-side,typicallyinfilesordatabases,anduseasessionIDstoredinacookietoretrievedata.2)Sessionsenhances

PHPsessionscanstorestrings,numbers,arrays,andobjects.1.Strings:textdatalikeusernames.2.Numbers:integersorfloatsforcounters.3.Arrays:listslikeshoppingcarts.4.Objects:complexstructuresthatareserialized.

TostartaPHPsession,usesession_start()atthescript'sbeginning.1)Placeitbeforeanyoutputtosetthesessioncookie.2)Usesessionsforuserdatalikeloginstatusorshoppingcarts.3)RegeneratesessionIDstopreventfixationattacks.4)Considerusingadatabaseforsessionstoragei

Session regeneration refers to generating a new session ID and invalidating the old ID when the user performs sensitive operations in case of session fixed attacks. The implementation steps include: 1. Detect sensitive operations, 2. Generate new session ID, 3. Destroy old session ID, 4. Update user-side session information.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

WebStorm Mac version
Useful JavaScript development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment
