PHP

PHP using PDO extension

The codes are from

  1. CSE405: Server Programming course
  2. my projects: CAL Map
  3. PDO Tutorial

Include other php

include_once "header.php";
require_once "config.php";
To include with absolute path
<?php
    $rootdir = realpath($_SERVER["DOCUMENT_ROOT"]);
    include "$rootdir/header.php";
?>

PHP Code Structure

<?php
try {

} catch (PDOException $e) {
exit($e->getMessage());
}
?>

Connect Server

try {
$dsn = "mysql:host=$host;dbname=$db;charset=utf8mb4";
$opt = [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES   => false,
];
$pdo = new PDO($dsn, $user, $pass, $opt);
} catch(PDOException $ex) {
    echo "Error occured during connecting to the server";
}
  • dsn: Data Source Name
  • pdo: PHP Data Object

alternative name of pdo

  • dbh: DataBase Handling
  • sth: Statement Handling

Login

Send the login information through <Form> Attribute of HTML to login.php. For example,

<form action="login.php" method="post">
    Username: <input type="text"     value = "alice" name="username" size="36" /> <br>
    Password: <input type="password" value = "1234"  name="password" size="36" /> <br>
              <input type="submit"   value = "Submit" />
</form>

login.php collects the ID and password by

$username = $_POST['username'];
$password = $_POST['password'];

With the inputs, compare them with Database.

    $stmt = $pdo->prepare("SELECT password FROM users WHERE id = :username");
    $stmt->bindParam(':username', $id);
    $stmt->execute();
    if ($stmt->rowCount() == 0) {         // When Nothing is found
        header('Location: ./index.php');
        exit();
    }

    $row = $stmt->fetch();
    $actualPassword = $row["password"];

    if ( $actualPassword != $password ) {
        header('Location: ./index.php');
        exit();
    }

The authentication is complete, so post the user ID into the session and go to next page.

    session_start();
    $_SESSION['username'] = $username;
    header('Location: ./nextpage.php');
    exit();

*** exit() must be followed after header();

Logout

<?php 
    // The following code can be used to log out a user by destroying the current session.
    // The code is taken from http://php.net/session_destroy

    // Initialize the session.
    // If you are using session_name("something"), don't forget it now!
    session_start();

    // Unset all of the session variables.
    $_SESSION = array();

    // If it's desired to kill the session, also delete the session cookie.
    // Note: This will destroy the session, and not just the session data!
    if (ini_get("session.use_cookies")) {
        $params = session_get_cookie_params();
        setcookie(session_name(), '', time() - 42000,
            $params["path"], $params["domain"],
            $params["secure"], $params["httponly"]
        );
    }

    // Finally, destroy the session.
    session_destroy();
    header("Location: ./index.php");
?>

If Logged In or Not

Logout Button

<form action="logout.php" method="post">
    <input type="submit" value="logout" />
</form>

Logout.php

if (!isset($_SESSION['username'])) {
    ?> <form action="login.php" method="post">
    Username: <input type="text"     value = "testuser" name="username" size="36" /> <br>
    Password: <input type="password" value = "1111"  name="password" size="36" /> <br>
              <input type="submit"   value = "Submit" />
    </form> <?php
}
else {
    print("Your are logged in");
    ?>
    <form action="logout.php" method="post">
        <input type="submit" value="logout" />
    </form>
    <?php
}

Send Variable with URL

To send with <a>
<a href="https://cse405-chid9202.c9users.io/blog/viewblog.php?id=testuser">testuser</a><br>
To send with <form>
<form action="editblog.php?id=<?php echo $id; ?>" method="post">
    <input type="submit" value="edit" />
</form>
To receive from URL
$id = $_POST['id']
$id = $_GET['id'];

use GET when someone is requesting data from your application

use POST when someone is pushing data to your application

avoid to use request

To receive from ajax
$row = $stmt->fetch() or exit("fetch failed."); //stmt contains result of a query
$counter = $row["count"];

$response = array(count => $count); 

print(json_encode($response));

Respond with JSON

create an object. Chrome generates error message with out new stdClass() construction, when the variable is not initalized.

if (!isset($myObj)) $myObj = new stdClass();

Put data into the object

$myObj->id = $id;
$myObj->title = $title;
$myObj->date = $date;
$myObj->count = $count;

Send

$myJSON = json_encode($myObj);

results matching ""

    No results matching ""