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

Chapter 3 _ PHP File

The document provides an overview of PHP file handling, including file uploads, downloads, cookies, and sessions. It details how to create HTML forms for file uploads, manage uploaded files using the $_FILES array, and handle file downloads with headers. Additionally, it explains the creation, retrieval, and destruction of cookies and session variables, along with a comparison between cookies and sessions.

Uploaded by

sujaltrivedib
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Chapter 3 _ PHP File

The document provides an overview of PHP file handling, including file uploads, downloads, cookies, and sessions. It details how to create HTML forms for file uploads, manage uploaded files using the $_FILES array, and handle file downloads with headers. Additionally, it explains the creation, retrieval, and destruction of cookies and session variables, along with a comparison between cookies and sessions.

Uploaded by

sujaltrivedib
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

1 Chapter 3 : PHP File

Chapter 3 : PHP File

PHP file upload


A PHP script can be used with a HTML form to allow users to upload files to the server. Initially
files are uploaded into a temporary directory and then relocated to a target destination by a
PHP script.

Information in the phpinfo.php page describes the temporary directory that is used for file
uploads as upload_tmp_dir and the maximum permitted size of files that can be uploaded is
stated as upload_max_filesize. These parameters are set into PHP configuration file php.ini

For creating HTML form to upload a file , method attribute must be set to post and enctype
attribute is set to multipart/form-data.

There is one global PHP variable called $_FILES. This variable is an associate double dimension
array and keeps all the information related to uploaded file. So if the value assigned to the
input's name attribute in uploading form was file, then PHP would create following five
variables −

● $_FILES['file']['tmp_name'] : the uploaded file in the temporary directory on the web


server.

● $_FILES['file']['name'] : the actual name of the uploaded file.

● $_FILES['file']['size'] : the size in bytes of the uploaded file.

● $_FILES['file']['type'] : the MIME type of the uploaded file.

● $_FILES['file']['error'] : the error code associated with this file upload.

The move_uploaded_file() function moves the uploaded file to a new location.

Syntax : move_uploaded_file(source, destination)

Example 1 :

<html>

<body>

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


2 Chapter 3 : PHP File

Select File : <input type=file name=f1>

<br>

<input type=submit name=b1 value=Display>

</form>

<body>

</html>

<?php

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

echo "File name : " . $_FILES["f1"]["name"];

echo "<br>File type : " . $_FILES["f1"]["type"];

echo "<br>File size : " . $_FILES["f1"]["size"] . "bytes";

echo "<br>Temporary File size : " . $_FILES["f1"]["tmp_name"];

?>

Example 2 : To upload a selected file

<html>

<body>

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

Select File : <input type=file name=f1>

<br>
3 Chapter 3 : PHP File

<input type=submit name=b1 value=Display>

</form>

<body>

</html>

<?php

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

$s=$_FILES["f1"]["tmp_name"];

$t="upload/". $_FILES["f1"]["name"];

if(move_uploaded_file($s,$t))

echo "File is uploaded";

else

echo "Error in file uploading";

?>

Example 3 : To upload only jpg and gif files

<html>

<body>

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

Select File : <input type=file name=f1>


4 Chapter 3 : PHP File

<br>

<input type=submit name=b1 value=Display>

</form>

<body>

</html>

<?php

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

$type=$_FILES["f1"]["type"];

if($type=="image/gif" || $type=="image/jpeg")

$s=$_FILES["f1"]["tmp_name"];

$t="upload/". $_FILES["f1"]["name"];

if(move_uploaded_file($s,$t))

echo "File is uploaded";

else

echo "Error in file uploading";

else

echo "File type is not permitted";

?>

Example 4 : To upload a file having size <10kb


5 Chapter 3 : PHP File

<html>

<body>

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

Select File : <input type=file name=f1>

<br>

<input type=submit name=b1 value=Display>

</form>

<body>

</html>

<?php

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

$size=$_FILES["f1"]["size"];

if($size<=10240)

$s=$_FILES["f1"]["tmp_name"];

$t="upload/". $_FILES["f1"]["name"];

if(move_uploaded_file($s,$t))

echo "File is uploaded";

else
6 Chapter 3 : PHP File

echo "Error in file uploading";

else

echo "File size is greater than the allowed size";

?>

PHP file download


PHP provides file downloading. You have to use header() and readfile() to download a file.

header(“content-type:application/octet-stream”);

Content-type determines how you want to read the page. Application/octet-stream means
downloading a file.

header(“content-disposition : attachment; Filename=kbssc.jpg”);

Content-Disposition determines how to handle the document. attachment value displays a


save as dialog box but if you specify filename attribute then it ignores it and then you must use
Filename attribute so that it can be downloaded.

The ob_clean() function deletes all of the contents of the topmost output buffer, preventing
them from getting sent to the browser.

At last readfile() is used to read a file and write to the output data.

<html>

<body>

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

<table border=3 cellpadding=10>

<tr>

<th>Select file
7 Chapter 3 : PHP File

<td><input type=file name=f1>

<tr>

<th colspan=2><input type=submit name=b1 value=Download>

</table>

</form>

</body>

</html>

<?php

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

$filename=$_FILES["f1"]["name"];

$newname=”kbssc”;

$ext = pathinfo($filename, PATHINFO_EXTENSION);

header("content-type:application/octet-stream");

header("content-disposition:attachment;filename=$newname.$ext”);

ob_clean();

readfile($filename);

?>

PHP cookie
Cookie is a text file stored in the client computer. Cookie is used to identify a user in php. We
can create, retrieve and delete cookie value.

Creating a cookie :
8 Chapter 3 : PHP File

Setcookie() is used to create a cookie.

Syntax : setcookie(name,value[,expire])

Name : It sets the name of the cookie variable.

Value : It sets the value of variable.

Expire : It specify a future time in second. After that time, cookie will become inaccessible. This
parameter is optional.

<?php

setcookie(“uname”,”kbssc”,time()+3600);

setcookie(“password”,”bscitbca”);

echo “Cookie variable set”;

?>

Reading a cookie variable:

PHP provides $_COOKIE associative array which is used to retrieve values of cookie variable.

<?php

echo "Username : " . $_COOKIE['uname'];

echo "<br>Password : ". $_COOKIE['password'];

?>

To view all cookie variable, you can use print_r().

<?php

print_r($_COOKIE);

?>

You can use isset() to check if cookie variable is set or not.


<?php
9 Chapter 3 : PHP File

setcookie("a",10);

if(isset($_COOKIE["a"]))

echo "cookie is set";

else

echo "cookie is not set";

?>

Destroying a cookie variable :

When you want to delete a cookie variable, you should ensure that the expiry time is in the
past.

<?php

setcookie("uname","kbssc",time()-1);

echo "Cookie variable is removed";

?>

PHP session
PHP session variable is used to store information for the user.

Session variable stores information about a single user and it is ava ilable to all pages in the
application.

Session variable is temporary and will be deleted after the user left.

Starting a session :

Session_start() is used to start a session. Before you can store and retrieve session information,
you must first start a session with this function. Session_start() will register a user for storing
variable.

Creating and retrieving session variable:

$_SESSION associative array is used to create and retrieve session data.


10 Chapter 3 : PHP File

//creating session data

<?php

session_start();

$_SESSION["uanme"]="kbssc";

$_SESSION["password"]="bscitbca";

echo "Session variable is set";

?>

//Retrieving session data

<?php

session_start();

echo $_SESSION["uanme"];

echo "<br>";

echo $_SESSION["password"];

?>

Destroying session data :

If you want to delete session data, you can use unset() or session_destroy(). If you want to
destroy a particular session variable, unset() is used. If you want to destroy all session data,
session_destroy() is used.

<?php

session_start();

$_SESSION["uname"]="kbssc";

$_SESSION["password"]="bscbscit";

echo "<br>";
11 Chapter 3 : PHP File

echo $_SESSION["uname"];

echo $_SESSION["password"];

unset($_SESSION["password"]);

echo "<hr>";

echo $_SESSION["uname"];

//echo $_SESSION["password"]; Generates an error

session_destroy();

echo "<hr>";

//echo $_SESSION["uname"]; Generates an error

?>

Write a program of page counter using session variable.

<?php

session_start();

if(isset($_SESSION["i"]))

$_SESSION["i"]=$_SESSION["i"]+1;

else

$_SESSION["i"]=1;

echo " Page visited : ". $_SESSION["i"];

?>

Explain difference between cookie and session.

Cookie Session

Cookie is a small text file stored in visitor’s Session is a small file that is saved on server.
12 Chapter 3 : PHP File

browser.

Cookie can have a long life time. Session can have limited life time because it is
expired when the browser is closed.

Cookies are limited in size depending on Session is unlimited in size.


browser’s setting.

Cookies can be disabled if the visitor’s browser Session cannot be disabled because they are
does not allow. stored on server.

Cookies can be edited by the visitor. Session cannot be edited by the visitor.

In PHP, $_COOKIE associative array is used to In PHP, $_SESSION associative array is used to
manage cookie. manage session.

You don’t need to start because it is stored Before using $_SESSION, you have to start
local. session using session_start().

$_SERVER variable
$_SERVER is an associative array which stored information such as address, server name,
protocol and script location. $_SERVER is a super global variable.

Element Description

$_SERVER['PHP_SELF'] Returns the filename of the currently


executing script

$_SERVER['SERVER_ADDR'] Returns the IP address of the host server

Returns the name of the host server

$_SERVER['SERVER_NAME']

$_SERVER['SERVER_SOFTWARE'] Returns the server identification string

$_SERVER['SERVER_PROTOCOL'] Returns the name and version of the


information protocol.

$_SERVER['REQUEST_METHOD'] Returns the request method used to access


the page
13 Chapter 3 : PHP File

$_SERVER['QUERY_STRING'] Returns the query string if the page is


accessed via a query string

$_SERVER['SCRIPT_NAME'] Returns the path of the current script

Example :

<html>

<body>

<form method =get action=server.php>

Enter name <input type=text name=t1>

<br>

<input type=submit name=b1 value=Display>

</form>

</body>

</html>

<?php

if(isset($_GET['b1']))

echo "<br>PHP_SELF : " . $_SERVER['PHP_SELF'];

echo "<br>SERVER_ADDR : " . $_SERVER['SERVER_ADDR'];

echo "<br>SERVER_NAME : ". $_SERVER['SERVER_NAME'];

echo "<br>SERVER_SOFTWARE : " . $_SERVER['SERVER_SOFTWARE'];

echo "<br>SERVER_PROTOCOL : ". $_SERVER['SERVER_PROTOCOL'];

echo "<br>REQUEST_METHOD : " . $_SERVER['REQUEST_METHOD'];

echo "<br>QUERY_STRING : " . $_SERVER['QUERY_STRING'];


14 Chapter 3 : PHP File

echo "<br>SCRIPT_NAME : " . $_SERVER['SCRIPT_NAME'];

?>

Output :

PHP_SELF : /check_php/server.php
SERVER_ADDR : 127.0.0.1
SERVER_NAME : localhost
SERVER_SOFTWARE : Apache/2.4.4 (Win32) PHP/5.4.16
SERVER_PROTOCOL : HTTP/1.1
REQUEST_METHOD : GET
QUERY_STRING : t1=kbssc&b1=Display
SCRIPT_NAME : /check_php/server.php

Environment variable
Environment variables are associative array passed to the current script.

1. $GLOBALS : It is the PHP global variable which is used to access global variables from
anywhere in PHP script.
2. $_GET : It returns the form field values passed using get method.
3. $_POST: It returns the form field values passed using post method.
4. $_REGUEST: It returns the form field values passed using either get or post method.
5. $_FILES: It is used in file upload. It is two dimensional array and returns the uploaded
file name, size, type and temporary name.
6. $_COOKIE: It is used to retrieve cookie variable.
7. $_SESSION: It is used to set and return session data.
8. $_SERVER: It returns the server identification information.

You might also like