DEV Community

Cover image for PHP on Ubuntu: Installation, Setup, and First Steps
Javier Jimenez
Javier Jimenez

Posted on • Edited on

PHP on Ubuntu: Installation, Setup, and First Steps

PHP - Logo

Prerequisites โ€“ installation of Homebrew and asdf on Ubuntu

๐Ÿ“˜ Official Documentation


โญ Popular Frameworks

(ordered from lowest to highest learning curve)


๐Ÿ› ๏ธ Installation on Ubuntu

sudo apt update
sudo apt install php php-cli php-common php-mbstring php-xml php-curl php-zip
Enter fullscreen mode Exit fullscreen mode

๐Ÿบ Installation with Homebrew

brew install php
Enter fullscreen mode Exit fullscreen mode

๐Ÿ“ฆ Standard package manager: Composer

Installation:

php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
php composer-setup.php
sudo mv composer.phar /usr/local/bin/composer
Enter fullscreen mode Exit fullscreen mode

Verify:

composer --version
Enter fullscreen mode Exit fullscreen mode

๐Ÿ”ง Install different versions with ASDF

Dependencies:

sudo apt update
sudo apt install autoconf bison build-essential libxml2-dev libssl-dev \
libcurl4-openssl-dev pkg-config re2c libsqlite3-dev
Enter fullscreen mode Exit fullscreen mode

Plugin + version:

asdf plugin add php
asdf install php 8.2.12
asdf global php 8.2.12
Enter fullscreen mode Exit fullscreen mode

๐Ÿ“„ Example .tool-versions

php 8.2.12
Enter fullscreen mode Exit fullscreen mode

๐Ÿ“โ–ถ๏ธ Create and run a PHP file

Create file: touch hola.php

Content of hola.php:

<?php
echo "Hola Mundo PHP\n";
Enter fullscreen mode Exit fullscreen mode

PHP can be run in 2 ways: as a system file, which makes it useful for local scriptsโ€”you could replace bash scripts, for exampleโ€”and in a web server. PHP already comes with an embedded server, but itโ€™s more common to use it with Apache or Nginx.

Run locally:

php hola.php
Enter fullscreen mode Exit fullscreen mode

Embedded server:

php -S localhost:8000
Enter fullscreen mode Exit fullscreen mode

Would you like know more?


๐ŸŸฆ Basic example in PHP

What it does:

  1. Defines the name of the query parameter.
  2. Gets the query parameter value from the URL.
    • $_GET is used to access query parameters.
    • htmlspecialchars is used for security, to prevent XSS attacks by converting special characters like < and > into HTML entities.
  3. It draws the value received through the query parameter inside the <h1> tag.

๐Ÿ“ Create file: touch index.php

โ–ถ๏ธ Content of index.php:

<?php
$paramName = 'username';
$textoRecibido = isset($_GET[$paramName])
    ? htmlspecialchars($_GET[$paramName])
    : "No se ha proporcionado un nombre.";
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <title>Mensaje Recibido</title>
</head>
<body style="text-align: center">
    <h1>Nombre de usuario en la URL: "<?php echo $textoRecibido; ?>"</h1>
    <p>Prueba a cambiar el valor de `texto` en la barra de direcciones.</p>
    <b><a href="/test.php?texto=cambiado%20en%20url">Click para cambio en url</a></b>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

run the project / start the server

php -S localhost:8000
Enter fullscreen mode Exit fullscreen mode

๐Ÿ‘‰ visit:
http://localhost:8000/?username=Homero


EJ:2 Json API Rest

Que Hace:

  1. Lee los datos desde un archivo data.json
  2. expones 1 endpoint con esos datos
    • Una Lista de personajes en /characters
    • y los datos de un personaje por id /characters/:id

Ejemplo de archivo: data.json

[
    {
        "id": 1,
        "age": 39,
        "name": "Homer Tompson",
        "portrait_path": "https://cdn.thesimpsonsapi.com/500/character/1.webp"
    },
    {
        "id": 2,
        "age": 39,
        "name": "Marge Simpson",
        "portrait_path": "https://cdn.thesimpsonsapi.com/500/character/2.webp"
    },
]
Enter fullscreen mode Exit fullscreen mode

๐Ÿ“ Create file: touch api.php

โ–ถ๏ธ Content of api.php:

<?php

header("Content-Type: application/json");

// Obtener la ruta actual
$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

// Cargar archivo JSON
function loadCharacters() {
    $json = file_get_contents("data.json");
    return json_decode($json, true);
}

$characters = loadCharacters();

// GET /characters โ†’ lista completa
if ($_SERVER['REQUEST_METHOD'] === 'GET' && $path === '/characters') {
    echo json_encode($characters);
    exit;
}

// GET /characters/:id โ†’ buscar por ID
if (
  $_SERVER['REQUEST_METHOD'] === 'GET'
  && preg_match('#^/characters/(\d+)$#', $path, $matches)
) {
    $id = intval($matches[1]);

    foreach ($characters as $c) {
        if ($c['id'] === $id) {
            echo json_encode($c);
            exit;
        }
    }

    http_response_code(404);
    echo json_encode(["error" => "Personaje no encontrado"]);
    exit;
}

// Ruta no encontrada
http_response_code(404);
echo json_encode([
    "error" => "Ruta no encontrada",
    "url_lista" => "http://localhost:8001/characters",
    "url_personaje" => "http://localhost:8001/characters/1"
]);
exit;

Enter fullscreen mode Exit fullscreen mode

run the project / start the server

php -S localhost:8001 api.php
Enter fullscreen mode Exit fullscreen mode

๐Ÿ‘‰ visit:
http://localhost:8001/characters

Test API Url:
http://localhost:8001/characters/1


Installation and configuration on Ubuntu of:


Top comments (0)