One place for hosting & domains


      How to Learn PHP… Fast

      PHP is a programming language that has a relatively simple but versatile syntax, making it a great starting point for beginners. However, you might still be overwhelmed by the thought of implementing PHP code for the first time.

      Fortunately, there are plenty of free resources you can use to learn PHP. Whether you watch a few YouTube tutorials or take an online course, you can quickly become familiar with this popular programming language.

      In this post, we’ll introduce you to PHP and explain the benefits of learning it. Then, we’ll show you some easy ways to get started. Ready to dive in?

      An Introduction to PHP

      PHP (PHP: Hypertext Preprocessor) is a server-side scripting language used in web development. It’s currently used on 77.6% of websites, including Facebook, Wikipedia, and Instagram:

      php official website

      Like WordPress, PHP is open-source. Originally, it was used simply to build a personal homepage. However, since its creation in 1994, PHP has evolved to accommodate more dynamic websites.

      The first thing you need to know about PHP programming is that it happens on the server. When someone tries to visit your website, your server will process its PHP code before sending any information to the browser.

      This is what makes PHP different from other scripting languages. If you’re writing HTML or CSS, this code will affect the information visitors see in a browser. However, PHP code is processed before the content loads.

      For example, a PHP script can be used as a source code for HTML. Here’s what the original PHP script can look like:

       <title>PHP Test</title>
      <?php echo '<p>Hello World</p>'; ?>

      In HTML, this will create the following output:

       <title>PHP Test</title>
      <p>Hello World</p>

      When visitors view your website, they will see the “Hello World” message in their web browser. Although PHP is powered by HTML, front-end viewers will only experience the HTML output.

      How PHP Works in WordPress

      If you download WordPress, you’ll notice that many of the files are written in PHP. This is because PHP code is the framework for the WordPress software:

      php files for WordPress

      After creating a WordPress website, your site files are stored in a MySQL database. This contains all your website’s data, including your posts, plugins, and themes.

      When someone clicks on your site link, their browser sends a request to your server. In WordPress, the server has to process PHP code to create HTML pages. Then, it can send the HTML code back to the visitor’s browser.

      Similar to other programming languages, PHP has several versions. If you’re using an outdated version, you won’t receive important bug fixes or security updates.

      As a WordPress user, it’s important to make sure to update your PHP version. WordPress recommends using PHP version 7.4 or greater. This can be the key to keeping your website fast and secure.

      Other than updating the PHP version, some website owners may never touch this code. Since WordPress comes with built-in PHP files, you likely won’t need to learn this programming language to manage your website. That being said, there are many reasons why you may want to consider becoming an expert PHP coder.

      Why You Might Want to Consider Learning PHP

      Since PHP usage has been slowly declining in recent years, you might be wondering if it’s worth learning it. Although fewer websites have been using PHP, it remains the most popular server-side programming language. Plus, it is still a vital part of many Content Management Systems (CMSs).

      In WordPress, PHP is the fundamental language behind all plugins and themes. When you want to modify these tools, you’ll likely need to use PHP coding.

      Plus, PHP is easy to learn. Its syntax is similar to HTML and even uses some embedded HTML in its code. Since you can reuse blocks of code and built-in functions, PHP is one of the simplest programming languages.

      Here are some additional advantages of learning PHP:

      • It’s free and open-source.
      • It integrates with popular databases like MySQL, Oracle, Sybase, PostgreSQL, and more.
      • It supports most web browsers.
      • It offers consistent updates to enhance security, performance, and support.

      If you want to become a web developer, it’s important to learn PHP. When creating new WordPress plugins and themes, you’ll need to know how to build and edit PHP files.

      Once you become familiar with this language, you can eventually become a PHP developer. In this position, you can write scripts to create and modify software for your clients.

      However, knowing PHP can also help you pursue other career paths, such as:

      • Cybersecurity
      • Information Technology (IT)
      • Back-end and full-stack development

      As you progress through your career in PHP development, you can look for higher-paying positions like software development management. You can even pursue directorial roles and become an information technology director.

      How to Learn PHP Fast (5 Methods)

      Although you could gain a college degree in web development, this can be an expensive option. Luckily, there are plenty of ways you can learn how to code online, without having to pay a penny. Let’s look at how you can become an expert in PHP, for free.

      1. Watch a YouTube Tutorial

      If you’re looking to learn a new skill, one of the best online resources is YouTube. By watching in-depth guides from expert coders, you can easily become familiar with PHP programming.

      Unlike other social media sites, YouTube tends to highlight the most popular videos, rather than the most recent ones. If you watch a tutorial that was published years ago, you could receive outdated information.

      To narrow your results, you can click on Filters at the top of the page. Next, select a recent upload date. You can choose your desired video length as well:

      youtube search php tutorial

      Then, you can find a video that suits your needs. One of the most popular PHP tutorials is PHP For Beginners by Traversy Media. This outlines the fundamentals of PHP:

      In this YouTube video, you can use timestamps to skip to an area you want to learn. If you watch the entire three-hour tutorial, you can learn everything about PHP, including functions, loops, arrays, and more. By following along with the voiceover, you can create your first PHP/MySQL project.

      You can also watch PHP Tutorial for Beginners – Full Course by Envato Tuts+. This is a more detailed PHP guide that takes you from an absolute beginner to an expert coder:

      envato tuts youtube learn php

      The instructor, Jeremy McPeak, starts with the basics, showing you everything you need to learn as a beginner. Then, he teaches you about variables, syntax, and how to make decisions in your code. By the end of the video, you’ll be able to write your own functions and respond to GET and POST requests.

      When you search for PHP tutorials on YouTube, you can find thousands of free videos to watch. With this method, you can watch coding in real-time rather than reading a static web page.

      2. Take an Online Course

      If you want to receive a more in-depth explanation of PHP, you can sign up for an online course. Although it can take longer to complete course modules, this can lead to a more thorough education in programming.


      Whether you’re trying to prepare for a career in web development or just learning programming languages as a hobby, you can learn how to code on Codecademy. This platform provides the free Learn PHP course, which has been taken by over 45 million people:

      Codeacademy learn php

      In 25 hours, you’ll receive a comprehensive overview of PHP, including variables, functions, arrays, loops, and more. Each module has instructions on how to immediately implement what you’ve learned:

      Codeacademy learn php exercise

      Once you follow the instructions and enter the correct coding, you can continue to the next lesson. If you need help, you can always use a hint:

      Codeacademy php exercise

      At any point, you can review key concepts using the cheatsheet. You can also browse the Codecademy community forums for that module. These links are provided at the end of each exercise:

      Codeacademy php concept review forums

      Since PHP interacts with HTML, you’ll likely need to know the basics of HTML before taking this course. Fortunately, Codecademy has a Learn HTML course that you can take beforehand.


      Another place to find PHP courses is Udemy. Here, you can join over six million users and start expanding your coding skills. Unlike Codecademy, Udemy contains many different PHP courses, so you can find the one that best suits your needs:

      udemy php courses

      With over 22,000 reviews, the most popular PHP course on Udemy is called PHP for Beginners. In this program, you can watch 37 hours of educational videos and obtain a certificate once you’re finished:

      udemy php for beginners course

      If you’re completely new to coding, this Udemy course takes you through the basics of PHP, as well as Object Oriented PHP and MySQLi. You’ll learn about custom functions, PHP security, control structures, and much more. It also teaches you how to create a content management system similar to WordPress or Joomla.

      3. Review the PHP Manual

      You can also learn the best practices of the PHP language straight from the creators themselves. In the official PHP manual, you’ll gain installation instructions, syntax advice, and Frequently Asked Questions (FAQs) from other emerging developers.

      When you first open the manual, you can read an overview of PHP and what it does. This will also list compatible operating systems and databases:

      php manual what is php

      Then, you can follow the installation and configuration guide. Depending on your operating system, you’ll see some requirements and best practices on how to get started:

      php manual how to install and configure

      One of the most helpful sections of this manual is the Language Reference. Here, you’ll find a list of outbound links about basic PHP syntax and how to start writing your own code:

      php manual language reference

      Similar to online courses, you can read how-to guides about variables, functions, operators, and much more. You’ll even learn how to handle PHP errors when they happen:

      php manual basics

      This manual also gives you information about PHP security. You can read about possible attacks, as well as error reporting:

      php manual security overview documentation

      As you become more knowledgeable in PHP, you can keep this manual for future reference. For example, you might need to look up certain functions to implement them properly:

      php manual function reference

      However, the PHP manual may not be the best option for beginners. Although its information is valuable and straightforward, it doesn’t include any interactive exercises. You’re likely better off using this as a reference during the learning process.

      4. Read a Book

      If you’re a visual learner, one way to learn PHP is by reading a book. Whether you find an online publication or go to your local library, you can find valuable information about the PHP programming language.

      PHP Apprentice is an online book that you can access for free. You can use this open-source reading material to start understanding PHP and its practices:

      php apprentice overview

      Using the table of contents, you can find a specific topic about PHP. For each chapter, there will be written explanations along with examples of coding:

      php apprentice module

      Plus, PHP Apprentice is a book that is constantly evolving. By giving feedback on its GitHub repository, you can request certain topics or more in-depth explanations:

      php apprentice code

      When learning a new skill like PHP, it can often be more convenient to read an e-book because they’re readily available online. However, you can also use your local library.

      On your library’s website, you can search its database for PHP books. Then, you can place a hold on the ones you want to read:

      learn php book recommendations

      Some libraries even let you check out e-books using an app like CloudLibrary or OverDrive. This way, you can get your hands on library books without ever leaving your home.

      Although the library can be a valuable resource for free books, you may not find the most up-to-date information. If you decide this method is right for you, you’ll want to look for books that were published in the last few years. This way, you’re not learning an outdated PHP version.

      5. Try an Interactive Tutorial

      Rather than signing up for an educational course in PHP, you can walk yourself through online tutorials. You don’t have to pay for the learning material or even create an account – you can simply open the website and start learning at your own pace. Let’s look at some options.


      W3Schools is one of the best resources for free coding tutorials. On this platform, you can learn the basics of PHP, CSS, HTML, JavaScript, and much more.

      When you click on its PHP guide, you’ll notice that there are tons of free modules to explore:

      php tutorial introduction to php

      In the introductory sections, W3Schools will outline the basic concepts of PHP, as well as everything you need to get started:

      php tutorial php installation

      When you dive into the learning modules, you can read detailed explanations about syntax, variables, operators, regular expressions, and any other PHP concept. You’ll also see coding examples on each page:

      php tutorial syntax

      By clicking on Try it Yourself, you can open a code editor in a new tab. Here, you can implement changes to the existing code and see how it’ll look on the front end:

      w3schools coding exercise

      Once you grasp the basics, you can learn more advanced concepts. W3Schools will show you how to create forms with data validation. You’ll also learn how to use PHP with Object-Oriented Programming, a MySQL database, XML parsers, and AJAX.

      When you feel comfortable with what you’ve learned, you can test your skills with quizzes and exercises:

      w3schools learn php quiz

      This can help you remember what you’ve studied. Plus, you can check whether you need to revise certain concepts and go back to those modules if needed.

      If you want to learn PHP with a simple but effective interface, you can try the interactive tutorial on Although this won’t turn you into a developer, you can use it to understand how PHP works: tutorial

      In just 11 modules, you’ll learn about variables, arrays, strings, loops, functions, and more. Like some other options on this list, includes simple explanations of concepts, followed by coding examples:

      php simple arrays

      At the bottom of the page, you can perform an exercise to test your knowledge. For example, you may have to create a new array in PHP: exercise

      Although doesn’t have a lot of modules yet, it is constantly being updated. Using its GitHub repository, developers can add new tutorials for you to learn for free.

      Start Learning PHP Today

      By learning the basics of PHP, you can jumpstart your career in web development. Since PHP is a vital part of WordPress, this skill can help you create new themes and plugins for personal or public use.

      Here are some ways you can start learning PHP as a beginner:

      1. Watch a YouTube tutorial from creators such as Traversy Media and Envato Tuts+.
      2. Take an online course on Codecademy or Udemy.
      3. Review the PHP manual.
      4. Read a book like PHP Apprentice.
      5. Try an interactive tutorial on W3Schools or

      If you want to start experimenting with PHP, you may want to create your own website. With our shared hosting plans, you can quickly launch a new site without breaking the bank!

      Web Hosting That Powers Your Purpose

      We make sure your website is fast, secure and always up so your visitors trust you. Plans start at $1.99/mo.

      shared hosting

      Source link

      Why You Should Update Your PHP Version (& How to Do It)

      Regularly updating your site’s copy of WordPress ensures that your website will have a high level of performance and security. If you forget to update your site’s PHP version though, you’re leaving your site vulnerable to both hackers and potential performance bottlenecks. Yikes!

      Fortunately, it’s fairly easy to check your site’s current PHP version and proceed with upgrades if it happens to be outdated. This process can contribute to faster load times, improved security, and support for new functionality.

      This article will discuss what PHP is, and why you should consider updating it. Then, we’ll show you how to check your current PHP version and upgrade it if needed. Let’s get started!

      An Introduction to PHP

      update your PHP version

      PHP is a programming and scripting language that plays an important role in WordPress development. PHP takes data from the database and converts it into an HTML web page whenever someone visits your website.

      As a website owner, you might never need to learn PHP coding. However, after downloading WordPress, you’ll automatically receive all of the PHP files that make up WordPress core:

      WordPress folder in FTP client

      Although these files have been written for you — and are just waiting for your content, themes, and plugins — there are some scenarios where you can benefit from editing PHP files:

      Since PHP is one of the key languages behind WordPress, learning a little bit about how to work with it will open up the scope of projects that you are able to do.

      It’s likely that you won’t have to edit your PHP files. Still, learning the language can be handy for developers who wish to create new software or customizations.

      Why You Should Update Your PHP Version

      You might already be familiar with the importance of updating your WordPress, themes, and plugins. It’s also crucial to regularly update your PHP version:

      PHP 8.1 released

      Currently, WordPress recommends upgrading your PHP version to at least 7.4. This isn’t required, but older versions may have reached their end of life, meaning they no longer have active support for bug fixes or security updates.

      Here are the main benefits of upgrading your sites to the latest PHP version:

      • Better security: Older PHP versions can be more vulnerable to cyberattacks.
      • Improved performance: Upgraded PHP can improve load times through internal code improvements and reduced memory usage.
      • More support: Currently supported versions have active support, with regular bug fixes and security patches.

      Take it from our Director of IT Operations, Luke Odom:

      “Running a modern, supported, version of PHP is one of the best things you can do for the health, security, and speed of your website. Let’s compare an outdated PHP version to an old car. Sure, it will run and get you from point A to B, but without modern safety sensors, technology, fuel efficiency, and GPS navigation you may find yourself in some trouble a bit more easily.”

      Ultimately, your website will be faster and more secure when it’s running on the latest version of PHP. Many web hosts provide automatic updates for their customers, but if you’re not with one of these hosts, you can follow this manual process.

      How to Check Your Current PHP Version

      Before you get started, you should check which PHP version is currently supporting your website. If you’ve installed WordPress 5.0 or higher, you can view your PHP version in your dashboard.

      First, go to Tools > Site Health:

      WordPress Tools Site Health

      On the Site Health page, click on Info. Then find the Server section:

      view server Site Health in WordPress

      Here, you should be able to see your current PHP version:

      view your server's PHP version

      Another simple method for checking your PHP version is using your web host’s control panel. For DreamHost websites, click on the Manage button next to your domain:

      manage websites in DreamPress Panel

      Then, find the section labeled PHP. This will list your site’s PHP version:

      modify your PHP version

      The latest PHP release is 8.1. If you have a version older than 7.4 — the version that the WordPress project suggests — you can proceed with the following steps.

      Skip the line and get tips right in your inbox

      Click below to sign up for more how-to’s and tutorials just like this one, delivered to your inbox.

      marketing tips

      How to Update Your PHP Version (In 4 Easy Steps)

      Once you decide to update your version of PHP, we recommend taking a few precautions. Firstly, consider backing up your website. If anything goes wrong, you can roll back your version of PHP and then revert your site to the backed-up version.

      Next, make sure your website is fully up to date. In your dashboard, go to the Updates page and install the latest versions of WordPress, themes, and plugins:

      WordPress Proxy Cache plugin

      After taking these preventative steps, you can start manually updating your PHP version. As a simpler alternative, you can also contact your hosting provider. The host can typically handle this process for you.

      Step 1: Create a Staging Site

      Updating your PHP version can cause software conflicts on your website. Therefore, it’s wise to test the update in a staging area initially. This creates a separate, safe environment to implement changes rather than breaking your live site.

      With many hosting providers, you can create a staging site through your control panel. For this tutorial, we’ll be using the DreamHost panel.

      If you have a managed DreamHost plan, you can set up your staging site in minutes. Simply open your control panel and navigate to WordPress > Managed WordPress > Manage:

      DreamPress managed WordPress settings in PanelOn the next page, go to Staging. Then, click on Create Staging Site:

      create a one click staging site with DreamPress managed WordPress hosting

      This will set up your staging site on an automatically generated subdomain. After this, you can update your PHP version without editing your live site.

      Step 2: Change Your PHP Version

      No matter your hosting provider, you can usually change your website’s PHP version through your control panel. This process will look different based on your host, but you’ll want to look for a MultiPHP Manager or PHP Selector.

      To edit your DreamHost staging site, you can simply scroll down to the Configure PHP section. This section will list your current PHP version and the most recent update option:

      change PHP version

      To update PHP, click on Change PHP to v8.1. If successful, this section will indicate that your site is up to date:

      configure your PHP version

      Although it isn’t recommended, you can also directly modify your live website. In your DreamHost panel, go to Manage Websites. Then, scroll down to PHP and click on the arrow next to Modify:

      select PHP version in the DreamHost panel

      Lastly, select the new version you want to run on your website. Click on Change PHP Version to finish the process.

      Step 3: Look for Conflicts

      After updating your PHP version, we recommend reviewing your plugins and themes for conflicts. Upgrading PHP may cause common problems such as the White Screen of Death or 500 internal server errors.

      Whether you updated a staging environment or your live site, visit the front end to see if everything is functioning correctly. If you notice any errors after browsing the website, you’ll need to troubleshoot the issue.

      One common reason for WordPress errors is a plugin conflict. When issues arise, try deactivating all of your plugins using the Bulk Actions on your Plugins page:

      deactivate WordPress plugins

      To target the conflicting plugin, reactivate each plugin one by one. Then, you can download a similar plugin or delete it if it’s unnecessary.

      If you face additional problems like exceeded maximum execution time or maintenance mode errors, you might need to edit your wp-config.php file. This process could require more extensive troubleshooting, such as increasing your PHP memory limit.

      Step 4: Publish Changes to Your Live Site

      If you implemented a new PHP version on a staging site, it’s time to publish this change on your live website. Usually, you can do this in your host’s control panel.

      For example, DreamHost provides a simple one-click transfer of your staging data to your website. Once you’re sure you’ve targeted any potential conflicts, you can click on Publish Staging to Live:

      push staging environment to live

      This will successfully update your website’s PHP version. Since you used a staging site, you won’t have to worry about unexpected errors!

      Ready for an Upgrade?

      You might be hesitant to update your PHP version because you’re worried about breaking your site. However, PHP updates ultimately improve the security and performance of your website. You can easily avoid any conflicts by testing changes before making them live.

      To review, here are the four steps you can take to update the PHP version of your website:

      1. Create a staging site.
      2. Change your PHP version.
      3. Look for conflicts.
      4. Publish changes to your live site.

      Although you can manually update your PHP version, you might want to avoid doing this for every new development. Here at DreamHost, our Website Maintenance plans now include automatic PHP updates! This way, you can sit back, relax, and leave this process to us.

      Website and PHP Version Management Made Easy

      Let us handle the backend — we’ll manage and monitor your website so it’s safe, secure, and always up.

      website tech support

      Source link

      How to Set Up a Website Hit Counter With Redis and PHP on Ubuntu 20.04

      The author selected the Apache Software Foundation to receive a donation as part of the Write for DOnations program.


      A hit counter is an application that records and indicates the number of visits your web page has received. The counter starts from 1 and is incremented once every time a web page is visited.

      To keep track of the visits, the hit counter application requires a form of a database. While disk-based database management systems like MySQL can work, an in-memory database is better in terms of speed, performance, scalability, simplicity, and ease of use. This is where the Redis server comes into play. Redis stores data in your computer’s RAM instead of hitting the disk every time you’re performing an input/output operation. This increases the throughput significantly.

      To track your site visits, you require a Redis hash map. This is a data structure that implements a key-value pair. A hash map provides a hash table that maps keys to values. Once a user visits your web page, you create a key based on their public IP address or username (for authenticated users), and then you initialize their total visits to a value of 1. Then, every time the user revisits your web page, you check their total visits from the Redis hash map based on their IP address/username and increment the value.

      In this guide, you’ll set up a website hit counter with Redis and PHP on your Ubuntu 20.04 server. The PHP scripts in this guide use the visitors’ public IP addresses to track their visits.


      To follow along with this guide, make sure you have the following:

      Step 1 — Installing PHP Redis Extension

      In this step, you’ll install a Redis extension that allows PHP to talk to the Redis server. You’ll also create a test web page that implements the Redis hash map to track web visits.

      Before installing the Redis extension, refresh your Ubuntu package information index:

      Then, run the following command to install php-redis. The extension provides an API for communicating with the Redis server key-value store:

      • sudo apt install -y php-redis

      Restart Apache to load the new extension:

      • sudo systemctl restart apache2

      You’ve now installed a PHP extension that talks to your Redis server. Next, you’ll create a test.php web page under the root directory of the Apache webserver. This is just a sample file that visitors request when they visit your website with a browser. Under the hood, the test.php page file loads a hit_counter.php script which you’ll later create to track page visits using the Redis server.

      In a real-life scenario, your website might have tens or even hundreds of web pages. For this guide, you’ll set up a single web page for demonstration purposes.

      In your terminal window, use nano to create a new test.php file under the root directory of your web-server /var/www/html/:

      • sudo nano /var/www/html/test.php

      Then, enter the following information into the test.php file:


        require_once 'hit_counter.php';
      <!DOCTYPE html>
          <title>Sample Test Page</title>
          <h1>Sample test page</h1>
          <p>This is a sample test page.</p>

      Save and close the file when you’re through with editing. In this step, you’ve created a simple HTML web page that loads a hit_counter.php file when visited. Next, you’ll code the hit_counter.php file to track the test page visits.

      Step 2 — Creating a Redis Hit Counter Script

      When working in a production environment, it’s very conventional to separate re-usable PHP files. This allows you to implement the logic in these files on different parts of the project just by including their paths instead of copy-pasting the code. This makes maintenance easier since you only need to edit a single file in case you need to change the logic. This saves you a lot of time.

      You’re going to apply the same strategy in this guide. You’ll create a single hit_counter.php file that you can include on any web page that requires visitors’ tracking.

      In this file, you’ll use the php-redis library to connect to the Redis server from PHP. Then, you’ll create a Redis hash map to store the number of visits a visitor has made to your website. You’ll use the visitors’ unique IP addresses as Redis keys to distinguish each visitor’s hit counts in the Redis server.

      In your terminal window, open a new hit_counter.php file using nano for editing purposes:

      • sudo nano /var/www/html/hit_counter.php

      With the hit_counter.php file now created, open a new PHP tag <?php. Then, inside a try { block enter the following code to connect to your local Redis server on port 6379. Replace EXAMPLE_PASSWORD with the authentication password for the Redis server:


          try {
              $redis = new Redis();
              $redis->connect('', 6379);

      Next, give the Redis hash map($siteVisitsMap) a name of your choice. This guide uses siteStats for demonstration purposes:


              $siteVisitsMap = 'siteStats';

      After defining the Redis hash map, you’ll now initialize an empty Redis key ($visitorHashKey). Then, you’ll populate it with the visitors’ IP addresses. You’ll use the value of the $visitorHashKey variable to uniquely identify each visitor requesting your web page:


              $visitorHashKey = '';           
              if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
                  $visitorHashKey = $_SERVER['HTTP_CLIENT_IP'];
              } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
                  $visitorHashKey = $_SERVER['HTTP_X_FORWARDED_FOR'];
              } else {
                  $visitorHashKey = $_SERVER['REMOTE_ADDR'];

      In this code, you’re using the PHP if statement to determine the visitor’s IP address by checking whether the $_SERVER['HTTP_CLIENT_IP'], $_SERVER['HTTP_X_FORWARDED_FOR'], or $_SERVER['REMOTE_ADDR'] variables are populated.

      Following this, initialize a $totalVisits variable to store the total visits for each IP address and assign it a value of 0. Then, use the PHP if (...) {...} else {...} and $redis->hExists($siteVisitsMap, $visitorHashKey) statements to check if the IP address has any entries in the Redis server.

      You’ll use the statement if ($redis->hExists($siteVisitsMap, $visitorHashKey)) {...} to check whether a $visitorHashKey exists in a map named $siteVisitsMap.

      In case the map and the key with the named IP address exist in the Redis server, retrieve it with the statement $visitorData = $redis->hMget($siteVisitsMap, array($visitorHashKey)); and use $totalVisits = $visitorData[$visitorHashKey] + 1; to increment the $totalVisits variable. You’re using the $redis->hMget statement to get hit count data associated with an IP address. The hMget function accepts the name of your map ($siteVisitsMap) and an array of the keys that you want to retrieve from the Redis server. In this case, you only have one key ($visitorHashKey), but you must convert it to an array using the statement array($visitorHashKey).

      In case your script encounters the IP address for the first time, set the $totalVisits variable to 1. Finally, use $redis->hSet($siteVisitsMap, $visitorHashKey, $totalVisits); to set the value of the $visitorHashKey according to the results of the previous if (...) {...} else {...} statement. The $redis->hSet($siteVisitsMap, $visitorHashKey, $totalVisits) statement creates a $siteVisitsMap hash map in the Redis server with a key named $visitorHashKey with a value of $totalVisits.

      Then, welcome the visitor by echoing the total visits and close the } catch (...) {...} block:


              $totalVisits = 0;
              if ($redis->hExists($siteVisitsMap, $visitorHashKey)) {
                  $visitorData = $redis->hMget($siteVisitsMap, array($visitorHashKey));
                  $totalVisits = $visitorData[$visitorHashKey] + 1;
              } else {
                  $totalVisits = 1;
              $redis->hSet($siteVisitsMap, $visitorHashKey, $totalVisits);
              echo "Welcome, you've visited this page " .  $totalVisits . " timesn";
          } catch (Exception $e) {
              echo $e->getMessage();

      Once completed, your /var/www/html/hit_counter.php file should be similar to the following code:


          try {
              $redis = new Redis();
              $redis->connect('', 6379);
              $siteVisitsMap  = 'siteStats';
              $visitorHashKey = '';           
              if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
                 $visitorHashKey = $_SERVER['HTTP_CLIENT_IP'];
              } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
                 $visitorHashKey = $_SERVER['HTTP_X_FORWARDED_FOR'];
              } else {
                 $visitorHashKey = $_SERVER['REMOTE_ADDR'];
              $totalVisits = 0;
              if ($redis->hExists($siteVisitsMap, $visitorHashKey)) {
                  $visitorData = $redis->hMget($siteVisitsMap,  array($visitorHashKey));
                  $totalVisits = $visitorData[$visitorHashKey] + 1;
              } else {
                  $totalVisits = 1;
              $redis->hSet($siteVisitsMap, $visitorHashKey, $totalVisits);
              echo "Welcome, you've visited this page " .  $totalVisits . " timesn";
          } catch (Exception $e) {
              echo $e->getMessage();

      Save and close the file when you’re through with editing. You’ve now coded a hit_counter.php script. Next, you’ll create another PHP script that generates a report from the data gathered in the Redis hash map.

      Step 3 — Creating a Site Stats Report Script

      Once you’ve collected data in a Redis hash map, it might not make any sense if you’re not able to retrieve and represent the information in a report. In this step, you’ll create a log report to show the different site visitors and the total visits they’ve made on the test web page.

      To create the log report script, run nano on your terminal window and create a new /var/www/html/log_report.php file:

      • sudo nano /var/www/html/log_report.php

      Then, enter the information below into the file. Replace EXAMPLE_PASSWORD with the correct password for the Redis server:


      <!DOCTYPE html>
          <title>Site Visits Report</title>
            <h1>Site Visits Report</h1>
            <table border="1">
                <th>Total Visits</th>
                  try {
                      $redis = new Redis();
                      $redis->connect('', 6379);
                      $siteVisitsMap = 'siteStats';                          
                      $siteStats = $redis->HGETALL($siteVisitsMap);
                      $i = 1; 
                      foreach ($siteStats as $visitor => $totalVisits) {
                          echo "<tr>";
                            echo "<td align = 'left'>"   . $i . "."     . "</td>";
                            echo "<td align = 'left'>"   . $visitor     . "</td>";
                            echo "<td align = 'right'>"  . $totalVisits . "</td>";
                          echo "</tr>";
                  } catch (Exception $e) {
                      echo $e->getMessage();

      Save and close the file when you’re through with editing. In the above script, you’re connecting to the Redis server and you’re using the statement $redis->HGETALL($siteVisitsMap); to retrieve your web page visits’ hash map. Then, you’re using the PHP foreach ($siteStats as $visitor => $totalVisits) { statement to loop and display the visitors’ IP addresses and the number of visits they’ve made to your site. You’re using the Redis HGETALL command to retrieve all fields (IP addresses) and values (total visits per each IP address) from the siteVisitsMap map.

      You now have a test page, a hit counter script, and a report page to check your site stats. Next, you’ll test the functionalities of your hit counter and see if everything works.

      Step 4 — Testing the Redis Hit Counter

      In this step, you’ll test the whole logic for your hit counter. Navigate to the following URL on your web browser. Replace your-server-IP with your server’s public IP address or domain name.


      Refresh the page several times using different devices to generate enough stats. After each visit, you should receive the following output.

      Next, visit the following URL to get your site visits report displayed in an HTML table


      You should now see a report similar to the following output.

      Your hit counter is now working as expected.


      In this guide, you’ve set up a website hit counter with Redis and PHP on your Ubuntu 20.04 server.

      As you can see from the sample source code in this guide, Redis provides cleaner methods for creating and updating hash maps.

      As mentioned at the beginning of this guide, using a relational database management system may still work but you’ll write tons of code to insert and update data in underlying tables. In addition, disk-based databases may experience scalability issues when your site grows.

      For more information on using Redis in-memory database, follow the guides below:

      Source link