PHP 3 - PHP Language Basics

By Sheldon L Published at 2020-06-20 Updated at 2020-06-20


Introduction

cd $hub/mysite_test
mkdir PHP_Course
sudo ln -s $hub/mysite_test/PHP_Course /opt/lampp/htdocs/PHP_Course

# open http://localhost/PHP_Course
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>PHP Course</title>
</head>
<body>
  <?php
    echo "variables"."<br>";
    $name = "Sheldon";        # variable
    echo $name;

    echo("<br>");
    echo "double quotes or single quotes"."<br>";
    echo "My name is $name"."<br>";
    echo 'My name is $name';  # `''` is different from `""`

    echo("<br>");
    echo "print"."<br>";
    print("hello");
    print("\r\n");            # NOT start a new line! Only a space.
    print "hello";
    // print("hello", " ", "world"); # syntax error
    // print "hello", " ", "world";  # syntax error
    print "hello" . " " . "world" . "<br>";

    echo("<br>");
    echo "echo"."<br>";
    echo nl2br(
      "Hello world,\r\n    My name is $name\r\n"   # start a new line, but not recmended
    );
    echo "Hello world, <br>My name is " . $name . "<br>";
    // echo("hello", " ", "world");  # syntax error
    echo("hello" . " " . "world" . "<br>");
    echo "hello", " ", "world", "<br>";
    echo "hello" . " " . "world", "<br>";

    /* PHPINFO:
      Out put php information,
      and configurations.
    */
    phpinfo();
  ?>
</body>
</html>

Data Types

/* String
*/
$name = "Dary";
echo "My name is ". $name . "<br>";
echo gettype($name) . "<br>";
echo "<br>";

/* Integer
*/
$age = 24;
echo "My age is " . $age . "<br>";
echo gettype($age) . "<br>";
echo "<br>";

/* Float, or Double
*/
$price = 10.5;
echo "The price is " . $price . "<br>";
echo gettype($price) . "<br>";
echo "<br>";

/* Boolean
*/
$is_allowed = true;
echo $is_allowed . "<br>";  # if true, return 1, else return 0!
echo gettype($is_allowed) . "<br>";
echo "<br>";

/* Null
*/
$x = null;
echo $x;  # nothing to print
echo gettype($x) . "<br>";
$y;       # y will be NULL, along with ERR: Undefined variable;
echo $y;                             # ERR: Undefined variable;
echo gettype($y) . "<br>";
echo "<br>";

/* Array
*/
# Indexed arrays: index=>value pair, index start from 0
$cars = array("BMW", "Audi", "Mercedes");
echo $cars[1] . "<br>";
echo $cars[3] . "<br>";  # ERR: Undefined offset

$myCar = array("Audi", 2015, 7550);
var_dump($myCar); # hard to read
echo "<br>";
print_r($myCar);  # easier to read
echo "<br><br>";

# Associative arrays: User defined key=>value type
$carsPrice = array("BMW"=>5000, "Audi"=>5500, "Mercedes"=>10000);

var_dump($carsPrice);
echo "<br>";
print_r($carsPrice);
echo "<br>";

$carsPrice["BMW"] = 8000;
echo $carsPrice["BMW"] . "<br>";
echo "<br>";

foreach ($carsPrice as $key => $value) {
  echo "My $key values $value $." . "<br>";
}
echo "<br>";

# Multi Dimentional arrays
$cars = array(
  "Expensive" => array("Audi", "Mercedes", "BMW"),
  "Inexpensive" => array("Vovo", "Ford", "Toyota"),
);
print_r($cars);
echo "<br>";
echo $cars["Expensive"][2];
echo "<br><br>";

/* Advanced Types
  # Object
  # Resource
*/

Operators

/* Calculator */
$x = 15;
$y = 8;
echo "x = ". $x. "<br>";
echo "y = ". $y. "<br>";
echo "x * y = ". $x * $y. "<br>";
echo "x ** y = ". $x ** $y . " - " . gettype($x ** $y). "<br>";
echo "x % y = ". $x % $y. "<br>";
echo "x / y = ". $x / $y. "<br>";
echo "<br><br>";

/* Assignment
  += --- Add    and assign
  -= --- Substr and assign
  *= --- Multip and assign
  /= --- Divide and assign
  .= --- Concat and assign
  ... and so on
*/
$x = 8;
echo "x = $x". "<br>";
$x += 5;
echo "x += 5, x = $x" . "<br>";
$x -= 5;
echo "x -= 5, x = $x" . "<br>";
$x *= 5;
echo "x *= 5, x = $x" . "<br>";
$x /= 5;
echo "x /= 5, x = $x" . "<br>";
$x .= 5;
echo "x .= 5, x = $x" . " - " . gettype($x) . "<br>";          # string
$x **= 5;
echo "x **= 5, x = $x" . " - cast to " . gettype($x) . "<br>"; # cast to int
$x %= 13;
echo "x %= 13, x = $x" . "<br>";
$x .= " is the result.";
echo '$x .= " is the result."; ';
echo "x = $x" . "<br>";
echo "<br>";
/* Comparison
  >
  <
  >=
  <=
  ==    Equal value
  ===   Equal value and data type
  <=>   Spaceship
          if the left is less then the right, return -1;
          if the left is equal to the right, return 0;
          if the left is greater then the right, return 1;
*/
$x = 5;
$y = 8;

if ($x == $y) {
  echo "This is true" . "<br>";
} else {
  echo "This is false" . "<br>";
}

echo $x <=> $y . "<br>";
echo "<br><br>";

/* Increment & Decrement
  ++$x  Pre-increment
  $x++  Post-increment
  --$x  Pre-decrement
  $x++  Post-decrement
*/
$x = 5;
echo --$x . "<br>";
echo $x . "<br>";

$x = 5;
echo $x-- . "<br>";
echo $x . "<br>";
echo "<br>";

/* Logical operaters
  TRUE   = 1
  FALSE  = 0
  AND    Both X and Y are True
  &&     Both X and Y are True
  OR     Either X or Y are True
  ||     Either X or Y are True
  Xor    Either X or Y are True, but not both
  !      True if X is not True

  NOTE: the key words are NOT casesensitive
*/

$x = 10;

if (! $x == 10 xor 1 == TRUE) {
  echo "True!". "<br>";
} else {
  echo "False!". "<br>";
}

Control Structures

/* Condition statement:
  if
  else
  elseif
  switch
*/
$age = 18;

if ($age < 10) {
  echo "Time to sleep!";
} elseif ($age < 20) {
  echo "Sorry, you are too young!";
} elseif ($age > 60) {
  echo "Sorry, you are too old!";
} else {
  echo "Welcome!";
}
echo "<br>";

switch ($age) {
  case $age < 10:
    echo "Little baby.";
  break;
  case $age < 20:
    echo "Sweet.";
  break;
  case 20:
    echo "Be careful!";
  break;
  case $age > 60:
    echo "Try somthing else.";
  break;
  default:
    echo "Come in, please.";
}
echo "<br>";

/* Loop statement:
  while       Don't know the number of iteration
  do - while  Don't know the number of iteration, first do whatever condition meet or not, then while
  for
  foreach     Iterate over array
*/

$x = 1;
while ($x <= 10) {
  echo "$x ";
  $x++;
}
echo "<br>";
echo $x . "<br>";

$x = 100;
do {
  echo "$x ";
  $x++;
} while ($x <= 10);
echo "<br>";
echo $x . "<br>";

for ($x = 1; $x <= 10; $x++) {
  echo "$x ";
}
echo "<br>";
echo $x . "<br>";

$names = array("Mike", "Sheldon", "Atom");
foreach ($names as $name) {
  echo "My name is " . $name . "<br>";
}

$persons = array("Name" => "Dary", "Age" => 45, "Gender" => "Male");
foreach ($persons as $key => $value) {
  echo "$key: $value" . "<br>";
}

/// Exercise:
// deposit is 1000 dollars, interest rate is 0.5%, how much after 5 years?
$deposit = 1000;
$rate = 0.5/100;

for ($year = 1; $year <= 5; $year++) {
  $deposit += $deposit * $rate;
  echo "After $year years, I'll have $deposit dollars. <br>";
}

Functions

Basics

/* Fuction
function name:
  myFunction();
  my_function();
*/

# pass no parameter
function helloWrold() {
  echo "Hello, world! <br>";
}
helloWrold();

# paas by value
function caculator($x=1, $y=1) {
  echo "x = ". $x . "<br>";
  echo "y = ". $y . "<br>";
  echo "x * y = ". $x * $y . "<br>";
  echo "x ** y = ". $x ** $y . "<br>";
  echo "x % y = ". $x % $y . "<br>";
  echo "x / y = ". $x / $y . "<br>";
  echo "<br><br>";
}
caculator();

# return value
function add($num1=1, $num2=1) {
  $sum = $num1 + $num2;
  return $sum;
}
echo "The number is " . add(3, 5) . "<br>";

# pass by reference, and global variables
$x =10;

function addByValue($x) {
  $x +=10;
}

function addByReference(&$x) { # by reference
  $x += 10;
}

echo $x . "<br>";
addByValue($x);     # refer to local $x
echo $x . "<br>";   # still 10
addByReference($x); # refer to global $x
echo $x . "<br>";   # 20

# Define constants:
# constants are always in upercase.

# Method 1: key word - const, defines at compile time
const MY_NAME = 'Dary';
echo MY_NAME;      # `$` sign is only for variables, not constants.
echo "<br>";

# Method 2: function - define(), defines at run time
define("COMPANY_NAME", "Apple");
echo COMPANY_NAME;
echo "<br>"

Include/Require Document

# index.php (similar to about.php and contact.php)
<?php
  include 'includes/head.php';
  include 'includes/header.php';
?>

<h1>Welcome!</h1>

<?php
  include 'includes/footer.php';
?>
# includes/head.php
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>PHP Course</title>
</head>

<body>
# includes/header.php
<header>
  <nav>
    <ul>
      <li><a href="index.php">Home</a></li>
      <li><a href="about.php">About</a></li>
      <li><a href="contact.php">contact</a></li>
    </ul>
  </nav>
</header>
# includes/footer.php

</body>

<footer>
  <hr>
  <p>This is my footer</p>
</footer>

</html>
# includes/functions.php
<?php
  function introduction() {
    echo "Hello User!";
    echo "<br>";
  }
?>
# includes/head.php
<?php
  include 'functions.php';
?>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>PHP Course</title>
</head>

<body>
# index.php
<?php
  include 'includes/head.php';
  include 'includes/header.php';
?>

<h1><?php introduction(); ?></h1>

<?php
  include 'includes/footer.php';
?>

Built-in Functions

/* String functions:
*/
# strlen(STR), str_word_count(STR)
$str = "Today is a sunny day.";
echo '$str = ' . $str . "<br>";
echo 'strlen($str) = ' . strlen($str) . "<br>";
echo 'str_word_count($str) = ' . str_word_count($str) . "<br>";
echo "<br><br>";

$str = "Today is a sunny day." . "<br>";
echo '$str = ' . $str . "<br>";
echo 'strlen($str) = ' . strlen($str) . "<br>";  # space and break are also count.
echo 'str_word_count($str) = ' . str_word_count($str) . "<br>";
echo "<br><br>";

# strpos(STR, PATTERN) - if pattern can be found
$email = "info@dary.com";
if (strpos($email, "@")) {
  echo "This is a valid email.";
} else {
  echo "This is NOT a valid email.";
}
echo "<br><br>";

# to uppercase or to lowercase
echo ucwords($str) . "<br>";
echo strtoupper($str) . "<br>";
echo strtolower($str) . "<br>";
echo "<br><br>";

# trim(), explode()
echo trim($str) . "<br>";             # strip
print_r(explode(" ", $str)); # split
echo "<br><br>";

/* Math functions
*/
$x = 15;
$y = 8;

echo "intval(x / y) = ". intval($x / $y). " - ". gettype(intval($x / $y)) . "<br>";
echo "ceil(x / y) = ". ceil($x / $y). " - ". gettype(ceil($x / $y)) . "<br>";
echo "floor(x / y) = ". floor($x / $y). " - ". gettype(floor($x / $y)) . "<br>";
echo "round(x / y) = ". round($x / $y). " - ". gettype(round($x / $y)) . "<br>";
echo "round(x / y, 2) = ". round($x / $y, 2). " - ". gettype(round($x / $y, 2)) . "<br>";
echo "e^4, exp(4) = ". exp(4) . "<br>";
echo "sqrt(4) = ". sqrt(4) . "<br>";
echo "<br><br>";

/* Date and Time
  'y' = year (2 digit)
  'Y' = year (full)
  'm' = months as number with leading 0s
  'n' = months as number without leading 0s
  'M' = months (3 letters)
  'F' = months (full name)
  'd' = day with leading 0s
  'j' = day without leading 0s
  'D' = day of week (3 letters)
  'l' = day of week (full name)
  'h' = hours in 12-h format with leading 0s
  'g' = hours in 12-h format without leading 0s
  'H' = hours in 24-h format with leading 0s
  'G' = hours in 24-h format without leading 0s
  'i' = minuts
  's' = seconds
  'a' = am/pm
  'A' = AM/PM
*/
# set timezone
date_default_timezone_set('Asia/Shanghai');
# get timezone
echo date_default_timezone_get() . "<br>";
# get timestamp now
echo time()."<br>";  # count by second
# get timestamp after a month
echo time() + 86400 * 30 . "<br>";
# show timestamp as datetime readable;
echo date('Y-m-d D h:i:s a') . "<br>";
echo date('Y-m-d D h:i:s a', time() + 86400 * 30) . "<br>";
# string to time
echo date('Y-m-d D h:i:s a', strtotime("4:00 pm December 03 2019"));
echo "<br><br>";

/* Array functions
*/
# array_merge(), array_keys(), array_values()
$personalInfo = array("Name" => "Dary", "Age" => 24, "City" => "Amsterdam");
$moreInfo = array("State" => "NH", "Weight" => 85);

$personalInfo = array_merge($personalInfo, $moreInfo);

foreach ($personalInfo as $key => $value) {
  echo "$key: $value" . "<br>";
}

print_r(array_keys($personalInfo));
echo "<br>";
print_r(array_values($personalInfo));
echo "<br><br>";

# array_push(), array_pop()
$cars = array("BMW", "Audi", "Mercedes");
print_r($cars);
echo "<br>";

array_push($cars, "Vovo", "Ford");
print_r($cars);
echo "<br>";

array_pop($cars);
print_r($cars);
echo "<br><br>";

// $cars = array_push($cars, "Toyota"); # NOTE: can't like this, will be trans to int!
// print_r($cars);
// echo "<br>";

# array_search() - find index in the array
echo array_search("Audi", $cars);
echo "<br><br>";

# count() - the number of elements in an array
echo count($cars);
echo "<br><br>";

/* Random number functions
*/
echo rand() . "<br>";
echo getrandmax() . "<br>";
echo rand(0, 1) . "<br>";
echo "<br><br>";

How to Work with Superglobals

$GLOBALS

$x = 100;
$y = 200;

function add() {
  $GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y'];
}

add();
echo $z . "<br>";
echo "<br>";

$_POST

# post.php

<?php
if (isset($_POST['submit'])) {
  echo $_POST['name'] . ", your form is submitted. <br>";
  print_r($_POST);
}
?>

<form action="post.php", method="post">
  <input type="text" name="name">
  <input type="text" name="age">
  <button type="submit" name="submit">SUBMIT</button>
</form>

$_GET

# get.php

<?php
# $_POST rely on the `name` attribute in the <form>
?>

<form action="get.php", method="get">
  <input type="text" name="name">
  <input type="password" name="password">
  <button type="submit" name="submit">SUBMIT</button>
</form>

$_SESSION

# session.php

session_start();

# storing information
$_SESSION['name'] = 'Dary';
$_SESSION['age'] = 24;

echo "Hello, " . $_SESSION['name'] . "<br>";

session_destroy();  # destroied whenever bowser is closed down

echo "Hello, " . $_SESSION['name'] . "<br>";

$_COOCIE

# cookie.php

/* Arguments:
  Name      must, name of the cookie
  Value     must, value of the cookie
  Expire    must, expire timestamp when the cookie can be accessed
  Path      mandatory, path on the server where the cookie is available
  Domain    mandatory, domain for the cookie is available
  Security  mandatory, indicate that the cookie should only available hunder https
*/

$expire = time() + 86400 * 30;     # if expire time not set, cookie only available in current session
// $expire = time() - 86400 * 30;  # if time expired, cookie will be unavailable

setcookie("name", "Dary", $expire);
print_r($_COOKIE);
echo "<br>";
echo $_COOKIE['name'];
echo "<br>";
echo $_COOKIE['PHPSESSID'];
echo "<br>";

$_FILES

# files.php

<?php
# enctype="multipart/form-data" in the <form> tag:
  # specifies how the form data should be encoded
?>

<form action="upload.php" method="post" enctype="multipart/form-data">
  <input type="file" name="file">
  <button type="submit" name="submit">SUBMIT</button>
</form>
# uplade.php

/* Script for upload
*/

if (isset($_POST['submit'])) {

  # to test if the POST is ready:
  // print_r($_POST);
  // print_r($_FILES['file']);
  // echo "<br>";

  $file = $_FILES['file'];
  $name = $_FILES['file']['name'];  // find file name
  $tmp_name = $_FILES['file']['tmp_name']; // tmp loc
  $size = $_FILES['file']['size'];  // find file size
  $error = $_FILES['file']['error'];// find error

  # Explode from punctuation mark `.`
  $tmpExtension = explode('.', $name);             // split, got an array of name and extension
  $fileExtension = strtolower(end($tmpExtension)); // lowercase the end element of the array

  # Allowed exentions
  $isAllowed = array('jpg', 'jpeg', 'png', 'pdf');

  if (in_array($fileExtension, $isAllowed)) {
    if ($error === 0) {
      if ($size < 6999) {  // in B
        $newFileName = uniqid('file', true). "." . $fileExtension; // name as new file, prefixed with 'file'
        $fileDest = "uploads/" . $newFileName;
        move_uploaded_file($tmp_name, $fileDest);
        header("Location: files.php?uploadedsuccess");
      } else {
        echo "Sorry, the file size is too large.<br>";
      }
    } else {
      echo "Sorry, there was an error! Pleas try again.<br>";
    }
  } else {
    echo "Sorry, your file type is not accepetd.<br>";
  }
}
# fileput.php

/* Open mode of files - See in php documentation for more
  'r'
  'r+'
  'w'   write, overwrite every time.
  'w+'  write, don't overwrite.
  ...
*/

if (isset($_POST['name'])) {
  print_r($_POST);

  $myFile = fopen("uploads/file.txt", 'w'); // if not exist, will create

  $text = "Hello World!\n";
  fwrite($myFile, $text);

  $text = "My name is " . $_POST['name']. "\n";
  fwrite($myFile, $text);

  $text = "My age is " . $_POST['age']. "\n";
  fwrite($myFile, $text);

  fclose($myFile);
}

?>

<form action="fileput.php", method="post">
  <input type="text" name="name">
  <input type="text" name="age">
  <button type="submit" name="submit">SUBMIT</button>
</form>
# getfile.php

<?php
  include 'includes/head.php';
  include 'includes/header.php';
?>

<?php
$filePath = "uploads/file.txt";
$output = file_get_contents($filePath);

echo $output . "<br>";

$wordCount = str_word_count($output);
$characterCount = count_chars($output);

$lines = explode("\n", $output);
$lineCount = count($lines);
echo $lineCount . "<br>";

$lineCount = 0;
foreach ($lines as $line) {
  if (! $line == "") {
    echo $line . "<br>";
    $lineCount++;
  }
}
echo $lineCount . "<br>";
?>

<?php
  include 'includes/footer.php';
?>
# contact/index.php
<div class="">
  <h1>Get in touch</h1>
  <form action="contact.php" method="post">
    <input type="text" name="name" placeholder="Full Name"><br>
    <input type="text" name="email" placeholder="E-mail"><br>
    <input type="text" name="subject" placeholder="Subject"><br>
    <textarea name="message" cols="30" rows="10" placeholder="Enter message"></textarea><br>
    <button type="submit" name="submit">SEND</button>
  </form>
</div>
# contact/contact.php
if (isset($_POST['submit'])) {
  $name = trim($_POST['name']);
  $email = trim($_POST['email']);
  $subject = trim($_POST['subject']);
  $message = trim($_POST['message']);

  $myMail = "info@dary.com";
  $header = "From: " . $email;
  $message2 = "You have received a message from " . $name . ".\n\n";

  /* mail function
    1. to whom
    2. subject
    3. information when recieved
    NOTE:
      gmail will block your email function;
      only on real server, you can recieve the message;
  */
  mail($myMail, $subject, $message2, $header);
  header("Location: index.php?mailsend");
}