PHP is mostly used to create dynamic web pages, but there is much more you can do with it.
In this post you will find 9 amazing examples of how you can use PHP besides creating web pages.
You’ll be surprised to see how many things it can be used for.
(By the way: if you are new to PHP, here is how you can learn it in less than a week).
So… what can you do with PHP?
Let’s find out.

WHY USE PHP?

Source: W3Techs
There are different reasons why PHP is such a popular language:
- it’s easier than many other languages
- it’s suitable for web content and backend data output
- it provides you with a complete toolkit of functions and classes right out of the box
The fact that it’s so widely used also means that you can find online support very easily (for example, in my Facebook group 😉 )
The main argument against PHP is its presumed poor performance and efficiency.
Sure, you can’t expect PHP to be as efficient as C or C++. That’s true.
However, unless you are working on critical or embedded systems where efficiency is a top priority, this performance gap is hardly an issue.
Moreover, PHP (version 7) fares quite well when compared with similar languages.
In fact, PHP can be 382% faster than Python, 378% faster than Perl and 195% faster than Ruby.
WHAT IS PHP USED FOR?
PHP is well suited for different kind of tasks.
For example:
let’s say you need to implement an HTTP backend or a REST service. In that case, you want to use a language that:
- is well supported by the most used web servers like Apache
- integrates perfectly with SQL databases like MySQL
- can handle text, strings and numeric data easily
PHP fits perfectly. In fact, it’s usually the first choice for such projects.
Look at this:

It’s an HTML5 graph I made at work. It shows the air temperature of the last 24 hours.
The graph itself is made with a canvas library named RGraph, but the actual temperature values (that is, the backend data) are calculated, stored and retrieved by a PHP backend.
But how do you know if PHP is a good choice for your projects?
A good starting point is to ask these 3 questions:
- will my project make use of PHP strengths and functionalities?
- can I run this project from a web server or with a command line PHP interpreter?
- does this project require extremely high performance and efficiency?
If you answered yes to the first two questions and no to the last one, then PHP is a good candidate.
Now, enough talking.
It’s time to see some practical examples of what you can do with PHP, starting with something you are definitely going to use: authentication.
[easy-tweet tweet="What can you do with PHP? 9 amazing examples of what PHP can be used for." via="no" hashtags="PHP"]
USER AUTHENTICATION
(INCLUDING TWO-STEP VERIFICATION)
User authentication is one of the cornerstones of web security.
If you are building a web application, chances are you need to implement user authentication.
There are a lot of different techniques you can use, from simple username/password validation to complex two (or more) steps verification.
And guess what?
With PHP, you can implement any of these techniques.
Let’s look at some of them.
Username and password authentication
Performing username and password validation is as easy as comparing two strings.
PHP can easily store and retrieve username and password pairs on a database, using top-level encryption.
You can learn exactly how to encrypt passwords in PHP here: PHP password hashing tutorial.
To see how it can be done in practice, look at the following login and add_account functions taken from my authentication tutorial:
/* Username and password authentication */
public function login($name, $password)
{
/* Check the strings' length */
if ((mb_strlen($name) < 3) || (mb_strlen($name) > 24))
{
return TRUE;
}
if ((mb_strlen($password) < 3) || (mb_strlen($password) > 24))
{
return TRUE;
}
try
{
/* First we search for the username */
$sql = 'SELECT * FROM accounts WHERE (account_name = ?) AND (account_enabled = 1) AND ((account_expiry > NOW()) OR (account_expiry < ?))';
$st = $this->db->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$st->execute(array($name, '2000-01-01'));
$res = $st->fetch(PDO::FETCH_ASSOC);
/* If the username exists and is enabled, then we check the password */
if (password_verify($password, $res['account_password']))
{
/* Log in ok, we retrieve the account data */
$this->account_id = $res['account_id'];
$this->account_name = $res['account_name'];
$this->is_authenticated = TRUE;
$this->expiry_date = $res['account_expiry'];
$this->session_start_time = time();
/* Now we create the cookie and send it to the user's browser */
$this->create_session();
}
}
catch (PDOException $e)
{
/* Exception (SQL error) */
echo $e->getMessage();
return FALSE;
}
/* If no exception occurs, return true */
return TRUE;
}
/* Adds a new account */
public static function add_account($username, $password, &$db)
{
/* First we check the strings' length */
if ((mb_strlen($username) < 3) || (mb_strlen($username) > 24))
{
return TRUE;
}
if ((mb_strlen($password) < 3) || (mb_strlen($password) > 24))
{
return TRUE;
}
/* Password hash */
$hash = password_hash($password, PASSWORD_DEFAULT);
try
{
/* Add the new account on the database (it's a good idea to check first if the username already exists) */
$sql = 'INSERT INTO accounts (account_name, account_password, account_enabled, account_expiry) VALUES (?, ?, ?, ?)';
$st = $db->prepare($sql);
$st->execute(array($username, $hash, '1', '1999-01-01'));
}
catch (PDOException $e)
{
/* Exception (SQL error) */
echo $e->getMessage();
return FALSE;
}
/* If no exception occurs, return true */
return TRUE;
}
You can find the full tutorial here: User authentication with PHP: an example class
Cookie authentication and session handling
Web cookies are the de facto standard for keeping a login session open.
You can handle cookie-based login sessions very easily by using PHP Sessions.
Thanks to PHP Sessions, you don’t need to think about all the cookies’ details: just start and close the session and you’re done.
It couldn’t be easier.
If you want, you can also choose to manage cookies by yourself to build more secure applications (this is what I usually do).
Cookies themselves can also be securely encrypted and stored on a database.
If you need to implement different security levels, you can even use different cookies on the same website.
Two-(or more)-step verification
Two-step verification is commonly used today.
This is what happens:
after logging in with your username and password, the website asks you for another code (or token). It could be a code generated by a mobile app, a text message sent to your mobile phone or a token sent to your mail inbox.
Some services use even more than two steps.
Home banking websites, for example, often send a token to your mobile phone and another one to your email for increased security.

The point is:
with PHP, you can implement any kind of two-(or more)-step authentication system.
In fact, PHP is fully capable of:
- generating a secure, random token and storing it on a database
- sending the token to your mail inbox using PHPMailer
- connecting to an SMS provider’s API service to send the token as SMS message
(In my PHP Security Course you can actually find a complete 2-Factor Authentication tutorial).
Want to see how easy is to generate a random token, store it on a database and send it to the user’s inbox?
Here is the example code:
<?php
/* Already defined variables:
$PHPMailer: a PHPMailer object
$PDO: a PDO connection resource
$user_id: the ID of the user associated with the login session
$user_email: the user's email address
*/
/* Generate a 6-digits random token */
$token = random_int(100000, 999999);
/* Cast the token to string */
$token = strval($token);
/* Create a database row with the token.
/* Query: */
$query = 'INSERT INTO user_tokens (user_id, token_timestamp, token_value) VALUES (?, NOW(), ?)';
/* Values array: */
$values = array($user_id, $token);
try
{
/* Execute the SQL query */
$result = $PDO->prepare($query, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$result->execute($values);
}
catch (PDOException $e)
{
/* If there is an error an exception is thrown */
echo 'PDO exception. Error message: "' . $e->getMessage() . '". Error code: ' . strval($e->getCode()) . '.';
die();
}
/* Now we send a message to the user with the token */
try {
/* Set the mail sender. */
$PHPMailer->setFrom('noreply@yoursite.com');
/* Set the user's email as recipient. */
$PHPMailer->addAddress($user_email);
/* Set the subject. */
$PHPMailer->Subject = 'Access Token';
/* Set the message body. */
$PHPMailer->Body = 'Please use the following security token to login: ' . $token;
/* Finally send the mail. */
$PHPMailer->send();
}
catch (Exception $e)
{
/* PHPMailer exception. */
echo $e->errorMessage();
die();
}
Would you like to talk with me and other developers about PHP and web development? Join my Facebook Group: Alex PHP café
See you there 🙂
DATABASES MADE EASY
PHP includes database support from its early days.
The list of supported database systems is long:
- MySQL
- PostgreSQL
- Berkeley DB (very useful for system administrators)
- Oracle
- Microsoft SQL Server
- SQLite
- …
You can also use NoSQL databases like MongoDB.
And here is the best part:
using databases with PHP is very easy.
Sit back and relax while watching this short video introduction on how to use the MySQLi PHP extension to connect to a MySQL server:
And what about security?
Don’t worry: PHP makes easy to implement secure SQL statements by using escaping and prepared statements.
For common scenarios including standard MySQL usage, the PDO extension is very well suited for building robust and secure SQL code.
In the above video you saw how to connect to a MySQL database by using the MySQLi extension; the code below shows you how you can do it with the PDO extension (from my PDO tutorial):
<?php
/* PDO database connection */
try
{
/* Connection */
$PDO = new PDO('mysql:host=localhost;dbname=my_db', 'my_user', 'my_passwd');
/* Set some parameters */
$PDO->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$PDO->setAttribute(PDO::ATTR_CASE, PDO::CASE_NATURAL);
}
catch (PDOException $e)
{
/* If there is an error, an exception is thrown */
pdo_exception($e);
}
SERVER-SIDE BACKEND CODE
Today’s web development is about the synergy between frontend and backend technologies.
Frontend applications can be very simple, like basic dynamic web pages with simple JavaScript and AJAX functions, or complex web apps built with frameworks and libraries such as JQuery, Node.JS, Angular and so on.
No matter what language or library a frontend app is created with, it always need to retrieve some data from a server backend.

Server backends too can be created using different technologies.
Python, Perl, Java and even C or C++ can be used together with HTTP servers to provide frontend apps with backend data.
But the most used language by far is PHP, because it has been specifically created for such task.
For example:
many frontend apps use the JSON format to communicate with the backend server.
As you can see in depth in my PHP JSON tutorial, using PHP to provide data in this format is easy and straightforward.
The following example code (taken from my tutorial) reads some user data from a database and then returns it in JSON format:
<?php
$users = array();
$query = 'SELECT * FROM test.users ORDER BY user_surname ASC';
$st = $PDO->prepare($query, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$st->execute();
while ($res = $st->fetch(PDO::FETCH_ASSOC))
{
/* Save the user's informations in the array */
$users_index = count($users);
$users[$users_index] = array(
'first name' => $res['user_first_name'],
'surname' => $res['user_surname'],
'address' => $res['user_address'],
'birthday' => $res['user_birthday']);
}
/* Create and output the JSON string */
$json = json_encode($users);
echo $json;
REAL-TIME APPLICATIONS
Real-time web applications include chats, monitoring systems, bots, social networks, web games and more.
You can build such applications using different technologies, notably with MEAN stack software including Node.JS, Express and Angular.JS
WebSocket based frameworks like Socket.IO are also very powerful and widely used today.
Some real-time applications use JavaScript libraries only, relying on backend technologies like Node.js server, but in some cases it can be useful to make use of PHP as well.
The Internet is full of “comparison” articles like “Node.JS VS PHP: which is better?”… but I think that’s a stupid way of looking at web technologies.
Look:
it’s much better to focus on how to make technologies work together instead of trying to find the “best”.
For example, not too long ago I made a Node.JS server backend for a simple chat system. However, I had some trouble using the database.
What I did, then? Simple: I made Node.JS connect to a local PHP backend and use that to perform the database operations I couldn’t do with Node alone.
Why choose between Node.JS and PHP when I can use both?
WORDPRESS THEMES AND PLUGINS
It’s not a secret that most web frameworks and CMS (content management systems) are written in PHP.
WordPress is among the most successful ones, having seen a surge in popularity in the last two decades.
Take a look at the official WordPress plugin repository or at sites like Envato Market: see how much software is being written (and sold) for WordPress?
One thing is clear:
if you plan to make some money with coding, then PHP is a safe bet.
[easy-tweet tweet="What can you do with PHP? 9 amazing examples of what PHP can be used for." via="no" hashtags="PHP"]
REST AND WEB SERVICES
Web services (including REST services) are machine-to-machine, HTTP(S) based data exchange systems.
Normally, dynamic websites exchange data with human users, for example through HTML input forms.
Web services, on the other hand, communicate directly with other systems like other web services, devices and remote applications.
If you don’t know what I’m talking about, here’s a short but very clear video explaining what REST APIs are:
A real-life example:
all weather forecast services have nice looking, public websites where you can search for your own location, see the daily and weekly forecast and get various information.
You have probably noticed that even if there are thousands of weather forecast websites out there, many of them provide the same exact information.
That’s not a coincidence:
only a few companies have the expensive infrastructure to gather all the weather-related data required for forecast. Most of the weather websites are just reading the forecast data from those companies and showing it on their own websites.
Very often, this data exchange is done through web services.
The client sends an HTTP request to the provider’s service and gets some data in return.
Since this data is not meant to be readable by humans but to be easily handled by scripts and applications, it wouldn’t make any sense to use any HTML or CSS formatting for this data, right?
(In fact, parsing an HTML document programmatically can be quite difficult!)
Instead, web services use data-exchange protocols like:
- CSV: a very simple list of elements separated by a marker, like “data1;data2;data3;…”
This format is used for very simple services only. - XML: a complex and powerful encoding language, suitable for very complex services.
- JSON: a modern encoding format very used today, simpler than XML and well supported by modern frameworks and libraries.
Writing a web service with PHP is easier than you think. In fact, support for both XML and JSON formats is already included in the standard PHP library.
See my XML and JSON tutorials to find some example code:
SOMETHING SCARY: PHP DAEMONS

What are PHP daemons?
Maybe we should start with explaining what daemons are in the first place.
Daemons are background processes that keep running without user interaction.
Think of a computer job scheduler, like CRON on Linux or the Task Scheduler on Windows: they run in the background and do their job without directly interacting with you.
Such processes are called daemons under Linux and Unix systems.
(You may have noticed that on Linux some processes’ names end with a d, like crond, httpd, mysqld… that d is for daemon).
Now, back to PHP.
Usually, a PHP script terminates after the web server PHP module has finished running it. It usually takes far less than a second.
However, you can create never-ending PHP scripts that keep running in background, just like daemons.
Such PHP daemons can accomplish a lot of tasks. For example, they can monitor some data and send email alerts when particular circumstances arise, almost in real time.
PHP daemons use a C-style structure which requires:
- A never-ending loop, for example a while() loop.
The loop can end under specific circumstances or after some time, but it can also go on indefinitely. - An iteration clock: something that sets the iteration pace.
You cannot just let the loop iterate without delay, or the script will use all the CPU power. You can use the sleep() and usleep() functions to pause each iteration for a certain amount of time.
Inside the loop, the script will perform its tasks.
It may sound complicated, but it’s quite simple really.
Look at the following example: it’s a simple PHP daemon that monitors a value from a database and sends an email if this value gets too high:
<?php
/* $PHPMailer: a PHPMailer object
$PDO: a PDO connection resource
*/
/* Remove the execution time limit */
set_time_limit(0);
/* Iteration interval in seconds */
$sleep_time = 600;
/* Threshold value */
$threshold = 100;
while (TRUE)
{
/* Sleep for the iteration interval */
sleep($sleep_time);
try
{
/* Query */
$query = 'SELECT value FROM values ORDER BY value_timestamp DESC';
$result = $PDO->prepare($query, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$result->execute();
$row = $result->fetch(PDO::FETCH_ASSOC);
}
catch (PDOException $e)
{
/* If there is an error an exception is thrown */
echo 'PDO exception. Error message: "' . $e->getMessage() . '". Error code: ' . strval($e->getCode()) . '.';
die();
}
/* Check the value against the threshold */
if ($row['value'] >= $threshold)
{
try
{
$PHPMailer->setFrom('noreply@yoursite.com');
$PHPMailer->addAddress('alerts@yoursite.com');
$PHPMailer->Subject = 'Value alert';
$PHPMailer->Body = 'Last value is: ' . $token;
$PHPMailer->send();
}
catch (Exception $e)
{
echo $e->errorMessage();
die();
}
}
}
GENERATE IMAGES WITH PHP
I bet you didn’t know this:
you can actually generate graphics directly from PHP.
The standard PHP library includes a toolset of GD Library functions that lets you create graphics such as JPEG files in just a few lines of code.
It’s true that frontend graphics are now handled by HTML5 and JavaScript.
However, backend graphics operations (creation, resizing, compression…) are still widely used today.
Think of all the WordPress plugins that shrinks images to save space and to increase the page load speed.
Here is a nice article about this topic: Image Resize, Crop, Thumbnail, Watermark PHP Script
SYSTEM SCRIPTS
PHP scripts are usually run by a web server, but that doesn’t need to be the case.
You can also run PHP scripts using the command line PHP interpreter, or PHP-CLI:

You can use PHP to perform system maintenance tasks such as:
- File system checks
- Logs analysis and maintenance
- Automatic downloading and storing of remote resources
- Periodic FTP uploads and downloads
- Database maintenance
You can execute these scripts using CRON or other schedulers, or use any kind of trigger just like you would do with C or BASH shell scripts.
CONCLUSION
In this post you saw for how many different tasks PHP can be used for.
It’s not just about building dynamic websites: backend data, REST services and authentication are just some of the possible uses of this language.
And believe me: if you learn how to use PHP in all these different scenarios, you will definitely stand out from other developers.
Now I want to hear from you:
how do you use PHP?
I’m waiting for your comments!
P.s. If this guide has been helpful to you, please spend a second of your time to share it… thanks!
Alex
Thanks so much for this objective analysis. Am currently with a task of implementing a chat feature inside an existing php billing system.
Am aware that Sockets.IO provides good functionality for such however my challenge is to use php with NodeJS just like you mentioned how can we use these technologies together.
The article is so informative and educational. Am sure going to use it as a reference even for other projects which need strengths from different technologies.
Thank you for your comment, Ashe.
About Node.JS and PHP, the idea is that you can run the Node.JS Server on its own port (for example, 8080) while still having a PHP backend server on the standard HTTP(S) port. You can either use client-side JavaScript to send commands to both systems, or you can send commands to the PHP backend only and let PHP connect to the local Node.JS server to communicate its operations.
Thanks for sharing this. I tried to learn PHP a little. Great post for me and people who are already using other languages like asp or laravel and want to learn PHP. It is very useful. Continue the great work. I just want to say that there is no need to dive too deeply into PHP if you don’t want to. A generic encoder can simply choose what it needs for a particular scenario.
check article on this topic https://axisbits.com/blog/Why-are-web-projects-using-PHP-so-popular
Thank you for your feedback and for sharing your post, Andrew.
Just starting my journey with php… wish to learn more from you…
Thanks in Advance..
You can subscribe to my newsletter (it’s completely spam-free). Once you’re in, you’ll receive my weekly PHP tips.
PHP has the widest open source contribution options that make it easy platform to start and scale to enterprise level advanced business solutions. Thank for the wonderful post.
I agree.
Thanks so much for good work sir
Thank you, Donraphael
Thanks Alex
Clear and well organize articles.
I’m using php for quite a while but always I learn new things
and that’s important.
Thank you Sorin!
Thanks very much for the great work you are doing.
I am new to PHP and I want to know how to learn it effectively.
Thank you for your comment, Joseph
Nice article alex, i am a big fan of yours articles.
Thanks….
Thanks, Yogesh.
Great! Alex, that really gave an good insight on php.
Thank you Uma 🙂
Wow, you’re right, I didn’t know about the GD library. Or maybe I did – I looked in php.ini and it’s already activated, so maybe I tried it years ago and forgot about it. Either way, thanks – that’s something I actually need, and I was already going to implement image processing with C++, but with PHP it does sounds easier.
Hi. How come when I try to get your free ebook, am asked to confirm my email, but the pdf doesn’t come.
Hi, sometimes it may take a few minutes for the email to arrive. Also, be sure to check the spam folder as it may be there.
Please let me know if you got it, otherwise I will send you the PDF myself. Thank you
Great alex i love ur work
Thanks Maroof, I’m glad you liked the article.
Wawww awesome! You do great Job Alex ! extremely happy to find your website ! I feel already that I will learn a lot with you in PHP ! Thank you for sharing your knowledge with others ! Keep doing this good work please !
Thanks Roland!