A Quick Guide to PHP in 2019

Introduction

What Is PHP?

PHP (Hypertext Preprocessor) is a versatile scripting language that gives users the ability to create a plethora of applications, especially server-side web development. You can use PHP for the following:

  • Create dynamic websites, web applications as well as your own API service
  • Interact with third party APIs
  • Process data (XML, HTML DOM and more)
  • Manipulate databases (PHP supports MySQL/MariaDB, SQLite, MongoDB, and more!)

Having said that, a large advantage to PHP is that it's a loosely typed language. You won't have to worry about declaring specific types. Rather than typing (int) $variable = 0;, for example, you can simply use $variable = 0; and PHP will automatically detect the variable type.

Other Advantages

In addition to being open source, PHP is also:

  • Easy to install
  • Multi-platform (runs on any operating system on which it is installed)
  • Fast (compilation of code is done real-time, as opposed to pre-compiled languages such as C#)
  • Open-source

What Will This Guide Cover?

This guide will cover:

  • PHP conventions
  • Creating a "Hello, world!" page and a simple calculator
  • How to interact and query a 3rd party API to get the current weather

Extra Documentation

If you ever get lost and need to find a method/function, visit PHP's documentation page.

Creating Your First Programs

Conventions

Before we create our first application, a few important things to note are as follows:

  1. PHP code always starts with <?php and typically terminates with ?>.
  2. PHP sends errors to a file called error_log. For example, if you try to call a nonexistent function, you will see PHP Fatal error: followed by Uncaught Error: Call to undefined function function_that_does_not_exist().
  3. PHP, like most languages, is case-sensitive. In other words, $var != $Var.
  4. While PHP variables don't specifically require types, you may need to cast (or change the type). This can be done by casting the type before a variable. Example: (int) $variable = ....

"Hello, world!"

This is the most basic part of the tutorial. The "Hello, world!" portion aims to teach you how to create a proper file in order to have it parsed properly. Before we start, though, please make sure that you have a working web-server with PHP running. This tutorial assumes you are using Apache configured with php-cli. Vultr offers several PHP stacks (LAMP, LEMP) as one-click applications. When you are ready, proceed to the following steps.

Create a file called "test.php" in your web-server's root directory:

nano test.php

Populate it with the following code:

<?php 
    $testString = "Hello, world!";
    print("Hello, world!<br/>"); // <br/> = HTML line break
    echo $testString;
?>

Save and exit.

When you visit test.php in your browser, you will see:

Hello, world!  
Hello, world!

Note: Architecturally, print & echo are different. Functionality-wise, they are about the same.

A Simple Calculator

This program will take two inputs and add them together. This section aims to teach you about how PHP handles data types.

Create a new file called calc.php:

nano calc.php

Populate it with the following code:

<!DOCTYPE html>
<html>
    <head>
        <title>Calculator</title>
    </head>
    <body>
        <form method="POST" action="calc.php">
            <input type="number" name="firstNumber" placeholder="First #"/>
            <p>+</p>
            <input type="number" name="secondNumber" placeholder="Second #"/>
            <p>=</p>
            <input type="submit" value="Submit"/>
            <p>
                <?php
                    // The line below checks if there is a value present in both boxes.
                    if (isset($_POST['firstNumber']) && isset($_POST['secondNumber'])) { 
                        // The line below returns the sum of the two values
                        echo $_POST['firstNumber'] + $_POST['secondNumber'];
                    }
                ?>
            </p>
        </form>
    </body>
</html>

Save and exit.

When you visit calc.php, you will see a form that looks like the following:

A Quick Guide to PHP in 2019

Enter any number you'd like; the answer should be the sum of the first and second numbers.

Note: This is a very basic code block without any error handling. If both numbers are not filled out, for example, the blank input will be considered 0, but a "non-numeric value" warning will be thrown.

A Simple Weather Checker

Now that we have most of the basics (simple mathematics & variables) done, we can create an application that pulls the weather for any city.

NOTE: We'll be using Dark Sky's weather API to get our data. Please obtain a free API key before proceeding to the first step.

Retrieve your API key once you've confirmed your email by clicking on "Console." You will see the following:

A Quick Guide to PHP in 2019

Proceed to the next step once you've copied the key.

Create a new file called temperature.php:

nano temperature.php

Populate it with the following code:

<?php
    // Retreive weather data for a certain set of coordinates (43.766040, -79.366232 = Toronto, Canada); change "YOUR_API_KEY" to your own API key
    $json = file_get_contents("https://api.darksky.net/forecast/YOUR_API_KEY/43.766040,-79.366232?exclude=daily,hourly,minutely,flags,alerts");

    // Tell PHP to parse the data and convert the JSON into an indexed array
    $data = json_decode($json, true);

    // Get our temperature from the array
    $temperatureInF = $data["currently"]["temperature"];

    // Convert it into Celsius using the formula: (Fahrenheit - 32) * 5 / 9
    $rawTemperatureInC = ($temperatureInF - 32) * (5 / 9);
    $temperatureInC = round($rawTemperatureInC, 2);

    // Return temperature in both Celsius and Fahrenheit
    echo "<h1>";
    echo "It is currently: " . $temperatureInF . "F or " . $temperatureInC . "C.";
    echo "</h1>"
?>

Once you save the file and visit the page, you will see something along the lines of the following:

It is currently: 57.78F or 14.32C.

This value is dynamic and updates every minute. Assuming everything worked out properly, you will have created a live weather page for your area. We've successfully combined basic PHP arithmetic along with storing values in our variables, as well as using a few basic functions.

Conclusion

Congratulations -- you've completed some basic programs! With these basics down, and some dedication, you should be able to create anything. If you're ever stuck or need to find a specific function, please refer to PHP's documentation. It will prove invaluable when you continue to discover new functions and techniques.

While this quick-start guide doesn't cover anything too in-depth, it should give you a general idea of how the language works. Practice makes perfect though -- you'll become more comfortable as you write more and more code in PHP.



Leave a Comment

Instalar phpBB con Apache en Ubuntu 16.04

Instalar phpBB con Apache en Ubuntu 16.04

PhpBB es un programa de tablón de anuncios de código abierto. Este artículo le mostrará cómo instalar phpBB en la parte superior de un servidor web Apache en Ubuntu 16.04. Fue escrito

Cómo instalar Vanilla Forum en CentOS 7

Cómo instalar Vanilla Forum en CentOS 7

¿Usando un sistema diferente? Vanilla forum es una aplicación de foro de código abierto escrita en PHP. Es totalmente personalizable, fácil de usar y admite dispositivos externos.

Cómo configurar ionCube Loader en CentOS 7

Cómo configurar ionCube Loader en CentOS 7

ionCube Loader es una extensión PHP que permite que un servidor web ejecute archivos PHP que han sido codificados usando ionCube Encoder y es necesario para ejecutar

Cómo instalar Zikula en Ubuntu 16.04

Cómo instalar Zikula en Ubuntu 16.04

¿Usando un sistema diferente? Introducción Zikula es un marco de aplicación web de código abierto escrito en PHP. Puedes diseñar un sitio web interactivo y editable

Use PHP5-FPM con Apache 2 en Ubuntu 14.04

Use PHP5-FPM con Apache 2 en Ubuntu 14.04

Introducción Apache es un popular software de servidor web que es utilizado por la mayoría de los proveedores de alojamiento web. PHP5-FPM es una implementación FastCGI para PHP. Es útil para

Cómo instalar Snipe-IT en CentOS 7

Cómo instalar Snipe-IT en CentOS 7

¿Usando un sistema diferente? Snipe-IT es una aplicación web gratuita y de código abierto para la gestión de activos de TI. Está escrito en el marco y uso de Laravel 5.2

Cómo instalar X-Cart 5 en Ubuntu 18.04 LTS

Cómo instalar X-Cart 5 en Ubuntu 18.04 LTS

¿Usando un sistema diferente? X-Cart es una plataforma de comercio electrónico de código abierto extremadamente flexible con toneladas de características e integraciones. El código fuente de X-Cart es hoste

How to Install Cachet on Debian 10

How to Install Cachet on Debian 10

Using a Different System? Cachet is an open-source status page system written in PHP. Cachet source code is hosted on Github. In this guide, we will go ove

Cómo instalar WordPress en una configuración LEMP

Cómo instalar WordPress en una configuración LEMP

Introducción En este tutorial, aprenderá cómo instalar WordPress en una instancia recién creada. Demostraré la instalación en un Ubuntu 14.0

Cómo instalar Apache 2.4, MariaDB 10.3 y PHP 7.2 en Ubuntu 18.04

Cómo instalar Apache 2.4, MariaDB 10.3 y PHP 7.2 en Ubuntu 18.04

En este artículo, aprenderá cómo configurar una pila LAMP actualizada instalando las últimas versiones estables de Apache 2.4 y MariaDB 10.3 en Ubuntu 18.04.

Cómo instalar Apache, MySQL y PHP en Ubuntu

Cómo instalar Apache, MySQL y PHP en Ubuntu

LAMP incluye Apache, MySQL, PHP y Ubuntu. Esta guía fue escrita para Ubuntu 14.04. Paso uno: Instalar Apache Apache es un software gratuito de código abierto para nosotros

Instale Nginx + PHP FPM + Caching + MySQL en Ubuntu 12.04

Instale Nginx + PHP FPM + Caching + MySQL en Ubuntu 12.04

Probablemente mucha gente vaya a usar sus VPS Vultr como servidores web, una buena opción sería Nginx como servidor web. En este tema voy a describir o

Configurar una aplicación Laravel 5 en Ubuntu 14

Configurar una aplicación Laravel 5 en Ubuntu 14

Introducción Laravel es un marco PHP maduro que puede usar para eliminar ideas muy rápidamente. Tiene una excelente documentación y es uno de los PH más populares.

Cómo instalar Apache, MySQL y PHP en CentOS 6

Cómo instalar Apache, MySQL y PHP en CentOS 6

Introducción LAMP es un acrónimo que significa Linux, Apache, MySQL y PHP. Esta pila de software es la solución de código abierto más popular para la configuración o

Cómo instalar PyroCMS en Ubuntu 16.04

Cómo instalar PyroCMS en Ubuntu 16.04

¿Usando un sistema diferente? PyroCMS es un CMS de código abierto escrito en PHP. El código fuente de PyroCMS está alojado en GitHub. En esta guía caminamos bien por el entir

Cómo instalar Vanilla Forum en Ubuntu 16.04

Cómo instalar Vanilla Forum en Ubuntu 16.04

¿Usando un sistema diferente? Vanilla forum es una aplicación de foro de código abierto escrita en PHP. Es totalmente personalizable, fácil de usar y admite dispositivos externos.

How to Install PyroCMS on FreeBSD 11

How to Install PyroCMS on FreeBSD 11

Using a Different System? PyroCMS is an open source CMS written in PHP. PyroCMS source code is hosted on GitHub. In this guide, well walk through the entir

Actualice a PHP 7.1 en la pila LEMP de un clic de Vultr

Actualice a PHP 7.1 en la pila LEMP de un clic de Vultr

Esta guía explica cómo actualizar de PHP 5.6 a la versión 7.1 en la pila LEMP de un clic de Vultr. Este tutorial solo es aplicable si su aplicación i

Cómo instalar Apache 2.4.x, MariaDB 10.xy PHP 7.x en Ubuntu 16.04

Cómo instalar Apache 2.4.x, MariaDB 10.xy PHP 7.x en Ubuntu 16.04

Al implementar un sitio web o una aplicación web, la solución de servicio web más común para eso es configurar una pila LAMP que consiste en Linux, Apache, MySQL, un

Instalar ImageMagick en CentOS 6

Instalar ImageMagick en CentOS 6

ImageMagick® es un paquete de software para crear, editar, componer o convertir imágenes de mapa de bits. Puede leer y escribir imágenes en una variedad de formatos (más de 100) incluyendo

ZPanel y Sentora en CentOS 6 x64

ZPanel y Sentora en CentOS 6 x64

ZPanel, un panel de control de alojamiento web popular, se bifurcó en 2014 a un nuevo proyecto llamado Sentora. Aprende a instalar Sentora en tu servidor con este tutorial.

Cómo instalar Vtiger CRM Open Source Edition en CentOS 7

Cómo instalar Vtiger CRM Open Source Edition en CentOS 7

Aprende cómo instalar Vtiger CRM, una aplicación de gestión de relaciones con el cliente, en CentOS 7 para aumentar tus ventas y mejorar el servicio al cliente.

Cómo instalar el servidor Counter-Strike 1.6 en Linux

Cómo instalar el servidor Counter-Strike 1.6 en Linux

Esta guía completa le mostrará cómo configurar un servidor Counter-Strike 1.6 en Linux, optimizando el rendimiento y la seguridad para el mejor juego. Aprende los pasos más recientes aquí.

¿Puede la IA luchar con un número cada vez mayor de ataques de ransomware?

¿Puede la IA luchar con un número cada vez mayor de ataques de ransomware?

Los ataques de ransomware van en aumento, pero ¿puede la IA ayudar a lidiar con el último virus informático? ¿Es la IA la respuesta? Lea aquí, sepa que la IA es una bendición o una perdición

ReactOS: ¿Es este el futuro de Windows?

ReactOS: ¿Es este el futuro de Windows?

ReactOS, un sistema operativo de código abierto y gratuito, está aquí con la última versión. ¿Puede satisfacer las necesidades de los usuarios de Windows de hoy en día y acabar con Microsoft? Averigüemos más sobre este estilo antiguo, pero una experiencia de sistema operativo más nueva.

Manténgase conectado a través de la aplicación de escritorio WhatsApp 24 * 7

Manténgase conectado a través de la aplicación de escritorio WhatsApp 24 * 7

Whatsapp finalmente lanzó la aplicación de escritorio para usuarios de Mac y Windows. Ahora puede acceder a Whatsapp desde Windows o Mac fácilmente. Disponible para Windows 8+ y Mac OS 10.9+

¿Cómo puede la IA llevar la automatización de procesos al siguiente nivel?

¿Cómo puede la IA llevar la automatización de procesos al siguiente nivel?

Lea esto para saber cómo la Inteligencia Artificial se está volviendo popular entre las empresas de pequeña escala y cómo está aumentando las probabilidades de hacerlas crecer y dar ventaja a sus competidores.

La actualización complementaria de macOS Catalina 10.15.4 está causando más problemas que resolver

La actualización complementaria de macOS Catalina 10.15.4 está causando más problemas que resolver

Recientemente, Apple lanzó macOS Catalina 10.15.4, una actualización complementaria para solucionar problemas, pero parece que la actualización está causando más problemas que conducen al bloqueo de las máquinas Mac. Lee este artículo para obtener más información

13 Herramientas comerciales de extracción de datos de Big Data

13 Herramientas comerciales de extracción de datos de Big Data

13 Herramientas comerciales de extracción de datos de Big Data

¿Qué es un sistema de archivos de diario y cómo funciona?

¿Qué es un sistema de archivos de diario y cómo funciona?

Nuestra computadora almacena todos los datos de una manera organizada conocida como sistema de archivos de diario. Es un método eficiente que permite a la computadora buscar y mostrar archivos tan pronto como presiona buscar.