How to build a website quickly using PHP

PHP is a powerful scripting language created for the web.

It has come a long way since it’s initial inception in 1994.

It was originally created to build websites quickly and easily and has become a lot more than that.

While many developers and companies use PHP along with extensive and oftentimes heavy frameworks, there is no reason that you have to do that; you can build websites quickly and very easily by making use of many standard PHP functions.

The purpose of this tutorial is to show you how to do just that.

PHP comes with a built-in web-server, that you can use for a development or for quick testing. Do note that you should not deploy anything to a production server with it though. For production environments, a hardened web server such as Apache2 or Nginx is highly advantageous and always advised!

Getting going

First we will create a new directory as our project root:

mkdir helloworld
cd $_

Now that we’re in our new project, we can create our initial file, which should always be called index.php.

touch index.php

Now we open our index.php file for editing and insert the following PHP code.

<?php

echo "Hello world!";

Note that we start a PHP file with <?php and we strictly don’t have to end it with ?>, but you can if you want…

We can now view it in a web browser by running the following command and navigating to the URL in our browser:

php -S localhost:8000

We can now see our text string rendered out in the browser!

A directory structure

Organising your files is crucial to a simple project, I often go with a similar layout to the below:

.
|___config.php
|___includes
|___index.php
|___pages

Routing

In order to be able to make use of different pages and routings, we can add a simple routing system; this is why we have a pages directory in our tree above.

Create two files under pages called home.php and about.php.

In home.php, add the following:

<?php

echo "Home";

In about.php add the following:

<?php

echo "About";

Now edit index.php and change the contents of the file to the following:

<?php

$home_page = "home";

if (isset($_GET['page'])) {
 if (file_exists("pages/$_GET[page]")) {
 include("pages/$_GET[page].php");
 }
} else {
 include("pages/$home_page.php");
}

Our project tree now looks like:

.
|___config.php
|___includes
|___index.php
|___pages
 |___about.php
 |___home.php

Navigating

You can now view your simple website at http://localhost:8000.

Tags:
0 0 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments