PHP Tips & Tutorials

PHP: True empty() function to check if a string is empty or zero in length

The strange thing is that the native empty() function of PHP treats a string of ‘0’ as empty: $str = ‘0’; echo empty($str) ? ’empty’ : ‘non-empty’; And it will output ’empty’. Therefore if you need to examine if a string is truly an empty string with zero length, you have to use: echo strlen($str) …

PHP: True empty() function to check if a string is empty or zero in length Read More »

PHP: Checking Text Strings against Reserved or Censored Words

I created a free online web form builder a while back and since it went well in search engine rankings, spammers and phishers found it and started to use it creating forms to collect email account usernames and passwords through phishing attempts. I’ve got to do something before my host closes down my site because …

PHP: Checking Text Strings against Reserved or Censored Words Read More »

How to create / generate .htpasswd password with PHP dynamically?

The easy way to add a username and password pair in the .htpasswd file is to use an online password generator tool that converts the clear text password into its hash, a.k.a. the encrypted password. The problem with this approach is that you have to manually create the pair and append it to .htpasswd. Is …

How to create / generate .htpasswd password with PHP dynamically? Read More »

Check how much memory your PHP script is using. (PHP script memory usage)

Depending on the web server software you use, your PHP script will be consuming significantly different amount of memory (RAM). If you are using Apache without proper optimization, the simplest request that does nothing but returns a status code will need 150kB of memory. Multiply this by 2000 visits per day and by 10 sites …

Check how much memory your PHP script is using. (PHP script memory usage) Read More »

How to get all the sub-directories of a given directory in PHP?

When you read the content of any specified directory with PHP functions such as scandir() or readdir(), they will return both files and directories. How does one get just the child directories of a given directory in PHP? The obvious solution is the is_dir() function that checks if a filename is a directory: $all = …

How to get all the sub-directories of a given directory in PHP? Read More »

How to check if a MySQL database connection is successful in PHP?

If you have mysqli extension installed with PHP and you use it to perform database operations, after you have tried to connect to MySQL by: $conn = new mysqli(‘localhost’, ‘db_user’, ‘db_pwd’, ‘db_name’); You can then check if the connection is successful by: if ($conn -> connect_errno) { // failure } else { // success } …

How to check if a MySQL database connection is successful in PHP? Read More »

PHP: Delay Function that Halt Code Execution Temporarily and Then Resume It

Sometimes you need to temporarily halt the code execution of your PHP script for certain seconds and then automatically resume it. For example, some mail delivery servers have the restriction that you have to wait a certain interval such as 12 seconds before sending another email. You can tell your PHP script to stop for …

PHP: Delay Function that Halt Code Execution Temporarily and Then Resume It Read More »

PHP and JavaScript Variable / Value Transfer / Exchange: How to pass variable values from PHP to JavaScript or JavaScript to PHP?

This is a rather common problem for novice web developers. While it may seem at first glance that it’s easy for PHP and JavaScript to communicate with each other, but they actually cannot interact with each other directly. They are very different technologies built for distinct purposes. How to transfer or pass variable values from …

PHP and JavaScript Variable / Value Transfer / Exchange: How to pass variable values from PHP to JavaScript or JavaScript to PHP? Read More »

How to execute / run PHP code inside JavaScript files?

Static files of JavaScript would survive most applications but sometimes the ability to include PHP code inside JavaScript scripts and generate the content of the script files on the fly by PHP is a better option. How does one do that? The simplest solution is to just include PHP code inside the <script></script> section of …

How to execute / run PHP code inside JavaScript files? Read More »

How to bring down / optimize memory usage in your unmanaged Linux VPS box and avoid OOM (Out Of Memory) errors?

The other day I was very upset about some extraordinary down times of my unmanaged VPS box at Linode. As it’s unmanaged, support staff at Linode are not responsible for the failures. I contacted them and they told me it’s OOM (Out Of Memory), pointing me to the right documentation to figure out how to …

How to bring down / optimize memory usage in your unmanaged Linux VPS box and avoid OOM (Out Of Memory) errors? Read More »

Simplest PHP Hit Counter or Download Counter – Count the Number of Times of Access (Page Views or File Downloads)

Here’s how you can create yourself the simplest PHP hit counter that records the number of times any resource on your website that has been accessed (visited or downloaded). It can be either a web page or a downloadable file package. The hits number will be stored in a plain text file named count.txt. Hit …

Simplest PHP Hit Counter or Download Counter – Count the Number of Times of Access (Page Views or File Downloads) Read More »

Turn off and disable magic_quotes_gpc in .htaccess

It’s not only insecure but it inconveniently commands the use of PHP function stripslashes() every time you pull something from the database or when you get something from the client side. While most of the hosts out there are using factory settings of PHP that turn off magic_quotes_gpc by default, there are a few that …

Turn off and disable magic_quotes_gpc in .htaccess Read More »

CSS: How to write CSS rules to detect or target Chrome, Safari or Opera browsers only?

It’s easy to target firefox, just write as expected by the standards, at least most of the time. It’s also easy to target IE and any specific versions of them by a few of the famous hacks or the IE conditional comments to selectively include style sheets by version numbers. But how does one write …

CSS: How to write CSS rules to detect or target Chrome, Safari or Opera browsers only? Read More »

PHP Security Guide & Checklist for Websites and Web Applications – Bottom Line for Every Good PHP Developer

It’s not easy to become a great PHP developer which may very well take years of training and practice, but this doesn’t mean you shouldn’t do your best to not be a bad one that undermines every project he’s involved in. Based on the project experiences of my team and some recent researches done on …

PHP Security Guide & Checklist for Websites and Web Applications – Bottom Line for Every Good PHP Developer Read More »

PHP: setcookie() with HttpOnly Option to Reduce XSS (Cross Site Scripting) Attacks by Preventing JavaScript from Reading Cookies

It may considerably reduce XSS attack possibilities if not completely eradicate it. XSS, or Cross Site Scripting, is probably the most common security problems in web applications that engage in heavy user input. If you’ve ever tried to build a web application that users can input data in a lot of different venues, chances are …

PHP: setcookie() with HttpOnly Option to Reduce XSS (Cross Site Scripting) Attacks by Preventing JavaScript from Reading Cookies Read More »

PHP: How to distinguish values in $_POST or $_GET that are sent via HTTP requests and those that are set / assigned in the code

To send parameters to a PHP script, you can either fabricate a form and post a few variables by the POST method or simply send a request of a URL full of GET value pairs. This way, in the server side PHP script code, you can retrieve these parameters sent from the client in $_POST …

PHP: How to distinguish values in $_POST or $_GET that are sent via HTTP requests and those that are set / assigned in the code Read More »

PHP: Check or Validate URL and Email Addresses – an Easier Way than Regular Expressions, the filter_var() Function

To check if a URL or an email address is valid, the common solution is regular expressions. For instance, to validate an email address in PHP, I would use: if (preg_match(‘|^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$|i’, $email)) { // $email is valid } A simpler and more forgiving one would be: |^\S+@\S+\.\S+$| Which is usually quite enough for signup forms …

PHP: Check or Validate URL and Email Addresses – an Easier Way than Regular Expressions, the filter_var() Function Read More »

PHP: How to detect / get the real client IP address of website visitors?

It may seem simple at first because most of us should be relying on the server side environmental variable REMOTE_ADDR solely for client IP addresses: echo $_SERVER[‘REMOTE_ADDR’]; Yet it’s barely enough to get the real IP for a variety of circumstances such as when the user is visiting your website from a proxy server. To …

PHP: How to detect / get the real client IP address of website visitors? Read More »

Use PHP to handle all incoming URL requests in a SEO friendly manner

While you can always use .htaccess and the mod_rewrite module to map SEO friendly URLs to actual PHP parameterized URLs with question marks and ampersands, you can simply put these lines in .htaccess and then rely on PHP entirely to recognize and handle all incoming URL requests of any kind / form: <IfModule mod_rewrite.c> RewriteEngine …

Use PHP to handle all incoming URL requests in a SEO friendly manner Read More »

Scroll to Top