STAY INFORMED
following content serves as a personal note and may lack complete accuracy or
certainty.
Minimal-Mistakes instruction
Useful vscode Shortcut Keys
Unix Commands
npm Commands
Vim Commands
Git Note
Useful Figma Shortcut Keys
PHP Session
Cookie
Operations on cookies:
- Setting
- Reading
- Deleting
Set Cookie
setcookie(name, value, expire, path, domain, secure, httponly);
e.g.
// $_COOKIE['userid'] is set as Henry 60*60 seconds which is 1 hour.
setcookie('user', 'Henry', time() + 60*60);
echo "Hello, " . $_COOKIE['user'];
First respond will give warning since the cookie is set after the client sends the cookie back on a subsequent request it appear in $_COOKIE.
Second respond
delete cookie
setcookie('user', '');
A cookie set by http://www.example.com/catalog/list.php is sent back with other requests in the catalog directory, such as
- http://www.example.com/catalog/search.php
- http://www.example.com/catalog/detailed/search.php
Not for such as
- http://www.example.com/sell.php
- http://www.example.com/users/profile.php
Session
To use a session in a page, call session_start() at the beginning of your script.
Session data is stored in the $_SESSION auto-global array.
The $_SESSION array is a way of sharing information between pages.
session_start();
if (isset($_SESSION['count'])){
$_SESSION['count'] = $_SESSION['count'] + 1;
}
else{
$_SESSION['count'] = 1;
}
echo "You have looked this page " . $_SESSION['count'] . "times";
simple example using session
processForm($input){
$_SESSION['order'][] = array('menu' => $input['menu'], 'quantity' => $input['quantity'])
}
$menus = array('beef' => 'beef soup', 'chicken' => 'chicken soup', 'pork' => 'pork soup')
if (isset($_SESSION['order']) && (count($_SESSION['order']) > 0)){
echo '<ul>';
foreach ($_SESSION['order'] as $order){
$menu = $menus[$order['menu']];
echo "<li> $order[quantity] of $menu </li>";
}
echo '</ul>';
}
else{
echo "You haven't ordered anything";
}
Login and User Identification
function validateForm(){
$input = array();
$errors = array();
$users = array('a' => 'a123', 'b' => 'b123' ,'c' => 'c123');
$input['username'] = $_POST['username'] ?? '';
if (!array_key_exists($input['username'], $users)){
$errors[] = 'Please enter a valid username and password';
}
else{
$savedPassword = $users[$input['username']];
$submittedPassword = $_POST['password']?? '';
if ($savedPassword != $submittedPassword){
$errors[] = 'Please enter a vlid username and password';
}
}
return array($erros, $input);
}
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
list($errors, $input) = validateForm();
if ($errors){
showForm($errors);
}
else{
echo "Hello, $_SESSION['username']";
}
}
else{
showForm();
}
Use unset() to remove a key and value from $_SESSION.
unset($_SESSION['username']);