One place for hosting & domains

      How To Write Your First PHP Program


      The author selected Open Sourcing Mental Illness Ltd to receive a donation as part of the Write for DOnations program.

      Introduction

      The “Hello, World!” program is a classic and time-honored tradition in computer programming. Serving as a complete first program for beginners and a good program to test systems and programming environments, “Hello, World!” illustrates the basic syntax of programming languages.

      This tutorial will walk you through writing a “Hello, World!” program in PHP. You’ll also learn about opening and closing PHP code blocks within your code and using different types of comments in your code.

      Prerequisites

      You will need PHP installed as well as a local programming environment set up on your computer.

      To set this up, follow the How to Install PHP 7.4 and Set Up a Local Development Environment for your operating system.

      Writing the “Hello, World!” Program

      To write the “Hello, World!” program, start by opening a command-line text editor, such as nano, and create a new file:

      Once the text file opens up in the terminal window, type out the program:

      hello.php

      <?php
      echo "Hello, World!";
      ?>
      

      Let’s break down the different components of the code.

      All PHP code falls within a PHP Code Block, starting with <?php and ending with ?>.

      echo is a language construct. Its arguments are a list of expressions following the echo keyword, separated by commas and not delimited by parentheses. echo tells PHP to display or output whatever is included between echo and the ending semicolon ;.

      Between the echo and the ; is a sequence of characters — Hello, World! — that is enclosed in quotation marks. Any characters that are inside quotation marks are called a string.

      After writing the program, hold down the CTRL key and press the X key to exit nano. When prompted to save the file, press Y.

      Once you exit nano, you’ll return to your shell.

      With that, you have written your “Hello, World!” program.

      Running the “Hello, World!” Program

      With your “Hello, World!” program written, you’re ready to run the program. Use the php command along with the name of the program file as follows:

      Running the hello.php program that you just created will cause your terminal to produce the following output:

      Output

      Hello, World!

      Let’s go over what the program did in more detail.

      PHP executed the line echo "Hello, World!"; by calling the language construct echo. The string value of Hello, World! was passed to the construct.

      In this example, the string Hello, World! is also called an argument since it is a value that is passed to another part of the code, such as a construct or a function.

      The quotes that are on either side of Hello, World! were not output to the screen because they are used to tell PHP that this section of code contains a string. The quotation marks delineate where the string begins and ends.

      Since the program ran successfully, you can now confirm that PHP is properly installed and that the program is syntactically correct. Before going any further in the code itself, let’s take a closer look at the PHP Code Block.

      Working Outside the PHP Code Block

      Within a .php file, anything outside of the PHP tags is treated as HTML or plain text. The PHP language was originally written as a way to extend the functionality of HTML. With this in mind, you may include multiple PHP code blocks throughout a file. Anything outside the code block will render as HTML or plain text.

      Update your hello.php file:

      hello.php

      Hi Sammy
      <?php echo "Hello, World!"; ?>
      
      How are you doing?
      <?php echo "Swimmingly!";
      

      Save the file and rerun it:

      Output

      Hi Sammy Hello, World! How are you doing? Swimmingly!

      Diving into the code, you’ll notice that Hi Sammy and How are you doing? are both outside the PHP code blocks and therefore render as plain text when running the program.

      This file contains two PHP code blocks. The first code block includes both the starting and ending tags, while the second code block, being at the end of the file, leaves off the final closing tag.

      Including the closing block tag ?> is not required. When ending a file with a PHP code block, it is recommended to leave off the closing tag. Any character, even a blank space, which is rendered after the closing tag will be output to the screen as HTML or plain text. This can cause unexpected consequences with the function of your application because certain functionality, such as a redirect, will not process if anything has been output to the browser. When writing a file that contains only PHP code, never include the closing PHP tag.

      As code gets more complicated, like when splitting concepts over multiple code blocks, it can be beneficial to leave notes for ourselves and others. You can do this through the use of comments.

      A comment in code is a line that will not execute as a part of the program. Its only purpose is to be read by a human who is looking at the code. One thing that comes as a shock to many developers is how much time is spent reading code versus writing code. This means it’s essential to have code that is as easy to read as possible. You can accomplish this in a few ways:

      • Use coding standards. These are a collection of guidelines and best practices for organizing and formatting code clearly and consistently. In PHP, the most common coding standards are those developed by the PHP-FIG (Framework Interop Group).
      • Choose ease of reading over ease of writing. Use descriptive variables over short variables. It’s not about how many lines of code your write, but how long it will take someone to read those lines and understand what’s going on.
      • Comment for clarity. While it isn’t a hard and fast rule, if you’ve followed the previous two bullet points, your code should explain what is happening, while the comments explain why something is happening the way it is.

      When writing comments in PHP, there are two types of comments: single-line comments and multiline comments. Single line comments can start at any point on a line and end at either the end of the line or the end of the code block, whichever comes first.

      The most common way to start a single-line comment is with the double forward slash (//), although PHP also recognizes a hash sign (#) as a valid start to a single-line comment:

      hello.php

      Hi Sammy
      <?php echo "Hello"; //, World!"; ?>
      
      How are you doing?
      <?php echo "Swimmingly!";
      // other options: Floating along
      

      Save the file and run it again:

      Output

      Hi Sammy Hello How are you doing? Swimmingly!

      The first comment starts in the middle of a line. A closing quote and semicolon were added after "Hello" and the rest of the line was commented out. Commenting out one or more lines of code is often used in debugging to test how the code responds if certain elements are removed.

      You use a second comment to give a secondary option for an answer. The next step in your project may be to respond with one of several different options each time you execute the application. The comment is used as a reminder for other options that could be added.

      Multiline comments start with /* and end with */. The PHP interpreter will ignore any text or code within those characters. To provide more options, let’s change the last line to a multi-line comment:

      hello.php

      Hi Sammy
      <?php echo "Hello"; //, World!"; ?>
      
      How are you doing?
      <?php echo "Swimmingly!";
      /* When responding with one of a number of answers, here are some other options:
      * Floating along
      * Fin-tastic
      * Going with the flow
      * Treading water
      * Swamped
      */
      

      Using a multi-line comment gives more room to add detail or formatting to once again make the code, and the intention of the code, easier to understand. This multi-line comment includes line breaks and added * as a delineator for a list. The */ combination signifies the end of our comment block.

      Using DocBlocks for Documentation

      There is a special type of multi-line comment called a DocBlock. This is a unique way of documenting the functionality of a particular file, class, method, or other structural elements. Although a DocBlock starts and ends like any other multi-line comment /* */, they are designed to give specific detail for working with an element. Not only do these details provide an overview of the code for developers, but they may also be used by a code editor (or IDE) to provide suggestions and validation.

      A DocBlock consists of several parts. The first is a brief summary to introduce the element and a longer description if more context is needed.

      The final section that makes a DocBlock unique is for tags and annotations. These provide a way to succinctly and uniformly provide meta-information about the associated element. Tags can, for example, describe the type of information that is accepted or returned by a method or function. It may also provide details about the author or copyright of a file:

      hello.php

      <?php
      /**
       * DocBlock example
       *
       * @author Sammy <sammy@digitalocean.com>
       */
       ...
      

      While you should strive to write code that is clear and easy to follow, adding clarifying comments can add additional context that will increase the understanding of the code and the choices behind the code.

      Conclusion

      In this tutorial, you have written the “Hello, World!” program in PHP. You learned about opening and closing PHP code blocks within your code and using different comments to clarify and add context as your code gets more complicated. From here, you can continue learning by following the How To Work with Strings in PHP tutorial.



      Source link

      How To Fix the WordPress Memory Exhausted Error by Increasing Your Site’s PHP Memory Limit


      As you may know, WordPress is built using PHP. This programming language is incredibly flexible, but it also has a few drawbacks. For example, if you don’t allocate enough memory for your WordPress installation, you might start running into the occasional “PHP Memory Exhausted” error.

      In a nutshell, this error means your server isn’t allocating enough resources for WordPress to execute the PHP scripts it needs to function properly. This issue can negatively affect your site’s functionality, but there are several ways you can fix and even prevent it.

      In this article, we’ll show you how to fix the memory exhausted problem by increasing your PHP memory limit. However, first, let’s talk about how to recognize this error and what it means!

      Why You’re Seeing a WordPress Memory Limit Error on Your Site

      As we mentioned earlier, the PHP memory limit error means you’re not allocating enough resources for your WordPress installation to function correctly. The problem usually presents itself with a message such as:

      The memory exhausted PHP fatal error.

      Don’t be scared by the word “fatal,” though. Your website isn’t broken, but you will need to make some changes to your WordPress installation if you want it to work properly. Specifically, you’ll want to increase your PHP memory limit.

      By “PHP memory limit,” we mean the amount of server memory that’s allocated to run PHP scripts. By default, that number should be around 64 MB or higher. In most cases, 64 MB is more than enough, however.

      Most hosting servers provide you with far more memory than that, so increasing the PHP allowed memory size shouldn’t negatively impact your website’s performance whatsoever. In fact, unless you’re using a cheap web host or you set up WordPress manually, your PHP memory limit shouldn’t be an issue at all.

      You can easily check to see what your PHP memory limit is by accessing your WordPress dashboard and navigating to Tools > Site Health > Info. Next, you can click on the Server tab and look for the PHP memory limit entry.

      A website with a high PHP memory size.

      Within the Server tab, you can also check other information such as your PHP version and the PHP time limit. The latter variable, which is in seconds, defines how long PHP scripts have to execute before they time out.

      For now, let’s focus on the PHP memory limit. As you can see, the above example has quite a high limit, which means that the website is unlikely to run into a WordPress Memory Exhausted error.

      If your site has a low memory limit (<64 MB), it’s in your best interests to increase it. There are a couple of ways you can do so.

      Take Your WordPress Website to the Next Level

      Whether you need help navigating your web hosting control panel, fixing an error, or finding the right plugin, we can help! Subscribe to our monthly digest so you never miss an article.

      How to Resolve the WordPress Memory Limit Error (2 Methods)

      As far as WordPress errors go, this one has a clear-cut cause and solution. You’re not allocating enough memory for your PHP installation, so you need to increase that number. In this section, we’ll go over two methods you can use: one manual technique and one that requires your wallet.

      1. Increase the PHP Memory Allocated to Your Website Manually

      WordPress enables you to declare your allowed memory size manually by modifying one of two files: .htaccess and wp-config.php. However, changing your WordPress installation’s .htaccess file can lead to site-wide errors since that file governs how it interacts with your server.

      Increasing your PHP memory limit through wp-config.php is, in most cases, the safest option, and it’s remarkably easy to do. All you need is a Secure File Transfer Protocol (SFTP) client such as FileZilla that you can use to connect to your website.

      Once you access your website via SFTP, open the WordPress root folder and look for the wp-config.php file within it.

      A WordPress wp-config.php file.

      Open that file using a text editor, and you should see something like this:

      Editing a wp-config.php file.

      To increase your PHP memory limit, you can simply add a single line of code anywhere after the <?php tag and before the part of the file that reads “/* That’s all, stop editing! Happy blogging. */”.

      This is the line of code to add:

      define( 'WP_MEMORY_LIMIT', 'XXXM' );

      You’ll need to replace the “XXX” variable within that line with the amount of memory you want to allocate to PHP. As we mentioned before, the absolute minimum you should settle for is 64 MB.

      However, you can also double the number to play it safe or increase it even further. For example, if you set a PHP memory limit of 256 MB, it would look like this:

      define( 'WP_MEMORY_LIMIT', ‘256M’);

      Once you’re set on a number, save the changes to wp-config.php and close the editor. Now return to your WordPress dashboard and navigate to Tools > Site Health > Info > Server to see if the changes went through.

      In some cases, declaring your PHP memory limit manually won’t work because you don’t have the necessary permissions to change that value. If you can’t adjust your WordPress memory size manually, that leaves you with one other option.

      2. Upgrade Your Website’s Hosting Plan

      Typically, if you use a decent WordPress hosting provider, you won’t need to worry about increasing your PHP memory limit. One caveat is that if you’re using shared hosting, you’ll likely face limited resources. So if you’re encountering this error, it might be time to upgrade to a better hosting plan.

      Upgrading your hosting package will usually result in an increase in available PHP memory. That means you’re much less likely to run into a WordPress memory limit error. The only limiting factor is your budget.

      If you can’t upgrade hosting plans right now, it might be worth contacting your provider’s support team and seeing if they can increase your PHP memory limit on their end. If they can’t, it might be time to switch to a better WordPress host that offers high PHP memory limits on affordable plans.

      Skip the Stress

      Avoid troubleshooting when you sign up for DreamPress. Our friendly WordPress experts are available 24/7 to help solve website problems — big or small.

      Want More WordPress Error Tips?

      Once you increase PHP memory on your WordPress website, we can help tackle other issues. We’ve put together several tutorials to help you troubleshoot every error message:

      Want more information on WordPress site management? Check out our WordPress Tutorials, a collection of guides designed to help you navigate the WordPress dashboard like an expert.

      Increasing PHP Memory Limit

      Running into a PHP fatal error can be worrying, but it’s not necessarily a cause for concern. Learning how to increase your PHP memory limit is relatively simple if you don’t mind using an SFTP client and adding a single line of code to one of WordPress’ core files.

      The alternative is to upgrade your hosting plan or opt for a better provider. Most WordPress-friendly hosting options offer high limits by default, so you’ll never run into a PHP memory exhausted error ever again.

      If you’re ready to use a web host optimized for WordPress websites, check out our DreamPress hosting packages! We offer optimized WordPress setups, so you spend less time troubleshooting errors and more time working on your website.



      Source link

      How To Install PHP 7.4 and Set Up a Local Development Environment on Ubuntu 18.04


      The author selected Open Sourcing Mental Illness Ltd to receive a donation as part of the Write for DOnations program.

      Introduction

      PHP is a popular server scripting language known for creating dynamic and interactive web pages. Getting up and running with your language of choice is the first step in learning to program.

      This tutorial will guide you through installing PHP 7.4 on Ubuntu and setting up a local programming environment via the command line. You will also install a dependency manager, Composer, and test your installation by running a script.

      Prerequisites

      To complete this tutorial, you will need a local or virtual machine with Ubuntu 18.04 installed and have administrative access and an internet connection to that machine. You can download this operating system via the Ubuntu releases page.

      Step 1 — Setting Up PHP 7.4

      You’ll be completing your installation and setup on the command line, which is a non-graphical way to interact with your computer. That is, instead of clicking on buttons, you’ll be typing in text and receiving feedback from your computer through text as well.

      The command line, also known as a shell or terminal, can help you modify and automate many of the tasks you do on a computer every day and is an essential tool for software developers. There are many terminal commands to learn that can enable you to do more powerful things. The article An Introduction to the Linux Terminal can get you better oriented with the terminal.

      On Ubuntu, you can find the Terminal application by clicking on the Ubuntu icon in the upper-left-hand corner of your screen and typing terminal into the search bar. Click on the Terminal application icon to open it. Alternatively, you can hit the CTRL, ALT, and T keys on your keyboard at the same time to open the Terminal application automatically.

      Ubuntu terminal

      You will want to avoid relying on the default version of PHP because that default version could change depending on where you are running your code. You may also wish to install a different version to match an application you are using or to upgrade to a newer version, such as PHP 8.

      Run the following command to update apt-get itself, which ensures that you have access to the latest versions of anything you want to install:

      Next, install software-properties-common, which adds management for additional software sources:

      • sudo apt -y install software-properties-common

      The -y flag will automatically agree to the installation. Without that, you would receive a prompt in your terminal window for each installation.

      Next, install the repository ppa:ondrej/php, which will give you all your versions of PHP:

      • sudo add-apt-repository ppa:ondrej/php

      Finally, you update apt-get again so your package manager can see the newly listed packages:

      Now you’re ready to install PHP 7.4 using the following command:

      • sudo apt -y install php7.4

      Check the version installed:

      You will receive something similar to the following:

      Output

      PHP 7.4.0beta4 (cli) (built: Aug 28 2019 11:41:49) ( NTS ) Copyright (c) The PHP Group Zend Engine v3.4.0-dev, Copyright (c) Zend Technologies with Zend OPcache v7.4.0beta4, Copyright (c), by Zend Technologies

      Besides PHP itself, you will likely want to install some additional PHP modules. You can use this command to install additional modules, replacing PACKAGE_NAME with the package you wish to install:

      • sudo apt-get install php7.4-PACKAGE_NAME

      You can also install more than one package at a time. Here are a few suggestions of the most common modules you will most likely want to install:

      • sudo apt-get install -y php7.4-cli php7.4-json php7.4-common php7.4-mysql php7.4-zip php7.4-gd php7.4-mbstring php7.4-curl php7.4-xml php7.4-bcmath

      This command will install the following modules:

      • php7.4-cli - command interpreter, useful for testing PHP scripts from a shell or performing general shell scripting tasks
      • php7.4-json - for working with JSON data
      • php7.4-common - documentation, examples, and common modules for PHP
      • php7.4-mysql - for working with MySQL databases
      • php7.4-zip - for working with compressed files
      • php7.4-gd - for working with images
      • php7.4-mbstring - used to manage non-ASCII strings
      • php7.4-curl - lets you make HTTP requests in PHP
      • php7.4-xml - for working with XML data
      • php7.4-bcmath - used when working with precision floats

      PHP configurations related to Apache are stored in /etc/php/7.4/apache2/php.ini. You can list all loaded PHP modules with the following command:

      You have installed PHP and verified the version you have running. You also installed any required PHP modules and were able to list the modules that you have loaded.

      You could start using PHP right now, but you will likely want to use various libraries to build PHP applications quickly. Before you test your PHP environment, first set up a dependency manager for your projects.

      Step 2 — Setting Up Composer for Dependency Management (Optional)

      Libraries are a collection of code that can help you solve common problems without needing to write everything yourself. Since there are many libraries available, using a dependency manager will help you manage multiple libraries as you become more experienced in writing PHP.

      Composer is a tool for dependency management in PHP. It allows you to declare the libraries your project depends on and will manage installing and updating these packages.

      Although similar, Composer is not a package manager in the same sense as yum or apt. It deals with “packages” or libraries, but it manages them on a per-project basis, installing them in a directory (e.g. vendor) inside your project. By default, it does not install anything globally. Thus, it is a dependency manager. It does, however, support a global project for convenience via the global command.

      This idea is not new, and Composer is strongly inspired by Node’s npm and Ruby’s bundler.

      Suppose:

      • You have a project that depends on several libraries.
      • Some of those libraries depend on other libraries.

      Composer:

      • Enables you to declare the libraries you depend on.
      • Finds out which versions of which packages can and need to be installed and installs them by downloading them into your project.
      • Enables you to update all your dependencies in one command.
      • Enables you to see the Basic Usage chapter for more details on declaring dependencies.

      There are, in short, two ways to install Composer: locally as part of your project or globally as a system-wide executable. Either way, you will start with the local install.

      Locally

      To quickly install Composer in the current directory, run this script in your terminal:

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

      This installer script will check some php.ini settings, warn you if they are set incorrectly, and then download the latest composer.phar in the current directory. The four lines will, in order:

      • Download the installer to the current directory
      • Verify the installer SHA-384, which you can also cross-check here
      • Run the installer
      • Remove the installer

      The installer will check a few PHP settings and then download composer.phar to your working directory. This file is the Composer binary. It is a PHAR (PHP archive), which is an archive format for PHP that can be run on the command line, amongst other things.

      In order to run Composer, you use php composer.phar. As an example, run this command to see the version of Composer you have installed:

      • php composer.phar --version

      To use Composer locally, you will want your composer.phar file to be in your project’s root directory. You can start in your project directory before installing Composer. You can also move the file after installation. You can also install Composer to a specific directory by using the --install-dir option and additionally (re)name it using the --filename option.

      Since Composer is something used across projects, it’s recommended that you continue to the next portion and set Composer to run globally.

      Globally

      You can place the Composer PHAR anywhere you wish. If you put it in a directory that is part of your $PATH, you can access it globally. You can even make it executable on Ubuntu (and other Unix systems) and invoke it without directly using the PHP interpreter.

      After installing locally, run this command to move composer.phar to a directory that is in your path:

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

      If you’d like to install it only for your user and avoid requiring root permissions, you can use ~/.local/bin instead, which is available by default on some Linux distributions:

      • mv composer.phar ~/.local/bin/composer

      Now to run Composer, use composer instead of php composer.phar. To check for your Composer version, run:

      As a final step, you may optionally initialize your project with composer init. This will create the composer.json file that will manage your project dependencies. Initializing the project will also let you define project details such as Author and License, and use Composer’s autoload functionality. You can define dependencies now or add them later.

      Run this command to initialize a project:

      Running this command will start the setup wizard. Details that you enter in the wizard can be updated later, so feel free to leave the defaults and just press ENTER. If you aren’t ready to install any dependencies, you can choose no. Enter in your details at each prompt:

      Output

      This command will guide you through creating your composer.json config. Package name (sammy/php_install): sammy/project1 Description []: Author [Sammy <sammy@digitalocean.com>, n to skip]: Minimum Stability []: Package Type (e.g. library, project, metapackage, composer-plugin) []: project License []: Define your dependencies. Would you like to define your dependencies (require) interactively [yes]? no Would you like to define your dev dependencies (require-dev) interactively [yes]? no { "name": "sammy/project1", "type": "project", "authors": [ { "name": "Sammy", "email": "sammy@digitalocean.com" } ], "require": {} } Do you confirm generation [yes]? yes

      Before you confirm the generation, you will see a sample of the composer.json file that the wizard will create. If it all looks good, you can confirm the default of yes. If you need to start over, choose no.

      The first time you define any dependency, Composer will create a vendor folder. All dependencies install into this vendor folder. Composer also creates a composer.lock file. This file specifies the exact version of each dependency and subdependency used in your project. This assures that any machine on which your program is run, will be using the exact same version of each packages.

      Note: The vendor folder should never be committed to your version control system (VCS). The vendor folder only contains packages you have installed from other vendors. Those individual vendors will maintain their own code in their own version control systems. You should only be tracking the code you write. Instead of committing the vendor folder, you only need to commit your composer.json and composer.lock files. You can learn more about ignoring specific files in How To Use Git: A Reference Guide.

      Now that you have PHP installed and a way to manage your project dependencies using Composer, you’re ready to test your environment.

      Step 3 — Testing the PHP Environment

      To test that your system is configured correctly for PHP, you can create and run a basic PHP script. Call this script hello.php:

      This will open a blank file. Put the following text, which is valid PHP code, inside the file:

      hello.php

      <?php
      echo 'Hello World!';
      ?>
      

      Once you’ve added the text, save and close the file. You can do this by holding down the CTRL key and pressing the x key. Then choose y and press ENTER.

      Now you can test to make sure that PHP processes your script correctly. Type php to tell PHP to process the file, followed by the name of the file:

      If the PHP is processed properly, you will see only the characters within the quotes:

      Output

      Hello World!

      PHP has successfully processed the script, meaning that your PHP environment is successfully installed and you’re ready to continue your programming journey.

      Conclusion

      At this point, you have a PHP 7.4 programming environment set up on your local Ubuntu machine and can begin a coding project.

      Before you start coding, you may want to set up an Integrated Development Environment (IDE). While there are many IDEs to choose from, VS Code is a popular choice as it offers many powerful features such as a graphical interface, syntax highlighting, and debugging.

      With your local machine ready for software development, you can continue to learn more about coding in PHP by following How To Work With Strings in PHP.



      Source link