PHP Complete Unit3 Notes
PHP Complete Unit3 Notes
$_ REQUEST Contains information about variables passed through the form or URL.
<html>
<head>
</head>
<body>
</body>
</html>
<html>
<head>
</head>
<body>
Name: <br>
<br>
Address: <br>
<br>
</form>
</body>
</html>
<html>
<head>
<body>
<?php
?>
</body>
</html>
<html>
<head>
</head>
<body>
Name: <br>
<br>
Address: <br>
<br>
<input type="submit" value="Submit">
</form>
</body>
</html>
<html>
<head>
</head>
<body>
<?php
?>
</body>
</html>
$_GET
$_POST
- Accessing form input using user-defined arrays allows you to group related form inputs
together in a structured manner.
- The following example shows The form with user defined array and pass the form
data to sample2.php.
<html>
<head>
</head>
<body>
Name: <br>
<br>
Address: <br>
<br>
<option>Sonic Screwdriver</option>
<option>Tricorder</option>
<option>ORAC AI</option>
<option>HAL 2000</option>
</select>
<br><br>
</form>
</body>
</html>
sample2.php
<html>
<head>
</head>
<body>
<?php
if (!empty($_POST['products'])) {
print "<ul>\n\n";
print "<li>$value\n";
print "</ul>";
?>
</body>
</html>
Combining HTML and PHP code on a Single Page
<?php
$num_to_guess = 42;
$message = "";
if (!isset($_POST['guess'])) {
?>
<html>
<head>
</head>
<body>
<h1>
</h1>
<form action="<?php print $_SERVER['PHP_SELF'] ?>" method="POST">
</form>
</body>
</html>
- Using hidden fields in HTML forms is a common technique to save state between
requests in PHP.
- Hidden fields allow you to store data that you want to send along with the form
submission but do not want to be visible to the user. This is useful for maintaining
state information.
math1.php
<body>
<h1>First Number</h1>
</form>
</body>
math2.php
<body>
<h1>Second Number</h1>
</form>
</body>
math3.php
<?php
$ans=$_POST['fn']+$_POST['sn'];
?>
<body>
<?php
?>
</body>
- The header function in PHP can be used to redirect the user from one page to
another.
- The website to which the page needs to be redirected is specified in the header
function
- exit statement after header function is mandatory.
<?php
header("Location:http://www.google.com");
exit;
?>
Sending Mail on Form Submission
<?php
if(isset($_POST['submit']))
$to=$_POST['to'];
$subject=$_POST['subject'];
$message=$_POST['message'];
$header="From:Sankar";
if(mail($to,$subject,$message,$header))
else
?>
<html>
<body>
<form method="post">
<pre>
<button name="submit">Send</button>
</pre>
</form>
</body>
</html>
move_uploaded_file()
The move_uploaded_file() function is a built-in PHP function used to move an uploaded file
to a new location. It takes two parameters:
1. $filename: The temporary file path of the uploaded file on the server (from the
$_FILES superglobal).
2. $destination: The new location where the file should be moved, including the file
name.
target_path
In your example, $target_path is a variable that holds the full path where the uploaded file
should be moved. It combines the directory path with the file name.
"c:/xampp/htdocs/test/uploads/" is the directory where you want to store the
uploaded files.
basename($_FILES['filetoupload']['name']) gets the file name of the uploaded file.
$target_path . basename($_FILES['filetoupload']['name']) concatenates the directory
path and the file name to form the complete path for the uploaded file.
basename()
The basename() function returns the base name of a given path. In this context, it is used to
extract the file name from the full path provided by the $_FILES superglobal.
uploadform.html
<html>
<body>
Select File:
</form>
</body>
</html>
uploader.php
<?php
$target_path="c:/xampp/htdocs/test/uploads/";
$target_path=$target_path.basename($_FILES['filetoupload']['name']);
if(move_uploaded_file($_FILES['filetoupload']['tmp_name'],$target_path))
else{
?>
Working with Cookies:
Cookies are small pieces of data that are stored on the user's computer by their web
browser while they are browsing a website. They are often used to store user preferences,
session information, or tracking data. In PHP, cookies can be set, accessed, and deleted using
specific functions.
- **Cookies**: Small pieces of data stored on the user's computer to keep track of stateful
information.
- **Setting a Cookie**: Use the `setcookie()` function to set a cookie before any output is
sent to the browser.
- **Deleting a Cookie**: Set the cookie's expiration date to a time in the past.
To set a cookie in PHP, you use the `setcookie()` function. The `setcookie()` function must be
called before any output is sent to the browser, which means it should be placed before any
HTML or echo statements.
### Syntax
<?php
?>
- **value**: The value of the cookie. This value is stored on the client's computer.
- **expire**: The expiration date of the cookie in UNIX timestamp format. If this parameter
is not set, the cookie will expire at the end of the session (when the browser closes).
- **path**: The path on the server in which the cookie will be available. If set to '/', the
cookie will be available within the entire domain.
- **secure**: Indicates that the cookie should only be transmitted over a secure HTTPS
connection.
- **httponly**: When `true`, the cookie will be accessible only through the HTTP protocol,
not via JavaScript.
<?php
$cookiename="user1";
$cookievalue="siva";
setcookie($cookiename,$cookievalue,time()+86400*30,"/");
?>
<html>
<body>
<?php
if(isset($_COOKIE[$cookiename]))
else
?>
</body>
</html>
Once a cookie is set, it can be accessed using the `$_COOKIE` superglobal array.
<?php
if(isset($_COOKIE["user"])) {
echo "User is: " . $_COOKIE["user"];
} else {
?>
To delete a cookie, you set its expiration date to a time in the past.
<?php
setcookie("user1","",time()-3600,"/");
?>
<html>
<body>
<?php
?>
</body>
</html>
Working with Sessions
Sessions in PHP provide a way to store data on the server side, making it possible to
maintain stateful information across multiple requests from the same user. Unlike cookies,
which store data on the client side, session data is stored on the server and only a session
identifier is stored in a cookie on the client's browser.
1. **Starting a Session**: When a session is started, PHP generates a unique session ID and
sends it to the client's browser as a cookie.
3. **Accessing Session Data**: Session data can be accessed and modified throughout the
user's session.
4. **Ending a Session**: A session can be destroyed to log out a user or clear session data.
- **Sessions** are used to store data on the server side, allowing you to maintain stateful
information across multiple page requests.
To start a session, use `session_start()`. This function must be called at the beginning of the
script, before any output is sent to the browser.
<?php
$_SESSION["username"] = "JohnDoe";
$_SESSION["email"] = "[email protected]";
?>
Data can be stored in the `$_SESSION` superglobal array. The array is associative, so you can
store data using key-value pairs.
<?php
$_SESSION["username"] = "JohnDoe";
$_SESSION["email"] = "[email protected]";
?>
<?php
?>
#### Modifying Session Data
You can modify session data by reassigning values to the `$_SESSION` array.
<?php
$_SESSION["username"] = "JaneDoe";
?>
<?php
unset($_SESSION["username"]);
if (!isset($_SESSION["username"])) {
?>
To destroy a session and delete all session data, use `session_destroy()`. This function should
be called after `session_start()`.
<?php
session_destroy();
if (session_status() == PHP_SESSION_NONE) {
?>
Page1.php
<?php
$color='blue';
?>
<hr>
<?php
$color=$_GET['color'];
echo 'The variabled $color contains the word <b>' . $color . '</b>';
?>
<hr>
1. **Setup a Database**:
```sql
);
```
- PHP code to handle form submission, hash the password, and store the user data in
the database.
```php
<?php
// Include database configuration file
require 'config.php';
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST['username'];
$email = $_POST['email'];
$sql = "INSERT INTO users (username, password, email) VALUES (?, ?, ?)";
if ($stmt = $conn->prepare($sql)) {
if ($stmt->execute()) {
} else {
$stmt->close();
$conn->close();
?>
</form>
```
- PHP code to verify the credentials, start a session, and store user information in the
session.
```php
<?php
require 'config.php';
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT id, username, password FROM users WHERE username = ?";
if ($stmt = $conn->prepare($sql)) {
$stmt->bind_param("s", $username);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows == 1) {
$stmt->fetch();
if (password_verify($password, $hashed_password)) {
$_SESSION["loggedin"] = true;
$_SESSION["id"] = $id;
$_SESSION["username"] = $username;
} else {
} else {
$stmt->close();
$conn->close();
?>
</form>
```
```php
<?php
exit;
?>
<!DOCTYPE html>
<html>
<head>
<title>Welcome</title>
</head>
<body>
<p><a href="logout.php">Logout</a></p>
</body>
</html>
```
- PHP code to destroy the session and redirect the user to the login page.
```php
<?php
$_SESSION = array();
session_destroy();
header("Location: login.php");
exit;
?>
```
6. **Database Configuration File** (`config.php`):
```php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
// Create connection
// Check connection
if ($conn->connect_error) {
?>
```
### Summary
2. **Registration**: Create a user registration form, hash passwords, and store user
data.
3. **Login**: Create a login form, verify credentials, and start a session.
By following these steps, you can effectively use sessions in PHP to manage registered
users and maintain state across multiple requests.