One place for hosting & domains

      PHP

      How To Set Up Visual Studio Code (VS Code) for PHP Development


      Introduction

      Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems.

      With a large collection of extensions for many programming languages, VS Code can be customized to serve a wide variety of development needs. In this guide, you’ll learn how to set up Visual Studio Code for working on PHP projects.

      The gif shows the VS Code interface for PHP development

      Prerequisites

      To follow this guide, you’ll need to download and install the appropriate version of Visual Studio Code for your operating system.

      The instructions in this guide were validated on an Ubuntu 20.04 desktop computer, but they should work seamlessly in all operating systems that are supported by VS Code. Please note, though, that keyboard shortcut keys may need to be slightly modified for compatibility with MacOS systems.

      Right after installation, VS Code already recognizes PHP code and helps with syntax highlighting, basic debugging, and code indentation. These features are suitable for quick edits or when working with individual PHP scripts. Working in larger projects, though, can become difficult without more context around the code and how each file interacts and integrates within the larger project.

      There are a number of VS Code extensions that can help speed up your productivity when working on PHP projects. In this guide, we’ll install and set up PHP Intelephense, a popular PHP extension for VS Code that provides several advanced features such as improved code completion, better navigation between components, rich information tooltips on mouse hover, code auto formatting, and real time error reporting based on static code analysis.

      Open the extensions tab by clicking on the last icon on the left menu bar, or by pressing CTRL + SHIFT + X. This will bring up a sidebar menu with a search box and a list of popular or recommended extensions. Type “php” or “intelephense” to locate the PHP Intelephense extension. Click on the Install button to install and enable the extension.

      The gif shows how to access the extensions menu on the left sidebar

      Once installation is complete, Intelephense’s official documentation recommends that you disable the built-in PHP Language Features extension that comes with VS Code.

      To disable this extension, type @builtin php in the Extensions search box to locate the built-in PHP extensions. Then click on the settings icon for the PHP Language Features extension, and click the Disable option in the drop-down menu.

      The gif shows how to disable the builtin PHP Language Features extension

      If you have any files open in VS Code, you’ll need to reload the editor to apply the changes.

      You can install other extensions by following the same process described for the PHP Intelephense extension, but be aware that some extensions will require additional software to be installed on your system. Check the extension documentation to make sure you have requirements set appropriately.

      Step 2 — Importing or Creating a New PHP Project

      To import an existing PHP project into VS Code, click on the first icon on the left menu bar or type CTRL + SHIFT + E to access the file explorer. Click the Open Folder button and select your project’s directory. In case you are creating a new project, you can create a new folder and select that as your project directory.

      The gif shows how to import a PHP project to VS Code

      The explorer window will now show the project’s directory tree, giving you quick access to files and directories on your project.

      Step 3 — Customizing Theme and Editor Font (Optional)

      Although not necessary, it is often a good idea to customize the appearance of your editor to make it more comfortable to use in the longer term. As a developer you may spend several hours every day looking at an IDE such as VS Code, and for that reason it’s important to make sure the editor font has an appropriate size, and the contrast is enough for good readability without tiring your eyes too quickly.

      You may want to experiment with different themes and fonts in order to find a custom setup that works well for you.

      Changing VS Code Theme

      VS Code comes with a few different themes that allow you to change the colors used in the editor interface and in the code highlighting. Both dark and light styles are included by default.

      Go to File -> Preferences -> Color Theme or type CTRL + K + T to select a different theme for VS Code.

      The gif shows how to change VS Code theme

      You can also install theme extensions to further customize VS Code’s appearance. If you search for theme within the extensions tab (CTRL + SHIFT + X), you’ll find several theme extensions in different styles and colors, including color schemes ported from other popular editors and platforms.

      Adjusting the Font

      Although the default VS Code font settings will be good enough for many users, you may want to adjust the size and the type of the editor font for increased readability.

      If you would like to modify the font size or change to another type, you can go to File -> Preferences -> Settings, then choose Text Editor on the left menu. Then, click on Font in the submenu that opens up. That section contains font family and size settings which you can tweak as preferred.

      The gif shows how to change VS Code editor font size

      The changes are immediately saved and applied to all current open files.

      Conclusion

      Visual Studio Code is a lightweight yet powerful code editor that can be customized to suit the needs of most developers. In this guide, you learned how to install and configure the PHP Intelephense extension for extra support while working on PHP projects, how to import and create new projects within VS Code, and how to customize the editor appearance for a more comfortable coding experience.

      For more tutorials on Visual Studio Code, check our VS Code tag page. If you’d like to learn more about PHP development, you can refer to our How To Code in PHP series for an introduction to the language, and our PHP tag page for more PHP tutorials.



      Source link

      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