php and the web: session : 4. predefined variables php provides a large number of predefined global...

48
PHP and the Web: PHP and the Web: Session : 4 Session : 4

Upload: claribel-carroll

Post on 16-Dec-2015

221 views

Category:

Documents


3 download

TRANSCRIPT

PHP and the Web: PHP and the Web:

Session : 4Session : 4

Predefined variables Predefined variables

• PHP provides a large number of predefined global variables to any script which it runs also called superglobal or autoglobal

PHP Superglobals

• $_SERVER

• $_GET

• $_POST

• $_COOKIE

• $_FILES

• $_ENV

• $_SESSION

$_SERVER$_SERVER

• $_SERVER stores several web server related variables which is very useful for various purposes.

$_SERVER$_SERVER

echo $_SERVER[‘PHP_SELF’];

Returns the file name currently executing in webserver.

$_SERVER$_SERVER

echo $_SERVER[‘PHP_SELF’];

Displays the server name

echo $_SERVER[' REMOTE_ADDR' ]

Displays the remote address of a client

$_SERVER …$_SERVER …

• There are several information available in the $_SERVER array check manual for more…

$_POST and $_GET$_POST and $_GET

A web form’s POST and GET variables are stored in associated array $_POST and $_GET.

like,

$_GET[“varname”];

$_POST[“varname”];

GET ExampleGET Example<?php echo $_GET[“fname”]; eco $_GET[“addr”];?>

<FORM method=GET>Name: <input type=text name=fname size=10>Addr: <input type=text name=addr size=30><input type=submit name=submit value=“Submit” size=30>

</FORM>

Handling FormHandling Form<?phpif ( isset($_GET[“submit”] ) ) { echo $_GET[“fname”]; echo $_GET[“addr”];}?>

<FORM method=GET>Name: <input type=text name=fname size=10>Addr: <input type=text name=addr size=30><input type=submit name=submit value=“Submit” size=30>

</FORM>

Handling FormHandling Form<?phpif ( isset($_POST[“submit”] ) ) { echo $_POST[“fname”]; echo $_POST[“addr”];}?>

<FORM method=POST>Name: <input type=text name=fname size=10>Addr: <input type=text name=addr size=30><input type=submit name=submit value=“Submit” size=30>

</FORM>

Variable FunctionVariable Function

• PHP has several variable function especially useful to validate, verify and manipulate the variable.

isset($var)isset($var)

• isset returns TRUE if var exists; FALSE otherwise

Example,

$k=0;

if(isset($t) ) echo “t is declared”;

if( isset($t) ) echo “k is declared”;

empty($var)empty($var)

• Determine whether a variable is empty

Example,

$var =0;

if (empty($var)) {    echo '$var is either 0, empty, or not set at all'; }

Checking variable typeChecking variable type

• To check whether a variable is an array use, is_array($var)

Example

$var = array(23,45,23);

If( is_array($var)) { echo “Array type”; }

Radio ButtonRadio Button<? if(isset($_POST[“submit”]) ) { $opt = $_POST[“opt”]; echo “Your choice is $opt;}<FORM methd=POST><input type=radio name=opt> Apple<br><input type=radio name=opt> Orange <br><input type=submit name=submit value=ok></FORM>?>

CheckboxCheckbox<? if(isset($_GET[“submit”]) ) { $opt = $_GET[“opt”]; echo “Your choice is $opt;}<FORM methd=GET><input type=checkbox name=opt> Apple<br><input type=checkbox name=opt> Orange <br><input type=submit name=submit value=ok></FORM>?>

Passing Array from FormPassing Array from Form

<FORM methd=POST>

<input type=text name=row[] size=30><br>

<input type=text name=row[] size=30><br>

<input type=text name=row[] size=30><br>

<input type=text name=row[] size=30><br>

<input type=text name=row[] size=30><br>

<input type=submit name=submit vale=Submit>

</FORM>

Getting valuesGetting values

<?$rows = $_POST[“row”];echo $row[0];echo $rows[5];foreach($rows as $r) { echo $r.”<BR>”;}?>

File UploadFile Upload

File Upload FormFile Upload Form

<FORM method=post enctype="multipart/form-data">

<input type="hidden" name="MAX_FILE_SIZE" value="51200">

<input type=file name=file1><br>

<input type=submit name=submit vale=upload>

</FORM>

To be rememberedTo be remembered

A file upload form must content an encoding

type. i.e

<FORM method=post enctype="multipart/form-data">

Restricting upload sizeRestricting upload sizePHP also requires that a hidden field beincluded before the file upload field. Thisshould be called MAX_FILE_SIZE andshould have a value representing themaximum size in bytes of the file that youare willing to accept.

<input type="hidden" name="MAX_FILE_SIZE" value="51200">

Inside file uploadInside file upload

• When a file is successfully uploaded, it is given a unique name and stored in a temporary directory (/tmp on UNIX systems). The full path to this file becomes

available to you in a global variable

Handling Uploaded FilesHandling Uploaded Files

PHP stores all the uploaded file information in the $_FILES autoglobal array.

$_FILES['userfile']['name']

$_FILES['userfile']['type']

$_FILES['userfile']['size']

$_FILES['userfile']['tmp_name']

$_FILES['userfile']['error']

$_FILES['userfile']['name']$_FILES['userfile']['name']

• The original name of the file on the client machine.

$_FILES['userfile']['type']$_FILES['userfile']['type']

• The mime type of the file, if the browser provided this information. An example would be "image/gif"

$_FILES['userfile']['size']$_FILES['userfile']['size']

• The size, in bytes, of the uploaded file

i.e

$totsize = $_FILES[‘userfile’][‘size’];

echo ‘Total uplodaed file size’.$totsize;

$_FILES['userfile']['tmp_name']$_FILES['userfile']['tmp_name']

• The temporary filename of the file in which the uploaded file was stored on the server.

$_FILES['userfile']['error']$_FILES['userfile']['error']

• The error code associated with this file upload. ['error'] was added from PHP 4.2.0.

Upload ExampleUpload Example

A upload formA upload form

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

<input type="hidden" name="MAX_FILE_SIZE" value="100000" />

Choose a file to upload: <input name="userfile" type="file" />

<input type="submit" value="Upload File" />

</form>

upload.phpupload.php<?phpIf( isset ($_POST[‘submit’) ) {$uploadFile = $_FILES['userfile']['name'];

if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadFile)) {

print "File is valid, and was successfully uploaded. "; print “File type is : “. $_FILES[‘userfile’][‘type’];}else { print "Possible file upload probs! Here's some

debugging info:\n"; print_r($_FILES); }} ?>

Some cautionSome caution

• Always check file type after uploading the files.

• Always check the extension of the file.

• Always use MAX_FILE_SIZE restricting the file upload size

Session managementSession management

Session ManagementSession Management

• Session management is a mechanism to maintain state about a series of requests from the same user across some period of time.

for example,

to store each user items while they are shopping a site.

separate session?separate session?

• Since TCP/IP has its own session why we need a seprate session handling?

Because..

• HTTP is a stateless protocol.

• It means in every transition the server immediately disconnect the connection.

• It present a problem when it comes to maintaining information about users visiting a Web site.

user session, how it works?user session, how it works?

• There must be unique identifier number for each user store in storage device.

• When the user return back they must have this number (session id) to identify to the server. So server can retrieved user information store in the storage device.

Session in clientSession in client

• The session variables can be stored in client side using Cookie

Session info can be stored inSession info can be stored in

• Cookies

• Hidden fields

• URL

• Web server process memory

• Files

• Database

Starting a SessionStarting a Session

• A PHP session is started explicitly by session_start()

session_start();

print($counter);

$counter++;

session_register("counter");

Inside session_start(..)Inside session_start(..)• PHP checks whether a valid session ID exist. • If there is no session ID, PHP creates a new ID.• If a valid ID exists, the frozen variables of that

session are reactivated and introduced back to the global namespace.

In next visit,• Checks whether session is generated or not.• If session id found then update the session

timeout time.

session_start(..)session_start(..)

• Put session_start(..) at top of every php script so that the page will remain the part of the each session.

Registering a session variableRegistering a session variable

• Registering a session variable is donethrough the session_register() command

• All variables you want to preserve across page requests must be registered to the session library with the session_register() function

exampleexample

session_start();

print($counter);

$counter++;

session_register("counter");

$bar = "This is a string";

$foo = "bar";

session_register($foo);

Ending a SessionEnding a Session

• You can force a session end with the command session_destroy().

the $_SESSION superglobalthe $_SESSION superglobal

• User $_SESSION to access the registered variables.