Learn from your fellow PHP developers with our PHP blogs, or help share the knowledge you've gained by writing your own.
![Web Sockets in PHP](https:/ /cdn.filestackcontent.com/uluFRmjARj6zAQWN05PZ)
In his talk **[Websockets in PHP](https:/ /nomadphp.com/video/219/websockets-in-php)**, [John Fransler](https:/ /johnfansler.com/) walks us through the use of WebSockets in PHP.
While discussing bi-directional real-time application development, John notes that PHP is often not invited to the table due to its lack of native support. Of all the possible attempts to bring in PHP on this stage of real-time development, Ratchet, a PHP WebSocket library, comes closest. "[Ratchet](http:/ /socketo.me/) is a loosely coupled PHP library providing developers with tools to create real-time, bi-directional applications between clients and servers over WebSockets."* Ahem!
### Today's dynamic world
In today's dynamic content world of the internet, it is required to serve real-time bi-directional messages between clients and servers. WebSockets are simple, full-duplex, and persistent. They work over Http and are a standard today.
> WebSockets have compatibility with 96.5% of clients globally
There's a very high chance your client has the necessary plumbing to access your content via WebSockets. WebSockets gives the ability to have real-time data on to your clients without the need for polling.
While on the Server, John uses Ratchet, which is built on [React PHP](https:/ /reactphp.org/). A server script is then configured and set up to run and listen on a port for incoming HTTP requests. For messages, JSON is used, and to find public methods, a router is set up. He then goes on to instantiate the server-side script in Ratchet.
**There are four functions of a Ratchets message component interface that are used in this example:**
`OnOpen` gets called when a new connection is made.
`OnClose` gets called when a client quits. It's essential to keep an eye on memory management, and essential to keep tidying up as you move through the code.
`OnError` gets called when there is an exception faced by the user.
`OnMessage` gives the text of the JSON message, which is being exchanged with the client.
For Initialization, Jason continues to walk through the example. He shows how one can loop through the clients, both inside the server and outside the server. Outside the server, it’s a feature of React PHP. On database access, and with traditional standard synchronous MySQL in PHP, what usually happens is that it forces the code to wait for the query to return a result and do nothing — Fortunately, with Asynchronous MySQLi, that is not the case.
John gets into the details explaining Variables, References & Pointers. He also gives a demo where a central site has updated information on the Bitcoin and ether prices. A client terminal reflects the last values. Now the client doesn't have to poll the server for new values. When there is a change in the Bitcoin or ether values, the server pushes down the client's update. No polling helps with a lot of overheads and gets closer to real-time.
### Using Supervisord
For Long-running applications - Jason recommends running a supervisord, use proxy to expose the port, and add a site certificate. Supervisord keeps an eye out for the server running the service; it can be used to restart the service and log any service issues. Recommended proxies are AWS load balancer, Nginx, and HA Proxy. For scalability, use multiple smaller WebSocket servers and a smaller number of clients per server used and load balancing. If one has to support a chat feature to allow clients to talk to each other in near real-time, it is recommended to use [Redis](https:/ /redislabs.com/). The Redis server proxies the messages between the server nodes.
The talk concludes with John summarizing best practices on error handling and takes QnA on various aspects of WebSockets such as handling load balancers and asynchronous calls to MSQLi.
The presentation for this video, along with the code, is hosted at [John Curt's GitHub](https:/ /github.com/johncurt). More info about John's current areas of interest can be found on [John's Blog](https:/ /engagedphp.com/).
### [Watch the video now](https:/ /nomadphp.com/video/219/websockets-in-php)
[Related videos](https:/ /nomadphp.com/search/videos?search_query=async)
![Top 12 PHP Libraries to Leverage Your Web App Development](https:/ /images.ctfassets.net/vzl5fkwyme3u/6Xd3PeEIm87bVI1UPb5q26/98abd4072971b7fc3f8d46aba3dc17f6/libraries2.png?w=1000)
PHP, by all means, is an immensely powerful language!
We may fall short of words, but there won't come any end to its qualities. The endless functionalities and possibilities of this server-side scripting language have managed to get it a strong and supportive community of PHP programmers on a global level. At present, PHP powers more than half on websites and applications on the internet.
**Do you know what makes PHP so praiseworthy?**
It is the simplicity, easy programming structure, and developer-friendly web functionalities that are to be credited to turn PHP into one of the top programming languages. You can create highly interactive and dynamic websites and applications with desired results by making use of PHP.
However, coding often could be a tough and tedious task to accomplish. As a solution to this, you get built-in PHP libraries that optimize the process of coding for maximum productivity.
### But what are these libraries?
That's exactly what you will find out as you move ahead in this article, a list of top 12 PHP libraries capable of leading the development process in an intended manner.
So, without waiting any further, let's move ahead to learn about PHP libraries in-depth.
#### [PChart](http:/ /www.pchart.net/)
PChart is a PHP library assisting with the generation of text data in the form of something more appealing to the eyes and known as visual charts.
You can use this library to represent data as bar charts, pie charts, and many more different formats. The PHP script here utilizes SQL queries to put data in the impressive charts or graphs form.
#### [Mink](http:/ /mink.behat.org/en/latest/)
Another well-known in the list of PHP libraries is Mink. It allows you to keep an eye on if a proper interaction is happening between your web apps and the browser. Eliminating the API differences between the two types of browser emulators, Mink offers an authentic testing environment for you. It also supports PHPUnit, Behat, and Symfony2.
#### [Monolog](https:/ /github.com/Seldaek/monolog)
Monolog is a PHP logging library that helps you with saving logs to the specified locations by sending them to set files, sockets, inboxes, databases, or other web services. The use of the PSR-3 interface permits to type-hint logs in counter to your libraries that maintain optimum interoperability.
#### [Hoa](https:/ /hoa-project.net/En/)
This modular, extensible, and structured set of PHP libraries we know as Hoa establishes a link between the research and the industry.
It recommends essential paradigms, mechanisms, and algorithms for building the reliability of a site. Many PHP developers in different parts of the world use Hoa for ideal PHP development.
#### [Guzzle](http:/ /docs.guzzlephp.org/en/stable/)
Guzzle is an HTTP client library for PHP that enables you to send HTTP requests to combine with web services.
It offers a simple interface that makes the development of query strings, POST requests, HTTP cookies, and many other attributes possible. You can also use Guzzle to send synchronous and asynchronous requests from the similar interface.
#### [Ratchet](http:/ /socketo.me/)
If your need is to develop real-time, two-directional apps between clients and servers over WebSockets, Ratchet is the PHP library you need to do it effectively.
Creating event-driven apps with Ratchet is a rapid, simple, and easy job to do!
#### [Geocoder](https:/ /geocoder-php.org/)
Geocoder is a library to create applications that are very well geo-aware.
With Geocoder, there is an abstraction layer that helps with geocoding manipulations.
It is further split into two parts, known as HttpAdapter and Provider.
#### [ImageWorkshop](https:/ /phpimageworkshop.com/)
ImageWorkshop is an open-source PHP library letting you work over the manipulation of images with layers. You can crop, resize, add watermarks, create thumbnails, and so much more. You can also enhance the images on the sites.
#### [PhpThumb](http:/ /phpthumb.sourceforge.net/)
phpThumb is the library specialized at handling the work associated with creating thumbnails with minimal coding. Accepting every image source type and image formats, it makes you do a lot ranging from rotating or cropping to watermarking or defining the image quality.
#### [Parody](https:/ /github.com/dotink/Parody)
This simple library we know as Parody is used to copy classes and objects. It also provides results for method calls, acquiring properties, instantiating objects, and more. Sequential method chaining is used by Parody to produce defining class structures.
#### [Imagine](https:/ /imagine.readthedocs.io/en/stable/)
This object-oriented PHP library is meant for working with images along with manipulating them. The often adopted operations such as resizing, cropping, and applying filters happen instantly and relatively well with Imagine.
With Imagine, you get a color class that forms the RGB values of any given color. Draw shapes like arc, ellipse, line, etc. with the features available.
#### [PhpFastCache](https:/ /www.phpfastcache.com/)
PhpFastCache is an open-source [PHP library](https:/ /www.hireindependentdevelopers.com/blog/libraries-for-php-web-development/) that makes caching feasible. Coming as a single-file, it can be integrated within a matter of minutes.
Caching methods supported by PhpFastCache involve apc, memcache, memcached, wincache, pdo, and mpdo.
**The Bottom Line**
It's not about what extra difference these libraries make; it's about what significant individual contributions these libraries make for a final desired PHP app or website.
A [PHP programmer](https:/ /hireindependentdevelopers.com/php-developers/), too, agrees with these libraries' benefits.
It's your time now to try and believe!
People that visit your website face an invisible threat each time they log on. Small businesses are especially vulnerable to digital data breaches, and that can change the way your customers feel about you. But, although you cannot stop hackers from trying, there are things you can do as a business owner to make your website a safer experience for everyone. Keep reading for tips.
### Mature digitally.
You may be ahead of the times when it comes to products and services, but, chances are, your website hasn't fully kept up. It's time to learn all you can about the internet and digital security. If you are already somewhat tech savvy, a [PHP Security Course](https:/ /nomadphp.com/courses/php-security) from Nomad PHP can help you better understand everything from cryptography to website error messages.
Adapting to today's digital environment means transforming your website to quickly and easily identify threats via machine learning and network monitoring. And, as Upwork explains, digital [maturity](https:/ /www.upwork.com/resources/accelerating-your-digital-transformation-in-2020) not only keeps your website safe, but adopting this mindset can also increase your efficiency and accuracy by reducing human errors.
### Understand the threats.
It is not enough to simply keep up with your website, you also have to understand the types of threats that are out there. You're likely familiar with ransomware and phishing, but, it's also a good idea to know how a website can get hacked. Your site's content management system and vulnerabilities within your operating system are all [weak points](https:/ /www.weborion.io/blog/five-ways-a-website-can-be-hacked/) that hackers can easily identify.
### Insist on security measures.
When customers log into your website, they input their credentials. Each time they do so, you can best protect their information by keeping your systems up to date. You'll also want to ensure that your site is hosted on a secure service and that you have an [SSL certificate](https:/ /us.norton.com/internetsecurity-how-to-ssl-certificates-what-consumers-need-to-know.html) installed.
If you are not already, have your IT department or managed IT services perform regular website security checks. PhoenixNAP, an IT services provider, notes that those websites working via WordPress should also be safely outfitted with the most recent [security plug-ins](https:/ /phoenixnap.com/blog/how-to-secure-a-website).
### Eliminate spam.
If your website allows for comments that are not manually approved, anyone on the internet can post. This leaves it open for hackers and other unscrupulous individuals to [comment with spam](https:/ /www.shivarweb.com/2450/my-blog-comment-spam-is-too-high-heres-why/) and malicious links that your customers may inadvertently click on. While many of these simply exist as a way for the commenter to [drive traffic](https:/ /www.wordstream.com/blog/ws/2014/08/14/increase-traffic-to-my-website) to another website, others are designed to draw your readers' attention, gain their trust, and access their personal information.
### Prioritize passwords.
Your customers' passwords are the keys by which they open the door to your website. Unfortunately, many people do not treat them with as much care as they do the keys they use in the non-digital world.
It's true, passwords can be a pain, but you are not doing yourself or your customers any favors by allowing simple one-word passcodes to access your site. Instead, design your site to require a strong password. How-To Geek asserts that this will have a [minimum of 12 characters](https:/ /www.howtogeek.com/195430/how-to-create-a-strong-password-and-remember-it/) and include a combination of upper and lower case letters, symbols, and numbers.
While you will likely rely on your IT experts to secure your website, the truth is that it is ultimately up to you to ensure this is done. So even if you are not a digital mastermind, knowing all you can about web security can help you be a better business owner. Your customers will be safer, and a secure website is just one way to strengthen your business's online presence and keep up with today's -- and tomorrow's -- technology.
![Why Cloudways is the Perfect Managed Hosting for PHP Applications](https://images.ctfassets.net/vzl5fkwyme3u/3VLCUBagZPfSLyxyt1AvvP/89e3b904a450454545eb885e2e0e76b4/cloudways.jpg?w=1000)
#### The following is a sponsored blogpost by [Cloudways](https://www.cloudways.com/en/?id=431739)
Developing an application is not the sole thing you should bank on. You must strive to find the best hosting solution to deploy that application also. The application’s speed is dependent on the hosting provider, that is why I always advise you to go for the best hosting solution to get the ultimate app performance.
Now a days, it is a big challenge to choose any web hosting, as each hosting has its own pros and cons which you must know, before considering it finally for the deployment. I don’t recommend shared hosting for PHP/Laravel based applications, because you always get lot of server hassles like downtime, hacking, 500 errors, lousy support and other problems that are part and parcel of shared hosting.
For PHP applications, you must focus on more technical aspects like caching, configs, databases, etc. because these are essential performance points for any vanilla or framework-based PHP application. Additionally, if the app focuses on user engagement (for instance, ecommerce store), the hosting solution should be robust enough to handle spikes in traffic.
Here, I would like to introduce Cloudways [PHP server hosting](https://www.cloudways.com/en/php-cloud-hosting.php?id=431739) to you which provides easy, developer and designer friendly managed hosting platform. With Cloudways, you don't need to focus on PHP hosting, but must focus on building your application. You can easily launch cloud servers on five providers including DigitalOcean, Linode, Vultr, AWS and GCE.
### Cloudways ThunderStack
Being a developer, you must be familiar with the concept of stack - an arrangement of technologies that form the underlying hosting solution.
To provide a blazing fast speed and a glitch-free performance, Cloudways has built a PHP stack, known as ThunderStack. This stack consists of technologies that offer maximum uptime and page load speed to all PHP applications. Check out the following visual representation of ThunderStack and the constituent technologies:
As you can see, ThunderStack comprises of a mix of static and dynamic caches with two web servers, Nginx and Apache. This combination ensures the ultimate experience for the users and visitors of your application.
### Frameworks and CMS
The strength and popularity of PHP lies in the variety of frameworks and CMS it offers to the developers. Realizing this diversity, Cloudways offers a hassle-free installation of major PHP frameworks including Symfony, Laravel, CakePHP, Zend, and Codeigniter. Similarly, popular CMS such as WordPress, Bolt, Craft, October, Couch, and Coaster CMS - you can install these with the 1-click option. The best part is that if you have a framework or CMS that is not on the list, you can easily install it through Composer.
### 1-Click PHP Server & Application Installation
Setting up a stack on an unmanaged VPS could take an entire day!
When you opt for Cloudways managed cloud hosting, the entire process of setting up the server, installation of core PHP files and then the setup of the required framework is over in a matter of minutes.
Just [sign up at Cloudways](https://www.cloudways.com/en/?id=431739), choose your desired cloud provider, and select the PHP stack application.
As you can see, your LAMP stack is ready for business in minutes.
Many PHP applications fail because essential services are either turned off or not set up properly. Cloudways offers a centralized location where you can view and set the status of all essential services such as:
* New Relic
Similarly, you can manage SMTP add-ons without any fuss.
### Staging Environment
With Cloudways, you can test your web applications for possible bugs and errors before taking it live.
Using the staging feature, developers can first deploy their web sites on test domains where they can analyze the applications performance and potential problems. This helps site administrators to fix those issues timely and view the application performance in real-time.
A default sub domain comes pre-installed with the newly launched application, making it easy for the administrators to test the applications on those testing subdomains. Overall, it's a great feature which helps developers know about the possible errors that may arise during the live deployment.
### Pre-Installed Composer & Git
PHP development requires working with external libraries and packages. Suppose you are working with Laravel and you need to install an external package. Since Composer has become the standard way of installing packages, it comes preinstalled on the Cloudways platform. Just launch the application and start using Composer in your project.
Similarly, if you are familiar with Git and maintain your project on GitHub or BitBucket, you don’t need to worry about Git installation. Git also comes pre-configured on Cloudways. You can start running commands right after application launch.
### Cloudways MySQL Manager
When you work with databases in PHP, you need a database manager. On the Cloudways platform, you will get a custom-built MySQL manager, in which you can perform all the tasks of a typical DB manager.
However, if you wish to install and use another database manager like PHPMyAdmin, you can install it by following this simple guide on installing [PHPMyadmin](https://www.cloudways.com/blog/installation-phpmyadmin/?id=431739).
### Server & Application Level SSH
If you use Linux, you typically use SSH for accessing the server(s) and individual applications. A third-party developer requires application and server level access as per the requirements of the client. Cloudways offers SSH access to fit the requirements of the client and users.
### PHP-FPM, Varnish & Cron Settings
Cloudways provides custom UI panel to set and maintain PHP-FPM and Varnish settings. Although the default configuration is already in place, you can easily change all the settings to suit your own, particular development related requirements. In Varnish settings, you can define URL that you want to exclude from caching. You can also set permissions in this panel.
Cron job is a very commonly used component of PHP application development process. On Cloudways platform, you can easily set up Cron jobs in just a few clicks. Just declare the PHP script URL and the time when the script will run.
### Cloudways API & Personal Assistant Bot
Cloudways provides an internal API that offers all important aspects of the server and application management. Through Cloudways API, you can easily develop, integrate, automate, and manage your servers and web apps on Cloudways Platform using the RESTful API. Check out some of the [use cases developed](https://www.cloudways.com/blog/category/use-cases/api/?id=431739) using Cloudways API. You just need your API key and email for authentication of the HTTP calls on API Playground and custom applications.
Cloudways employs a smart assistant named CloudwaysBot to notify all users about server and application level issues. CloudwaysBot sends the notifications on pre-approved channels including email, Slack and popular task management tools such as Asana and Trello.
### Run Your APIs on PHP Stack
Do you have your own API which you want to run on the PHP stack? No problem, because you can do that, too with Cloudways! You can also use REST API like [Slim](https://www.cloudways.com/blog/simple-rest-api-with-slim-micro-framework/?id=431739&utm_source=phpjabber&utm_medium=referral), [Silex](https://www.cloudways.com/blog/create-rest-api-silex/?utm_source=phpjabber&utm_medium=referral&id=431739), [Lumen](https://www.cloudways.com/blog/creating-rest-api-with-lumen/?utm_source=phpjabber&utm_medium=referral&id=431739), and others. You can use APIs to speed up performance and require fast servers with lots of resources. So, if you think that your API response time is getting slower due to the large number of requests, you can easily scale your server(s) with a click to address the situation.
### Team Collaboration
When you work on a large number of applications with multiple developers, you need to assign them on any specific application. Cloudways provides an awesome feature of team collaboration through which you can assign developers to specific application and give access to them. You can use this tool to assign one developer to multiple applications. Through team feature, you can connect the team together and work on single platform. Access can be of different type; i.e. billing, support and console. You can either give the full access or a limited one by selecting the features in Team tab.
### Final Words
Managed cloud hosting ensures that you are not bothered by any hosting or server related issues. For practical purposes, this means that developers can concentrate on writing awesome code without worrying about underlying infrastructure and hosting related issues. Do [sign up](https://www.cloudways.com/en/?id=431739) and check out Cloudways for the best and the most cost-effective cloud hosting solution for your next PHP project!
![Custom extension to Laravel Application class](https://images.ctfassets.net/vzl5fkwyme3u/505z7itnLO8suUC6oGMmKq/fa48e59682497e2480e9f1822ec8a498/AdobeStock_184180246.jpeg?w=1000)
Hello folks! This post is for those of you using Laravel. This beautiful framework makes web development super-easy compared to most of competitors. In the heart of Laravel is the Application class, which is responsible for bootstrapping, registering services and also serves as a dependency injection container. What I do with my Laravel apps, is that I take a slight detour from the common path by adding a custom Application class. While this is not really necessary, I find this approach nice, and will try to share my thought below.
It's normal practice in Laravel world to build all kinds of objects like this:
$cache = app("cache");
I find it a bit confusing to call `app("cache"")` and expect a `Cache\Repository` instance as result. If I pass the result of this call to a function that requires a `Cache\Repository` as parameter, I will probably have a code inspection warning from IDE. Moreover, if I want proper autocompletion, I will have to add additional comment:
/ ** @var \Illuminate\Contracts\Cache\Repository */
$cache = app("cache");
This is where a custom application class might be handy:
class MyApp extends Application
public function cacheRepository(): Repository
This way I get a `TypeError` in case of a misconfiguration, and I have a type-hint which allows the IDE to recognize the return value. Bye-bye nasty comment lines and IDE warnings! I make a method per service, with type-hints, like `dbConnection()` or `viewFactory()` - works really well for me!
I also thought that, if I have a custom class, then all the custom setup that normally you have in `bootstrap/app.php`, should reside in that custom class:
class MyApp extends Application
public function __construct()
define("APP_ROOT", realpath(__DIR__ . "/../"));
private function setUp()
/ / all the stuff from bootstrap/app.php, goes here
Then your `bootstrap/app.php` becomes just this:
return new \App\MyApp;
The Laravel `app()` function will also return an instance of MyApp from now on. However, it's @phpdoc says it returns `\Illuminate\Foundation\Application`, so for better clarity, I also added my own accessor method:
class MyApp extends Application
public static function app(): self
/ ** @var self $ret */
$ret = parent::getInstance();
I tend to limit the use of global/static functions and methods, but sometimes it can be handy, and whenever I need an instance of MyApp, I just call `MyApp::app()`. The IDE wil be aware of the return type due to the type-hint, so I get everything I want for clean and clear development.
With your projects in Laravel, you may or may not want to follow this particular advice, but just be aware that extending a framework built-in classes for your team's comfort, is definitely something that can make your life easier. See you around, don't forget to leave comments!