Saturday, November 24, 2012

Javascript popup window

Javascript popup window is the small window which is created by javascript.
The syntax for javascript popup window is given below:
window.open(url, name, [windowFeatures])
where
url: The url of the page to open in the new window.
name: A name is the name of the window.
windowFeatures: They are the parameters which determines the various features of window to be included in the popup window like status bar, address bar,width,height, etc.
The table shows the features and the string tokens you use:
status     The status bar at the bottom of the window.
toolbar     The standard browser toolbar, with buttons such as Back and Forward.
location     The Location entry field where you enter the URL.
menubar     The menu bar of the window
directories     The standard browser directory buttons, such as What’s New and What’s Cool
resizable     Allow/Disallow the user to resize the window.
scrollbars     Enable the scrollbars if the document is bigger than the window
height     Specifies the height of the window in pixels. (example: height=’350′)
width     Specifies the width of the window in pixels.
Simple example of javascript popup window
Code:
<html>
<head>
<script type=”text/javascript”>
function popUp(url,name)
{
    testwindow = window.open(url, name, “location=1,status=1,scrollbars=1,width=300,height=200″);
   testwindow.moveTo(0, 0);
}
</script>
</head>
<body>
<a href=”" onClick=”popUp(‘counter.php’,'Pop up Window’)” > Click here</a>
<body>
</html>
In above code, we have used window.moveTo function to move the popup window to a desired location.

Javascript: alert box, prompt box and confirm box

Alert box:

It displays an alert dialog with a text message and OK button
Example:
Code:
<html>
<head>
<script type=”text/javascript”>
function showAlert()
{
    alert(“Hey!! This is an alert box”);
}
</script>
</head>
<body>
<input type=”button” onClick=”showAlert()” value=”Show” />
</body>
</html>
In above example, only the text Hey!! This is an alert box appears.

Prompt Box:

Prompt is used to allow a user to enter something, and do something with that value.
Code:
<html>
<head>
<script type=”text/javascript”>
function showPrompt()
{
    var name=prompt(“Please enter your name”, “Awaken Nepal”);
    if(name!=null && name!=”")
    {
    document.write(“Hello”+name+”! How are you?”);
    }
}
</script>
</head>
<body>
<input type=”button” onClick=”showPrompt()” value=”Show” />
</body>
</html>
In above example, the alert box with user input field appears to take an input from the user and then do the necessary process.

Confirm Box:

Confirm is used to confirm a user about certain action, and decide between two choices depending on what the user chooses.
Code:
<html>
<head>
<script type=”text/javascript”>
function showConfirm()
{
    if(confirm(“Are you sure you want to delete this record?”))
    {
        alert(“Okay deleted”);
    }
    else
    {
        alert(“Not deleted”);
    }
}
</script>
</head>
<body>
<input type=”button” onClick=”showConfirm()” value=”Show” />
</body>
</html>
In above example, user can choose whether or not an action to be  performed. A confirm box will pop up much like an alert box, but will allow the viewer to press an “OK” or “Cancel” button.

To show/hide any content using javascript

Code:
<script language=”javascript”>
function showContent() {
var ele = document.getElementById(“toggleText”);
var text = document.getElementById(“displayText”);
if(ele.style.display == “block”) {
ele.style.display = “none”;
text.innerHTML = “show”;
}
else {
ele.style.display = “block”;
text.innerHTML = “hide”;
}
}
</script>
<a id=”displayText” href=”javascript:showContent();”>show</a> <== click Here
<div id=”toggleText” style=”display: none”><h1>This is hidden content</h1></div>

Output:
Before link is clicked





After link is clicked

 

HTML Layouts – Using Tables

Website Layouts
Website Layout is very important to make your website look good. So you need to design your website properly.
There is two ways of designing layout.
  1.  Using Table
  2. Using CSS(Without using table)
Here, we will discuss using tables.

HTML Iframes

An iframe is used to display a web page within a web page.
Syntax for adding an iframe:
<iframe src=”URL”></iframe>
The URL points to the location of the separate page.

Nesting of Table

To use table inside of another table is called nesting of tables.
As according to the need, we might need to show different information in an appropriate ways, so we need table inside another table.

HTML Frames

With frames, several Web pages can be displayed in the same browser window.
Note:Do not expect frames to be supported in future versions of HTML.
Frames allow for multiple .html documents to be displayed inside of one browser window at a time. This means that one page has no content on it, but rather tells the browser which web pages you would like to open. With the addition of CSS and PHP, frames have become outdated.
The disadvantages of using frames are:
  •     Frames are not expected to be supported in future versions of HTML
  •     Frames are difficult to use. (Printing the entire page is difficult).
  •     The web developer must keep track of more HTML documents
The HTML frameset Element
The frameset element holds one or more frame elements. Each frame element can hold a separate document.
The frameset element states HOW MANY columns or rows there will be in the frameset, and HOW MUCH percentage/pixels of space will occupy each of them.
The HTML frame Element
The <frame> tag defines one particular window (frame) within a frameset.
In the example below we have a frameset with two columns.
The first column is set to 25% of the width of the browser window. The second column is set to 75% of the width of the browser window. The document “frame_a.htm” is put into the first column, and the document “frame_b.htm” is put into the second column:
<frameset cols=”25%,75%”>
<frame src=”frame_1.htm” />
<frame src=”frame_2.htm” />
</frameset>
Note: The frameset column size can also be set in pixels (cols=”200,500″), and one of the columns can be set to use the remaining space, with an asterisk (cols=”25%,*”).

Frameset Attributes
COLS: how many cols in the frameset
ROWS: how many rows in the frameset
FRAMEBORDER: if the frames should have borders
FRAMESPACING: space between the frames
BORDER: space between frames
BORDERCOLOR: color of frame borders

HTML Forms

HTML forms are used to pass data to a server.
A form can contain input elements like text fields, checkboxes, radio-buttons, submit buttons and more. A form can also contain select lists, textarea, fieldset, legend, and label elements.
The <form> tag is used to create an HTML form:

MySQL: SQL

SQL is a standard language for accessing and manipulating databases. To connect any and every database and to execute, insert, update or delete any records, we need SQL..
Brief description about SQL:
  •     SQL stands for Structured Query Language
  •     SQL lets you access and manipulate databases
  •     SQL is an ANSI (American National Standards Institute) standard
What Can SQL do?
  •     SQL can execute queries against a database
  •     SQL can retrieve data from a database
  •     SQL can insert records in a database
  •     SQL can update records in a database
  •     SQL can delete records from a database
  •     SQL can create new databases
  •     SQL can create new tables in a database
  •     SQL can create stored procedures in a database
  •     SQL can create views in a database
  •     SQL can set permissions on tables, procedures, and views
SQL DML and DDL
SQL can be divided into two parts: The Data Manipulation Language (DML) and the Data 
 Definition Language (DDL).

The query and update commands form the DML part of SQL:
SELECT – extracts data from a database
UPDATE – updates data in a database
DELETE – deletes data from a database
INSERT INTO – inserts new data into a database
The DDL part of SQL permits database tables to be created or deleted. It also defines indexes (keys), specifies links between tables, and imposes constraints between tables. The most important DDL statements in SQL are:
CREATE DATABASE – creates a new database
ALTER DATABASE – modifies a database
CREATE TABLE – creates a new table
ALTER TABLE – modifies a table
DROP TABLE – deletes a table
CREATE INDEX – creates an index (search key)
DROP INDEX – deletes an index
So to start writing query, practice with sql editor.
  • Open localhost/phpmyadmin
  • Click on sql tab
The SQL SELECT Statement
The SELECT statement is used to select data from a database.
The result is stored in a result table, called the result-set.

SQL SELECT Syntax

SELECT column_name(s) FROM table_name
and
SELECT * FROM table_name
Examples:
Now write following command.
And press go button.


SELECT * Example
Now we want to select all the columns from the “tbl_member” table.
We use the following SELECT statement:
SELECT * FROM tbl_member
Output:




SELECT DISTINCT Statement

In a table, some of the columns may contain duplicate values. This is not a problem, however, sometimes you will want to list only the different (distinct) values in a table.
The DISTINCT keyword can be used to return only distinct (different) values.
SQL SELECT DISTINCT Syntax
SELECT DISTINCT column_name(s) FROM table_name
Example:
tbl_member table


SELECT DISTINCT ‘address’ FROM tbl_member
Output:

Here, redundant data of address column is removed.
 SQL WHERE Clause
The WHERE clause is used to extract only those records that fulfill a specified criterion.
SQL WHERE  Syntax
SELECT column_name(s)FROM table_name WHERE column_name operator value
Example:
SELECT * FROM `tbl_member` WHERE `name`=”Ram”;
Output:



Operators Allowed in the WHERE Clause
With the WHERE clause, the following operators can be used:
=         Equal
<>     Not equal
>     Greater than
<     Less than
>=     Greater than or equal
<=     Less than or equal
BETWEEN     Between an inclusive range
LIKE     Search for a pattern
IN     To specify multiple possible values for a column
The ORDER BY Keyword
The ORDER BY keyword is used to sort the result-set by a specified column.
The ORDER BY keyword sort the records in ascending order by default.
If you want to sort the records in a descending order, you can use the DESC keyword.
SQL ORDER BY Syntax
SELECT column_name(s) FROM table_name ORDER BY column_name(s) ASC|DESC
Example:
SELECT * FROM `tbl_member` ORDER BY `name` DESC
Output:




The AND & OR Operators
The AND operator displays a record if both the first condition and the second condition is true.
The OR operator displays a record if either the first condition or the second condition is true.
Example:
SELECT * FROM `tbl_member` WHERE `name`=”Ram” AND `address`=”KTM”
Output:

 The INSERT INTO Statement
The INSERT INTO statement is used to insert a new row in a table.

SQL INSERT INTO Syntax
It is possible to write the INSERT INTO statement in two forms.
The first form doesn’t specify the column names where the data will be inserted, only their values:
INSERT INTO table_name VALUES (value1, value2, value3,…)
The second form specifies both the column names and the values to be inserted:
INSERT INTO table_name (column1, column2, column3,…) VALUES (value1, value2, value3,…)
Example:
INSERT INTO tbl_member VALUES (’5′,’Binay’,'Chapagaun’,’9849111111′)
Output:


The UPDATE Statement
The UPDATE statement is used to update existing records in a table.
SQL UPDATE Syntax
UPDATE table_name SET column1=value, column2=value2,…     WHERE some_column=some_value
Example:
UPDATE `tbl_member` SET `address`=”Anamnagar” WHERE `id`=”5″

The DELETE Statement
The DELETE statement is used to delete rows in a table.
SQL DELETE Syntax
DELETE FROM table_name WHERE some_column=some_value
Example:
DELETE FROM `tbl_member` WHERE id=”2″

MySQL Connection

Connection with MySQL Database
Before accessing database, you must create a connection to the database

Syntax:
mysql_connect(servername,username,password);
where,
servername specifies the server to connect to. Default value is “localhost”
username specifies the username to log in with. Default value is the name of the user that owns the server process. To connect offline we use username “root”.
password specifies the password to log in with. Default is “”

Code:
Creating connection to the database and selecting the required database
<?php
$con = mysql_connect(“localhost”,”root”,”");
if (!$con)
{
die(‘Could not connect: ‘ . mysql_error());
} else{
mysql_select_db(“test”, $con)
};
?>
Here, we have store connection in a variable called $con and trap error using die function.

Closing connection
The connection will be closed automatically when the script ends. To close the connection before, use the mysql_close() function:
<?php
$con = mysql_connect(“localhost”,”root”,”");
if (!$con)
{
die(‘Could not connect: ‘ . mysql_error());
} else{
mysql_select_db(“test”, $con)
};
mysql_close($con);
?>

MySQL: Introduction

MySOL is a database. With PHP, default database is MySQL. Database is needed to create any dynamic website or web application. Records or information for any website is kept in database in the forms of tables.
Table is the collection of related data entries and it consist of columns and rows.
A row of information is called tuple.

What is Query?
Query is a question or a request. With the help of query you can show, add,edit and delete any record.

How to create database?
Its very simple, just open your database, create database as below:
1)Open link http://localhost/phpmyadmin.
2)Click on the database tab.
3)Give name of database and create like below.

now  I will inside the database called test as below:
How to create tables?
1)Once you have created database, click on the database.
For example, I have created a database called test. So 



2) Create table on the database test.
3) Give table name and number of fields needed and click on create..
4) After that give the field names, data types and most important a primary key.
5) And also set your primary key to auto-increment as it will be auto-incremented as you add data from front-end.

PHP Error Handling

All the possible errors should be managed in such a way, it should be debugged properly. So in this case default error handling is used which is very simple. An error message with filename, line number and a message describing the error is sent to the browser.

Error handling is an important part while creating any web applications or scripts or pages.

If you want your viewers to not display any errors on your web page then you following code on the top of your page:
   error_reporting(0);

or if you only want to see Warning Messages and not Notice Messages:
ini_set('display_errors',1);
error_reporting(E_ALL);

Error Handling with die() function
Lets try using a simple example below:

Code:
  
<?php
 if(isset($_POST['submit'])){
$filename=$_FILES['image']['name'];
$tmp_name=$_FILES['image']['tmp_name'];
if(!move_uploaded_file($tmp_name,"img".$filename)){
die("Error in uploading");
}
else {
print("Uploaded successfully");
}
}
?>
 
<form method="post" action="" enctype="multipart/form-data">
<label>Select:</label>
<input type="file" name="image" />
<input type="submit" name="submit" value="submit" />
</form>

Output:



It will display as:
Error in Uploading


Now fix the code by making a folder called img and copy, paste following code.
 
<?php
if(isset($_POST['submit'])){
$filename=$_FILES['image']['name'];
$tmp_name=$_FILES['image']['tmp_name'];
if(!move_uploaded_file($tmp_name,"img/".$filename)){
die("Error in Uploading");
}
else {
print("Uploaded successfully");
}
}
?>
 
<form method="post" action="" enctype="multipart/form-data">
<label>Select:</label>
<input type="file" name="image" />
<input type="submit" name="submit" value="submit" />
</form>


The output should be
Uploaded successfully.

Sending Emails

PHP makes use of mail() function to send an email. This function requires three mandatory arguments that specify the recipient’s email address, the subject of the the message and the actual message additionally there are other two optional parameters.

mail( to, subject, message, headers, parameters );

Here is the description for each parameters.

Parameter Description
to Required. Specifies the receiver / receivers of the email
subject Required. Specifies the subject of the email. This parameter cannot contain any newline characters
message Required. Defines the message to be sent. Each line should be separated with a LF (\n). Lines should not exceed 70 characters
headers Optional. Specifies additional headers, like From, Cc, and Bcc. The additional headers should be separated with a CRLF (\r\n)
parameters Optional. Specifies an additional parameter to the sendmail program

As soon as the mail function is called PHP will attempt to send the email then it will return true if successful or false if it is failed.

Multiple recipients can be specified as the first argument to the mail() function in a comma separated list.
 
Example:

Following example will send an HTML email message to xyz@somedomain.com. You can code this program in such a way that it should receive all content from the user and then it should send an email.

<html>
<head>
<title>Sending email using PHP</title>
</head>
<body>
<?php
   $to = "xyz@somedomain.com";
   $subject = "This is subject";
   $message = "This is simple text message.";
   $header = "From:abc@somedomain.com \r\n";
   $retval = mail ($to,$subject,$message,$header);
   if( $retval == true ) 
   {
      echo "Message sent successfully...";
   }
   else
   {
      echo "Message could not be sent...";
   }
?>
</body>
</html>

Sending HTML email:

When you send a text message using PHP then all the content will be treated as simple text. Even if you will include HTML tags in a text message, it will be displayed as simple text and HTML tags will not be formatted according to HTML syntax. But PHP provides option to send an HTML message as actual HTML message.

While sending an email message you can specify a Mime version, content type and character set to send an HTML email.
Example:

Following example will send an HTML email message to xyz@somedomain.com copying it to afgh@somedomain.com. You can code this program in such a way that it should recieve all content from the user and then it should send an email.

<html>
<head>
<title>Sending HTML email using PHP</title>
</head>
<body>
<?php
   $to = "xyz@somedomain.com";
   $subject = "This is subject";
   $message = "<b>This is HTML message.</b>";
   $message .= "<h1>This is headline.</h1>";
   $header = "From:abc@somedomain.com \r\n";
   $header = "Cc:afgh@somedomain.com \r\n";
   $header .= "MIME-Version: 1.0\r\n";
   $header .= "Content-type: text/html\r\n";
   $retval = mail ($to,$subject,$message,$header);
   if( $retval == true )
   {
      echo "Message sent successfully...";
   }
   else
   {
      echo "Message could not be sent...";
   }
?>
</body>
</html>

Sending attachments with email:

To send an email with mixed content requires to set Content-type header to multipart/mixed. Then text and attachment sections can be specified within boundaries.

A boundary is started with two hyphens followed by a unique number which can not appear in the message part of the email. A PHP function md5() is used to create a 32 digit hexadecimal number to create unique number. A final boundary denoting the email’s final section must also end with two hyphens.

Attached files should be encoded with the base64_encode() function for safer transmission and are best split into chunks with the chunk_split() function. This adds \r\n inside the file at regular intervals, normally every 76 characters.

Following is the example which will send a file /tmp/test.txt as an attachment. you can code your program to receive an uploaded file and send it.

<html>
<head>
<title>Sending attachment using PHP</title>
</head>
<body>
<?php
  $to = "xyz@somedomain.com";
  $subject = "This is subject";
  $message = "This is test message.";
  # Open a file
  $file = fopen( "/tmp/test.txt", "r" );
  if( $file == false )
  {
     echo "Error in opening file";
     exit();
  }
  # Read the file into a variable
  $size = filesize("/tmp/test.txt");
  $content = fread( $file, $size);

  # encode the data for safe transit
  # and insert \r\n after every 76 chars.
  $encoded_content = chunk_split( base64_encode($content));

  # Get a random 32 bit number using time() as seed.
  $num = md5( time() );

  # Define the main headers.
  $header = "From:xyz@somedomain.com\r\n";
  $header .= "MIME-Version: 1.0\r\n";
  $header .= "Content-Type: multipart/mixed; ";
  $header .= "boundary=$num\r\n";
  $header .= "--$num\r\n";

  # Define the message section
  $header .= "Content-Type: text/plain\r\n";
  $header .= "Content-Transfer-Encoding:8bit\r\n\n";
  $header .= "$message\r\n";
  $header .= "--$num\r\n";

  # Define the attachment section
  $header .= "Content-Type:  multipart/mixed; ";
  $header .= "name=\"test.txt\"\r\n";
  $header .= "Content-Transfer-Encoding:base64\r\n";
  $header .= "Content-Disposition:attachment; ";
  $header .= "filename=\"test.txt\"\r\n\n";
  $header .= "$encoded_content\r\n";
  $header .= "--$num--";

  # Send email now
  $retval = mail ( $to, $subject, "", $header );
  if( $retval == true )
   {
      echo "Message sent successfully...";
   }
   else
   {
      echo "Message could not be sent...";
   }
?>
</body>
</html>

PHP Sessions

A PHP session variable is used to store information about, or change settings for a user session. Session variables hold information about one single user, and are available to all pages in one application.A session creates a file in a temporary directory on the server where registered session variables and their values are stored. This data will be available to all pages on the site during that visit.

A session ends when the user loses the browser or after leaving the site, the server will terminate the session after a predetermined period of time, commonly 30 minutes duration.

Starting a PHP Session:

A PHP session is easily started by making a call to the session_start() function.This function first checks if a session is already started and if none is started then it starts one. It is recommended to put the call to session_start() at the beginning of the page.

Session variables are stored in associative array called $_SESSION[]. These variables can be accessed during lifetime of a session.

The following example starts a session then register a variable called counter that is incremented each time the page is visited during the session.

Make use of isset() function to check if session variable is already set or not.

Put this code in a test.php file and load this file many times to see the result:

<?php
session_start();
if( isset( $_SESSION['counter'] ) )
{
$_SESSION['counter'] += 1;
}
else
{
$_SESSION['counter'] = 1;
}
$msg = “You have visited this page “.  $_SESSION['counter'];
$msg .= “in this session.”;
?>
<html>
<head>
<title>Setting up a PHP session</title>
</head>
<body>
<?php  echo ( $msg ); ?>
</body>
</html>

Destroying a PHP Session:

A PHP session can be destroyed by session_destroy() function. This function does not need any argument and a single call can destroy all the session variables. If you want to destroy a single session variable then you can use unset() function to unset a session variable.

Here is the example to unset a single variable:

<?php
unset($_SESSION['counter']);
?>

Here is the call which will destroy all the session variables:

<?php
session_destroy();
?>

Turning on Auto Session:

You don’t need to call start_session() function to start a session when a user visits your site if you can set session.auto_start variable to 1 in php.ini file.
Sessions without cookies:

There may be a case when a user does not allow to store cookies on their machine. So there is another method to send session ID to the browser.

Alternatively, you can use the constant SID which is defined if the session started. If the client did not send an appropriate session cookie, it has the form session_name=session_id. Otherwise, it expands to an empty string. Thus, you can embed it unconditionally into URLs.

The following example demonstrates how to register a variable, and how to link correctly to another page using SID.

<?php
session_start();

if (isset($_SESSION['counter'])) {
$_SESSION['counter'] = 1;
} else {
$_SESSION['counter']++;
}
?>
$msg = “You have visited this page “.  $_SESSION['counter'];
$msg .= “in this session.”;
echo ( $msg );
<p>
To continue  click following link <br />
<a  href=”nextpage.php?<?php echo htmlspecialchars(SID); >”>
</p>

The htmlspecialchars() may be used when printing the SID in order to prevent XSS related attacks.

PHP Cookies

A cookie is often used to identify a user.A cookie is a tiny little file on your client’s hard drive which contains data you have asked to be stored. Some clients specifically configure their browser to reject cookies, believing for one reason or another that they are malicious, and there is nothing you can do about this – that person’s browser will not be able to store your data. When creating cookies, you specify how long you want it to be valid for, and, once done, the cookie remains in place until that date, when it “expires”.

Cookies are automatically sent to the web server (and received/parsed by PHP) each time a user visits you. That means that once we place our cookie, our visitors’ browsers will automatically send the contents of that cookie across to us each time they view our messageboard index, and PHP will read the value into the $_COOKIE superglobal array. As cookies are sent each time, it is incredibly important not to store too much information there – they can really waste a lot of bandwidth.

The nice thing about cookies is that they are decentralised – you do not need to worry about creating databases to hold information or adding and removing rows, you just store the data and check whether it is set. As such, cookies are good for any pages where you have got a small amount of information to handle – usually this involves user preferences. For example, use cookies to store how users want their messageboard index sorting, what order they like their news printed, etc.

If you are storing information such as their email address, ICQ number, etc, you should probably use a database – data like that is generally stored for long periods of time, whereas cookies are usually more throwaway information. That said, if you are storing personal information in cookies, please take the time to encrypt it.

Setting Cookies with PHP:
PHP provided setcookie() function to set a cookie. This function requires upto six arguments and should be called before <html> tag. For each cookie this function has to be called separately.

setcookie(name, value, expire, path, domain, security);

Here is the detail of all the arguments:

Name – This sets the name of the cookie and is stored in an environment variable called HTTP_COOKIE_VARS. This variable is used while accessing cookies.

Value -This sets the value of the named variable and is the content that you actually want to store.

Expiry – This specify a future time in seconds since 00:00:00 GMT on 1st Jan 1970. After this time cookie will become inaccessible. If this parameter is not set then cookie will automatically expire when the Web Browser is closed.

Path -This specifies the directories for which the cookie is valid. A single forward slash character permits the cookie to be valid for all directories.

Domain – This can be used to specify the domain name in very large domains and must contain at least two periods to be valid. All cookies are only valid for the host and domain which created them.

Security – This can be set to 1 to specify that the cookie should only be sent by secure transmission using HTTPS otherwise set to 0 which mean cookie can be sent by regular HTTP.

Following example will create two cookies name and age these cookies will be expired after one hour.

<?php
setcookie(“name”, “John Watkin”, time()+3600, “/”,”", 0);
setcookie(“age”, “36″, time()+3600, “/”, “”,  0);
?>
<html>
<head>
<title>Setting Cookies with PHP</title>
</head>
<body>
<?php echo “Set Cookies”?>
</body>
</html>

Accessing Cookies with PHP

PHP provides many ways to access cookies.Simplest way is to use either $_COOKIE or $HTTP_COOKIE_VARS variables. Following example will access all the cookies set in above example.

<html>
<head>
<title>Accessing Cookies with PHP</title>
</head>
<body>
<?php
echo $_COOKIE["name"]. “<br />”;
/* is equivalent to */
echo $HTTP_COOKIE_VARS["name"]. “<br />”;

echo $_COOKIE["age"] . “<br />”;
/* is equivalent to */
echo $HTTP_COOKIE_VARS["name"] . “<br />”;
?>
</body>
</html>

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

<html>
<head>
<title>Accessing Cookies with PHP</title>
</head>
<body>
<?php
if( isset($_COOKIE["name"]))
echo “Welcome ” . $_COOKIE["name"] . “<br />”;
else
echo “Sorry… Not recognized” . “<br />”;
?>
</body>
</html>

Deleting Cookie with PHP

Officially, to delete a cookie you should call setcookie() with the name argument only but this does not always work well, however, and should not be relied on.

It is safest to set the cookie with a date that has already expired:

<?php
setcookie( “name”, “”, time()- 60, “/”,”", 0);
setcookie( “age”, “”, time()- 60, “/”,”", 0);
?>
<html>
<head>
<title>Deleting Cookies with PHP</title>
</head>
<body>
<?php echo “Deleted Cookies” ?>
</body>
</html>