Data types
Variable
// string, single quote works too
$name = "Shawn";
// number
$num = 100;
//cat, use dot .
echo $name . " " . $num;
//assign html tag to variable (only one value)
$str = "<h1>Hello</h1>";
Math
// +, -, *, / (get float result)
echo 56 + 4;
Arrays
// any type of data is allowed, and can be mixed
$numList = array(23, 64, "hello", '<h1>hello</h1>');
// or abbr
$numList = [23, 64, "hello", '<h1>hello</h1>'];
// array is zero-indexed;
// access element
echo $numList[0];
// print all elements
print_r($numList);
Associative Arrays
- Unordered
- Labeled, key-value
$names = array("first" => "Jack", "sec" => "Mark");
echo $names["first"];
Control structures
If
if (3 < 10>) {
echo "works";
} elseif (3 < 15) {
} else {
}
Comparison operators
- equal,
==
(4 == "4"
) - identical,
===
(4 !== "4"
) - not equal,
!=
- not identical,
!==
- and,
&&
- or,
||
- not,
!
Switch
$num = 10;
switch($num) {
case 1:
echo "1";
break;
case 10:
echo "10";
break;
default:
echo "nothing";
break;
}
Loop
// while
$cnt = 0;
while ($cnt < 10) {
echo "ok";
$cnt++;
}
// for
for ($i = 0; $i < 10; $i++) {
echo $i;
}
// for each
$nums = array(1, 2, 3);
foreach ($nums as $n) {
echo $n;
}
Custom functions
function greet($msg) {
echo $msg;
}
greet("hi");
// return value
function addNums($num1, $num2) {
return $num1 + $num2;
}
$res = addNums(1, 2);
// change global var
$x = "out";
function change() {
global $x;
$x = "in";
}
// constant, cannot be changed once defined
define("NAME", 1000);
echo NAME;
Built-in functions
Math functions
Ref: http://php.net/manual/en/ref.math.php
pow(2, 7);
// random integer from start to end
rand($start, $end)
sqrt(100);
// ceiling, floor
ceil(4.6);
floor(4.3);
String functions
Ref: http://php.net/ref.strings
$str = "hello";
// length
strlen($str);
// upper, lower case
strtoupper($str);
strtolower($str);
Array functions
Ref: http://php.net/manual/en/ref.array.php
$list = [1, 2, 3];
// max, min
echo max($list);
// whole array
print_r($list);
// sort
sort($list);
// if exist
in_array(1, $list);
Form data
A form is as below. The data will be sent to form.php
, method is post
.
<form action="form.php" method="post">
<input type="text" name="username" placeholder="Enter Name">
<input type="password" name="password" placeholder="Enter Password">
<br>
<input type="submit" name="submitName">
</form>
The form.php
will have a $_POST
variable containing the data. The php
code should be put before any html
code so the data can be used by the html
code.
if (isset($_POST['submitName'])) {
$username = $_POST['username'];
// validation
if (strlen($username) < 5) {
echo "short name!";
}
}
External page submission
In the page of form_external.php
, form data can be sent to another page form_process.php
.
<form action="form_process.php" method="post">
<input type="text" name="username" placeholder="Enter Name">
<input type="password" name="password" placeholder="Enter Password">
<br>
<input type="submit" name="submitName">
</form>
Database
phpMyAdmin: localhost/phpmyadmin
if (isset($_POST['submit'])) {
$username = $_POST["username"];
$password = $_POST["password"];
if ($username && $password) {
// connect mysql
$connection = mysqli_connect("localhost", "user_name", "password", "table_name");
if ($connection) {
echo "Connected";
} else {
die("DB connection failed");
}
// execute query, insert
$query = "INSERT INTO " . "users(username, password)" . " VALUES " . "("$username", "$password")";
$result = mysqli_query($connection, $query);
if (!$result) {
die("Failed query " . mysqli_error());
}
// fetch result
$select_q = "SELECT * FROM users";
$select_res = mysqli_query($connection, $select_q);
// this func returns assoc array, like map. mysqli_fetch_row will return just the row
while ($row = mysqli_fetch_assoc($select_res)) {
print_r($row);
}
}
}
An example, show result as select list in form
<form action="form.php" method="post">
<input type="text" name="username" placeholder="Enter Name">
<input type="password" name="password" placeholder="Enter Password">
<select name="id" id="">
<?php
while ($row = mysqli_fetch_assoc($select_res)) {
$id = $row["id"];
echo "<option value="$id">$id</option>"
}
?>
</select>
<br>
<input type="submit" name="submitName">
</form>
PHP security
// to prevent sql injection
$firstname = mysqli_real_escape_string($con, $_POST['firstname']);
$lastname = mysqli_real_escape_string($con, $_POST['lastname']);
$age = mysqli_real_escape_string($con, $_POST['age']);
// execute query with vars
More efficient choice is use prepared
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (?, ?)");
$stmt->bindParam(1, $name);
$stmt->bindParam(2, $value);
// insert one row
$name = 'one';
$value = 1;
$stmt->execute();
Password encryption
Ref: http://php.net/manual/en/function.crypt.php
$hashFormat = "$2y$10$";
// 22 chars
$salt = "adsfadvewqwsejfotufmzc";
$hashFAndSalt = $hashFormat . $salt;
$encrypt_password = crypt($password, $hashFAndSalt);
PHP and the web
$_GET
is a super global variable. It can get params from url localhost/demo.php?id=10&name=jack
will get an assoc array with id and name
$_GET;
<a href="get.php?id=100">Click</a>
<?php
print_r($_GET);
?>
Cookies
$_COOKIE;
//set cookie
$name = "jack";
$value = 100;
$expiration = time() + (60 * 60 * 24 * 7); // time() will return all seconds from 1970
setcookie($name, $value, $expiration);
//use cookie
if (isset($_COOKIE["jack"])) {
$val = $_COOKIE["jack"]; // get the value
}
Session
Can pass variables between pages, do session_start();
on every page.
<?php sesssion_start();
$_SESSION["greeting"] = "hello";
?>
PHP OOD
define a class:
class Car {
// field
// public, anywhere
public $wheels = 1;
// protected, this class and subclass
protected $hood = 2;
// private, only this class
private $engine = 3;
var $name = "default";
// static
static $material = "steel";
// method
function greeting() {
echo "Hi";
// $this refers to the current object
$this->name = "hi";
Car::$material = "iron";
}
}
if (class_exists("Car")) {
echo "class exists";
if (method_exists("Car", "greeting")) {
echo "method exists";
}
// access static
echo Car::$material;
}
// instantiate
$car = new Car();
$car->greeting();
// for static
Car::greeting();
echo $car->name = "bmw"; // no $ sign
Inheritance
// inheritance
class Benz extends Car {
}
$c200 = new Benz();
$c200->greeting();
Constructor
class Car {
function __construct() {
echo "constructed";
}
}
PHP and File
$file = "ex.txt";
// may need to give permission to the file, chmod
if ($handle = fopen($file, 'w')) {
// write
fwrite($handle, "line");
// read
$cont = fread($handle, 10); // second arg is the number of bytes to read
// read all
$allCont = fread($handle, filesize($file));
// read line by line
while ($line = fgets($handle) !== false) {
}
fclose($handle);
} else {
echo "read failed";
}
// delete
unlink("filename.php");
Misc
include tags in php
<?php
echo "<h1>Hello</h1>";
?>
execute external php
The global vars in external php
file can be passed.
<?php include "includes/header.php"?>
<?php include "db.php";
echo "<h1>Hello</h1>";
?>
<?php include "includes/footer.php"?>