0% found this document useful (0 votes)
20 views

PHP Complete Unit3 Notes

php Unit3 notes

Uploaded by

sankarkumarkvdc
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

PHP Complete Unit3 Notes

php Unit3 notes

Uploaded by

sankarkumarkvdc
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 29

Unit-3

SUPER GLOBAL VARIABLES:


$_GET Contains information about variables passed through a URL or a form.

$_POST Contains information about variables passed through a form.

$_COOKIE Contains information about variables passed through a Cookie.

$_SESSION Contains information about variables passed through a Session.

$_SERVER Contains information about the Server environment.

$_ENV Contains information about the Environment Variables.

$_FILES Contains information about files upload to the Script.

$_ REQUEST Contains information about variables passed through the form or URL.

About Server Information:

<html>

<head>

</head>

<body>

<ul> <li> Host: <?php echo $_SERVER['HTTP_POST']; ?> </li>

<li> Document Root: <?php echo $_SERVER['DOCUMENT_ROOT'];?></li>

<li> Server Port: <?php echo $_SERVER['SERVER_PORT'];?></li>

<li> Current File Dir: <?php echo $_SERVER['PHP_SELF'];?></li>

<li> Request URI: <?php echo $_SERVER['REQUEST_URI'];?></li>

<li> Server Software: <?php echo $_SERVER['SERVER_SOFTWARE'];?></li>

<li> Client info: <?php echo $_SERVER['HTTP_USER_AGENT'];?> </li>

<li> Remote Address: <?php echo $_SERVER['REMOTE_ADDR'];?></li>

<li> Remote Port: <?php echo $_SERVER['REMOTE_PORT'];?></li>

</body>
</html>

Creating Forms and Reading Form Data using POST Method:

- We can create form using HTML <form> tag .


- The <form> tag action attribute indicates , to where the form data will be submitted.
- The <form> tag method=POST attribute indicates that the form data should be sent
using the HTTP POST method.
- The following example creates a simple form and collects user name and address data and
submitted to sample1.php script.

<html>

<head>

<title>A simple HTML form</title>

</head>

<body>

<form action="sample1.php" method="POST">

Name: <br>

<input type="text" name="user">

<br>

Address: <br>

<textarea name="address" rows="5" cols="40"></textarea>

<br>

<input type="submit" value="Submit">

</form>

</body>

</html>

Reading Form Data using POST Method:

<html>

<head>

<title> Reading input from the form</title>


</head>

<body>

<?php

echo "Welcome <b>$_POST[user]</b><P>\n\n";

echo "Your address is:<P>\n\n<b>$_POST[address]</b>";

?>

</body>

</html>

Creating Forms and Reading Form Data using GET Method:

- We can create form using HTML <form> tag .


- The <form> tag action attribute indicates , to where the form data will be submitted.
- The <form> tag method=GET attribute indicates that the form data should be sent using
the HTTP GET method and the data will be appended to the URL as query parameters.
- The following example creates a simple form and collects user name and address data and
submitted to sample1.php script.

<html>

<head>

<title>A simple HTML form</title>

</head>

<body>

<form action="sample1.php" method="GET">

Name: <br>

<input type="text" name="user">

<br>

Address: <br>

<textarea name="address" rows="5" cols="40"></textarea>

<br>
<input type="submit" value="Submit">

</form>

</body>

</html>

Reading Form Data using GET Method:

<html>

<head>

<title> Reading input from the form</title>

</head>

<body>

<?php

echo "Welcome <b>$_GET[user]</b><P>\n\n";

echo "Your address is:<P>\n\n<b>$_GET[address]</b>";

?>

</body>

</html>

$_GET

- Data is appended to the URL


- NOT Secure
- Limited Characters
- GET requests can be cached
- Better for a Search Page.

$_POST

- Data is packed inside the Body of the HTTP Request


- More Secure
- No data Limit
- POST Requests are not cached.
- Better for submitting Credentials.
Accessing Form Input with User defined Arrays

- 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>

<title>An HTML form including a SELECT element</title>

</head>

<body>

<form action="sample2.php" method="POST">

Name: <br>

<input type="text" name="user">

<br>

Address: <br>

<textarea name="address" rows="5" cols="40"></textarea>

<br>

Pick Products: <br>

<select name="products[]" multiple>

<option>Sonic Screwdriver</option>

<option>Tricorder</option>

<option>ORAC AI</option>

<option>HAL 2000</option>

</select>

<br><br>

<input type="submit" value="hit it!">

</form>
</body>

</html>

sample2.php

<html>

<head>

<title> Reading input from the form </title>

</head>

<body>

<?php

print "Welcome <b>$_POST[user]</b><p>\n\n";

print "Your address is:<p>\n\n<b>$_POST[address]</b><p>\n\n";

print "Your product choices are:<p>\n\n";

if (!empty($_POST['products'])) {

print "<ul>\n\n";

foreach ($_POST['products'] as $value) {

print "<li>$value\n";

print "</ul>";

?>

</body>

</html>
Combining HTML and PHP code on a Single Page

- PHP Code is normally mixed with HTML Tags


- PHP is an embedded language meaning that you can jump between raw HTML code
and PHP with out sacrificing readability.
- In order to embed PHP code with HTML code, The PHP must be set apart using PHP
start and end tags.

<?php

$num_to_guess = 42;

$message = "";

if (!isset($_POST['guess'])) {

$message = "Welcome to the guessing machine!";

} elseif ($_POST['guess'] > $num_to_guess) {

$message = "$_POST[guess] is too big! Try a smaller number";

} elseif ($_POST['guess'] < $num_to_guess) {

$message = "$_POST[guess] is too small! Try a larger number";

} else { // must be equivalent

$message = "Well done!";

?>

<html>

<head>

<title> A PHP number guessing script</title>

</head>

<body>

<h1>

<?php print $message ?>

</h1>
<form action="<?php print $_SERVER['PHP_SELF'] ?>" method="POST">

Type your guess here: <input type="text" name="guess">

</form>

</body>

</html>

Using Hidden Fields to save state:

- 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 action="math2.php" method="post">

<label for="fn">First Number</label>

<input type="text" name="fn" value=" " id="fn">

<p><input type="submit" value="Continue&arr;"></p>

</form>

</body>

math2.php

<body>

<h1>Second Number</h1>

<form action="math3.php" method="post">

<input type="hidden" name="fn" value="<?php echo $_POST['fn']?>" id="fn">


<label for="sn">Second Number</label>

<input type="text" name="sn" value=" " id="sn">

<p><input type="submit" value="Continue &arr;"></p>

</form>

</body>

math3.php

<?php

$ans=$_POST['fn']+$_POST['sn'];

?>

<body>

<h1> Answer is..... </h1>

<?php

echo "The Answer is $ans";

?>

</body>

Redirecting the user

- 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

- This example uses the built-in mail() function in PHP.


- Make sure your server is configured to send emails using PHP's mail() function
- syntax of mail() function: mail($to, $email_subject, $email_body, $headers)

<?php

if(isset($_POST['submit']))

$to=$_POST['to'];

$subject=$_POST['subject'];

$message=$_POST['message'];

$header="From:Sankar";

if(mail($to,$subject,$message,$header))

echo "Email sent successfully";

else

echo "Email failed";

?>

<html>

<body>

<h1>Send Email with PHP</h1>

<form method="post">
<pre>

To: <input type="text" name="to" placeholder="To..."/>

Subject: <input type="text" name="subject" placeholder="Subject..."/>

Message: <input type="text" name="message" placeholder="Message..."/>

<button name="submit">Send</button>

</pre>

</form>

</body>

</html>

Working with File Uploads

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.

$_FILES['filetoupload']['tmp_name'] is the temporary file path on the server where PHP


stores the uploaded file.
$target_path is the destination path where the file will 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.

$_FILES['filetoupload']['name'] contains the original name of the uploaded file.

basename($_FILES['filetoupload']['name']) strips any directory information and returns just


the file name.

uploadform.html

<html>

<body>

<form action="uploader.php" method="post" enctype="multipart/form-data">

Select File:

<input type="file" name="filetoupload"/>

<input type="submit" value="Upload Image" name="submit"/>

</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))

echo "File uploaded successfully";

else{

echo "sorry, file not uploaded,please try again";

?>
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.

- **Accessing a Cookie**: Use the `$_COOKIE` superglobal array.

- **Deleting a Cookie**: Set the cookie's expiration date to a time in the past.

### Setting a Cookie in PHP

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

setcookie(name, value, expire, path, domain, secure, httponly);

?>

- **name**: The name of the cookie.

- **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.

- **domain**: The (sub)domain that the cookie is available to.

- **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.

### Example: Setting a Cookie

<?php

$cookiename="user1";

$cookievalue="siva";

setcookie($cookiename,$cookievalue,time()+86400*30,"/");

?>

<html>

<body>

<?php

if(isset($_COOKIE[$cookiename]))

echo "cookie - " . "$cookiename" . " is set";

else

echo "cookie - " . "$cookiename" . " is not set";

?>

</body>

</html>

### Accessing a Cookie

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 {

echo "User cookie is not set.";

?>

### Deleting a Cookie

To delete a cookie, you set its expiration date to a time in the past.

<?php

setcookie("user1","",time()-3600,"/");

?>

<html>

<body>

<?php

echo "Cookie user1 is deleted";

?>

</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.

### How Sessions Work

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.

2. **Storing Data in a Session**: Data is stored in a superglobal array called `$_SESSION`.

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.

- **Start a Session** with `session_start()` before any output.

- **Store Data** in the `$_SESSION` superglobal array.

- **Access and Modify Data** using the `$_SESSION` array.

- **Unset Session Variables** with `unset()`.

- **Destroy a Session** with `session_destroy()`.

### Basic Session Operations

#### Starting a Session

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_start(); // Start the session

// Store data in the session

$_SESSION["username"] = "JohnDoe";
$_SESSION["email"] = "[email protected]";

// Accessing session data

echo "Username: " . $_SESSION["username"];

echo "Email: " . $_SESSION["email"];

?>

#### Storing Data in a Session

Data can be stored in the `$_SESSION` superglobal array. The array is associative, so you can
store data using key-value pairs.

<?php

session_start(); // Start the session

// Store data in the session

$_SESSION["username"] = "JohnDoe";

$_SESSION["email"] = "[email protected]";

?>

#### Accessing Session Data

Access session data using the `$_SESSION` superglobal array.

<?php

session_start(); // Start the session

// Access session data

echo "Username: " . $_SESSION["username"];

echo "Email: " . $_SESSION["email"];

?>
#### Modifying Session Data

You can modify session data by reassigning values to the `$_SESSION` array.

<?php

session_start(); // Start the session

// Modify session data

$_SESSION["username"] = "JaneDoe";

echo "Updated Username: " . $_SESSION["username"];

?>

#### Unsetting Session Variables

To unset a session variable, use the `unset()` function.

<?php

session_start(); // Start the session

// Unset a session variable

unset($_SESSION["username"]);

// Check if the variable is unset

if (!isset($_SESSION["username"])) {

echo "Username is not set.";

?>

#### Destroying a Session

To destroy a session and delete all session data, use `session_destroy()`. This function should
be called after `session_start()`.
<?php

session_start(); // Start the session

// Destroy the session

session_destroy();

// Check if the session is destroyed

if (session_status() == PHP_SESSION_NONE) {

echo "Session is destroyed.";

?>

Passing Session IDs in the Query String

- There are two methods to pass a session id


1. Cookies
2. URL parameter
- The session module supports both methods. Cookies are optimal. But, because they
are not always available, we also provide an alternative way.
- The second method embeds the session ID directly into URL.

The following is the example.

Page1.php

<?php

$color='blue';

echo 'The Variable $color contains the word <b>'.$color.'</b>';

?>

<hr>

<a href="page2.php?color=<?php echo $color;?>">a link to page2</a>


page2.php

<?php

$color=$_GET['color'];

echo 'The variabled $color contains the word <b>' . $color . '</b>';

?>

<hr>

<a href="page1.php">a Link t page1</a>


Using Sessions in an Environment with Registered Users

Using sessions in an environment with registered users is a common practice for


managing user authentication and maintaining state across multiple pages. Here's a
detailed explanation of how to implement sessions in a typical user registration and login
system in PHP.

### Step-by-Step Implementation

1. **Setup a Database**:

- Create a database to store user information.

- Example table structure:

```sql

CREATE TABLE users (

id INT AUTO_INCREMENT PRIMARY KEY,

username VARCHAR(50) NOT NULL UNIQUE,

password VARCHAR(255) NOT NULL,

email VARCHAR(100) NOT NULL

);

```

2. **Registration Script** (`register.php`):

- A form to collect user information.

- 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'];

$password = password_hash($_POST['password'], PASSWORD_DEFAULT); // Hash


the password

$email = $_POST['email'];

// Insert user data into database

$sql = "INSERT INTO users (username, password, email) VALUES (?, ?, ?)";

if ($stmt = $conn->prepare($sql)) {

$stmt->bind_param("sss", $username, $password, $email);

if ($stmt->execute()) {

echo "Registration successful.";

} else {

echo "Error: " . $stmt->error;

$stmt->close();

$conn->close();

?>

<!-- Registration Form -->

<form method="post" action="register.php">


Username: <input type="text" name="username" required><br>

Password: <input type="password" name="password" required><br>

Email: <input type="email" name="email" required><br>

<input type="submit" value="Register">

</form>

```

3. **Login Script** (`login.php`):

- A form to collect login credentials.

- PHP code to verify the credentials, start a session, and store user information in the
session.

```php

<?php

session_start(); // Start the session

require 'config.php';

if ($_SERVER["REQUEST_METHOD"] == "POST") {

$username = $_POST['username'];

$password = $_POST['password'];

// Retrieve user data from the database

$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->bind_result($id, $username, $hashed_password);

$stmt->fetch();

if (password_verify($password, $hashed_password)) {

// Password is correct, start a new session

$_SESSION["loggedin"] = true;

$_SESSION["id"] = $id;

$_SESSION["username"] = $username;

header("Location: welcome.php"); // Redirect to welcome page

} else {

echo "Invalid password.";

} else {

echo "No account found with that username.";

$stmt->close();

$conn->close();

?>

<!-- Login Form -->


<form method="post" action="login.php">

Username: <input type="text" name="username" required><br>

Password: <input type="password" name="password" required><br>

<input type="submit" value="Login">

</form>

```

4. **Welcome Page** (`welcome.php`):

- A page that is accessible only to logged-in users.

- PHP code to check if the user is logged in by verifying session variables.

```php

<?php

session_start(); // Start the session

// Check if the user is logged in

if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true) {

header("Location: login.php"); // Redirect to login page if not logged in

exit;

?>

<!DOCTYPE html>

<html>

<head>

<title>Welcome</title>
</head>

<body>

<h1>Welcome, <?php echo htmlspecialchars($_SESSION["username"]); ?>!</h1>

<p><a href="logout.php">Logout</a></p>

</body>

</html>

```

5. **Logout Script** (`logout.php`):

- PHP code to destroy the session and redirect the user to the login page.

```php

<?php

session_start(); // Start the session

// Unset all session variables

$_SESSION = array();

// Destroy the session

session_destroy();

// Redirect to login page

header("Location: login.php");

exit;

?>

```
6. **Database Configuration File** (`config.php`):

- Contains the database connection details.

```php

<?php

$servername = "localhost";

$username = "root";

$password = "";

$dbname = "test";

// Create connection

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection

if ($conn->connect_error) {

die("Connection failed: " . $conn->connect_error);

?>

```

### Summary

1. **Database**: Store user credentials securely.

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.

4. **Session Management**: Use `$_SESSION` to store and access user data.

5. **Protected Pages**: Check session variables to restrict access to certain pages.

6. **Logout**: Destroy the session to log out the user.

By following these steps, you can effectively use sessions in PHP to manage registered
users and maintain state across multiple requests.

You might also like