Learning PHP - Part 2 - Lets get coding!

Part 2

Laracasts main site
Laracasts - PHP for beginners


Chapter 2 - Install a code editor
Chapter 3 - Variables
Chapter 4 - PHP and HTML
Chapter 5 - Seperation of PHP logic

Hello World

Are you really learning a new program if you don’t create a simple hello world?

// hello-world.php

echo 'Hello World';

In a terminal run:

php hello-world.php

Should echo ‘Hello World’ to the command line.

Note: Also of note, when in a plain php file, without the closing ?> it is best practice due to parsing errors if you add extra lines after ?>

Easy win after the nightmare install process.


// index.php

$name = 'Konnor Rogers';

// Concats $name onto 'Hello'
echo 'Hello' . $name;

// Or
echo "Hello {$name}";


Pulling in parameters

// index.php

// pulls in the 'name' parameter
$name = htmlspecialchars($_GET['name']);

echo "Hello, " . $name;
// localhost:8888/?name=konnor #=> Hello, Konnor

htmlspecialchars(); Will convert special characters as the name suggests so people cannot inject malicious links, scripts, etc

Seperating php logic

In a small low level MVC framework, this is a microcosm of a view. index.view.php is essentially a template to be rendered, and index.php provides any necessary variables to be rendered. For example:
$greeting may be the result of a database call. You want that to be done server side without concern for the actual way it is being rendered.

// index.php

$greeting = 'Hello World';

// pulls in the view defined below
require 'index.view.php';
// Optionally, you can use: include 'index.view.php';
// Read the note below about the difference

Note: After perusing some documentation, include and require do essentially the same thing. They pull in variables and other data @ the level it is called. The only difference is the following:
include will not cause a compilation error if the file does not exist or is unreadable. It will only send a compilation warning.
require will cause a compilation error if the file does not exist or is unreadable

// index.view.php
<!DOCTYPE html>
<html lang="en">
  <meta charset="UTF-8">
    header {
      background: #e3e3e3;
      padding: 2rem;
      text-align: center;
      <h1><?= $greeting; ?></h1>

<?= ?> is the same as <?php echo "string" ?>

Follow along with my repo
Laracasts main site
PHP for beginners