This article mainly introduces nine very useful PHP code snippets. when developing websites, apps, or blogs, code snippets can really save you time, interested friends can refer to this article to share some of the most useful PHP code snippets I have collected. Let's take a look!
1. create a data URI
Data URI is useful when embedding images into HTML, CSS, and JS to save HTTP requests and reduce the loading time of websites. The following function creates a data URI based on $ file.
function data_uri($file, $mime) { $contents=file_get_contents($file); $base64=base64_encode($contents); echo "data:$mime;base64,$base64";}
2. Merge JavaScript and CSS files
Another good suggestion for minimizing HTTP requests and saving page loading time is to merge your CSS and JS files. Although I suggest using specialized plug-ins (such as minify), it is also very easy to use PHP to merge files. Let's take a look:
Function combine_my_files ($ array_files, $ destination_dir, $ dest_file_name) {if (! Is_file ($ destination_dir. $ dest_file_name) {// continue only if file doesn't exist $ content = ""; foreach ($ array_files as $ file) {// loop through array list $ content. = file_get_contents ($ file); // read each file} // You can use some sort of minifier here // minify_my_js ($ content); $ new_file = fopen ($ destination_dir. $ dest_file_name, "w"); // open file for writing fwrite ($ new_file, $ content); // write to destination fclose ($ new_file); return'