Unit 03 - Full Stack Web Development
Unit 03 - Full Stack Web Development
Development
by Dr. Piyush Bagla
PHP
• echo does not have a return value. It simply outputs the specified content to the screen and
does not return anything.
• print has a return value of 1, which means it can be used within expressions or assigned to
variables.
• print can only accept a single parameter, attempting to use multiple parameters will result
in a parse error.
• echo "Hello", "world"; // correct
• print "Hello", "World"; // Error
• echo is generally considered to be marginally faster than print
Display Errors in PHP
Key Differences:
1. Variable Parsing
• Double quotes: Variables inside the string are parsed.
• Single quotes: Variables are not parsed.
2. Special Characters
• Double quotes: Recognizes escape sequences like \n, \t, \\, etc.
• Single quotes: Treats most escape sequences literally, except for \\ and \'.
PHP string
$person = array(
"name" => "Piyush",
"age" => 34,
"city" => "Dehradun"
);
echo $person["name"]; // Output: Piyush
PHP Array
3. Multidimensional Array (array of arrays)
$students = [
["Swastik", 7, "A"],
["Ravi", 8, "B"],
["Neha", 7, "A"]
];
echo $students[0][0]; // Output: Swastik
Most Commonly Used PHP Array Functions
PHP Object
class Car
{
public $color;
public $model;
public function __construct($color, $model)
{
$this->color = $color;
$this->model = $model;
}
public function message()
{
return "My car is a " . $this->color . " " . $this->model . "!";
}
}
$myCar = new Car("red", "Volvo");
var_dump($myCar);
Decision, Looping and Function
• Decision
• if-else
• switch
• Loops
• for
• while
• do-while
• foreach
• Functions
• In PHP, a function can be defined before or after it is called.
Form Processing
HTML form
process.php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST['username'];
$email = $_POST['email'];
Sanitize input:
$name = htmlspecialchars(trim($_POST['username']));
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
Form Processing
Important: Validating and Sanitizing Input
Validate email:
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Invalid email!";
}
filter_var() with FILTER_SANITIZE_EMAIL removes illegal characters (like spaces, quotes, etc.) from the email input.
Form Processing
Validate email
if (filter_var($sanitized, FILTER_VALIDATE_EMAIL)) {
echo "Valid email after sanitization!";
} else {
echo "Still invalid.";
}
Form Processing
Validate email
$email = "<script>alert('hack')</script>@gmail.com";
$sanitized = filter_var($email, FILTER_SANITIZE_EMAIL);
echo $sanitized;
_GET
_POST
_REQUEST
_COOKIE
_ SESSION and more
COOKIES in PHP
Cookies are text files that contain small amounts of data, which are sent
from a server to a user's web browser and then returned to the server each
time the browser requests a page from the server. They can store various
types of information, such as user preferences, login status, and tracking
identifiers.
Cookies
How are Cookies Sent?
1.Setting Cookies: When a server wants to store a cookie on the user's device, it sends
an HTTP header with the Set-Cookie directive. This header includes the cookie name,
value, expiration date, path, domain, and security attributes.
2.Sending Cookies Back: When the user makes subsequent requests to the same
server, the browser automatically includes the relevant cookies in the HTTP request
headers. This allows the server to recognize the user and retrieve any stored
information.
Cookies
setcookie(name, value, expire, path, domain, secure, httponly);
path
If the cookie stores the user's location and you set it with the path /, then:
• Any page on your website — like Home, About Us, Contact Us — can read that
location cookie.
Cookies
setcookie(name, value, expire, path, domain, secure, httponly);
Httponly
It protects your cookie (especially things like session IDs or login tokens) from:
$name = "user";
$value = "John";
$expire = time() + (60 * 60 * 24 * 30); // 30 days from now
$path = "/"; // available in the entire domain
$domain = ”.example.com"; // available for the domain and all subdomains
$secure = true; // available only over HTTPS
$httponly = true; // accessible only through HTTP (not JavaScript)
• If the path parameter is set to "/account", meaning the cookie will only be available
within the "/account" directory and its subdirectories.
• The domain parameter is set to "example.com", meaning the cookie will only be
available for the domain "example.com" and not for any subdomains or other
domains.
Homework
Summary of the Flow in Terms of Session and Cookie:
Data Access Read and written by the client and server. Managed primarily by the server; accessed via session ID.
Security Vulnerable to XSS attacks; can be tampered with. More secure as data is stored on the server.
Persistence Can be persistent or session-based; set with an expiration date. Typically expires after a set time or when the session ends.
Used for storing small, non-sensitive data, such as user Used for storing sensitive data like user authentication, session
Use Case
preferences, shopping cart, or tracking data. data, or complex data structures.
Can be accessed via client-side scripts (JavaScript), increasing Not directly accessible to client-side scripts, providing better
Accessibility
risk of exposure. security.
Session ID May hold session ID for server-side session tracking. Identified by a session ID, typically stored in a cookie.
Session
Note: The session_start() function must be the very first thing in your document before any
HTML tags.
1. Start a session
2. Set session variables
3. Get the session variable values
4. Modify the session variables
5. Destroy session
Remove all session variables first; then, only the session will be
destroyed
login.php
<?php
session_start();
$valid_username = "admin";
$valid_password = "password123";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST['username'];
$password = $_POST['password'];
continue
<!DOCTYPE html>
<html>
<head><title>Login</title></head>
<body>
<h2>Login Page</h2>
<form method="POST” action=“login.php”>
Username: <input type="text" name="username" required><br><br>
Password: <input type="password" name="password" required><br><br>
<input type="submit" value="Login">
</form>
</body>
</html>
dashboard.php
<?php
session_start();
if (!isset($_SESSION['username'])) {
header("Location: login.php");
exit();
}
?>
<!DOCTYPE html>
<html>
<head><title>Dashboard</title></head>
<body>
<h2>Welcome, <?php echo $_SESSION['username']; ?>!</h2>
<p>This is your dashboard.</p>
<a href="logout.php">Logout</a>
</body>
</html>
logout.php
<?php
session_start();
session_unset(); // Remove all session variables
session_destroy(); // Destroy the session
header("Location: login.php");
exit();
Database & PHP
• PDO will work on 12 different database systems, whereas MySQLi will only
work with MySQL databases.
- So, if you have to switch your project to use another database, PDO makes
the process easy. You only have to change the connection string and a few
queries. With MySQLi, you will need to rewrite the entire code - queries
included.
$username = "username";
- This line specifies the username needed to authenticate with the MySQL server.
$password = "password";
- This line specifies the password for the specified username.
// Create connection
$conn = new mysqli($servername, $username, $password);
- This line creates a new instance of the MySQLi class, which establishes a connection to the MySQL database
server using the server name, username, and password specified earlier.
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error); }
- This block checks whether the connection to the MySQL server was successful. If there is a connection error
(`connect_error` property is set), the script terminates (`die`) and outputs an error message indicating the
reason for the connection failure.
try {
$conn = new PDO("mysql:host=$servername;dbname=gehu", $username, $password);
/*The first argument specifies the DSN (Data Source Name), which includes the database type (mysql), the hostname ($servername), and
the database name (gehu). The second and third arguments specify the MySQL username and password, respectively.*/
real_escape_string()
Prepare Statement ()
Protection from SQL Injection (Method 2)
• i - Integer
• d - Double
• s - String
• b - Blob
PHP MySQL Prepared Statements
Prepared statements are very useful against SQL injections.
A prepared statement is a feature used to execute the same (or similar) SQL statements
repeatedly with high efficiency.
1.Prepare: An SQL statement template is created and sent to the database. Certain values are left
unspecified, called parameters (labeled "?"). Example: INSERT INTO MyGuests VALUES(?, ?, ?)
2.The database parses, compiles, and performs query optimization on the SQL statement
template, and stores the result without executing it
3.Execute: At a later time, the application binds the values to the parameters, and the database
executes the statement. The application may execute the statement as many times as it wants
with different values
PHP MySQL Prepared Statements
• Prepared statements reduce parsing time as the preparation of the query is done only
once (although the statement is executed multiple times)
• Bound parameters minimize bandwidth to the server as you need to send only the
parameters each time, and not the whole query.
• Prepared statements are one of the most effective ways to prevent SQL injection
attacks, which occur when an attacker attempts to manipulate the query by inserting
malicious SQL code through user input fields.
Prepared Statements
// prepare and bind
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES
(?, ?, ?)");
$stmt->bind_param("sss", $firstname, $lastname, $email);
$firstname = ”Danish";
$lastname = ”Khan";
$email = ”[email protected]";
$stmt->execute();
$stmt->close();
$conn->close();