GET /index.php?catid=3 HTTP/1.1
Host: www.shop.ierg4210.org
POST /admin-process.php HTTP/1.1
Host: secure.shop.ierg4210.org
Content-Length: 37
Content-Type: application/x-www-form-urlencoded
name=Fresh%20Fruits&action=cat_insert
(Note that there are 2 additional request headers)
| Language | Usage |
|---|---|
| 1. PHP | 79.2% |
| 2. ASP.NET | 9.1% |
| 3. Ruby | 4.4% |
| 4. Java | 3.4% |
| 5. Scala | 1.8% |
Ref: W3Techs.com, retrieved on Feb. 17, 2021
chmod 705 to allow read (4) and
execution (1) for public.php, e.g.,
test.php
<?php echo date(); ?>
<?php ... ?>
tags will be kept as it is<?php ... ?>
tags will be executed and be replaced by
its execution results (like output to stdout)$ sign,
e.g., $data, $array$a = 1; $a = 'hello';)hello.php with its content as
follows:
<h1><?php echo "Hello World"; ?></h1>hello.php:
<h1>Hello World</h1><h1>Good morning, <?php echo $name; ?>.</h1><h1>Good morning, <?php echo htmlspecialchars($name); ?>.</h1>htmlspecialchars() escapes
< to
< and > to
>,
etc.| PHP code | Output |
|---|---|
echo "Hello\nWorld"; |
Hello World |
echo "Hello<br/ >World"; |
Hello World |
echo 'Hello\nWorld'; |
Hello\nWorld |
<ul><?php $name="Apple";
echo "<li>" . $name . "</li>";?></ul><?php strlen("hello") == 5 // true
strpos("hello", "l") == 2 // true
$a = ''; empty(a) // true
print_r($array);
?> [])
$fruits = array("apple", "orange", "pineapple");{})
$ages=array("Niki"=>6, "Jon"=>9, "Steve" => 40); $fruits[] = "banana";// create a new element
$fruits[1] = "o2"; // changed orange to o2
$ages["Peter"] = 10; // added a new element
$ages["Niki"]++; // passed her birthday unset($fruits[1]); // o2 is *deleted*
unset($ages["Steve"])// R.I.P. Steve... for ($i = 0, $len = count($fruits); $i < $len; $i++) foreach ($ages as $key => $val)
/* do something with $key and $val */array_push() and array_pop()
implode()
- Join array elements with a string
explode()
- Split a string by string
String.split()/.join()in JavaScript)array_map('callback_fx', array)
callback_fx to the elements of the given arrayssort()
- Sort an array (pass it by reference)array_diff()
- Output different elements (what if no diff.?)Reference: http://php.net/manual/en/control-structures.foreach.php
// Example Call: hello()
function hello() { echo "Hello!"; }// Example Call: hello('Niki')
function hello($name) {
echo "Hello, " . htmlspecialchars($name) . "!"; } // Example Call: hello('Niki') or hello('Niki', 'F')
function hello($name, $sex = 'M') {}
function hello2($name, $sex = 'M', $income = 10000){...}
// Is the function call "hello2('Niki',1000)" legal?
// Is the function call "hello2('Niki',1000)" "meaningful"?<?php readfile('html/header.html'); ?>
<h1>Product Description:</h1>
<!-- Description goes here -->
<?php readfile('html/footer.html');
?><?php include_once('lib/myLib.php'); ?>readfile() is faster than include_once() as
no parsing is needed to look for PHP, e.g., see
hererequire() and require_once()
POST /admin-process.php?action=cat_insert HTTP/1.1
Host: secure.shop.ierg4210.org
Content-Length: 19
Content-Type: application/x-www-form-urlencoded
name=Fresh%20Fruits $_POST['name'] == 'Fresh Fruits' // true;
// Values are auto-urldecoded, '%20' -> ' '
$_GET['action'] == 'cat_insert' // true
$_REQUEST['action'] == 'cat_insert'// true <?php
if ($_REQUEST['action'] == 'cat_insert') {
// See next slide for details
inputValidate($_POST['name'], '/^[\w\- ]+$');
// DB Manipulation with SQL
DB_insertCategory($_POST['name']);
}
?><?php
// Using the same regular expression as done in JavaScript
if (preg_match('/^[\w\-\/][\w\-\/\.]*@[\w\-]+(\.[\w\-]+)*(\.[\w]{2,6})$/',
$_POST['email'])) {
/* Only validated inputs can go for further processing */
} else {
/* reject the input */
exit();
} ?>function ierg4210_cat_fetchall() {
// DB manipulation
global $db;
$db = ierg4210_DB();
$q =$db->prepare("SELECT * FROM categories LIMIT 100;");
if ($q->execute())
return $q->fetchAll(); // i.e., an array of categories
}function ierg4210_cat_insert() {
// input validation or sanitization
if (!preg_match('/^[\w\-, ]+$/', $_POST['name']))
throw new Exception("invalid-name");
// DB manipulation
global $db;
$db = ierg4210_DB();
$q = $db->prepare("INSERT INTO categories (name) VALUES (?)");
return $q->execute(array($_POST['name']));
// will return True/False - whether it is success
}admin.php, and
associate
an unique action name as hidden parameter with each formadmin.php, routes HTTP
requests to a corresponding function based on action nameadmin.phpfunction ierg4210_cat_fetchall() {
/* return an array of categories */
}
function ierg4210_cat_insert() {
/* return true or false to indicate success */
}if (!empty($_REQUEST['action'])) {
header('Content-Type: application/json');
// JSON to be discussed in next slide
try {
// call corresponding function based on action name
$targetFunction = 'ierg4210_' . $_REQUEST['action']
$returnVal = call_user_func($targetFunction)
if ($returnVal === false)
echo json_encode(array('failed'=>true));
else echo 'while(1);'.json_encode(
array('success' => $returnVal));
} catch(Exception $e) {
echo 'while(1);'.json_encode(
array('failed' => $e->getMessage()));
}
} else echo json_encode(array('failed'=>'undefined'));<?php
readfile('html/header.html');
for ($categories=ierg4210_cat_fetchall(), $i=0, $cat;
$cat = $categories[$i]; $i++) {
/* Re-populate the HTML with $cat['catid'] and $cat['name'] */
}
if (ierg4210_cat_insert())
echo '<h2>The category is created successfully.</h2>';
/* Reproduce other HTML snippets here, e.g., forms
*/
readfile('html/footer.html');
?><?php
function ierg4210_cat_fetchall() {
/* return an array of categories */
}
function ierg4210_cat_insert() {
/* return true or false to indicate success */
}
header('Content-Type: application/json');
if (($returnVal=
call_user_func('ierg4210_'.$_REQUEST['action']))===false)
echo json_encode(array('success' => $returnVal)); ?>{"success":[{"catid":"1","name":"Fruits"},
{"catid":"2","name":"Candies"}]}JSON.parse() in JavaScript decodes the JSON output at
client-side:
<script type="text/javascript">
myLib.ajax({url:'admin-process.php?action=cat_fetchall',
success:function(output){
// to decode the returned data into an object
var json = JSON.parse(output);
if (json.success) {
// output each record with proper output sanitizations
for (var i = 0, record; record = json.success[i]; i++) {
somewhere.innerHTML +=
'CatId: ' + parseInt(record.catid)
+ '<br/>' + 'Name: ' + record.name.escapeHTML();
}
} else alert('Error!');
}});
</script>Ref: http://www.json.org
echo()/print()
functions
print_r(),
var_dump()