PHP Archives - The A2 Posting https://www.a2hosting.com/blog The Official Blog for A2 Hosting Fri, 03 Mar 2023 10:28:11 +0000 en-US hourly 1 https://wordpress.org/?v=5.8.1 A2 Hosting Supports Newest PHP Version 8.1 https://www.a2hosting.com/blog/a2-hosting-supports-newest-php-version-8-1/ Mon, 24 Jan 2022 12:23:38 +0000 https://www.a2hosting.com/blog/?p=12982 A2 Hosting is proud to announce that we are now supporting our customers on the latest version of PHP, Version 8.1. This means that you can take advantage of all …

The post A2 Hosting Supports Newest PHP Version 8.1 appeared first on The A2 Posting.

]]>
A2 Hosting is proud to announce that we are now supporting our customers on the latest version of PHP, Version 8.1. This means that you can take advantage of all the features and updates that this new release has to offer! One example is the addition of scalar-type hints for functions that will help improve security by preventing errors in your code. This is just one way we’re helping our clients stay ahead with their development needs.

This new PHP version has allowed popular frameworks like Symfony and WordPress to run on PHP 8.1, so you know that A2 Hosting’s servers will be able to support it! You can now take advantage of PHP 8.1 with your PHP applications hosted by us.

New Updates!

PHP 8.1 is the most recent release of PHP and features new updates, such as:

Scalar Type Hints

PHP will now receive better error messages when type hinting doesn’t match. This means that if you’re expecting a string and PHP receives an integer, PHP will throw a clear and concise error message to help you debug the issue easier. PHP will also not allow errors to occur when typing hinting at your PHP variables. This is just one of the ways PHP 8.1 helps you keep your PHP applications secure and bug-free!

Return Type Declarations

PHP 8.1 now supports return type declarations which means that PHP will be able to tell what kind of data you’re expecting back from a function. PHP 8.1 can not only help with security but also PHP performance as PHP will be able to execute the function and return the type of data you’ve requested without an extra step which speeds up PHP execution!

PHP 7 Compatibility

PHP 8.1 now has improved compatibility with PHP 7 so PHP developers don’t have to rewrite their PHP scripts for PHP 7. PHP 8.1 is backward compatible with PHP 7 so you don’t have to rewrite your code!

Contact Us Today

A2 Hosting is a leading provider of PHP hosting with a 99.9% uptime guarantee and a 24/7 support team to help you get the most out of PHP 8.1, today! Our expert Guru Crew team can help you with any questions or concerns about your PHP application, PHP 8.1 support, or migrating to PHP 8.1! We are available 24/7/365.

 

The post A2 Hosting Supports Newest PHP Version 8.1 appeared first on The A2 Posting.

]]>
https://www.a2hosting.com/blog/content/uploads/2022/01/Blog-Images-17-235x150.jpg
A2 Hosting Continues to Support PHP 7.1 Customers https://www.a2hosting.com/blog/a2-hosting-continues-to-support-php-7-1-customers/ Tue, 14 Sep 2021 14:00:30 +0000 https://www.a2hosting.com/blog/?p=12249 Have A Website on PHP 7.1? Find Your Home at A2 Hosting We’ve recently seen talk that some of our fellow hosting companies are no longer supporting PHP 7.1. While …

The post A2 Hosting Continues to Support PHP 7.1 Customers appeared first on The A2 Posting.

]]>
Have A Website on PHP 7.1? Find Your Home at A2 Hosting

We’ve recently seen talk that some of our fellow hosting companies are no longer supporting PHP 7.1. While being updated on the most recent version of PHP is best, we know that businesses need time to gather resources and upgrade their sites. That’s why we will continue to support our customer’s on PHP 7.1! We want to give you the time you need to update, especially since we know the busy months of holiday sales are coming up. 

If you will be staying on versions of PHP 7.1 and older we do recommend going through the process of hardening your PHP for increased security to keep your websites safe. Here’s a great knowledge base article that will walk you through the process! We are committed to keeping our customers safe and to your continued success in Q4. Feel free to reach out to our support team with any further questions.

The post A2 Hosting Continues to Support PHP 7.1 Customers appeared first on The A2 Posting.

]]>
https://www.a2hosting.com/blog/content/uploads/2021/09/Checklist-10-235x150.jpg
What Is PHP (And How Can You Use It in WordPress)? https://www.a2hosting.com/blog/php-functions-in-wordpress/ Wed, 14 Jul 2021 13:20:37 +0000 https://www.a2hosting.com/blog/?p=11730 Many WordPress website owners run successful blogs, e-commerce stores, and businesses without ever writing a single line of code. While you don’t have to be a programming master to manage …

The post What Is PHP (And How Can You Use It in WordPress)? appeared first on The A2 Posting.

]]>
Many WordPress website owners run successful blogs, e-commerce stores, and businesses without ever writing a single line of code. While you don’t have to be a programming master to manage a website, learning some fundamentals can give you an edge over the competition.

Fortunately, you don’t need to spend years learning the intricacies of writing code. By familiarizing yourself with how WordPress uses its core programming languages and learning the basic syntax, you can unlock a whole new world of possibilities.

In this post, we’ll look at the role PHP plays in the world’s most popular Content Management System (CMS). We’ll then show you how to customize the core WordPress platform, themes, and plugins by writing some simple PHP functions. Let’s get started!

An Introduction to PHP

PHP is an open-source programming language that is used by almost 80 percent of all websites whose programming language is known. As a server-side language, the majority of PHP processing happens on your server.

Whenever a visitor requests a page that contains PHP, this code is processed by the PHP module installed on your web server. The pre-processor then generates the HTML output and sends it to the visitor’s browser.

Part of PHP’s popularity is due to the fact that it’s used by different Content Management Systems (CMS), including WordPress. In fact, the bulk of the core WordPress software is written in PHP. If you download and unzip a copy of WordPress core, you’ll see plenty of PHP files:

The WordPress core software.

Whenever someone visits your WordPress website, the server will run the PHP code contained in your theme and core files, plus any plugins you’ve installed on your site. Once your server has processed all of that PHP, it will deliver the HTML code to the web browser. This means that the visitor will only ever encounter the processed HTML, and never the PHP code that powers your WordPress website.

Like other programming languages, there are many different versions of PHP. At the time of writing, the most recent release is 8.0.8, with everything prior to PHP 7.3 considered end of life. This means that PHP developers no longer issue updates or security patches for older versions. Thus, we recommend avoiding all versions of PHP prior to 7.3.

Why PHP Is Important for Website Owners

You don’t need to be a PHP master in order to run a successful WordPress website. The great thing about opting for WordPress as your CMS is that the majority of the PHP is already written for you. In fact, most WordPress users never learn how to write or understand this popular programming language.

However, there are some benefits to learning PHP. Out of the box, WordPress is a powerful and flexible CMS, but there may come a time when the built-in options aren’t enough.

If you want to modify WordPress’ core behaviors, some basic PHP skills can help you create more complex and unique customizations. In particular, WordPress supports a number of hooks, classes, and functions that you can use to extend this platform in new and exciting ways.

If you dream of developing your own WordPress theme or plugin, then you’ll also need to know PHP. In addition, many themes and plugins are open sources, so you’re free to modify the underlying code. Similar to WordPress core, if you download and unzip any theme or plugin, you’ll see a list of PHP files:

The WordPress Jetpack plugin.

Even if you don’t plan to code a theme or plugin from scratch, you may still benefit from tweaking these existing PHP files. By getting to grips with the basic syntax, you’ll have the freedom to modify that theme or plugin in order to make it the perfect fit for your WordPress website.

How to Write PHP Code and Functions

Becoming a PHP master is beyond the scope of this post. However, it helps to have a basic understanding of the syntax. To start, all PHP code is surrounded by tags, for example:

<?php echo 'This is PHP'; ?>

Here, we’re defining a string, which is a sequence of characters. In PHP, you differentiate a string from the rest of the code using either single quotation marks or double quotation marks, for example:

'This is PHP'

Each line of code generally ends with a { or a semicolon. However, statements like echo should always end with a semicolon.

In the above example, we’re using the ?> closing PHP tag. While you’ll use this closing tag throughout your code, it’s best practice not to use the closing PHP tags at the end of your file.

Although there is some interaction between HTML and PHP, it’s important to differentiate between these two programming languages by using the appropriate tags. For example, a file containing both HTML and PHP might look something like this:

<html>
<?php echo 'This is PHP'; ?>
</html>

Another fundamental element of PHP are functions, which are stored procedures. You can define functions using the following structure:

function functionName() {
code to be executed;
}

The function name must start with either a letter or an underscore. It’s also worth noting that function names aren’t case-sensitive. Let’s look at an example of a simple function:

<?php
function displayMsg() {
echo "Hello World";
}

displayMsg();
?>

Here, we’re creating a function called displayMsg. This function will output the value Hello World. To call this function, we’re simply writing the name of the function followed by brackets. Although this may seem like a simple example, you can apply this exact structure to more complex PHP functions.

A Few PHP Best Practices

As one of the world’s most popular programming languages, PHP is a prime target for hackers. If a malicious third party manages to uncover a vulnerability in PHP code, they could use this exact same attack against multiple WordPress sites.

To help keep your site safe, it’s important to ensure that you’re running the latest version of PHP. At A2 Hosting, we give our customers the flexibility to switch between different versions of PHP. If you have a shared or managed hosting account, you can log into your cPanel and choose the Select PHP Version tool.

A2 Hosting's cPanel dashboard.

Then, open the Current PHP dropdown and choose a version of PHP from the list:

A2 Hosting's PHP Selector tool.

Alternatively, if you have a managed Virtual Private Server (VPS) or managed server account, you can open a support ticket specifying the version of PHP that you want to use. Our team will be happy to make this change for you.

When writing custom PHP, you can protect against Cross-Site Scripting (XSS) attacks by sanitizing your data. PHP’s filter_var function contains disinfection indicators that enable you to check all user-submitted data. You can then remove any values that aren’t of the expected type. You can also use PHP’s validation features to ensure that user-submitted values match your expectations.

Error messages may be vital when testing your website, but a hacker might use these messages to glean valuable information about your site. For this reason, it’s smart to hide error messages before deploying your website on a live server.

To close this potential security loophole, start by launching cPanel’s File Manager tool:

A2 Hosting's File Manager tool.

Then, navigate to your wp-admin directory and open the php.ini file. To disable error logging, simply add the following text to your file: display_errors=Off.

How to Add PHP Functions Using a WordPress Plugin

By default, WordPress won’t execute PHP inside of a page or post. If you want to add custom PHP code to a specific webpage, you’ll need to use the Insert PHP Code Snippet plugin.

This plugin provides a central location where you can define each PHP snippet. You can then insert these snippets anywhere on your site, using the automatically-generated shortcode.

After installing and activating the Insert PHP Code Snippet plugin, navigate to XYZ PHP Code > PHPCode Snippets:

The PHP Code Snippets plugin.

On the next page, select Add New PHP Code Snippet. Inside the code box, you can either copy/paste or type the PHP function that you want to use:

Inserting PHP functions.

In the Tracking Name field, you’ll need to give this PHP snippet a title. This will represent the PHP function throughout the WordPress dashboard, so it’s a good idea to choose something distinctive. You’ll also use the tracking name when calling this snippet manually. When you’re happy with the information you’ve entered, click on Create.

You can now add this PHP snippet to any page or post, using a shortcode. To access this shortcode, head to XYZ PHP Code > PHPCode Snippets. You can then find the snippet in question and copy its corresponding shortcode:

PHP functions, created using a WordPress plugin.

Next, open the page or post where you want to insert the associated PHP. You can then create a new shortcode block:

The WordPress shortcode block.

Simply paste the shortcode into this block and save your changes. This custom PHP will now be installed on this specific page or post.

How to Remove PHP Functions From a Page or Post

At some point, you may want to remove custom PHP snippets from your website. Perhaps you no longer require a particular function, or you’re concerned that it’s making your site more vulnerable to attack.

If you want to remove a function from a specific page or post, then simply open that webpage for editing, find the shortcode in question, and delete it. Alternatively, you can deactivate a PHP snippet without removing it from the pages where it’s installed. This can be useful if you’ve deployed the same snippet across multiple pages and want a quick and easy way to deactivate every instance of this function.

To temporarily suspend a snippet, navigate to XYZ PHP Code > PHPCode Snippets. You can then find the snippet and click on its accompanying Pause button.

Another option is to delete the function from the Insert PHP Code Snippet plugin. This can be a serious time-saver if you’ve used a snippet multiple times and want to permanently remove it from every single webpage.

To delete a snippet, navigate to XYZ PHP Code > PHPCode Snippets. Then, locate the snippet that you want to scrub from your WordPress website and click on its accompanying Delete action.

How to Add PHP Functions Without a Plugin (In 2 Easy Steps)

If you want all the benefits of custom PHP without installing yet another WordPress plugin, then a child theme may be the answer. Before proceeding, we recommend creating a backup so you’ll have something to restore in case anything goes wrong. Once your backup is in place, you’re ready to start.

1. Create a Child Theme

You can create a child theme via the File Transfer Protocol (FTP) using a client such as FileZilla. After connecting to your site, your first task is to create a directory for your child theme.

In FileZilla, navigate to wp-content/themes and create a new folder. When naming your directory, we recommend using the parent theme’s name, appended with -child:

The FileZilla FTP client.

The next step is to create a style sheet. This file will contain the code that determines your website’s design. When creating this file, make sure you assign it the filename style.ss:

Inserting PHP functions into a child theme.

To build an eye-catching and effective child theme, you’ll usually have to write a considerable amount of code. However, if you just want to spin up a quick child theme to test your custom PHP functions, the WordPress Codex provides some boilerplate code that you can use:

/*
Theme Name: Twenty Fifteen Child
Theme URI: http://example.com/twenty-fifteen-child/
Description: Twenty Fifteen Child Theme
Author: John Doe
Author URI: http://example.com
Template: twentyfifteen
Version: 1.0.0
License: GNU General Public License v2 or later
License URI: http://www.gnu.org/licenses/gpl-2.0.html
Tags: light, dark, two-columns, right-sidebar, responsive-layout, accessibility-ready
Text Domain: twentyfifteenchild
*/

Next, you’ll need to create a functions.php file, which is where you’ll add features to your theme. After creating this file, open it in your text editor and add the following:

<?php
add_action( 'wp_enqueue_scripts', 'enqueue_parent_styles' );
function enqueue_parent_styles() {
wp_enqueue_style( 'parent-style', get_template_directory_uri().'/style.css' );
}

In this snippet, we’re inheriting information from the parent’s style sheet. Now that you have all of the essential elements in place, you can navigate to Appearance > Themes in the WordPress dashboard. Here, you should be able to see your child theme. Assuming that you’re happy with your theme’s appearance, you can activate it.

2. Add a PHP Function

The next step is adding your custom PHP functions to your child theme. In your WordPress dashboard, go to Appearance > Theme Editor. Then, open the Select theme to edit dropdown and choose your child theme:

The WordPress theme editor.

In the left-hand menu, select the functions.php file. You can now add all of your PHP functions to this file.

As a quick example, let’s create a simple function that will display some text. To achieve this, copy and paste the following:

function test_func( $atts ){
return 'This is a PHP function' ;
}
add_shortcode( 'test', 'test_func' );

You can then select Update File. Now, you can call this PHP function using the defined shortcode. In the above example, we set the shortcode as test.

In your WordPress dashboard, navigate to the page or post where you want to call this PHP function. Then, create a new shortcode block and add your shortcode:

Inserting PHP functions into a shortcode.

You can now save your changes and head to the page that you’ve just edited. The string from your test function should appear on this webpage:

PHP functions, as seen in the visitor's browser.

This is just a simple example. WordPress supports a wide range of functions that you can use to customize and extend your new child theme. You’ll find a complete library of all these functions over at the WordPress Codex.

Why You Might Want to Add PHP Functions Without a Plugin

Plugins can be a quick and easy way to insert PHP into a specific webpage. However, if you only need to insert the occasional PHP function, then installing an entire plugin may feel like overkill.

WordPress plugins are also a huge source of security vulnerabilities. In 2021, WP White Security discovered almost 4,000 known plugin vulnerabilities. With this in mind, you may want to try minimizing the number of plugins installed on your WordPress website.

As we have seen, you can insert PHP manually by creating a child theme. You can then add your custom code to that child’s functions.php file. The downside is that your PHP functions will only work when you’re using this particular theme.

While it may be tempting to simply apply your PHP code to your current theme, it’s always best to create a child theme first. If you edit the parent theme’s functions.php file directly, then these changes will be overwritten every time you update your theme. By taking the time to create a child theme now, you can continue installing the latest updates without losing all of your custom code.

Conclusion

You don’t need to know PHP in order to run a successful WordPress website. However, PHP can be an effective tool for enhancing and extending the core Content Management System (CMS) platform.

Armed with some PHP know-how, you can add your own custom hooks to any page or post. You can also tweak your favorite themes and plugins so they’re the perfect fit for your WordPress website. If you’re feeling adventurous, then learning PHP may even be the first step towards developing your own themes and plugins.

Custom PHP can be a powerful addition to your site. However, hackers may try to weaponize this programming language against you. At A2 Hosting, we offer all the security features you need in order to reap the rewards of bespoke PHP without any risks.

Related Resources:

PHP and WordPress Compatability: Everything You Need to Know

Top 8 Security Practices for PHP

How to Find the Right WordPress Plan

9 Ways to Keep Your WordPress Website Secure

 

Image credit: Pexels.

 

 

The post What Is PHP (And How Can You Use It in WordPress)? appeared first on The A2 Posting.

]]>
https://www.a2hosting.com/blog/content/uploads/2021/07/computer-code-glasses.png
Top 8 Security Practices for PHP https://www.a2hosting.com/blog/security-practices-for-php/ Thu, 01 Jul 2021 17:50:33 +0000 https://www.a2hosting.com/blog/?p=11047 As a responsible website owner, you likely want to do everything in your power to keep your visitors safe. However, there’s one aspect of security that’s easy to overlook: Hypertext …

The post Top 8 Security Practices for PHP appeared first on The A2 Posting.

]]>
As a responsible website owner, you likely want to do everything in your power to keep your visitors safe. However, there’s one aspect of security that’s easy to overlook: Hypertext Preprocessor, better known as PHP.

PHP is the backbone of many websites and applications, including WordPress sites. So it’s important to familiarize yourself with relevant security practices for it and follow them carefully. Fortunately, out-of-the-box PHP has all of the features and functions you need to protect your site against hackers.

In this post, we’ll discuss what PHP is and why it’s essential for website security. We’ll then share eight ways that PHP can protect your site against a range of attacks, including session hijacking, Cross-Site Request Forgery (CSRF), and Cross-Site Scripting (XSS). Let’s get started!

An Introduction to PHP (And Why It’s Important for Web Security)

PHP is a server-side programming language that’s used in many Content Management Systems (CMS). This includes WordPress, which uses it as the scripting language:

The PHP logo.

PHP is used by 79 percent of all the websites whose server-side programming language is known. Since most sites are created with PHP, it’s a popular target for hackers. If an attacker manages to uncover a PHP vulnerability, they could potentially use the same attack against millions of websites – including yours.

If your site is compromised, a hacker could steal your data. Even worse, if you take payments on your site, a security breach could result in your customers’ credit card information being hijacked or even published.

This will have immediate consequences for your business by damaging customer trust and your reputation. However, it can also have long-term financial implications. In 2020, researchers estimated that the average total cost of a data breach was $3.86 million. By learning proven security practices for PHP, you’ll be in a strong position to fend off these attacks.

Top 8 Security Practices for PHP

Hackers are always looking for ways to break into your site, including exploiting your website’s PHP. Let’s look at eight actions you can take to ensure that PHP doesn’t give attackers a route into your data.

1. Update Your Version of PHP Regularly

New versions of PHP often introduce fixes for security vulnerabilities. If you’re not running the latest version, hackers could potentially expose those known weaknesses. Therefore, keeping your software up-to-date is one of the most important security practices for PHP.

You can check the latest stable release of PHP over at the official website. If you’re not running this version, your site may be at risk.

If you’re unsure which version of PHP you’re currently using, don’t worry. You can find this information on the WordPress Site Health screen. Assuming that you have WordPress 5.0 or higher installed, navigate to Tools > Site Health > Info > Server:

The WordPress Site Health screen.

The PHP version is set at the server level, so if you’re running an outdated version, you may need to contact your hosting provider. If you have an A2 Hosting managed Virtual Private Server (VPS) or managed server account, you can open a support ticket specifying the version of PHP that you want to use. Our Guru Crew will upgrade you to your chosen version.

If you have a shared or managed hosting account, you can switch between different PHP versions using the cPanel control panel. Simply log into your cPanel account and launch the Select PHP Version tool:

The A2 Hosting cPanel dashboard.

Next, open the Current PHP drop-down menu and choose any release from the list. We’ll change you over to that version immediately.

Alternatively, if you manage your account using the Plesk control panel, you can log into the A2 Hosting Customer Portal and navigate to Services > My Services:

The 'Services' tab of the A2 Hosting Customer Portal menu.

Under My Products & Services, locate your hosting package, then click on Manage > Open Control Panel. Next, in Plesk, select Websites & Domains > PHP Selector. Finally, you can select the desired version of PHP and click on Set as current.

2. Install a Secure Sockets Layer (SSL) Certificate

A Secure Sockets Layer (SSL) certificate is essential for securely transferring files via HyperText Transfer Protocol Secure (HTTPS) instead of HyperText Transfer Protocol (HTTP). This certificate is important for any website, but it’s particularly vital if you collect or transmit sensitive information, such as customers’ payment details. If your site features login functionality, an SSL certificate can also prevent malicious third parties from eavesdropping and stealing visitors’ usernames and passwords.

At A2 Hosting, we provide a range of SSL certificates from a wide variety of providers. We’re confident you’ll find a solution that meets your exact needs:

SSL Certificate options provided by A2 Hosting.

After purchasing a certificate, we’ll send you an SSL Token via email. This is the key to installing your certificate and protecting your data against hackers.

If you’re a cPanel user, you can log into your account and launch the AutoInstall SSL tool. Next, you can paste your SSL Token into the field and click on Verify token:

A2 Hosting AutoInstall SSL tool.

After submitting a valid token, cPanel will prompt you to enter more information about your certificate and your website. After providing these details, AutoInstall SSL will upload your certificate, and after a few moments, your site will be protected with SSL.

If you manage your site using Plesk, you can log into your account and select Websites & Domains > SSL Certificates. You should then see the SSL certificates page for your domain.

In the Upload, the certificate as text section, paste all of the text from your SSL certificate, including the BEGIN CERTIFICATE and END CERTIFICATE headers. Next, go ahead and click on Upload Certificate, and Plesk will install your SSL certificate.

Alternatively, WordPress users can install their certificates using a plugin. Some popular options include Really Simple SSL and WP Encryption.

3. Protect Against XSS Attacks

XSS attacks occur when a hacker exploits a vulnerability on your website. As part of this intrusion, the agent will upload a malicious script, which can then be executed on the client-side in the browser. The cybercriminal may also execute the script on your server.

An example of an XSS attack is when your site accepts user input and prints it directly to the web page. In this scenario, a hacker might execute the remote code by submitting JavaScript, HTML, or even CSS to your website.

Nefarious third parties often use XSS attacks to steal data, including your customers’ passwords and payment information. Some invasions can even change how your site looks or behaves. For example, hackers might use an XSS to redirect your visitors to another website.

XSS attacks are hugely popular with cybercriminals. In 2020, Wordfence identified 330 million attempted XSS attacks, making it the fourth most commonly attacked category of vulnerabilities.

You can protect against this frequent attack by sanitizing your data. PHP’s filter_var contains disinfection indicators that enable you to check all user-submitted data. You can then remove all values that aren’t of the expected type. For example, if you make a call to filter_var ($ val, FILTER_SANITIZE_NUMBER_INT), all characters that are not numbers will be deleted. This can help ensure that you’re receiving legitimate data and not malicious scripts.

You can also use validation to verify that user-submitted values match your expectations. You can perform this validation using the filter_var security practices for PHP function, such as filter_var ($ _GET [’email’], FILTER_VALIDATE_EMAIL).

If this function provides an error, the data is likely invalid. You can learn more about these important security practices for PHP at the official validation features documentation.

4. Use Prepared SQL Statements

If you insert any user input directly into an SSL statement, you’re leaving your site vulnerable to SQL injection attacks. This is where a malevolent third party attempts to break the intended SQL query and instead queries for different information, such as a customer’s payment details.

To protect against these injection attacks, it’s important to ensure that the inputted values are properly escaped. You can achieve this by using a prepared statement to execute all of your SQL statements.

As part of a prepared statement, the SQL statement template is created and sent to the database. The database then parses, compiles, and performs query optimization on the SQL template and stores the result without executing it.

The application then binds the values to the parameters and executes the statement. Since the parameters are transferred later using a different protocol, this leaves no room for an SQL injection attack.

You can also validate the data type of the input using the bind_param function. This function binds the parameters to the SQL query and tells the database what these parameters are. For example:

$stmt->bind_param("sss", $firstname, $lastname, $email);

Here, SSS lists the types of data that these parameters should include. These arguments can either be: i (integer), d (double), s (string), or b (BLOB). By telling the database what type of data to expect, you can further minimize the risk of SQL injections.

It’s also smart to use Object Relational Mapping (ORM), such as Doctrine or Eloquent. This reduces the chances of hackers injecting SQL queries.

5. Protect Against CSRF Attacks

CSRF occurs when a hacker performs unwanted actions on your website. As part of this attack, the nefarious third party attempts to transfer malicious commands to your site.

The intruder cannot see the responses to the forged requests, so CSRF attacks mostly target state-changing requests. The cybercriminal may send a link or alter data in an HTML tag, which triggers a change of state, such as transferring funds or modifying the user’s login credentials.

To launch a CSRF invasion, a hacker must know the parameters and value combinations that you use in your user-input fields. You can help the server spot invalid requests by adding an extra parameter with a value that is unknown to the hacker.

One approach is to use an anti-CSRF token. This is a random string that is known only to the visitor’s browser and your web application. It is typically stored inside a session variable. You can add this token in a hidden field that gets sent with the request.

The server will only accept your request if the values of the session variable and the hidden form field match. Due to the same-origin policy, hackers cannot read the response that contains the token.

Alternatively, you can use the SameSite cookie attribute. This prevents browsers from automatically adding cookies to requests, regardless of where they originate. You can add the SameSite attribute to the SetCookie response header when the server issues a cookie:

SetCookie: SessionId=sYMnfCUrAlmqVVZn9dqevxyFpKZt30NN; SameSite=Strict;

If you set the SameSite attribute to Strict, the browser won’t include the cookie in any requests that originate from another site. However, this can impact the User Experience (UX). For example, if a logged-in user follows a link to a third-party site, they will appear not to be logged into their account.

6. Bind Your IP Address With Session ID

Session hijacking occurs when a hacker secretly steals the visitor’s session ID. This ID is then sent to the server, where the $_SESSION array validates its storage in the stack.

At this point, the hacker will have access to the web application. Session hijacking can occur via an XSS attack, or when the agent gains entry into the directory where you store session data.

To prevent this from happening, we recommend binding the session ID to other user or client properties. One possible way to do this is by binding the session to the client IP address:

$IP = getenv ( "REMOTE_ADDR" );

If the web application detects any changes to this property in the middle of an established session, it is a strong indication that a third party is attempting to seize the session. You can then take action to protect your website and your visitors. For example, you can terminate the suspicious session.

Just be aware that a skilled hacker may be able to reuse the same IP address that’s assigned to the visitor. They can achieve this by using the same outbound web proxy or manually modifying the User-Agent to mimic the visitor. However, while the binding isn’t guaranteed to protect you against this kind of sophisticated session hijacking attack, it can make your site less susceptible to one.

7. Hide All Errors in Production

Error messages are vital when building and testing your website. These messages can provide valuable information about any problems with your site, which can help you resolve the issues more efficiently. Error notifications can also highlight subtle problems you may not otherwise have noticed.

Unfortunately, hackers can weaponize error messages against you. A cybercriminal might use the information contained within them to learn more about your site and identify any security loopholes that they can exploit.

For this reason, it’s important to hide error messages when deploying your site on a live server. To achieve this, we recommend that you set the following parameter in your site’s php.ini file:

display_errors=Off

Typically, you won’t want to discard these error messages entirely, as they can be useful for diagnosing any future issues that occur. You can log PHP errors in a specific file using the following command:

log_errors=On
error_log=/var/log/httpd/php_error.log

This will record all of your PHP errors to a file named php_error.log. You can change the name of this file if desired.

8. Choose a Reliable Hosting Provider

Hosting is a crucial factor in securing your site against a wide range of attacks, including those that specifically target PHP. At A2 Hosting, all our hosting packages come with a range of built-in security features, including HackScan Protection, which can help block hackers before they damage your site:

A2 Hosting packages.

We also offer KernelCare rebootless kernel updates, a dual firewall, and Cloudflare as standard. Cloudflare in particular can identify and block malicious requests before they reach your site, which can prevent hackers from exploiting a wide range of PHP vulnerabilities:

The Cloudflare WAF.

We also understand that every website’s security needs are unique. That’s why we ensure you have easy access to all the add-ons you need to secure your particular website. All of our packages include the user-friendly cPanel control panel and Softaculous installer:

 The Softaculous installer.

This installer provides you with easy access to software, tools, and extra configurations. By taking advantage of Softaculous, you can feel confident that your site is properly protected against malicious third parties.

Conclusion

Security is an important topic that generates lots of attention. However, many website owners focus on protecting their sites against attack and sometimes overlook their programming language.

By following security practices for PHP, you can close a potential loophole and defend your site against a wide range of common intrusions. To start, it’s essential to get the fundamentals right by installing the latest version of PHP. Then you can shift your focus to protecting the data submitted to your website via advanced security practices for PHP, such as prepared SQL statements and data sanitization.

To set your site up for success, it’s also critical to choose a hosting provider that takes security seriously. At A2 Hosting, all of our packages come with built-in security features that can help strengthen your defenses against all the popular PHP-based attacks, including XSS!

Image credit: Pexels.

Related Resources

PHP 8 and WordPress Compatability: Everything You Need to Know

How to Managed Dependencies in PHP Using Composer

What is Memcached, and Why Does My Site Need It?

12 Advantages of Using Frontity for Your WordPress Projects

 

 

 

The post Top 8 Security Practices for PHP appeared first on The A2 Posting.

]]>
https://www.a2hosting.com/blog/content/uploads/2021/04/glasses-laptop-programming.png
PHP 8 and WordPress Compatibility: Everything You Need to Know https://www.a2hosting.com/blog/php-8-wordpress-compatibility/ Wed, 07 Apr 2021 14:54:10 +0000 https://www.a2hosting.com/blog/?p=10363 If you’re a developer or you follow web development trends, you’re probably aware that a new, major update to PHP was released late last year. You may be wondering if …

The post PHP 8 and WordPress Compatibility: Everything You Need to Know appeared first on The A2 Posting.

]]>
If you’re a developer or you follow web development trends, you’re probably aware that a new, major update to PHP was released late last year. You may be wondering if it’s a good idea to upgrade your website to this new version.

PHP 8 brings lots of fresh features and changes, as well as the promise of big performance improvements. However, major version updates sometimes introduce compatibility issues with WordPress core and WordPress plugins, so the answer isn’t necessarily clear-cut.

In this article, we’ll explore the biggest features and changes in PHP 8, and give advice on when (and if) you should upgrade. Let’s dig in!

An Introduction to PHP 8

PHP 8, the latest version of the popular scripting language, was released at the end of November 2020. If you’re not familiar with PHP, it’s one of the main programming languages used both in platforms like WordPress and across much of the web. In fact, most of the core parts of WordPress are written in PHP.

PHP 8 brings a huge number of changes to the language when compared to the current version (7.4). There are also new functions and features, like the Just-In-Time (JIT) compiler, as well as updates to attributes and error handling. You can check out the full list of changes for all the details.

Of course, like any major PHP update, this one may also contain ‘breaking changes’, code updates that aren’t compatible with software built using older versions of PHP. PHP 7 was no different in this regard. For that reason, it’s smart to exercise some caution and do plenty of research and testing before updating.

We’ll look into all these details in a bit. First, however, let’s explore some of the new features in PHP 8.

8 Changes to Know About in PHP 8

As with any major release, PHP 8 contains a collection of new and updated features, as well as some behind-the-scenes bug fixes and changes. Here, we’ll cover some of the most interesting and exciting updates.

1. Significant Performance Improvements

Perhaps the most hyped and anticipated change in PHP 8 is in the realm of performance – particularly in the form of the Just-In-Time (JIT) compiler. In layman’s terms, a compiler takes the source code (in PHP) and turns it into something readable by the computers executing the code.

The difference with a JIT compiler is that it does this only as needed, during ‘run time’ rather than beforehand. The aim is to be more efficient and provide faster performance, and the JIT compiler in PHP 8 seems to deliver on that promise.

Unfortunately, the speed and efficiency improvements to PHP as a whole from the JIT compiler may not translate directly to a huge boost in WordPress performance. While you may notice a slight bump in speed, WordPress depends on more than just PHP to function: there are also elements like JavaScript in play that won’t benefit from these changes.

Still, it’s a step in the right direction, and one that ultimately paves the way for future changes to increase WordPress performance. It’s also going to be a big boon to developers working with PHP code in other contexts.

2. New PHP Functions

Performance improvements aren’t the only thing that’s exciting about PHP 8. There are also several all-new functions that make searching easier and more convenient:

str_contains is a new function designed to make searching for a ‘needle’ inside a given string of code (the haystack in this analogy) simpler and less error-prone. In prior PHP versions, strstr and strpos were the functions used for this, but they require more complex code blocks and have some issues.

The new function looks like this:

str_contains ( string $haystack , string $needle ) : bool

If the ‘haystack’ contains the ‘needle’, it returns a true/false message, which can be customized. Pretty simple!

str_starts_with() and str_ends_with() are also new functions intended to simplify searching within strings. These are more specific, however: they simply look to see if the string either starts or ends with the given term and return a true/false response. This is a commonly-needed function in PHP, so its inclusion is welcome.

Finally, get_debug_type is a function that returns the type of a specified variable. PHP already has a similar function in the form of gettype, but the new option is intended to be more useful for developers and can also resolve class names.

3. The Introduction of Named Parameters

PHP 8 now supports Named Parameters, rather than simply positional parameters. If that leaves you scratching your head, don’t worry: we’ll explain.

Essentially, positional parameters require your code to place the parameters in the same order as the function you’re calling. On the other hand, named parameters can be placed in any order, since the code recognizes their names and not just their positions. To use the str_contains function from above as an example, positional parameters would look like this:

function str_contains(string $haystack, string needle): bool {}
str_contains('FooBar', 'Foo');

Whereas named parameters would look like this:

function str_contains(string $haystack, string $needle): bool {}
str_contains(haystack: 'FooBar', needle: 'Foo');

What that means in practice is that with named parameters, both of these pieces of code would be correct and return the same result:

str_contains(haystack: 'FooBar', needle: 'Foo');
str_contains(needle: 'Foo', haystack: 'FooBar');

For seasoned developers, this enables increased readability with certain functions, whereas those new to development get a bit more forgiveness if they forget the order of operations for a given function.

Finally, named parameters use the default values if they’re not explicitly called in the code. This means you can skip optional parameters that don’t require deviation from the default. This is not possible with positional parameters.

4. Attributes v2

PHP 8 introduces Attributes v2. This expands and improves on the attributes system in PHP, and promises to bring it more in line with other languages.

Attributes are a form of ‘structured metadata’ for classes, properties, functions, and more. They enable developers to define configuration directives directly in the code. In previous versions of PHP, attributes came in the form of ‘doc-comments’, which are simple strings that lack structure and aren’t parsed automatically.

Attributes are added before the declaration they belong to, but can be declared either before or after a doc-comment that documents them. See this example from the PHP wiki:

<<ExampleAttribute>>
class Foo
{
<<ExampleAttribute>>
public const FOO = 'foo';

<<ExampleAttribute>>
public $x;

<<ExampleAttribute>>
public function foo(<<ExampleAttribute>> $bar) { }
}

$object = new <<ExampleAttribute>> class () { };

<<ExampleAttribute>>
function f1() { }

$f2 = <<ExampleAttribute>> function () { };

$f3 = <<ExampleAttribute>> fn () => 1;

These new attributes will help streamline a process that is already used by PHP developers in a more convoluted way, and should also help standardize attributes across developers.

5. Improved Error Handling

Another big change in the newest version of PHP is in the realm of error handling. In PHP 8, internal functions now throw exceptions on ‘type’ errors. This is a major improvement that is, unfortunately, not backward-compatible with old code. However, it will make debugging errors much simpler in the future.

In older versions, PHP would simply return null when it found a value it can’t use, like in this example:

var_dump(strlen(new stdClass));
// Warning: strlen() expects parameter 1 to be string, object given
// NULL

This isn’t useful at all, and worse, it’s not consistent across functions. PHP 8 will provide developers with a clearer picture to help them troubleshoot these errors and get things working. The new standard format is:

declare(strict_types=1);
var_dump(strlen(new stdClass));
// TypeError: strlen() expects parameter 1 to be string, object given

This standardized behavior should be a big boon for developers.

6. Arrays Starting With a Negative Index

In previous versions of PHP, when an array started with a negative index, the following indices would start with 0. Consider this example code:

$a = array_fill(-5, 4, true);
var_dump($a);

In older versions of PHP, this would give the following output:

array(4) {
        [-5]=>
        bool(true)
        [0]=>
        bool(true)
        [1]=>
        bool(true)
        [2]=>
        bool(true)
}

As you can see, the numbers jump immediately from -5 to 0, skipping everything in between – which is not terribly useful. Of course, if you know this is the expected behavior, then you can prepare for it. If you’re new to the language or not familiar with this functionality, however, it can be pretty confusing.

In PHP 8, this changes. Now, the next index will be one more than the starting index, regardless of whether it’s positive or negative. Here’s the output of the same code in PHP 8:

array(4) {
        [-5]=>
        bool(true)
        [-4]=>
        bool(true)
        [-3]=>
        bool(true)
        [-2]=>
        bool(true)
}

It’s important to note that this change is not backward compatible. Therefore, code that relies on or expects the behavior from previous PHP versions will need to be updated for the new index handling.

7. Weak Maps

PHP 8 introduces a new class: WeakMap. This class takes the existing support for weak references (added in PHP 7.4) and expands it into a much more useful form.

According to the PHP Wiki, weak maps “allow creating a map from objects to arbitrary values (similar to SplObjectStorage) without preventing the objects that are used as keys from being garbage collected”. In the event that an object key is garbage collected, it’s removed from the map.

Although support for weak references was added in PHP 7.4, it was less useful than it could have been because weak references by themselves aren’t particularly common. They almost always appear in the context of a weak map.

Additionally, the way the weak references were implemented in PHP 7.4 made simply adding a weak map feature impossible. For this reason, the entire feature was scrapped and rewritten for PHP 8, and the result should be much more useful for developers.

8. Saner Numeric Strings

PHP makes use of what’s known as ‘numeric strings’, which are strings that can be interpreted as numbers by the language. In past versions of PHP, there were three categories for strings that contain numbers:

  1. Numeric strings
  2. Leading-numeric strings
  3. Non-numeric strings

The first two categories count as numeric strings, but they were treated differently depending on which operation was being performed. This isn’t entirely intuitive, and unless you were aware of these differences, you might get some unexpected results.

In PHP 8, these categories have been unified into a single concept. According to the official documentation: “Numeric characters only with both leading and trailing whitespace are allowed. Any other type of string is non-numeric and will throw TypeErrors when used in a numeric context.”

This results in a much simpler system behind the scenes. It also helps to make expected outcomes clearer for developers, so overall this is a welcome change.

PHP 8 and WordPress Compatibility

Since WordPress (and its plugins) depend so heavily on PHP, new versions of the language can result in compatibility issues if other software hasn’t been updated. This is particularly true for major version releases, such as PHP 8.

Typically, WordPress releases its own new versions to coincide with these major PHP updates, in order to help ensure a smooth transition. The latest version of WordPress, 5.6, is designed to fulfill this role. However, WordPress has stated that version 5.6 should only be considered ‘beta-compatible’ at this time.

What this means is that WordPress 5.6 should be compatible with PHP 8, and the developers have done fairly extensive testing on this front. There is still the risk of undiscovered issues with WordPress core, however, so the developers can’t guarantee yet that everything will work perfectly.

What’s more, this update only applies to WordPress core. Plugins and themes by third-party developers will need to be updated separately, a process that can take some time.

What does that mean for you? First, if you’re considering updating, you’ll want to double-check that the theme and plugins you use are certified as compatible by their developers.

It’s also a good idea to do a trial run of major updates on a test server before implementing them in your live environment. PHP 8 is no different – it should be tested thoroughly.

Testing can be done in a staging environment created through your hosting account, or you can create a local copy of your site using tools like XAMPP, MAMP, and Local. Each of these solutions enables you to create a copy of your site directly on your computer.

This lets you perform whatever tests and configuration changes you need without impacting your live site at all. Most tools enable you to create as many local installations as you like, so they’re a fantastic way to try out new things.

Finally, you should only consider updating at this time if there’s a feature in PHP 8 that you absolutely can’t live without. The previous version, PHP 7.4, will still receive active support until November 28, 2021, and it will receive security updates for another year after that.

This means that you don’t need to update until the end of 2022. Take your time, test thoroughly, and update only when you’re sure your site will operate smoothly with the new version.

How to Update Your Version of PHP

If you’re eager to get your hands on PHP 8, either for testing or for a live environment, A2 Hosting makes it easy. First, you’ll need to access your cPanel. To do so, log into your A2 Hosting account. This admin area enables you to manage everything related to your domains and websites:

The A2 Hosting admin area.

Locate the domain you want to update and click on cPanel Login:

The main cPanel page in A2 Hosting.

From there, scroll down to the Software section and click on Select PHP Version:

The Select PHP Version tool in cPanel.

This tool enable you to easily edit your PHP version, extensions, and settings from one place. To change the version, just click the drop-down menu at the top of the page and choose the one you want to update to:

The menu to select the version of PHP used on your site.

You can also switch to an older version of PHP if you like. If you need more help, check out the full instructions in our knowledge base.

If you’re on a different hosting provider, there’s a chance that they offer a similar tool. Your best bet is to consult with your provider’s documentation or contact support.

Conclusion

PHP 8 brings significant performance improvements and new features to the popular scripting language. The new JIT Compiler in particular has been the source of much excitement and seems to live up to the hype.

However, keep in mind that the latest version of WordPress, 5.6, is only ‘beta compatible’ with PHP 8. It may be a good idea to hold off if your site is a critical part of a business. Meanwhile, you can try it out on a testing site to learn more about what it has to offer.

To ensure that you’re always running the latest and greatest software, including PHP 8, be sure to check out our WordPress hosting plans. There’s something for every need and budget!

Image credit: geralt.

The post PHP 8 and WordPress Compatibility: Everything You Need to Know appeared first on The A2 Posting.

]]>
https://www.a2hosting.com/blog/content/uploads/2021/02/colorful-city-skyline.jpg
How to Manage Dependencies in PHP Using Composer https://www.a2hosting.com/blog/manage-dependencies-php-composer/ Tue, 22 Oct 2019 18:19:54 +0000 https://www.a2hosting.com/blog/?p=7476 When working with PHP, you’re going to have to manage your dependencies. As your project develops, however, the number of dependencies you are using is likely to grow. If you …

The post How to Manage Dependencies in PHP Using Composer appeared first on The A2 Posting.

]]>
When working with PHP, you’re going to have to manage your dependencies. As your project develops, however, the number of dependencies you are using is likely to grow. If you are managing them manually, this can quickly become overwhelming.

As such, it’s important to employ a system that enables you to work more efficiently. Composer, for example, is a dependency manager for PHP that enables you to list your dependencies in a composer.json file. Then, with a few simple commands, it will automatically download your project’s dependencies and set up autoloading for you.

In this piece, we’ll begin by explaining what dependencies are in PHP, and discussing how difficult it can be to manage them manually. Then we’ll show you how Composer can make this process easier. Let’s get to work!

An Introduction to Dependencies in PHP

Dependencies are PHP libraries, frameworks, and components that you can use in your web development projects. They help to make coding easier and more efficient, and most projects will rely on a number of them.

The issue with dependencies lies in how difficult they can be to manage. The more of them you incorporate into a project, the harder it is to keep track of all those moving pieces. What’s more, managing them manually is often tedious and time-consuming.

For this reason, it’s critical to find a solution for managing your dependencies in PHP more effectively. There are several solutions that can help with this problem, but we’ll focus on one of the more powerful and accessible options.

How Composer Can Make Managing Dependencies Easier

The Composer dependency manager logo.

Composer is a dependency manager built specifically for PHP. It works by providing a file for you to list the dependencies you are using.

For instance, you can list the dependencies for your project in a composer.json file, which will enable you to access those files whenever you need them. With this system in place, you will no longer have to worrying about having to locate and re-download key assets.

On top of that, Composer is a free and easy-to-use tool, which also happens to be open source. If you’re not yet convinced to give it a try, however, let’s take a closer look at how it works.

How to Manage Dependencies in PHP Using Composer (In 4 Steps)

When it comes to dependency management, Composer is a popular choice. It only takes a few simple steps to get it set up and start using it.

Step 1: Download and Install Composer

To begin with, you’ll want to pull up your favorite HTML editor. From there, run the following script in your terminal to install Composer in the current directory,:

php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
php -r "if (hash_file('sha384', 'composer-setup.php') === 'a5c698ffe4b8e849a443b120cd5ba38043260d5c4023dbf93e1558871f1f07f58274fc6f4c93bcfd858c6bd0775cd8d1') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"
php composer-setup.php
php -r "unlink('composer-setup.php');"

These four lines of code will download the installer, verify and run it, and remove it when the process is finished. Just like that, you’re ready to get started, although you may also want to run this line of code next:

mv composer.phar /usr/local/bin/composer

By default, Composer will install locally to a project. However, this command will move it to your local bin directory, so you can easily use it anywhere.

Step 2: Create a New File to Manage Your Packages

Next, you need to create a new folder on your system. Within that folder, create a blank file called composer.json, and add the following code to it:

{

        “require”: {

            “phpunit/phpunit”: “4.3.*”

        }

    }

With that done, you have just created the file where you will list all the packages you are using in your project. On the next line, you can list the first package:

The composer.json file.

You must include a vendor name, project name, and version number, in the following format. The first part is the vendor, followed by the project name, and then the version number in brackets:

phpunit/php-code-coverage {2.0.11}

Start a new line for each package, and repeat this process until you have input all the packages you are using. Also, it should be noted that the version numbers should be written using the standard semantic versioning notation.

Step 3: Install the Dependencies You Will Need For Your Project

With that complete, you’re ready to install your dependencies. In your terminal, type “composer install” and run the command:

The script showing some packages being installed on Composer.

Now, you’re just about ready to create a new file and get to work. However, before you can dive fully into your project, you’ll probably want to set up autoloading.

Step 4: Set Up Autoloading to Make Development Easier

Autoloading will fetch dependencies from your list to meet the requirements of your code. To use this handy feature, you’ll need to open a PHP tag in your project file and add a single line of code:

`require ‘./vendor/autoload.php’;`

When you installed your dependencies using the Composer install command, the ‘autoload.php’ file was created. This file will make your current dependencies available to your project file. The best part is that, since this is a command line tool, it installs that command in the vendor/bin folder for you to use. That way, the package does not have to be installed system wide.

With that, you’re done. Of course, now the real work begins. It’s time to start coding!

Conclusion

Using a dependency manager provides instant access to your packages, frameworks, and other components during a project, as and when you need them. As a result, you can save yourself the headache of having to download them each time.

Fortunately, it’s easy to install and get started with Composer in just four steps:

  1. Download and install Composer.
  2. Create a new file to manage your packages.
  3. Install the dependencies you will need for your project.
  4. Set up autoloading to make development easier.

Image credit: Pexels.

The post How to Manage Dependencies in PHP Using Composer appeared first on The A2 Posting.

]]>
https://www.a2hosting.com/blog/content/uploads/2019/10/business-coding.jpg
PHP 7.4: Why It Will Be Worth the Effort to Update https://www.a2hosting.com/blog/php-7-4-update/ Thu, 10 Oct 2019 18:13:07 +0000 https://www.a2hosting.com/blog/?p=7396 Over the years, the PHP programming language has become one of the most popular methods for building dynamic web applications. In November, we will see the release of version 7.4. …

The post PHP 7.4: Why It Will Be Worth the Effort to Update appeared first on The A2 Posting.

]]>
Over the years, the PHP programming language has become one of the most popular methods for building dynamic web applications. In November, we will see the release of version 7.4. It’s important to understand in advance the changes this update will bring.

Fortunately, there are several new features in PHP 7.4 that you can expect to improve the user experience. For example, this update will introduce typed properties to help developers write cleaner code, as well as preloading to improve performance.

In this post, we’ll discuss PHP and the upcoming update to version 7.4. We’ll talk about five major changes it brings, and discuss how they can improve the user experience. Let’s get started!

Why PHP Is Still the Best Language for Server-Side Programming

The PHP home page.

PHP is a server-side programming language especially suited for web development. The name was originally derived from ‘Personal Home Page’ tools, and now stands for ‘Hypertext Preprocessor’. Today, it remains one of the most widely-used web scripting languages.

There are many reasons for this popularity. For example, PHP can be embedded into HTML, and interacts with many other languages such as MySQL. Therefore, it is fairly easy to learn. In addition, it’s open-source and doesn’t require a licensing fee.

On top of that, it’s easy to set up and create a website using PHP. There’s a thriving community of users who are happy to answer questions, as well as lots of documentation to get you started.  Plus, it’s easy to find developers who know the language if you’re looking to put together a team.

Of course, just like any actively-used piece of software, there are going to be updates to PHP. It’s often necessary to tweak certain commands and develop new features to keep up with changes in technology. The last major update, PHP 7, brought many positive changes, but smaller updates can be surprisingly game-changing as well.

5 Key Updates Coming in PHP 7.4

With the approaching update on November 28th, 2019, PHP is looking stronger than ever before. Here are some of the most important changes to look forward to in PHP 7.4.

1. Preloading for Improved Performance

A boost in performance is always welcome. With PHP 7.4, you can configure opcache to compile your code files first, and then save them in shared memory.

Doing this enables you to make these files freely available, rather than having to compile them every time there is a request:

The preloading function being implemented in PHP.

This is a lot like caching for end users, and offers similar benefits. Improved performance means that you can work more efficiently, have a better UX, and meet those pressing deadlines.

2. Arrow Functions for Cleaner One-Line Functions

Anything that enables you to write shorter code is a helpful improvement to PHP’s UX. The good news is that 7.4 will include arrow functions, which help you shorten your anonymous functions.

They allow the usage of short closures when creating one-line functions:

The arrow function basic form in PHP.

Arrow functions work by defining the expression in the parent scope. In that way, they can certainly help when it comes to making your code less verbose.

3. Typed Properties for Cleaner Code

As with arrow functions, typed properties also help to clean up your code, which is another positive development. With typed properties, you can now easily declare type hints to class variables and properties.

In addition, you can now declare types on static properties. In other words, class variables can be type hinted:

A type hinted class variable in PHP.

The great part about this is that it cuts down on unnecessary boiler plate code. It does so by making sure you don’t have to use getter and setter methods to enforce type contracts.

4. WeakReferences for Retaining a Reference to an Object

WeakReferences enable you to retain a reference to an object, without preventing the object from being destroyed. This new function works similar to a cache structure:

The proposed API for WeakReferences in PHP.

WeakReferences are helpful for some types of object-oriented design that need to index a reference. You can use them by installing the PECL Weakref extension to improve UX for certain projects.

5. Deprecations in Preparation for PHP 8.0

Deprecations are old features that are no longer needed, or won’t function after the implementation of an update. Some of the deprecations to look out for in PHP 7.4 include:

  • Short open tags are to be removed.
  • The left-associative ternary operator will likely be removed, which means you’ll have to use explicit parentheses instead.
  • Curly brace syntax are no longer used, only square brackets.

These changes are in preparation for the next major program update to PHP 8.0. As the software evolves, you can expect more deprecations, as well as new functions and commands to replace them.

Conclusion

Since the 1990s, PHP has been one of the strongest languages for server-side programming. It continues to evolve to this day, with a new update dropping in November 2019.

This update comes with a number of important changes and new features for web developers. As we’ve seen, these include:

  1. Preloading for improved performance
  2. Arrow functions for cleaner one-line functions
  3. Typed properties for cleaner code
  4. WeakReferences for retaining a reference to an object
  5. Deprecations in preparation for PHP 8.0

Image credit: StockSnap.

The post PHP 7.4: Why It Will Be Worth the Effort to Update appeared first on The A2 Posting.

]]>
https://www.a2hosting.com/blog/content/uploads/2019/09/coding.jpg
CodeIgniter: How To Build Dynamic Sites With PHP Framework https://www.a2hosting.com/blog/codeigniter-framework/ Mon, 05 Aug 2019 22:43:56 +0000 https://www.a2hosting.com/blog/?p=6979 There are many different ways to build a website. A lot of people opt for the ease of use of a Content Management System (CMS), which can be an excellent …

The post CodeIgniter: How To Build Dynamic Sites With PHP Framework appeared first on The A2 Posting.

]]>
There are many different ways to build a website. A lot of people opt for the ease of use of a Content Management System (CMS), which can be an excellent option. If you are looking to create a truly dynamic website, however, you may need to dig deeper into the web development world. 

One way to build a fully-featured website is to employ a framework. This can help to make the development process easier, faster, and safer. For instance, the CodeIgniter PHP framework provides an elegant solution for web developers seeking a simple toolkit for getting the job done.  

In this article, we’ll look at the different methods for creating a website, and discuss how a framework can improve the process. We’ll then look at Codelgniter, and explain how it can help you with the task of creating dynamic sites. Let’s get to it!

4 Traditional Methods of Building a Website

Once you’ve registered your domain name and figured out your server requirements, your next task is to choose a method for creating your website. Choosing the right option requires thinking carefully about its design and features. There are four primary routes that website owners and developers take – let’s look at each in turn.

1. Website Builders

When it comes to creating a website fast, site builders are the easiest and most beginner-friendly option. Wix, SquarespaceWordPress.com, and other website builders walk you through setting up a simple site, and host it for you.

Wordpress.com is a website builder.

These solutions are helpful for non-technical users, but are often extremely limited. You’ll only be able to customize certain aspects of the site, and will likely have access to a small pool of add-ons and potential improvements.

2. Content Management Systems (CMSs)

Since website builders are so constraining, many people choose to use a Content Management System (CMS) to design their websites instead. Popular examples include WordPress.org, Joomla, and Drupal.

Wordpress.org is a content management system (CMS).

A CMS offers much more flexibility, typically enabling you to tweak nearly any aspect of your site by hand if you like. Plus, you’ll have plenty of add-ons (such as themes and plugins) on hand to expand your site’s functionality. However, you’re still somewhat limited by what the base software has to offer.

3. Custom Coding

It’s a less popular option these days, but you can still create a site entirely from scratch if you want to. Typically, this means coding it using HTML, CSS, and other programming languages such as PHP. This approach offers complete freedom over how your site looks and functions.

php.net programing language home page.

Of course, building a site from the ground up requires a lot of technical knowledge and a significant time commitment. However, if you use a framework (which we’ll talk about in a minute) it may be easier than you think. If you are building a complex site, this is likely the cheapest option. 

4. Hire a Website Developer

Finally, you can always hire a developer to build your site. This is nearly always the most expensive option, but it lets you commission a site to your exact needs without requiring you to build it yourself.

How much this costs will depend on who you hire and which one of the above methods they are using to build your website (as well as your site’s complexity). The investment involved often makes this only a viable option for sites that will be monetized, such as e-commerce stores.

How CodeIgniter Can Help You Build Websites Faster

All four of the methods described above are valid ways to build a website. For developers in particular, the first three each have their own advantages. However, the inherent drawbacks in these approaches often leave people seeking an alternative solution.

That’s where frameworks come into the picture. A framework is software that helps you build a website, but is less rigid and constricting than a CMS. Rather than providing a platform, it’s simply a pre-built structure written in PHP that handles most of the common and repetitive features for you. 

If you are going to build a website from the ground up, using a framework can save you a lot of time. It enables you to avoid the need to write code for every minor function, providing you with a basic set of starting tools you can work with instead. In other words, you’ll be writing code to interact with and customize the framework. 

The code in the framework is already tested (if it’s a high-quality option), so you’ll know how it works. It will handle most of the low-level functions of your site, letting you focus your attention on more unique and complex features.

Why You Should Consider Using the CodeIgniter Framework

CodeIgniter is a helpful tool for those who choose to build their websites using PHP. It can make completing projects much faster, and is based on the popular Model-View-Controller (MVC) development pattern.

CodeIgniter framework home page.

This solution is also noteworthy for its speed when compared to other PHP frameworks. CodeIgniter’s source code is maintained by GitHub, and is open-source. It’s designed for web developers who are looking to create fully-featured websites, and can also be used for designing web applications. 

In addition, it has an impressive user’s guide and is easy to pick up for those new to frameworks. At the same time, it can be configured and customized to your specifications. Unlike many other frameworks, CodeIgniter comes with a collection of set commands. For example, SQL queries can be activated effortlessly.

Fortunately, getting started with CodeIgniter is a fairly quick process. There’s a bit of a learning curve, as with any framework, but with a little time and reading you’ll find yourself using it to improve the development process in no time.

CodeIgniter Conclusion

If you’re looking to create complex and unique websites, using a website builder or CMS can be limiting. On the other hand, building a site from scratch is incredibly time-intensive.

The good news is that there’s a third option. You can create sites more quickly with the assistance of a framework like CodeIgniter. This tool is easy for framework beginners to pick up, and offers an impressive toolkit for building websites to your (or your clients’) exact specifications.

Image credit: Pixabay.

The post CodeIgniter: How To Build Dynamic Sites With PHP Framework appeared first on The A2 Posting.

]]>
https://www.a2hosting.com/blog/content/uploads/2019/07/legos-building-paper.png
What’s New in PHP 7.3? https://www.a2hosting.com/blog/php-7-3/ Fri, 08 Feb 2019 14:42:36 +0000 https://www.a2hosting.com/blog/?p=6253 The release of PHP 7.0 bought with it numerous features, vastly improving the performance and security of PHP applications. Since they’re known for frequent updates, however, it comes as no …

The post What’s New in PHP 7.3? appeared first on The A2 Posting.

]]>
The release of PHP 7.0 bought with it numerous features, vastly improving the performance and security of PHP applications. Since they’re known for frequent updates, however, it comes as no surprise that the core PHP maintenance team had even more up their sleeves.

December 6th, 2018 saw the launch of PHP 7.3 – the most recent update for this key scripting language. The update brings a host of new features and functionality to the table, including bug fixes and another boost in performance speed.

In this post, we’ll explore some of the exciting new elements included in PHP 7.3. Let’s get started!

A Brief Introduction to PHP (And Why It Matters)

PHP is a widely-used, open-source, and general-purpose scripting language that is especially well suited for web development. PHP can be easily embedded into HTML, meaning that it is both accessible and flexible.

This scripting language was first developed in 1994 by Rasmus Lerdorf. He created the language entirely for personal use, hence the original name: “Personal Home Page Tools”. Despite its humble beginnings, PHP is now one of the most commonly-used server side programming languages in the world.

That’s because PHP is generally considered simple enough for beginners to understand, yet it offers advanced features that more experienced developers can take advantage of. Regardless of your level of expertise, having a basic understanding of PHP is handy if you’re in the business of running or building websites.

PHP is compatible with all major Operating Systems (OSs), and can also be used with popular database tools like MySQL. It’s often used to create dynamic content, such as PDFs, images, and videos. What’s more, it’s always being updated, in order to provide new features and improve performance.

3 Key Changes Introduced in PHP 7.3

PHP 7.3 is the most recent in a long line of updates to this scripting language, as the developers are constantly making changes and improvements. The latest version of PHP brings a number of exciting changes to the table – let’s explore three of the most prominent.

1. Flexible Heredoc and Nowdoc Syntaxes

Perhaps one of the most relevant improvements PHP 7.3 brings is an update to the existing heredoc and nowdoc syntaxes. These are two key methods for defining strings within PHP.

Traditionally, these syntaxes have required that the ending identifier should be the first string appearing in a new line. The update within PHP 7.3 brings two changes: it enables the closing marker for indenting, and removes the new line requirement after the closing marker. This is especially useful when using Heredoc in an already-nested context.

Heredoc and nowdoc syntaxes have very rigid requirements that have often caused them to be ignored by developers. Their usage in code can look ‘ugly’, and harm readability. The 7.3 update brings an improved look and boosted readability to these key syntaxes.

2. A Boost in Performance Speed

When PHP 7.0 was released, it claimed to be twice as fast as PHP 5.6. Now, PHP 7.3 is 31% faster than PHP 7.0 – meaning that it smashes the previous benchmark out of the water.

It’s also just shy of being 10% faster than PHP 7.2, meaning that this update brings dramatically-improved performance speed no matter what previous version you were using. This is important, since performance plays a huge role in creating a positive user experience. Just to give one example, when Mozilla shaved 2.2 seconds off its landing page’s loading time, Firefox downloads increased by 15.4%.

Slow-loading pages can mean loosing out on potential customers, as they’ll often move on to a faster service. Fortunately, the new boost to PHP should benefit sites that rely on this scripting language. Plus, a faster programming speed also means that developers are able to work more efficiently.

3. Allowance for a Trailing Comma in Function Calls

Trailing commas are commas added to a list of elements, parameters, or properties. They can come in handy, as they allow for cleaner code that is simpler to understand and edit.

PHP already permitted trailing commas in arrays. Now, the 7.2 update brings the addition of commas in grouped namespaces. PHP 7.3 enables developers to add trailing commas in function declarations. However, it’s important to note that this change will affect function calls only – function declaration syntax isn’t going to change.

While these are some of the most prominent changes PHP 7.3 brings, they’re just the tip of the iceberg. The update also includes Argon2 password hash enhancements, and a few new functions. You can check out the PHP website for a more extensive list of features.

Conclusion

As one of the most popular open-source scripting languages, PHP is known for its frequent updates and improvements in user experience. The latest release, PHP 7.3, is no different – bringing with it plenty of new and improved functionality.

In this post, we explored a few of the new features this PHP update includes. These are:

  • Further improvements to the existing heredoc and nowdoc syntaxes.
  • An increase in overall performance speed.
  • The ability to add a trailing comma in function calls.

Image credit: Pixabay.

The post What’s New in PHP 7.3? appeared first on The A2 Posting.

]]>
https://www.a2hosting.com/blog/content/uploads/2019/01/php-computer-screen.png
How to Update Your WordPress Website to PHP 7 https://www.a2hosting.com/blog/php-7/ Tue, 13 Jun 2017 16:01:14 +0000 https://www.a2hosting.com/blog/?p=2936 Hypertext Preprocessor, or PHP is a widely used server-side scripting language that is at the forefront of web development. In fact, around 80% of websites – whose programming languages we …

The post How to Update Your WordPress Website to PHP 7 appeared first on The A2 Posting.

]]>
Hypertext Preprocessor, or PHP is a widely used server-side scripting language that is at the forefront of web development. In fact, around 80% of websites – whose programming languages we know – use PHP. The problem is, most of them are still using deprecated versions even though PHP 7 has been around since 2015.

Imagine that most PCs were still running Windows XP and you’d have the right idea. Sure, it still works, but newer versions have far better performance and are more stable. The same goes for PHP. Its latest version offers a staggering improvement over past releases, and adopting it en masse could help propel the web forward.

In this article, we’ll tell you everything you need to know about PHP 7, including what its benefits are and how it compares to PHP 5. Then, we’ll teach you how to update your WordPress site to the latest version in three steps. Let’s get cracking!

An Introduction to PHP 7 (And Its Benefits)

PHP is a significant component of today’s web landscape. It helps power a large share of websites, applications, and even popular Content Management Systems (CMSs) like WordPress.

The PHP homepage.

The fact is, PHP 7 is a sharp improvement over past iterations. You don’t even need to be a developer to appreciate its impact or to benefit from what the language brings to the table. Let’s discuss why:

  • It has better performance. Thanks to its new engine, PHP 7 is almost twice as fast as its predecessor.
  • It gets more done with fewer resources. Increased speed means your site’s performance is less dependent on your server’s hardware, which can save you money.
  • It has new language features. If you’re a developer, you’ll appreciate that PHP 7 includes new functionality, such as return type declarations for functions.

If you’re a web hosting provider, then the benefits of PHP 7 should be self-evident. Not only will it enable you to provide a better experience for your users, but you’ll also save on server costs while doing so. The same goes if you’re an end user, so upgrading is a win-win situation.

Plus, it’s always a good idea to keep up with the latest software developments in your field. Similar to using an outdated Operating System (OS), running an old version of PHP leaves you open to security vulnerabilities.

WordPress offers an excellent example of why you should upgrade to the latest version of PHP. Since the CMS is primarily based on said language, it can really benefit from the added performance of PHP 7. If you’re ready to update your WordPress site, we’ll show you how in the next section.

How to Update Your WordPress Site to PHP 7 (In 3 Steps)

When it comes to updating to PHP 7, one of the major issues is many web hosts still don’t support it, or won’t let you update to it if you’re using a shared plan. So you have two options – either upgrade your plan to something more customizable, such as a Virtual Private Server (VPS) or a dedicated one, or switch hosts.

In most cases, the second option will save you money, so that’s what we’ll teach you how to do. We’ll tell you how to prepare for the switch and execute it, in three simple steps.

Step #1: Check Your WordPress Site for Compatibility Errors

Before updating to PHP 7,  the smart move is to check whether any of your WordPress site’s components are incompatible with it. There are a few ways to go about this. The first is a simple plugin option, but this may not give accurate results every time.

The approach we recommend involves setting up a local environment. This way, you make a copy of your site and test it’s compatibility with PHP 7 without affecting your live website. There are many ways to set up a local WordPress site, but we’re big fans of using MAMP (which is available on both Windows and macOS):

The MAMP homepage.

Once you’ve installed it, these are the steps you need to follow to test your site on a local environment:

  1. Create a full backup of your site using a plugin such as UpdrafPlus.
  2. Set up a local WordPress site using MAMP and PHP 7, which is set as the default option for any sites you create with the service.
  3. Install UpdraftPlus on your local website.
  4. Restore the backup of your site to your local environment using UpdraftPlus.
  5. Check your website for compatibility issues.

This is the most thorough way you can go about testing whether your site is ready for PHP 7. Plus, having a local testing environment ready can come in handy the next time you want to make a major update to your site.

It’s worth noting that if you’re an A2 Hosting user, you can use our PHP Switcher feature to test your site with PHP 7 in a matter of minutes. Keep in mind this will affect your live website, though, so you’ll probably want to test it during off hours just in case.

Step #2: Fix Any Errors on Your Site

If you didn’t find any issues with your site’s plugins and themes, then you can skip this step. Otherwise, you have two options available – the first is to update the offending elements in case they have new versions available. Then, test it again and see if they still display the same errors.

Now, if there aren’t any updates available, you’ll need to think about replacing the problem theme or plugins with alternatives. That way, you still get to enjoy similar functionality and the benefits of PHP 7.

One place to start looking for options is in the official WordPress.org repository:

The WordPress plugins repository.

Unless you’re using a highly specific plugin, chances are you’ll find a similar one there. As for themes, Themeforest offers some of the best premium options around, and a quick Google search can help you find great alternatives for specific niches.

Step #3: Move Your Site to a Web Host that Supports PHP 7

Now that your site is free of any incompatibilities with PHP 7, it’s time to make the leap and upgrade to it. In this case, that means moving to a web host that already implements the latest version of the language with its plans (which we do).

Our PHP 7 plans page.

Moving a WordPress website to a new host might sound like a tall order, but it doesn’t have to be. If you need help, most reputable web hosts offer free migrations for new customers. In our case, we can help you get your site moved quickly, especially if your former host used the cPanel platform.

On the other hand, you can always migrate your site manually if you don’t mind following a few steps. The process may take a little while, but the rewards should be evident once you get to test drive how WordPress feels running on PHP 7.

Conclusion

PHP 7 isn’t merely a step forward from PHP 5 – it’s a giant leap in terms of performance and usability. If your site is among the 80% or so that use PHP to power their applications, you might be shortchanging yourself by not upgrading.

If you’re a WordPress user, you’re in luck. All it takes is three steps to adopt PHP 7 if your current host doesn’t already support it:

  1. Check your WordPress site for compatibility errors.
  2. Fix any errors on your website.
  3. Move your site to a new web host that supports PHP 7.

Image credit: Pixabay.

The post How to Update Your WordPress Website to PHP 7 appeared first on The A2 Posting.

]]>
https://www.a2hosting.com/blog/content/uploads/2017/05/php-code.png