Nothing Special   »   [go: up one dir, main page]

PHP File Cookiee Session

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 20

File Handeling

PHP 5 File Handling

<?php
echo readfile("webdictionary.txt");
?>

The PHP code to read the file and write it to the output buffer is as follows (the
readfile() function returns the number of bytes read on success
PHP Open File - fopen()

<?php
$myfile = fopen("webdictionary.txt", “r") or die("Unable to open file!");
$size = filesize("webdictionary.txt");
echo fread($myfile, $size );
fclose($myfile);
?>
The first parameter of fread() contains the name of the file to read from and the
second parameter specifies the maximum number of bytes to read.
Modes Description

r Open a file for read only. File pointer starts at the beginning of the file

w Open a file for write only. Erases the contents of the file or creates a new file if it doesn't exist. File pointer
starts at the beginning of the file

a Open a file for write only. The existing data in file is preserved. File pointer starts at the end of the file. Creates
a new file if the file doesn't exist

x Creates a new file for write only. Returns FALSE and an error if file already exists

r+ Open a file for read/write. File pointer starts at the beginning of the file

w+ Open a file for read/write. Erases the contents of the file or creates a new file if it doesn't exist. File pointer
starts at the beginning of the file

a+ Open a file for read/write. The existing data in file is preserved. File pointer starts at the end of the file. Creates
a new file if the file doesn't exist

x+ Creates a new file for read/write. Returns FALSE and an error if file already exists
PHP Read Single Line - fgets()

The fgets() function is used to read a single line from a file.


<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
echo fgets($myfile);
fclose($myfile);
?>
PHP Check End-Of-File - feof()

<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
// Output one line until end-of-file
while(!feof($myfile)) {
  echo fgets($myfile) . "<br>";
}
fclose($myfile);
?>
PHP Read Single Character - fgetc()

<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
// Output one character until end-of-file
while(!feof($myfile)) {
   $x = fgetc($myfile);
If($x == ‘a’)
{
$C++;
}
}
fclose($myfile);
?>
PHP 5 File Create/Write

$myfile = fopen("testfile.txt", "w")


The fopen() function is also used to create a file. Maybe a little confusing, but in
PHP, a file is created using the same function used to open files.

If you use fopen() on a file that does not exist, it will create it, given that the
file is opened for writing (w) or appending (a).
PHP Write to File - fwrite()

<?php
$myfile = fopen("newfile.txt", “w") or die("Unable to open file!");
$txt = "John Doe\n";
fwrite($myfile, $txt);
$txt = "Jane Doe\n";
fwrite($myfile, $txt);
fclose($myfile);
?>
PHP 5 Cookies

A cookie is often used to identify a user. A cookie is a small file that the server
embeds on the user's computer. Each time the same computer requests a page
with a browser, it will send the cookie too. With PHP, you can both create and
retrieve cookie values.
PHP Create/Retrieve a Cookie
<?php
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 =
1 day
?>
<html> creates a cookie named "user" with
<body>
the value "John Doe". The cookie
<?php
will expire after 30 days (86400 *
if(!isset($_COOKIE[$cookie_name])) { 30). The "/" means that the cookie
    echo "Cookie named '" . $cookie_name . "' is not set!"; is available in entire website
} else { (otherwise, select the directory you
    echo "Cookie '" . $cookie_name . "' is set!<br>"; prefer).
    echo "Value is: " . $_COOKIE[$cookie_name];
}
?>

</body>
</html>
Delete a Cookie

<?php
// set the expiration date to one hour ago
setcookie("user", "", time() - 3600);
?>
<html>
<body>

<?php
echo "Cookie 'user' is deleted.";
?>

</body>
</html>
What is a PHP Session?

When you work with an application, you open it, do some changes, and then you
close it. This is much like a Session. The computer knows who you are. It knows
when you start the application and when you end. But on the internet there is one
problem: the web server does not know who you are or what you do, because the
HTTP address doesn't maintain state.

Session variables solve this problem by storing user information to be used across
multiple pages (e.g. username, favorite color, etc). By default, session variables
last until the user closes the browser.

So; Session variables hold information about one single user, and are available to
all pages in one application.
Session variables are used to store individual client’s information on the web
server for later use,  as a web server does not know which client’s request to be
respond because HTTP address does not maintain state
Start a PHP Session

<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>

</body>
</html>
Get PHP Session Variable Values

<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// Echo session variables that were set on previous page
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
?>

</body>
</html>
Destroy a PHP Session

<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// remove all session variables
session_unset(); 

// destroy the session 


session_destroy( ); 
?>

</body>
</html>
PHP Exception Handling
Exception handling is used to change the normal flow of the code execution if a
specified error (exceptional) condition occurs. This condition is called an
exception.
This is what normally happens when an exception is triggered:
 The current code state is saved
 The code execution will switch to a predefined (custom) exception handler
function
 Depending on the situation, the handler may then resume the execution from
the saved code state, terminate the script execution or continue the script
from a different location in the code
Try, throw and catch

To avoid the error from the example above, we need to create the proper code to
handle an exception.

Proper exception code should include:

 try - A function using an exception should be in a "try" block. If the exception does
not trigger, the code will continue as normal. However if the exception triggers, an
exception is "thrown"
 throw - This is how you trigger an exception. Each "throw" must have at least one
"catch“
 catch - A "catch" block retrieves an exception and creates an object containing the
exception information
<?php
//create function with an exception
function checkNum($number) {
  if($number>1) {
    throw new Exception("Value must be 1 or
below");
  }
  return true;
} The checkNum() function is created. It checks if a
number is greater than 1. If it is, an exception is thrown
//trigger exception in a "try" block The checkNum() function is called in a "try" block
try { The exception within the checkNum() function is thrown
  checkNum(2); The "catch" block retrieves the exception and creates an
  //If the exception is thrown, this text will object ($e) containing the exception information
not be shown The error message from the exception is echoed by
  echo 'If you see this, the number is 1 or calling $e->getMessage() from the exception object
below';
}

//catch exception
catch(Exception $e) {
  echo 'Message: ' .$e->getMessage();
}
?>

You might also like