Você está na página 1de 39

Storing Images

Create a database named as postcard and create a table, images consisting of three fields, imageid, imageurl, imagedes. That table stores the image details. For this, all the images should be stored in a folder called postcards. The following programs explain it. DBcreation.php <?php //Connect to the server using the correct username and password. $conn = mysql_connect(yourserver, joeuser, yourpass);

/*Create the database. Call it postcard. If it is successful, print Database created to the screen and move on. */
$sql = CREATE DATABASE postcard; $success = mysql_query($sql, $conn) or die(mysql_error()); Echo Database created. . .; ?>

Storing Images (cont)


Create a program to connect with database DBconnect.php <?php $conn = mysql_connect(yourserver, joeuser, yourpass); mysql_select_db(postcard, $conn); ?> Create the images table in the database, containing three columns. Createtable.php <?php require(dbconnect.php); //imports the db connection prg. $sql = CREATE TABLE images (id int NOT NULL primary key auto_increment, img_url VARCHAR (255) NOT NULL, img_desc text ); $success = mysql_query($sql, $conn) or die(mysql_error()); echo images table created. . . ?>

Storing Images (cont)


Create two arrays, to store image url and image description. Then insert those values into the images table storeimages.php
<?php require(dbconnect.php); //Now create two arrays of values to place in the images table. $imgURL = array(/postcards/punyearth.gif, /postcards/grebnok.gif, /postcards/sympathy.gif, /postcards/congrats.gif); $imgDESC = array(Wish you were here!, See you soon!, Our Sympathies, Congratulations!);
//Loop through the arrays, pulling the location and description text and inserting them into the images table.

for ($i=0; $i<4; $i++) { $sql = INSERT INTO images ( img_url , img_desc ) VALUES ( $imgURL*$i+, $imgDESC*$i+); $success = mysql_query($sql, $conn) or die(mysql_error()); } Echo Data entered. . .; ?>

Getting Confirmation
It is quite easy for the user to use any e-mail address in the From field. This is a bad thing because nasty e-mails can be sent on someone elses behalf.

In order to prevent such maliciousness, you must first send a confirmation e-mail to the From address.
Once you get the confirmation, you know the user entered a good email address, and you can go ahead and send the e-mail. This will explain with the following screen shots.

Getting Confirmation
Create a PHP program to collect the following information

Getting Confirmation
Send the selected card & message to from address to get confirmation.

Getting Confirmation
Now the user gives confirmation by using the link given below.

Click here to confirm

Can send the mail to address in to field, if receives confirmation.

Cookies
A cookie is a small piece of information that a Web server can store through your Web browser on to your hard disk when you visit the corresponding site. The Web server can also retrieve this information later when you visit the same site next time. When you visit a cookie-enabled Web site, you might need to log in to the site or register using a password and other relevant information. This information is stored into a small text file whose maximum size is 4 KB. This file is referred to as a cookie and contains the relevant userrelated information, such as User ID, password, list of pages that the user visited, and the date the user last visited a page.

Why Cookie

Internet is based on Hypertext Transfer Protocol (HTTP), which is a stateless protocol. This implies that once a transaction between the client machine and the Web server is finished, the Web server loses all the memory regarding the transaction. Maintaining the state between your subsequent visits to a Web page prevent loss of sensitive data

Use of Cookies
To determine how many users visit the given Web site and how often For storing details of the users who visit the site or register on the Web site. Allowing users to customize the interface (such as layout and colors) as per their liking.

To prevent repetitive logins, thus making the login process faster. In addition, since the cookie is stored at the client end, the Web server need not be burdened each time a user needs to log in to the site. The server only needs to authenticate the first-time users.
For tracking a user's path and activities on a given Web site. This feature allows the Web administrators to track miscreants. For generating individual user profiles. For example, some sites display personalized messages to their users when they log in to the site. For storing the items selected by the site users in their respective shopping carts.

10

How does a Cookie work?

No

Yes ->Updates cookie value No -> Creates new cookie

11

How does a Cookie work?


When you type the URL of the destination Web site in the Address bar of your
browser, the address is located and if found successfully, a request is sent to the Web server that hosts the site. If the Web server accepts the request, the Web browser at the client end checks for an existing cookie from the given site. If the cookie is found, the browser sends all the name-value pairs in the cookie to the server as the HTTP header. In addition, the expiration date of the cookie, if any, and a path is also sent to the server along with the name-value pairs. If the corresponding cookie is not found on the local hard disk, the server is notified about the absence of a cookie. In this case, the server generates a new ID for the client who requested a connection and sends the cookie containing the name-value pair(s) to the requester's Web browser. The browser then stores this cookie on the hard disk of your machine.

12

Setting a Cookie
setcookie() defines a cookie to be sent along with the rest of the HTTP headers. Like other headers, cookies must be sent before any output from your script (this is a protocol restriction). This requires that you place calls to this function prior to any output, including <html> and <head> tags as well as any whitespace. Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE.

To be first.. HEADER REQUESTS


As the setcookie command involves sending a HTTP header request, it must be executed before any xhtml is echoed to the browser, including whitespace.
echoed whitespace before setcookie incorrect.

correct!

Parameters of setcookie()
setcookie(name [,value [,expire [,path [,domain [,secure]]]]])
name = cookie name All the arguments except the name argument are optional. You may also replace an argument with an empty string ("") in order to skip that argument. Because the expire argument is integer, it cannot be skipped with an empty string, use a zero (0) instead. value = data to store (string) The value of the cookie. This value is stored on the clients computer; do not store sensitive information. Assuming the name is 'cookiename', this value is retrieved through $_COOKIE*cookiename+

Parameters of Cookie
Expire The time the cookie expires. This is a Unix timestamp so is in number of seconds since the epoch. In other words, you'll most likely set this with the time() function plus the number of seconds before you want it to expire. Or you might use mktime(). time()+60sec*60min*24hours*30days will set the cookie to expire in 30 days. If set to 0, or omitted, the cookie will expire at the end of the session (when the browser closes).

Parameters of Cookie
Path
The path on the server in which the cookie will be available on. If set to '/', the cookie will be available within the entire domain. If set to '/foo/', the cookie will only be available within the /foo/ directory and all sub-directories such as /foo/bar/ of domain. The default value is the current directory that the cookie is being set in.

domain = Domain at which the cookie is available for. secure = If cookie should be sent over HTTPS connection only(then set as 1). Default false.

Set a cookie - examples


setcookie(name,Robert) This command will set the cookie called name on the users PC containing the data Robert. It will be available to all pages in the same directory or subdirectory of the page that set it (the default path and domain). It will expire and be deleted when the browser is closed (default expire).

Set a cookie - examples


setcookie(gender,male,0,/) This command will set the cookie called gender on the users PC containing the data male. It will be available within the entire domain that set it. It will expire and be deleted when the browser is closed.

Set a cookie - examples


setcookie(age,20,time()+60*60* 24*30) This command will set the cookie called age on the users PC containing the data 20. It will be available to all pages in the same directory or subdirectory of the page that set it (the default path and domain). It will expire and be deleted after 30 days.

Restrictions of Cookie
1. A cookie can be a maximum size of 4KB only.
2. A domain can stores upto 20 cookies in a clients hard disk. 3. At a moment, a client can stores maximum of 300 cookies only.

21

Accessing Cookies in PHP

In php, cookies can be accessed in three ways: 1. Use the super global $_COOKIE*cookiename+ 2. Can access through the super global cookie array HTTP_VARS_COOKIE*cookiename+. 3. Can use a cookie name as a php variable.

22

Sample cookies program


1. Setcookie.php <?php $username = jeremys; setcookie(username, $username, time() + 60 * 60 * 24); // cookie for 1 day echo $_COOKIE*username+ . created with expiration time of 1 day; setcookie(secondcookie,$username); //expiration time is Session time. setcookie(third,sample,time()+60*60*24*30);//cookie for 30 days //accessing cookie echo $_HTTP_COOKIE_VARS*third+; echo $secondcookie; ?>

23

Delete a cookie
To remove a cookie, simply overwrite the cookie with a new one with an expiry time in the past
setcookie(cookie_name,,time()-6000)

Note that theoretically any number taken away from the time() function should do, but due to variations in local computer times, it is advisable to use a day or two.

Delete Cookie program


<?php echo "<font size=8>"; if (isset($_COOKIE["kookie"])) { setcookie("kookie","",time()-10); // deletes cookie echo "Cookie named as <color = red>kookie </color>was deleted"; } else echo "there is no cookie with name 'KOOKIE'"; ?>
25

SESSION
A normal HTML website will not pass data from one page to another.
(OR)

In other words, all information is forgotten when a new page is loaded. This makes a quite problem for tasks like a shopping cart, which requires data (the user's selected product) to be remembered from the time of selection to billing. (i.e. one page to the next page). Cookie used for such requirements, however, limitations on cookie size and the number of cookies allowed, and various inconveniences surrounding their implementation, prompted to introduce another solution called as session handling. A PHP session solves this problem by allowing you to store user information on the server for later use (i.e. username, shopping cart items, etc). However, this session information is temporary and is usually deleted very quickly after the user has left the website that uses sessions.

26

SESSION Mechanism
There are two things that the session mechanism must hang onto: the session ID itself and any associated variable bindings. The session ID is either stored as a cookie on the browser's machine, or it is incorporated into the GET/POST arguments submitted with page requests. The contents of session variables are stored in special files on the server, one file per session ID:
Doing this kind of storage requires the session code to serialize the data by turning it into a linear sequence of bytes that can be written to a file and read back to recreate the data It's possible to configure PHP to store the contents of session variables in a server-side database, rather than in files

27

Storing the Sessions


The session variables are stored on the web server The Path is /var/lib/php/session The file name is the session ID Eg. sess_076opqrstu56kldr670ndft0op

28

Working of a Session
Sessions work by creating a unique identification(UID) number for each visitor and storing variables based on this ID. This helps to prevent two users' data from getting confused with one another when visiting the same webpage. session_start() it is required, for every sessions program. $_SESSION*session_name+ can access the created sessions through this super global. isset($_SESSION*session_name+) used to check the availability of a session. unset($_SESSION*session_name+) deletes the session session_destroy() deletes all sessions.

29

Start a Session
Before you can begin storing user information in your PHP session, you must first start the session. When you start a session, it must be at the very beginning of your code, before any HTML or text is sent. bool session_start (void) Sample program to Start Session: Session_start.php
<?php session_start(); // starts PHP session! echo The session was started; ?>

This tiny piece of code will register the user's session with the server, allow you to start saving user information and assign a UID (unique identification number) for that user's session.

30

Create a Session
When you want to store user data in a session use the $_SESSION (super global). This is used for both store and retrieve session data. $_SESSION*session_name+ Sample program to Create Session: Session_Create.php <?php session_start(); // starts PHP session! $_SESSION*view+ = 1; // creates a new session with name view ?>

31

Access Session
Can access the existing sessions through the following super global: $_SESSION*session_name+ global array $_HTTP_SESSION_VARS*session_name+ environment variables

Sample program to Access a Session: Session_Access.php <?php session_start(); // starts PHP session! if (isset($_SESSION*view+) // checks the availability $_SESSION*view+ += 1; // access the existing ?>

32

Delete Session
Imagine that you were running an online business and a user used your website to buy your goods. The user has just completed a transaction on your website and you now want to remove everything from their shopping cart. Can delete the existing session by the function unset . The sample program shows it:

Sample program to Delete Session: Session_Delete.php


<?php session_start(); // starts PHP session! if (isset($_SESSION*view+) // checks the existing { unset($_SESSION*view+); // deletes the existing // (or) session_unset(view); // deletes the existing session echo The session view was deleted; } else echo no session with name view; ?>
33

Delete All Sessions


Session_destroy() destroys all of the data associated with the current session. It does not unset any of the global variables associated with the session. Variables associated with the session, or unset the session cookie. bool session_destroy (void) Sample program to Delete all Session: Sessions_Delete.php <?php session_start(); // starts PHP session //codings session_destroy(); // deletes all sessions ?> Note: destroy will reset your session, so don't call that function unless you are entirely comfortable losing all your stored session data!

34

Register a Session
session_register() accepts a variable number of arguments, any of which can be either a string holding the name of a variable or an array consisting of variable names or other arrays. For each name, session_register() registers the global variable with that name in the current session.

bool session_register (mixed $name [,mixed $...])


Sample program to Register a Session: Session_Register.php <?php // Use of session_register() is deprecated session_register("barney"); // barney can use later ?>

35

Use Registered Session


The registered session can be used later. It is must to check a session is registered or not, before use it. For that, session_is_registered is used to find whether a global variable is registered in a session bool session_is_registered (string $name) Sample program to use Registered Session: Session_Registerd_use.php <?php // use the registered sesssion session_start(); if (session_is_registered(barney)) { $_SESSION*barney+=1; echo "barney is ",$_SESSION['barney']."<br>"; } else echo The session barney is not yet registered; ?>

36

Session Name
session_name() returns the name of the current session. bool session_name (string $name) If name is given, session_name() will update the session name and return the old session name. The session name is reset to the default value stored in session.name at request startup time. Thus, you need to call session_name() for every request (and before session_start() or session_register() are called). Sample program for Session Name: Session_Name.php

<?php session_start();
Echo The session name is , session_name(); // set the session name to WebsiteID $previous_name = session_name("WebsiteID"); echo "The previous session name was $previous_name<br />"; ?>

37

Session id
session_id() is used to get or set the session id for the current session. The constant SID can also be used to retrieve the current name and session id as a string suitable for adding to URLs. string session_id () The session id can be updated by the function string session_regenerate_id ([bool $delete_old_session=false])

Sample program for Session Name: Session_Name.php <?php session_start(); echo current session id is ".session_id()."<br>"; echo The new id is , session_regenerate_id().<br>; echo "barney is ",$_SESSION['barney']++."<br>"; ?>

38

So
Cookies Limited storage space Insecure storage clientside User controlled Sessions Practically unlimited space Reasonably securely stored server-side No user control

Você também pode gostar