Public speaking course notes Read "Dynamo, Amazon’s Highly Available Key-value Store" Read "Bigtable, A Distributed Storage System for Structured Data" Read "Streaming Systems" 3, Watermarks Read "Streaming Systems" 1&2, Streaming 101 Read "F1, a distributed SQL database that scales" Read "Zanzibar, Google’s Consistent, Global Authorization System" Read "Spanner, Google's Globally-Distributed Database" Read "Designing Data-intensive applications" 12, The Future of Data Systems IOS development with Swift Read "Designing Data-intensive applications" 10&11, Batch and Stream Processing Read "Designing Data-intensive applications" 9, Consistency and Consensus Read "Designing Data-intensive applications" 8, Distributed System Troubles Read "Designing Data-intensive applications" 7, Transactions Read "Designing Data-intensive applications" 6, Partitioning Read "Designing Data-intensive applications" 5, Replication Read "Designing Data-intensive applications" 3&4, Storage, Retrieval, Encoding Read "Designing Data-intensive applications" 1&2, Foundation of Data Systems Three cases of binary search TAMU Operating System 2 Memory Management TAMU Operating System 1 Introduction Overview in cloud computing 2 TAMU Operating System 7 Virtualization TAMU Operating System 6 File System TAMU Operating System 5 I/O and Disk Management TAMU Operating System 4 Synchronization TAMU Operating System 3 Concurrency and Threading TAMU Computer Networks 5 Data Link Layer TAMU Computer Networks 4 Network Layer TAMU Computer Networks 3 Transport Layer TAMU Computer Networks 2 Application Layer TAMU Computer Networks 1 Introduction Overview in distributed systems and cloud computing 1 A well-optimized Union-Find implementation, in Java A heap implementation supporting deletion TAMU Advanced Algorithms 3, Maximum Bandwidth Path (Dijkstra, MST, Linear) TAMU Advanced Algorithms 2, B+ tree and Segment Intersection TAMU Advanced Algorithms 1, BST, 2-3 Tree and Heap TAMU AI, Searching problems Factorization Machine and Field-aware Factorization Machine for CTR prediction TAMU Neural Network 10 Information-Theoretic Models TAMU Neural Network 9 Principal Component Analysis TAMU Neural Network 8 Neurodynamics TAMU Neural Network 7 Self-Organizing Maps TAMU Neural Network 6 Deep Learning Overview TAMU Neural Network 5 Radial-Basis Function Networks TAMU Neural Network 4 Multi-Layer Perceptrons TAMU Neural Network 3 Single-Layer Perceptrons Princeton Algorithms P1W6 Hash Tables & Symbol Table Applications Stanford ML 11 Application Example Photo OCR Stanford ML 10 Large Scale Machine Learning Stanford ML 9 Anomaly Detection and Recommender Systems Stanford ML 8 Clustering & Principal Component Analysis Princeton Algorithms P1W5 Balanced Search Trees TAMU Neural Network 2 Learning Processes TAMU Neural Network 1 Introduction Stanford ML 7 Support Vector Machine Stanford ML 6 Evaluate Algorithms Princeton Algorithms P1W4 Priority Queues and Symbol Tables Stanford ML 5 Neural Networks Learning Princeton Algorithms P1W3 Mergesort and Quicksort Stanford ML 4 Neural Networks Basics Princeton Algorithms P1W2 Stack and Queue, Basic Sorts Stanford ML 3 Classification Problems Stanford ML 2 Multivariate Regression and Normal Equation Princeton Algorithms P1W1 Union and Find Stanford ML 1 Introduction and Parameter Learning

PHP basics

2017-12-18

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"?>

Creative Commons License
Melon blog is created by melonskin. This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License.
© 2016-2024. All rights reserved by melonskin. Powered by Jekyll.