PHP & Web Development Blogs

Search Results For: testing
Showing 1 to 5 of 9 blog articles.
19214 views · 5 years ago
How to install PHPUnit

PHPUnit is an essential tool for every PHP developers. It is one of those tools that every PHP developer should have installed in their development environment. The problems most first time PHPUnit developers run into are where to install it and how to install it. This quick guide will walk you through the process and answer both questions.

How do I install PHPUnit

The Easy Way

In your project’s root directory use this command.

composer require --dev phpunit/phpunit ^6.0


This command adds PHPUnit to your project as a development dependency. This is the absolute best way to install PHPUnit. It is the best way because this way the version of PHPUnit does not change unless you change it. We specified ^6.0 as the version which means we’ll get all the updates to the 6.0 branch but not 6.1. While BC breaks don’t happen often in PHPUnit, they have happened. If you have a globally installed version of PHPUnit and you upgrade it to a version that breaks BC, you have to go update all of your tests immediately. This is a lot of hassle if you have a lot of projects with a lot of tests. Keeping a copy of PHPUnit installed as a dev requirement in each project means that each project has its own copy that can be upgraded as necessary.

The Hard Way

In a command prompt regardless of where you are in your file system, use this command.

composer global require phpunit/phpunit ^6.0


On MacOS and Linux machines, this will install PHPUnit in ~/.composer/vendor/bin. If you add this directory to your path, then from any project, you can execute PHPUnit. However, as noted above, if you ever upgrade your globally installed packages then you will have problems.

composer global update


Run that when there is a new version of PHPUnit, it will be installed, regardless of whether this will break your existing unit tests on one or more of your projects. Windows users will need to locate the .composer/vendor/bin directory in your user’s home directory.

The “ZOMG why would you do it this way” Way

Here is the old-school use wget and move it into the correct position manually. You can do it this way, but you will have to take care of all upgrades manually as well. If you only have a single project on the computer and you never ever plan on changing the version of PHPUnit….nope, still better to usecomposer require --dev.

wget https://phar.phpunit.de/phpunit-6.0.phar


chmod +x phpunit-6.0.phar


sudo mv phpunit-6.0.phar /usr/local/bin/phpunit


phpunit --version


These instructions are of course for MacOS or Linux. Windows user won’t need to do chmod or sudo but will need a BAT file.

That’s it. One of those commands should get you a working copy of PHPUnit on your computer.

Resources:

* Installing PHPUnit
* Composer Introduction (For the Global option)
17712 views · 5 years ago
Creating a Virus with PHP

In his talk, “Writing Viruses for Fun, Not Profit,”Ben Dechrai (after making the viewer take a pledge to only use this knowledge for good and not evil) walks through how many viruses operate, and just how easy it is to build your own self-replicating virus in PHP.

The danger of many of these viruses according to Ben is that the most dangerous viruses often escape detection by not looking like a virus. Instead they encrypt their code to hide their true intent, while also constantly adapting and evolving.

Perhaps even more dangerously, they act like they’re benign and don’t actually do anything - often times laying dormant until called upon by the malicious actor.

Creating the Virus

What’s scary is just how simple it was for Ben to create such a virus, one that mutated ever so slightly as it infected every other file on the server. Opening up unlimited possibilities from scraping customer data, to DDOS attacks, to simply hijacking your domain.



But those attacks are just the start as Ben demonstrated how easy it is to write new files, delete files, eval() and execute foreign code - which could even be extended to accessing the underlying server itself if shell_exec() is enabled.

To add to the problem, Ben shares how challenging it can be to identify malicious code on your server as many of these attacks are far more sophisticated than the the virus he created in a matter of minutes - hiding themselves and often appearing as if they are part of the original source code.

Deploying the Virus

To drive his point home, Ben demonstrates how even seemingly secure systems can be vulnerable - as all it takes is one tiny misstep within your application.

He highlights this by building what should be a secure photo gallery - one that checks the extension and mime-type of the image - and even stores it outside of the public directory. He goes even farther by adding additional sanity checks with a PHP script that then renders the image.

After walking through the code and it’s security features, he then downloads a simple image from the internet. Opening his editor he quickly injects the virus (written in PHP) into the image and uploads it, passing all of the server checks.

Surely, since it passed these checks the system is secure, right? Ben loads the gallery to proudly show off the image - which is just that… an image, with nothing special or out of the ordinary.
Except that when he opens the image gallery files, each has been infected with the malicious code.

The culprit that allowed for Ben to hijack an entire system and execute foreign code, create new files, and even hijack the entire site? When displaying the image the file was included using PHP’s include() function, instead of pulling in the data using file_get_contents() and echoing it out.

Such a simple mistake provided Ben, if he was a malicious hacker, complete access to all of the files on the system.

Protecting Yourself

Security always exists in layers - and this could have been prevented by including a few more layers, such as using an open source library to rewrite the image, reviewing the image source before pulling it in, or again not giving it executable access by using the PHP include() function.

But what’s terrifying is how simple it is to hijack a site, how easy it is to get access to your system and private data, and how easy it is to overlook security vulnerabilities - especially with open source tooling and those that take plugins.

As Ben explains, sometimes the core code itself is really secure, but then you get two different plugins that when used together accidentally create a security vulnerability. That by itself is one of the most challenging as you can audit each plugin individually, and still not know you’re opening up your system to malicious actors.

This is why it's not just important to stay up to date on the latest security measures and best practices, but to be constantly thinking like a hacker and testing your code for vulnerabilities.

Learn More

You can watch thefull video to learn more how viruses operate, how to quickly build your own PHP virus (but you must promise to use it for good), and what to watch for in order to protect yourself, your customers, and your architecture.
12814 views · 4 years ago
Why Cloudways is the Perfect Managed Hosting for PHP Applications

The following is a sponsored blogpost by Cloudways


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 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:


alt_text


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, choose your desired cloud provider, and select the PHP stack application.


alt_text


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:



* Apache
* Elasticsearch
* Memcached
* MySQL
* PHP-FPM
* Nginx
* New Relic
* Redis
* Varnish


alt_text


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.

alt_text

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.

alt_text


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.


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.

alt_text


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.

alt_text


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.

alt_text


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 using Cloudways API. You just need your API key and email for authentication of the HTTP calls on API Playground and custom applications.

alt_text


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, Silex, Lumen, 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.

alt_text


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 and check out Cloudways for the best and the most cost-effective cloud hosting solution for your next PHP project!
9660 views · 5 years ago
Halloween is filled with ghouls, ghosts, zombies and lots of other spookiness, but the scariest thing ever is FOMO. It’s conference season and several have their call for papers out (including us at Nomad PHP :D). This is the perfect time for you to share your knowledge with the community. Whether it’s your first time or 100th time - it can be scary to put yourself out there and do a talk, but worse than that is not taking the chance and submitting your talk and doing the presentation. Plus, many of these events host lightning talks (short 5-15 minute talks) - meaning you can test out your talk risk free ;)

So here is your chance - submit for one or submit for all of them. May the odds be ever in your favor!

Fosdem 2019

First we have Fosdem 2019 which will take place on February 2 & 3 in Brussels,Belgium. Some facts about this call for papers:
*Deadline: November 3, 2018
* Presentations are expected to be 50 minutes long (including audience questions) and should cater to a varied technical audience. For examples check out youtube.
*Submit your proposals via Pentabarf: https://fosdem.org/submit.
* The conference covers reasonable travel expenses agreed upon in advance as well as arranges accommodations

Midwest PHP 2019

Next up we have Midwest PHP which will take place on March 8 & 9 in Bloomington, Minnesota.
*Deadline: November 15, 2018
* There is a speaker package included (conference pass, 2 hotel nights, airfare/travel - $500 max, lunch, etc.)
* Make sure the talk title and abstract define the exact topic and what you hope people will learn from it.
* Recommended to submit more than one talk because it can increase your chances of one of them being picked.
*Submit your talk here: [https://cfp.midwestphp.org/] (https://cfp.midwestphp.org/)

Longhorn PHP

Next we have Longhorn PHP which will take place on May 2 (tutorial day) then MAy 3 &4 (conference) in Austin, Texas.
*Deadline: December 15, 2018
* For all speakers, you'll get a full conference pass (tutorial day and main conference days), including access to lunch, after-parties, and any other activities included in the conference.
* For speakers remote to the Austin area, we'll provide 3 nights at the speaker hotel (4 nights if presenting a talk and a tutorial) near the conference venue.
* For speakers outside Texas, we'll book you an Economy or equivalent round-trip airfare on a flight into Austin we'd be comfortable taking ourselves (we're conference speakers too!). Plus, we'll arrange transportation between the Austin airport and the speaker hotel.
* Three different session lengths: 3 hour tutorials, 60 minute talks, and 30 minute talks.
* It doesn't have to just be a PHP related talk. For more information on talks click here.
*Submit your talk here: https://cfp.longhornphp.com/.

Laravel Live India 2019

Then we have LaravelLive India 2019 in Mumbai, India.
*Deadline: December 31, 2018
* Talk length is 30 minutes - Q&A up to the presenters discretion but would be included in the 30 minute time limit.
* Talks will be recorded and distributed for free as well as the presentation slides.
* Looking for a range of talks from PHP (security, testing and frameworks), web development, HTML5, JavaScript, mobile development, emerging technologies and non-technical proposals that will appeal to developers.
*Talk guidelines: Objective with clear expectation for audience, short and to the point description, mention of employer is only allowed at the beginning of the content and background image/wallpaper shouldn’t include company name/logos.
*Submit your talk here: [https://www.papercall.io/laravellive-india] (https://www.papercall.io/laravellive-india)

Nomad PHP

(you know you want to)

Last but not least - this is an ongoing call for papers. This is perfect if you want to present from the comfort of your office, home or really wherever you are. It’s via RingCentral meetings and will be live and recorded. This is for none other than Nomad PHP.
*Deadline: Anytime :D
* Talk length: 45 - 60 minutes.
* Talks should be unique to Nomad PHP and not available in video format online.
* Talk should not be recorded or made available elsewhere online for at least 3 months following your talk.
* The talk will be featured on our page and promoted via social media.
* Speakers will receive a financial stipend.
* Upon being selected we will reach out with further details.
*Submit here: [https://www.papercall.io/nomadphp] (https://www.papercall.io/nomadphp)
Now that you have some information - it’s the perfect time to take it all in and get started on your talk proposals :)! Looking forward to seeing all the amazing talks that will be coming out!!!
9646 views · 3 years ago


Welcome back!, if you’re new please be sure to read Part 1 here.


This tutorial will focus primarily on Security and will touch on how to plan functionality.

Planning out an application and seeing progress regularly is a good strategy as you are most likely to complete your tasks in a timely fashion with this approach.

Ready?, ok let’s jump into it!

DISCLAIMER


We highly recommend that you follow these tutorials on a localhost testing server like Uniserver. Read through Part 1 here to look at our recommendations. These tutorials follow a phased approach and it is highly recommended that you do not make snippets of code live prior to completing this tutorial series.


Where we left off – the serious stuff.


In the previous tutorial we saved variables to the database.

It’s important to note that further steps are needed to ensure that data transactions to / from the database are secure.

A great first step is to ensure that all POST data (data transmitted after a user clicks a form’s submit button) is sanitized.

What we’re trying to prevent


One of the most common exploits is SQL Injection, an attack most commonly used to insert SQL into db queries. POST data that’s not sanitized leaves a huge security hole for malicious exploits. In some cases SQL injection can be leveraged to rage an all out assault on a server’s operating system.

A few examples of a basic version of what this might look like can be seen below.



OUTCOME


This might delete your database table



OUTCOME


This might provide access to the entire user table and the password protected area/dashboard.


***Please note that there are various types of SQL injection techniques and I will delve into this during the course of this series.***


So what exactly is sanitization and what does it do?


When sanitizing POST data, we are essentially looking for any special characters that are often used in SQL injection attacks.

In many ways, this tiny piece of code is the unsung superhero of many database driven applications.

Let’s secure that POST data!


Navigate to your backend folder and open index.php

Locate the following line of code:

$sql = "INSERT INTO content(title,content,author)VALUES ('".$_POST["title"]."', '".$_POST["content"]."', '".$_POST["author"]."')";


Ok, let’s get to work.

Based on what I mentioned a few moments ago, it’s clear that our SQL statement is vulnerable so we need to sanitize the POST data pronto!

The method I will focus on first is $mysqli->real_escape_string. This will escape any special characters found in the POST data.

Add the following just above your $sql.

$title = $letsconnect -> real_escape_string($_POST['title']);

$content = $letsconnect -> real_escape_string($_POST['content']);

$author = $letsconnect -> real_escape_string($_POST['author']);


Did you notice the use of $letsconnect? This was used because of our db connection defined in conn.php.

Our new query will look like this:

$sql = "INSERT INTO content (title,content,author) VALUES ('".$title."', '".$content."', '".$author."')";


Go ahead and replace the old $sql.

Phew!, we can breathe easy now.

Next, let’s lighten things up a bit by focusing on functionality and aesthetics.


A phased approach is the best way to tackle projects of any size.

I tend to jot this down on paper before creating a more legible professional spec!.

Typically the phased approach lends itself to logical progression.

For example, over the next several days I will go over the following:

* Account Access
* The login process
* The registration process
* The password recovery process
* Frontend
* The look and feel
* Menus
* Sidebars
*Main Content
*Footer
* Backend
* Content Management
* Add/Edit/Delete
* Security

This will give us a good springboard to delve into more complex functionality.

The aesthetic I have in mind will be barebones at first with clean CSS practices (this will make life a whole lot easier when we have to make changes down the line!).

Challenge :


Plan out your own CMS, think about the user interface and design choices you’d like to implement, and create a phased approach.

Conclusion


I hope this tutorial encouraged you to think about security and understand one of the most common exploits. During the course of this series, you will receive the tools necessary to beef up security while maintaining your sanity!

Next up


CodeWithMe – Let’s go templating.

SPONSORS