Creating apps with PHP blocks

Build with Blocks

© Lead Image © Vladimir Nenov, 123RF.com

© Lead Image © Vladimir Nenov, 123RF.com

Article from Issue 237/2020
Author(s):

Build simple PHP applications quickly with ready-to-use blocks.

PHP is great. It feels approachable and intuitive, and it allows you to write a working application with just a handful of lines of code. PHP basics are relatively easy to master, and there are plenty of books and online resources that can help. As with any programming language, things can get rather hairy sooner or later. But even with basic PHP knowledge, you can build simple yet useful applications. As you progress, you'll notice that many PHP applications share a lot of common code. With time, you may even build your own library of reusable PHP blocks that can significantly reduce the amount of effort required to build an application.

The good news is that you don't have to grow your PHP collection from scratch: The PHPlattenbau project [1] created by yours truly (see the "Personal Note" box) provides several blocks for building a wide range of PHP applications. Each block in PHPlattenbau is actually an application that performs a simple task using one or several common PHP techniques. By adding and mixing these blocks or their parts, you can quickly build a wide range of PHP applications.

Personal Note

I'm not a programmer by any stretch of the imagination. I like writing simple applications and tools that make my everyday life easier. I enjoy the challenge of figuring out how to solve a problem at hand with a few lines of code. Basically, I'm an amateur coder. But there are a great many people like me who are not looking to become professional programmers but who nevertheless would like to be able to write useful applications. These may not be perfect but are good enough to perform the tasks for which they are designed. If you belong to this category, PHPlattenbau is for you.

Tooling Up

You don't need much to get started with PHP and PHPlattenbau on Linux. Obviously, you need PHP 7.x installed on your system. To install PHP on openSUSE, run the command:

sudo zypper in php7

To do the same on Ubuntu, use:

sudo apt install php

Since PHP comes with a built-in web server, you can use it for testing and experimenting instead of installing a dedicated web server.

You also need a text editor. If you are looking for an editor that is designed specifically for working with PHP and can grow with you, you can do much worse than opting for CodeLite [2] (Figure 1). While you might not need CodeLite's advanced functionality when you start your PHP programming journey, the editor offers plenty of creature comforts that make coding more convenient. This includes workspaces, code folding, autocompletion, bracket matching, and much more. CodeLite is available for all major platforms and mainstream Linux distributions.

Figure 1: CodeLite is a solid PHP editor.

Zeal [3], an offline documentation browser, is another utility you might want to add to your toolbox right from the start. Having PHP documentation at your fingertips can be a real timesaver. Instead of trawling the web for answers, you can install Zeal and consult it whenever needed.

Normally, running PHP code requires a dedicated web server like Apache. But to run and experiment with the PHP blocks, you can use PHP's built-in server. In the terminal, switch to the directory of the desired block (e.g., csv-to-table) and run either

php -S localhost:8000

or

php -S 0.0.0.0:8000

The first command allows you to access the running application only from the same machine the server is running on, while the second command makes it possible to access the application from any machine.

Block by Block

In many programming languages, adding a graphical user interface (GUI) is no trivial matter. With PHP, you can whip up a usable GUI using HTML and a dash of CSS. The template block of PHPlattenbau gives you exactly that: a basic HTML/PHP template that you can use as a starting point for practically any PHP application (Figure 2). The template uses lit [4], a tiny CSS framework, for basic styling. Lit is responsive by design, which means that the template works equally well on desktop and mobile browsers.

Figure 2: You can use the supplied responsive PHP page template as a starting point for your application.

Most PHP applications are meant to be run on a web server, so they are exposed to the world. This is not an issue if you have a simple application that only reads and displays data. But if your application includes editing functionality, you might want to limit access to it. One way to do this is to use password protection. This is exactly what the password-protect block offers. By using it, you can easily protect any page with a password. To do this, add the following PHP code to the page you want to protect:

<?php
include('config.php');
if ($protect) {
    require_once('protect.php');
}

Change the default password in the config.php file, and you are done. Keep in mind that while this protection mechanism is simple and easy to add, it's not particularly sophisticated. So don't rely on it as your only line of defense.

PHP is often used in combination with MySQL or SQLite databases, and there are plenty of tutorials and examples on how to use these database engines as back ends for PHP applications. But using a database for a simple PHP application can be overkill, especially if you consider the amount of effort required. At the very least, you need to write scripts for adding, editing, and querying database records. You also have to ensure that the database queries are properly sanitized (i.e., formatted in a way that prevents misuse). Before you even get that far, you need to deploy a database instance and make sure it works with PHP.

Instead of using a database, you can opt for storing data in comma-separated values (CSV) plain text. Each line in the text file acts as a database record, where each value is separated by a comma (hence the name). The CSV format is easy to read, and you can use a regular text editor or a spreadsheet application to work with CSV data. But how do you view CSV data in a text file using PHP? This is where the csv-to-table block comes into the picture. It reads the data in the specified text file (by default, it's data.csv) and renders the contents as a nicely-formatted HTML table (Figure 3).

Figure 3: The csv-to-table block lets you use a CSV text file as a simple database back end.

If you need to deal with Markdown in your PHP applications, the fetch-markdown block can help. It uses the Parsedown PHP library [5] to parse Markdown-formatted text. In addition to that, the block uses routines to fetch remote contents, which can be useful for publishing content, while delegating the task of editing and managing it to a third-party system.

Speaking of editing, the edit-text module allows you to do just that. It's basically a bare-bones editor that you can plug into any PHP application (Figure 4). The block reads the contents of a text file into a text area, where you can edit it. When you press Save, the editor creates a backup copy of the text file and saves the modified contents in the file itself.

Figure 4: The edit-text block lets you add text editing capabilities to your PHP applications.

Many web-based applications nowadays pull data from APIs in XML or JSON format. Two blocks make it possible to add this functionality to your PHP applications: get-json and parse-xml. As the name suggests, the get-json block demonstrates how to pull and parse weather data in the JSON format from the OpenWeatherMap service (Figure 5). It also shows how to obtain values from an HTTP request using the GET method. To use the get-json block, you need an OpenWeatherMap API key. You can get it free of charge by creating an account with the service. The parse-xml block illustrates how to parse and display XML data by fetching and processing RSS feeds (Figure 6).

Figure 5: Using the get-json block, you can fetch and process JSON data.
Figure 6: The parse-xml block demonstrates how to process XML data.

Finally, the shell-exec block can come in handy when you need to trigger shell commands via PHP. This block scans the mp3 directory for MP3 files and then populates the drop-down list in the main page with the names of the found files. You can then select the title you like from the drop-down list and use the appropriate buttons to play and to stop the track (Figure 7). This block requires the mpg123 command-line MP3 player to be installed on your system.

Figure 7: The shell-exec block illustrates how to run shell commands from PHP.

Building a Weight Tracker Application

You'll be forgiven for thinking that seven simple PHP blocks and a template are hardly enough to build anything usable. But you really don't need much to create simple yet functional applications. For example, combining the template with the csv-to-table, edit-text, and password-protection blocks, you can whip up a minimal application for tracking weight.

Here's how this application works. The password-protected main page based on the template integrates the csv-to-table block that reads CSV data from the data.csv file and presents the results as a table. The main page also has a form for entering weight values. When you press the Save button, a simple PHP routine gets the value entered in the input field, obtains the current date, and saves both values in the data.csv file. You can edit the data file using any text editor, but if you prefer to manipulate the saved data using the application, you can easily integrate the edit-text module into it. Add the Edit button to the form on the main page, specify the correct name of the data file in the edit.php file, and you are done.

The Weight Tracker example application comes with PHPlattenbau (Figure 8), so you can dissect and study it.

Figure 8: A simple weight tracker application built with PHPlattenbau blocks.

Buy this article as PDF

Express-Checkout as PDF
Price $2.95
(incl. VAT)

Buy Linux Magazine

SINGLE ISSUES
 
SUBSCRIPTIONS
 
TABLET & SMARTPHONE APPS
Get it on Google Play

US / Canada

Get it on Google Play

UK / Australia

Related content

  • Network Block Devices

    You don’t need Samba or NFS to support a diskless client. A remote block device can help improve performance and efficiency. We'll show your how.

  • OpenLaszlo

    Long before Ajax hit the scene, Flash gave developers a basis for designing interactive web content. The OpenLaszlo framework, with its easy-to-learn command syntax, is the foundation on which many Flash applications build.

  • OpenDocument Intro^

    OpenDocument format offers a new approach to data storage and document exchange for office applications. But what does ODF mean for the user? What’s inside an ODF file? How portable is ODF? We examine these questions in this month’s cover story.

  • Tapping Data with the RaspPi

    If you have a weather station that allows you to access data via a USB port, you can use your Raspberry Pi to analyze the data and publish the results via a web application.

  • Cloop

    The cloop module lets you manage compression at the block device level. Read on to learn how Knoppix and other Live CDs fit all that software on a single disc.

comments powered by Disqus

Direct Download

Read full article as PDF:

Price $2.95

News