Prevent the browsers to use old cached CSS and JS files

Browser cache is very useful when users download the same CSS and JS files multiple times. Some browsers, however, use the old CSS and JS files from the cache, even though they have been updated. This may lead to unpleasant situations, when the pages are displayed to the user with the wrong styles or pages will work incorrectly. Fortunately, these unpleasant situations is easy to avoid and let the browsers cache files as long as they are changed.
Read more →

CSS compression with own PHP class VS CSSTidy

It makes sense to optimize the site’s cascading style sheets (CSS), as it pages load faster, and it reduce the amount of data transferred, and just combining css files could significantly reduce requests to server. So users benefit from faster page loads and webmaster of the sites benefits from the cheaper price of the transferred data. I have used CSSTidy on many projects. And CSSTidy is very good tool for packing CSS and it can even fix CSS errors. Sometimes, however, feel that csstidy is even a bit too wide and “heavy” tool for the CSS files packing. Thats why I decide to write my own simple PHP class for the CSS files packing.
Read more →

PHP Script to Generate PostgreSQL Table Partitioning (Part 2)

As Part 1 (Howto create PostgreSQL table partitioning) shows, making of PostgreSQL partitioning needs a lot of SQL commands. So this Part 2 explains how SQL commands for PostgreSQL partitioning can be made with a simple PHP script. This example script make SQL for child tables, indexes, trigger function and parent table trigger. This example script can make PostgreSQL table partitioning with using Date ranges. Script can be configured with following configuration section:
Read more →

PHP: Loop through dates (from date to date) with strtotime() function

This is very easy way loop through dates (from date to date) with PHP strtotime() function. This example only echo dates, but of course this model can be used more complicated situations. <?php // Set timezone date_default_timezone_set('UTC'); // Start date $date = '2009-12-06'; // End date $end_date = '2020-12-31'; while (strtotime($date) <= strtotime($end_date)) { echo "$date\n"; $date = date ("Y-m-d", strtotime("+1 day", strtotime($date))); } Note: All different PHP strtotime() function syntaxes can be used.
Read more →

Format bytes with PHP – B, KB, MB, GB, TB, PB, EB, ZB, YB converter

Simple PHP function that formats the bytes to the desired form. Possible unit options are: Byte (B) Kilobyte (KB) Megabyte (MB) Gigabyte (GB) Terabyte (TB) Petabyte (PB) Exabyte (EB) Zettabyte (ZB) Yottabyte (YB) PHP byteFormat function for formatting bytes Function takes three parameter: (bytes mandatory, unit optional, decimals optional) <?php function byteFormat($bytes, $unit = "", $decimals = 2) { $units = array('B' => 0, 'KB' => 1, 'MB' => 2, 'GB' => 3, 'TB' => 4, 'PB' => 5, 'EB' => 6, 'ZB' => 7, 'YB' => 8); $value = 0; if ($bytes > 0) { // Generate automatic prefix by bytes // If wrong prefix given if (!array_key_exists($unit, $units)) { $pow = floor(log($bytes)/log(1024)); $unit = array_search($pow, $units); } // Calculate byte value by prefix $value = ($bytes/pow(1024,floor($units[$unit]))); } // If decimals is not numeric or decimals is less than 0 // then set default value if (!is_numeric($decimals) || $decimals < 0) { $decimals = 2; } // Format output return sprintf('%.' . $decimals . 'f '.$unit, $value); } Example usage echo byteFormat(4096, "B"); echo byteFormat(8, "B", 2); echo byteFormat(1, "KB", 5); echo byteFormat(1073741824, "B", 0); echo byteFormat(1073741824, "KB", 0); echo byteFormat(1073741824, "MB"); echo byteFormat(1073741824); echo byteFormat(1073741824, "TB", 10); echo byteFormat(1099511627776, "PB", 6); Output
Read more →

BitLy (bit.ly) PHP Class – Shorten and Expand URLs (and Hashes) with BitLy API

BitLy (bit.ly) is a service which allows users to shorten, expand, share and track URLs (links). bit.ly can be accessed through bit.ly website and a robust and open API. Example: Shorten http://www.if-not-true-then-false.com/ url -> http://bit.ly/8cZ1fb Expand http://bit.ly/8cZ1fb url -> http://www.if-not-true-then-false.com/ This post deals with bit.ly API usage with a simple PHP Class. This PHP class allows to shorten normal urls, expand bit.ly urls and expand bit.ly hashes. BitLy PHP Class <?php class BitLy { private $break; private $api_version; private $format; private $login; private $apikey; // Constructor for BitLy class public function __construct($login, $apikey) { // Browser output then use "<br></br>" // Command line output use "\n" $this->break = "\n"; $this->api_version = "2.0.1"; $this->format = "json"; $this->login = $login; $this->apikey = $apikey; } // Shorten given url and returns shortened url public function shortenUrl($url) { $shortened_url = ""; $encoded_url = urlencode($url); $bitly_url = "http://api.bit.ly/shorten?" . "version=" . $this->api_version . "&format=" . $this->format . "&longUrl=" . $encoded_url . "&login=" . $this->login . "&apiKey=" . $this->apikey; $content = file_get_contents($bitly_url); try { $shortened_url = $this->parseContent($content, $url); } catch (Exception $e) { echo "Caught exception: " . $e->getMessage() . $this->break; exit; } return $shortened_url; } // Expand given url and returns expanded url public function expandUrlByUrl($url) { $expanded_url = ""; $hash = $this->parseBitlyUrl($url); $expanded_url = $this->expandUrlByHash($hash); return $expanded_url; } // Expand given hash and returns expanded url public function expandUrlByHash($hash) { $expanded_url = ""; $bitly_url = "http://api.bit.ly/expand?" . "version=" . $this->api_version . "&format=" . $this->format . "&hash=" . $hash . "&login=" . $this->login . "&apiKey=" . $this->apikey; $content = file_get_contents($bitly_url); try { $expanded_url = $this->parseContent($content, $hash); } catch (Exception $e) { echo "Caught exception: " . $e->getMessage() . $this->break; exit; } return $expanded_url; } // Parse Bitly url returns bitly hash private function parseBitlyUrl($url) { $parsed_url = parse_url($url); return trim($parsed_url['path'], "/"); } // Parse Content from Bitly API private function parseContent($content, $key) { // Decode json to array $content = json_decode($content, true); // Check errors if ($content['errorCode'] != 0 || $content['statusCode'] != "OK") { throw new Exception($content['statusCode'] . ": " . $content['errorCode'] . " " . $content['errorMessage']); } // Return right url or throw exception if not set if (isset($content['results'][$key]['longUrl'])) { return $content['results'][$key]['longUrl']; } else if (isset($content['results'][$key]['shortUrl'])) { return $content['results'][$key]['shortUrl']; } else { throw new Exception("ERROR. URL not found: " . $key); } } } BitLy PHP Class usage <?php require_once("BitLy.php"); $bitly = new BitLy("bitlyapidemo", "R_0da49e0a9118ff35f52f629d2d71bf07"); $url = "http://www.if-not-true-then-false.com/"; $short_url = $bitly->shortenUrl($url); echo "Shorten " . $url . " url -> " . $short_url . "\n"; echo "Expand " . $short_url . " url -> " . $bitly->expandUrlByUrl($short_url) . "\n"; echo "Expand 8cZ1fb hash -> " . $bitly->expandUrlByHash("8cZ1fb") . "\n"; Output $ php test_bitly_class.php Shorten http://www.if-not-true-then-false.com/ url -> http://bit.ly/8cZ1fb Expand http://bit.ly/8cZ1fb url -> http://www.if-not-true-then-false.com/ Expand 8cZ1fb hash -> http://www.if-not-true-then-false.com/
Read more →

nginx, PHP 5.3 and FastCGI on CentOS 5.5, Fedora 13, Red Hat RHEL 5.5/6

This is guide howto install nginx, PHP 5.3 and FastCGI webserver with MySQL and/or PostgreSQL and Memcache support on Fedora 12 and Fedora 13, CentOS 5.5, Red Hat (RHEL) 5.5/6. nginx (engine x) is a robust, small and high performance http server, reverse proxy server and also mail proxy server. 1. Add and enable needed repositories: Updated 19.3.2010 Use following repositories to install nginx 0.8.xx version (currently 0.8.36 version) rpm -Uvh http://download.fedora.redhat.com/pub/epel/5/i386/epel-release-5-4.noarch.rpm rpm -Uvh http://rpms.famillecollet.com/enterprise/remi-release-5.rpm rpm -Uvh http://yum.chrislea.com/centos/5/i386/chl-release-5-3.noarch.rpm rpm --import /etc/pki/rpm-gpg/RPM-GPG-KEY-CHL Just Epel repository is now obsolete, since there can be found only nginx 0.6.xx branch (currenlty version 0.6.39) Check this comment for more info.
Read more →

PHP stdClass to Array and Array to stdClass – stdClass Object

I think every PHP coders have come accross Arrays and stdClass Objects (belongs to PHP Predefined Classes). Sometimes it’s very useful convert Objects to Arrays and Arrays to Objects. This is easy if arrays and objects are one-dimensional, but might be little tricky if using multidimensional arrays and objects. This post defines two ultra simple recursive function to convert multidimensional Objects to Arrays and multidimensional Arrays to Objects. Function to Convert stdClass Objects to Multidimensional Arrays <?php function objectToArray($d) { if (is_object($d)) { // Gets the properties of the given object // with get_object_vars function $d = get_object_vars($d); } if (is_array($d)) { /* * Return array converted to object * Using __FUNCTION__ (Magic constant) * for recursive call */ return array_map(__FUNCTION__, $d); } else { // Return array return $d; } } Function to Convert Multidimensional Arrays to stdClass Objects <?php function arrayToObject($d) { if (is_array($d)) { /* * Return array converted to object * Using __FUNCTION__ (Magic constant) * for recursive call */ return (object) array_map(__FUNCTION__, $d); } else { // Return object return $d; } } Function usage // Create new stdClass Object $init = new stdClass; // Add some test data $init->foo = "Test data"; $init->bar = new stdClass; $init->bar->baaz = "Testing"; $init->bar->fooz = new stdClass; $init->bar->fooz->baz = "Testing again"; $init->foox = "Just test"; // Convert array to object and then object back to array $array = objectToArray($init); $object = arrayToObject($array); // Print objects and array print_r($init); echo "\n"; print_r($array); echo "\n"; print_r($object); Test output:
Read more →

PHP - Measure Scripts Execution Time and Page Generation Time

In many cases, it is really useful to know the exact time for how long a PHP script is running or how long will take PHP web page load. On the other hand it is also useful to know that how long a particular script operation or part of page load will take. Following PHP Timing class is very simple to use, only create class and start timing and stop timing. Elapsed time function can be used also (elapsed time is calculated from script start time). Statistics can be displayed in print-functions and the same information without any formatting can also get with get-functions.
Read more →

PHP CLI Colors – PHP Class Command Line Colors (bash)

PHP Command Line Interface (CLI) has not built-in coloring for script output, like example Perl language has (perldoc.perl.org/Term/ANSIColor.html). So I decided to make own class for adding colors on PHP CLI output. This class works only Bash shells. This class is easy to use. Just create new instance of class and call getColoredString function with string and foreground color and/or background color. PHP Class for Coloring PHP Command Line (CLI) Scripts Output <?php class Colors { private $foreground_colors = array(); private $background_colors = array(); public function __construct() { // Set up shell colors $this->foreground_colors['black'] = '0;30'; $this->foreground_colors['dark_gray'] = '1;30'; $this->foreground_colors['blue'] = '0;34'; $this->foreground_colors['light_blue'] = '1;34'; $this->foreground_colors['green'] = '0;32'; $this->foreground_colors['light_green'] = '1;32'; $this->foreground_colors['cyan'] = '0;36'; $this->foreground_colors['light_cyan'] = '1;36'; $this->foreground_colors['red'] = '0;31'; $this->foreground_colors['light_red'] = '1;31'; $this->foreground_colors['purple'] = '0;35'; $this->foreground_colors['light_purple'] = '1;35'; $this->foreground_colors['brown'] = '0;33'; $this->foreground_colors['yellow'] = '1;33'; $this->foreground_colors['light_gray'] = '0;37'; $this->foreground_colors['white'] = '1;37'; $this->background_colors['black'] = '40'; $this->background_colors['red'] = '41'; $this->background_colors['green'] = '42'; $this->background_colors['yellow'] = '43'; $this->background_colors['blue'] = '44'; $this->background_colors['magenta'] = '45'; $this->background_colors['cyan'] = '46'; $this->background_colors['light_gray'] = '47'; } // Returns colored string public function getColoredString($string, $foreground_color = null, $background_color = null) { $colored_string = ""; // Check if given foreground color found if (isset($this->foreground_colors[$foreground_color])) { $colored_string .= "\033[" . $this->foreground_colors[$foreground_color] . "m"; } // Check if given background color found if (isset($this->background_colors[$background_color])) { $colored_string .= "\033[" . $this->background_colors[$background_color] . "m"; } // Add string and end coloring $colored_string .= $string . "\033[0m"; return $colored_string; } // Returns all foreground color names public function getForegroundColors() { return array_keys($this->foreground_colors); } // Returns all background color names public function getBackgroundColors() { return array_keys($this->background_colors); } } Colors class basic usage examples <?php // Create new Colors class $colors = new Colors(); // Test some basic printing with Colors class echo $colors->getColoredString("Testing Colors class, this is purple string on yellow background.", "purple", "yellow") . "\n"; echo $colors->getColoredString("Testing Colors class, this is blue string on light gray background.", "blue", "light_gray") . "\n"; echo $colors->getColoredString("Testing Colors class, this is red string on black background.", "red", "black") . "\n"; echo $colors->getColoredString("Testing Colors class, this is cyan string on green background.", "cyan", "green") . "\n"; echo $colors->getColoredString("Testing Colors class, this is cyan string on default background.", "cyan") . "\n"; echo $colors->getColoredString("Testing Colors class, this is default string on cyan background.", null, "cyan") . "\n"; Output:
Read more →

cURL: Check Nginx/Apache Compression (br, gzip, deflate) is Working

This is a quick method to check with using cURL that Nginx/Apache (or any other web server) compression with Nginx ngx_http_gzip_module (gzip), Nginx google/ngx_brotli (br), Apache mod_brotli (br), Apache mod_gzip (gzip) and Apache mod_deflate (deflate) is working. Only the remote server headers are needed. Check that the Nginx/Apache Compression is Working Get headers curl -s -I -H 'Accept-Encoding: br,gzip,deflate' https://www.if-not-true-then-false.com -s option silent, disable progress bar. -I option which will make just HEAD request to server and get headers. -H option add header for accept content-encoding br, gzip and deflate.
Read more →

PHP: Calculate Real Differences Between Two Dates or Timestamps

I was using simple function to calculate difference between two dates and timestamps until I noticed, it’s not working correctly in long intervals. It’s very easy to calculate difference between two timestamps in seconds, but it’s much more complicated print difference in human readable format. The Internet can be found in a wide range of ways to do this thing, but as a rule they use a fixed amount of seconds for the year and the month. So if we calculate year with using 365 or 365.25 days and month using 30 or 31 then the difference is not accurate, because of leap years, DST (Daylight Saving Time) and so on.
Read more →

PHP __DIR__, __FILE__, __FUNCTION__, __CLASS__, __METHOD__, __LINE__, __NAMESPACE__

PHP has large number of predefined constants. This HOWTO will present the seven most important, most practical and most useful PHP Magic Constants. __FILE__ – The full path and filename of the file. __DIR__ – The directory of the file. __FUNCTION__ – The function name. __CLASS__ – The class name. __METHOD__ – The class method name. __LINE__ – The current line number of the file. __NAMESPACE__ – The name of the current namespace This is example PHP script with comments, which demonstrate howto use all previously mentioned PHP Magic Constants.
Read more →

Install PHP MongoDB (mongo) Driver on Linux, Mac OS X, Windows, UNIX, BSD

PHP MongoDB (Mongo Database) Driver Installation on Linux, UNIX, BSD and Mac OS X MongoDB PHP driver is very simple install on Linux, UNIX, BSD and Mac OS X. You need just PEAR (PHP Extension and Application Repository) with PECL repository. Normally PHP development (dev) package and PHP Pear package installation from package management system is enough to get PEAR working. Also go-pear.php script can be used. Check that the PEAR and PECL are working with the following commands:
Read more →

PHP mb_ucfirst Make a String’s First Character Uppercase-Multibyte (UTF-8) Function

PHP’s ucfirst function is very usefull when you want to change words first letters to uppercase and other letters to lowercase. Currently on PHP does not have a multibyte (UTF-8) version of ucfirst function. So I decided write my own multibyte mb_ucfirst function. Perhaps the multibyte version of ucfirst function is added later on PHP, so that’s why is better add this function only if it does not already exist.
Read more →

SVN Remove Added File From Repository and Keep Local File – Subversion

This is quick SVN (Subversion) tip, howto remove added file from SVN repository without deleting file from local filesystem. Remove File From SVN Repository and Keep Local File svn delete --keep-local path/to/file.example Real example: svn delete --keep-local css/test.css **Real world usage example** Adding a whole directory add a file that was not intended to SVN reads, but should be retained locally. svn add css/ A css A css/testing_styles.css A css/style.css style.css is OK, but testing_styles.css should not be commited, but it should be kept on locally. Simply remove it from svn but keep it locally:
Read more →

Install NetBeans IDE 6.9.1 on Fedora 14/13, CentOS 5.5, Red Hat (RHEL) 5.5/6

This is guide with screenshots, howto install NetBeans 6.9.1 on Fedora 14, Fedora 13, Fedora 12, CentOS 5.4, CentOS 5.5, Red Hat (RHEL) 5.4, Red Hat (RHEL) 5.5, Red Hat (RHEL) 6. What is NetBeans? The NetBeans IDE (integrated development environment) is available for Windows, Mac, Linux, and Solaris. The NetBeans project consists of an open-source IDE and an application platform that enable developers to rapidly create web, enterprise, desktop, and mobile applications using the Java platform, as well as JavaFX, PHP, JavaScript and Ajax, Ruby and Ruby on Rails, Groovy and Grails, and C/C++.
Read more →

Install Eclipse Mars 4.5 on Fedora 24/23, CentOS/RHEL 7.2/6.8/5.11

This is guide, howto install latest Eclipse Mars.2 4.5.2 on Fedora, CentOS and Red Hat (RHEL). This guide should work with Fedora 24/23/22/21/20/19/18/17/16/15/14/13/12, CentOS 7.2/6.8/5.11 and Red Hat (RHEL) 7.2/6.8/5.11 and even with earlier versions. Latest working version on CentOS/RHEL 5.11 is Eclipse Luna 4.4.2. Eclipse is a multi-language software development environment comprising an integrated development environment (IDE) and an extensible plug-in system. It is written primarily in Java and can be used to develop applications in Java and, by means of various plug-ins, other languages including C, C++, COBOL, Python, Perl, PHP, Scala and Ruby (including Ruby on Rails framework).
Read more →

Install Sun/Oracle Java JDK/JRE 6u45 on Fedora 19/18, CentOS/RHEL 6.4/5.9

Please note: This guide still working normally if you want install Sun/Oracle Java 6, but if you want Java 8 version, then check Install Oracle Java JDK/JRE 8 on Fedora, CentOS/RHEL or if you want Java 7 version, then check Howto Install Sun/Oracle Java JDK/JRE 7 on Fedora, CentOS/Red Hat (RHEL).
Read more →

Eclipse 3.6 Install PDT, JavaScript, CDT, Ruby, MarketPlace Plugins

This is guide, howto install plugins on Eclipse 3.6 SDK. This guide shows howto install PDT (PHP Development Tools), CDT (C/C++ Development Tooling), Javascript Development Tools, Ruby Development Tools (including Ruby on Rails framework) and Eclipse MarketPlace. This guide shows PDT, JavaScript, CDT, Ruby and MarketPlace install as an example, but same methods can be used for installing anything from Helios Repository. Install PDT, JavaScript, CDT, Ruby and MarketPlace Plugins on Eclipse 3.6 Open ‘Install New Software’ window (Help -> Install New Software…)
Read more →

Support inttf:

Buy Me a Coffee:

Support inttf:

Buy me a coffee Buy me a coffee