Thursday, November 29, 2012

Comparison and Logical Operators

Comparison and Logical operators are used to test for true or false.

Comparison Operators

 Comparison operators are used in logical statements to determine equality or difference between variables or values. Given that x=5, the table below explains the comparison operators:

Operator
Description Comparing Returns
== is equal to x==8 false
x==5 true
=== is exactly equal to (value and type) x==="5" false
x===5 true
!= is not equal x!=8 true
!== is not equal (neither value nor type) x!=="5" true
x!==5 false
> is greater than x>8 false
< is less than x<8 true
>= is greater than or equal to x>=8 false
<= is less than or equal to x<=8 true

Logical Operators

Logical operators are used to determine the logic between variables or values.
Given that x=6 and y=3, the table below explains the logical operators:
Operator Description Example
&& and (x < 10 && y > 1) is true
|| or (x==5 || y==5) is false
! not !(x==y) is true


Wednesday, November 28, 2012

Doctype Defination

A Document Type Declaration, or DOCTYPE, is an instruction that associates a particular SGML or XML document (for example, a webpage) with a Document Type Definition (DTD).

Syntax

The general syntax for a document type declaration is:

<!DOCTYPE root-element PUBLIC "FPI" ["URI"] [
<!-- internal subset declarations -->
]>

Tuesday, November 27, 2012

Accessible Forms

Forms aren't the easiest of things to use for people with disabilities. Navigating around a page with written content is one thing, hopping between form fields and inputting information is another. Because of this, it is a good idea to add a number of elements to the form.

Labels

Each form field should have its own label. The label tag sorts this out, with a for attribute that associates it to a form element:

Monday, November 26, 2012

Advanced Tables

Okay till now, you must be confident with creating tables and its tags. You have already done or used tags like table, tr, td, th and even rowspan and colspan. So now I am moving on to the advance tutorial of the table tags.

Those are as below:
colgroup and col
summary and caption
headers, footers and scrolling table


Download Wamp

Quotations

Quotations

blockquote, q and cite are used for quotations. blockquote is block-line and used for large citations, whereas q is in-line and used for smaller phrases. cite is also in-line and preferable to q for its semantic nature and possible future deprecation of q.

Again, the title attribute can be used to show where the citation has come from.

Abbreviations and acronyms

abbr and acronym are used for abbreviations and acronyms respectively.

An abbreviation is a shortened form of a phrase. Very general. An acronym however is an abbreviation made up of the initial letters (or parts of words) of the phrase it is representing. So CSS is a valid acronym, whereas HTML and XHTML are not (if 'Hypertext markup language' was an acronym, it would be 'HML'. Similarly, XHTML would be EHML).

Definition Lists

Definition Lists

The dl element gets the ball rolling, similar to the ul and ol elements, establishing the list. Rather than there being an li element though, definition lists have a dt element, which is the definition term, followed by a dd element which is a definition description associated to the dt element.

There doesn't have to be one dt followed by one dd, there can be any number of either. For example, if there are a number of words that have the same meaning, there might be a number of dt's followed by one dd. If you have one word that means various different things, there might be one dt followed by several dd's.

Javascript events

Javascript events

Javascript is all about cool stuffs displayed in the website. So here we will learn how these cool stuffs happens in the website. This all are the ability of Javascript which increase the user interaction and flash like features.

The building blocks of an interactive web page is the JavaScript event system. An event in JavaScript is something that happens with or on the webpage. A few example of events:
  1.     A mouse click
  2.     The webpage loading
  3.     Mousing over a hot spot on the webpage, also known as hovering
  4.     Selecting an input box in an HTML form
  5.     A keystroke

For example:
<html>
<head>
<script type="text/javascript">
<!--
function popup() {
    alert("Wow!! I feel good.")
}
//-->
</script>
</head>
<body>

<input type="button" value="Click Me!" onclick="popup()"><br />
<a href="#" onmouseover="" onMouseout="popup()">
Hover Me!</a>

</body>
</html>

Javascript Array

Javascript Array

An array is a variable that can store many variables within it. Many programmers have seen arrays in other languages, and they aren't that different in JavaScript.

Creating a JavaScript Array

Creating an array is slightly different from creating a normal variable. Because JavaScript has variables and properties associated with arrays, you have to use a special function to create a new array. This example shows how you would create a simple array, store values to it, and access these values.
JavaScript Code:

<script type="text/javascript">
<!--
var myArray = new Array();

myArray[0] = "Football";
myArray[1] = "Baseball";
myArray[2] = "Cricket";

document.write(myArray[0] + myArray[1] + myArray[2]);
//-->
</script>

Output:
FootballBaseballCricket

JavaScript Array Sorting

Imagine that you wanted to sort an array alphabetically before you wrote the array to the browser. Well, this code has already been written and can be accessed by using the Array's sort method.
JavaScript Code:

<script type="text/javascript">
<!--
var myArray2= new Array();

myArray2[0] = "Football";
myArray2[1] = "Baseball";
myArray2[2] = "Cricket";

myArray2.sort();

document.write(myArray2[0] + myArray2[1] + myArray2[2]);
//-->
</script>

Display:
BaseballCricketFootball

Constructors and Destructors

Constructor

PHP 5 allows developers to declare constructor methods for classes. Classes which have a constructor method call this method on each newly-created object, so it is suitable for any initialization that the object may need before it is used.

Syntax:
void __construct ([ mixed $args [, $... ]] )

For example:

<?php
class constExample{
    function __construct()
    {
        echo "This will execute without calling a method";
    }

   
}

$obj = new constExample();

?>

Destructors

PHP 5 introduces a destructor concept similar to that of other object-oriented languages, such as C++. The destructor method will be called as soon as there are no other references to a particular object, or in any order during the shutdown sequence.

Syntax:
void __destruct ( void )

For example:
<?php
class MyDestructableClass {
   function __construct() {
       print "In constructor\n";
       $this->name = "MyDestructableClass";
   }

   function __destruct() {
       print "Destroying " . $this->name . "\n";
   }
}

$obj = new MyDestructableClass();
?>

Sunday, November 25, 2012

Class and object

Creating a Class:

To create a class use the class keyword and a name. Class names can be any combination of numbers and letters, although they must not begin with a number.
The code associated with a class must be enclosed within braces.

Class Defination:

<?php
class ClassName {
  // class body
}
?>

For example:
<?php

class Books{

public $name;
public $author;

public function showBook(){
$name="Munna Madan";
echo $name;
}
}
?>

Setting Properties and Methods

In the class body are defined its properties and methods.
        - Properties are variables defined inside the class.
        - Methods are functions created within the class, with the word "function".

The name of the variable (property) and the "function" word must be preceded by a specific attribute that determines the level of access that is allowed for the property or the method to be accessed outside its class. This can be: public, protected, or private.

    public - available in all script
    protected - available to the class itself and to sub-classes that inherit from it
    private - available only inside that class

If no attribute is added, it is considered "public".

Full syntax to create a class is:

<?php
class Class_Name {
  attribute $property1;
  attribute $property2;
  ...

  attribute function Method1() {
    // method code
  }
  attribute function Method2() {
    // method code
  }
  ...
}
?>

Creating Objects:

Once a class is created, to be used in your script, you must instantiate an object of that class. The instance is declared in the PHP script with the new operator, followed by the name of the class and two parentheses.
   Syntax:

$object_Name = new Class_Name();

- $object_Name is the name of the object by which can be used properties and methods of that class.


Now full example of Class and object below:

<?php

class Books{

public $name;
public $author;

function showName(){
    $name="Munna Madan";
    $author="Laxmi Prasad Devkota";
   
    echo "Book named ".$name." was written by".$author;
}
   
}

$obj=new Books(); //creating an object
$obj->showName();// calling function via object

?>
I hope it was not very hard !!!

Object Oriented Programming

PHP is an object- oriented programming language.

What is object-oriented programming (OOP)?

Object-oriented programming(OOP) is a programming language using objects usually instances of a class, consisting of data fields and methods together with their interactions to design applications and computer programs.

Main features of OOP are as below:

 Class and object:
    A class is a group of objects and an object is an instance of a class. It contains the code for properties and methods.


Encapsulation:
    Encapsulation is the ability of an object to protect the data (properties) of a class from outside influences. You can use a class (its properties) through an object instance, without having access to its code.

Inheritance:
    Inheritance is the ability of a class to copy or inherit the properties and methods of a parent class.

Polymorphism:
    Polymorphism is a class ability to do more different things, or use one class or another to achieve the same thing, having similar functions.

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>

Friday, November 23, 2012

Some useful functions for manipulating array

Function
Explanation
Example
sizeof($arr) This function returns the number of elements in an array.Use this function to find out how many elements an array contains; this information is most commonly used to initialize a loop counter when processing the array. Code: $data = array("red", "green", "blue");echo "Array has " . sizeof($data) . " elements"; ?>Output: Array has 3 elements
array_values($arr) This function accepts a PHP array and returns a new array containing only its values (not its keys). Its counterpart is the array_keys() function.Use this function to retrieve all the values from an associative array. Code: $data = array("hero" => "Holmes", "villain" => "Moriarty"); print_r(array_values($data)); ?>Output: Array ( [0] => Holmes [1] => Moriarty )
array_keys($arr) This function accepts a PHP array and returns a new array containing only its keys (not its values). Its counterpart is the array_values() function.Use this function to retrieve all the keys from an associative array. Code: $data = array("hero" => "Holmes", "villain" => "Moriarty"); print_r(array_keys($data)); ?>Output: Array ( [0] => hero [1] => villain )
array_pop($arr) This function removes an element from the end of an array. Code: $data = array("Donald", "Jim", "Tom"); array_pop($data); print_r($data); ?>Output: Array ( [0] => Donald [1] => Jim )
array_push($arr, $val) This function adds an element to the end of an array. Code: $data = array("Donald", "Jim", "Tom"); array_push($data, "Harry"); print_r($data); ?>Output: Array ( [0] => Donald [1] => Jim [2] => Tom [3] => Harry )
array_shift($arr) This function removes an element from the beginning of an array. Code: $data = array("Donald", "Jim", "Tom"); array_shift($data); print_r($data); ?>Output: Array ( [0] => Jim [1] => Tom )
array_unshift($arr, $val) This function adds an element to the beginning of an array. Code: $data = array("Donald", "Jim", "Tom"); array_unshift($data, "Sarah"); print_r($data); ?>Output: Array ( [0] => Sarah [1] => Donald [2] => Jim [3] => Tom )
each($arr) This function is most often used to iteratively traverse an array. Each time each() is called, it returns the current key-value pair and moves the array cursor forward one element. This makes it most suitable for use in a loop. Code: $data = array("hero" => "Holmes", "villain" => "Moriarty"); while (list($key, $value) = each($data)) { echo "$key: $value \n"; } ?>Output: hero: Holmes villain: Moriarty
sort($arr) This function sorts the elements of an array in ascending order. String values will be arranged in ascending alphabetical order.Note: Other sorting functions include asort(), arsort(), ksort(), krsort() and rsort(). Code: $data = array("g", "t", "a", "s"); sort($data); print_r($data); ?>Output: Array ( [0] => a [1] => g [2] => s [3] => t )
array_flip($arr) The function exchanges the keys and values of a PHP associative array.Use this function if you have a tabular (rows and columns) structure in an array, and you want to interchange the rows and columns. Code: $data = array("a" => "apple", "b" => "ball"); print_r(array_flip($data)); ?>Output: Array ( [apple] => a [ball] => b )
array_reverse($arr) The function reverses the order of elements in an array.Use this function to re-order a sorted list of values in reverse for easier processing—for example, when you're trying to begin with the minimum or maximum of a set of ordered values. Code: $data = array(10, 20, 25, 60); print_r(array_reverse($data)); ?>Output: Array ( [0] => 60 [1] => 25 [2] => 20 [3] => 10 )
array_merge($arr) This function merges two or more arrays to create a single composite array. Key collisions are resolved in favor of the latest entry.Use this function when you need to combine data from two or more arrays into a single structure—for example, records from two different SQL queries. Code: $data1 = array("cat", "goat"); $data2 = array("dog", "cow"); print_r(array_merge($data1, $data2)); ?>Output: Array ( [0] => cat [1] => goat [2] => dog [3] => cow )
array_rand($arr) This function selects one or more random elements from an array.Use this function when you need to randomly select from a collection of discrete values—for example, picking a random color from a list. Code: $data = array("white", "black", "red"); echo "Today's color is " . $data[array_rand($data)]; ?>Output: Today's color is red
array_search($search, $arr) This function searches the values in an array for a match to the search term, and returns the corresponding key if found. If more than one match exists, the key of the first matching value is returned.Use this function to scan a set of index-value pairs for matches, and return the matching index. Code: $data = array("blue" => "#0000cc", "black" => "#000000", "green" => "#00ff00"); echo "Found " . array_search("#0000cc", $data); ?>Output: Found blue
array_slice($arr, $offset, $length) This function is useful to extract a subset of the elements of an array, as another array. Extracting begins from array offset $offset and continues until the array slice is $length elements long.Use this function to break a larger array into smaller ones—for example, when segmenting an array by size ("chunking") or type of data. Code: $data = array("vanilla", "strawberry", "mango", "peaches"); print_r(array_slice($data, 1, 2)); ?>Output: Array ( [0] => strawberry [1] => mango )
array_unique($data) This function strips an array of duplicate values.Use this function when you need to remove non-unique elements from an array—for example, when creating an array to hold values for a table's primary key. Code: $data = array(1,1,4,6,7,4); print_r(array_unique($data)); ?>Output: Array ( [0] => 1 [3] => 6 [4] => 7 [5] => 4 )
array_walk($arr, $func) This function "walks" through an array, applying a user-defined function to every element. It returns the changed array.Use this function if you need to perform custom processing on every element of an array—for example, reducing a number series by 10%. Code: function reduceBy10(&$val, $key) { $val -= $val * 0.1; }$data = array(10,20,30,40); array_walk($data, 'reduceBy10'); print_r($data); ?>Output: Array ( [0] => 9 [1] => 18 [2] => 27 [3] => 36 )

Differences between echo, print and print_r in PHP

echo :
Outputs one or more strings. And echo is not a function, but a language construct. echo has a void return type.echo is not actually a function (it is a language construct), so you are not required to use parentheses with it. echo (unlike some other language constructs) does not behave like a function, so it cannot always be used in the context of a function. Additionally, if you want to pass more than one parameter to echo, the parameters must not be enclosed within parentheses.
For example:
<?php   echo “Hello World”; ?>

echo also has a shortcut syntax, where you can immediately follow the opening tag with an equals sign. This short syntax only works with the short_open_tag configuration setting enabled.
For example:
My name is <?=$name; ?>.

Note: However, short tags are discouraged to use in modern versions on PHP..

print:
print is not actually a real function (it is a language construct) so you are not required to use parentheses with its argument list. print has a return value of 1 so it can be used in expressions.
For example:
<?php
print(“hello world!”);
print “hello world”;
?>

However, echo is slightly faster than print.

print_r():
It displays information about a variable in a way that’s readable by humans.
For example:
<pre>
<?php
$a = array (‘a’ => ‘apple’, ‘b’ => ‘banana’, ‘c’ => array (‘x’, ‘y’, ‘z’));
print_r ($a);
?>
</pre>

PHP File Upload

Create an Upload-File Form

To allow users to upload files from a form can be very useful.

Look at the following HTML form for uploading files:

<html>
<body>
<form action=”upload_file.php” method=”post”
enctype=”multipart/form-data”>
<label for=”file”>Filename:</label>
<input type=”file” name=”file” id=”file” />
<br />
<input type=”submit” name=”submit” value=”Submit” />
</form>

</body>
</html>

Notice the following about the HTML form above:

The enctype attribute of the <form> tag specifies which content-type to use when submitting the form. “multipart/form-data” is used when a form requires binary data, like the contents of a file, to be uploaded
The type=”file” attribute of the <input> tag specifies that the input should be processed as a file. For example, when viewed in a browser, there will be a browse-button next to the input field
Note: Allowing users to upload files is a big security risk. Only permit trusted users to perform file uploads.

Create The Upload Script

The “upload_file.php” file contains the code for uploading a file:

<?php
if ($_FILES["file"]["error"] > 0)
{
echo “Error: ” . $_FILES["file"]["error"] . “<br />”;
}
else
{
echo “Upload: ” . $_FILES["file"]["name"] . “<br />”;
echo “Type: ” . $_FILES["file"]["type"] . “<br />”;
echo “Size: ” . ($_FILES["file"]["size"] / 1024) . ” Kb<br />”;
echo “Stored in: ” . $_FILES["file"]["tmp_name"];
}
?>
By using the global PHP $_FILES array you can upload files from a client computer to the remote server.

The first parameter is the form’s input name and the second index can be either “name”, “type”, “size”, “tmp_name” or “error”. Like this:

$_FILES["file"]["name"] – the name of the uploaded file
$_FILES["file"]["type"] – the type of the uploaded file
$_FILES["file"]["size"] – the size in bytes of the uploaded file
$_FILES["file"]["tmp_name"] – the name of the temporary copy of the file stored on the server
$_FILES["file"]["error"] – the error code resulting from the file upload

PHP File

Opening a File The fopen() function is used to open files in PHP. The first parameter of this function contains the name of the file to be opened and the second parameter specifies in which mode the file should be opened: <html> <body> <?php $file=fopen("welcome.txt","r"); ?> </body> </html> Note: If the fopen() function is unable to open the specified file, it returns 0 (false). Example The following example generates a message if the fopen() function is unable to open the specified file: <html> <body> <?php $file=fopen("welcome.txt","r") or exit("Unable to open file!"); ?> </body> </html>

Modes Description
r Read only. Starts at the beginning of the file
r+ Read/Write. Starts at the beginning of the file
w Write only. Opens and clears the contents of file; or creates a new file if it doesn't exist
w+ Read/Write. Opens and clears the contents of file; or creates a new file if it doesn't exist
a Append. Opens and writes to the end of the file or creates a new file if it doesn't exist
a+ Read/Append. Preserves file content by writing to the end of the file
x Write only. Creates a new file. Returns FALSE and an error if file already exists
x+ Read/Write. Creates a new file. Returns FALSE and an error if file already exists
Closing a File
The fclose() function is used to close an open file:
<?php $file = fopen("test.txt","r"); //some code to be executed fclose($file); ?>

 Check End-of-file
The feof() function checks if the "end-of-file" (EOF) has been reached. The feof() function is useful for looping through data of unknown length.
 Note: You cannot read from files opened in w, a, and x mode! if (feof($file)) echo "End of file";  

Reading a File Line by Line The fgets() function is used to read a single line from a file.
 Note: After a call to this function the file pointer has moved to the next line.
Example
 The example below reads a file line by line, until the end of file is reached:
<?php $file = fopen("welcome.txt", "r") or exit("Unable to open file!");
 //Output a line of the file until the end is reached
 while(!feof($file)) { echo fgets($file). "<br />"; } fclose($file); ?>
  
Reading a File Character by Character The fgetc() function is used to read a single character from a file. Note: After a call to this function the file pointer moves to the next character.
 Example
 The example below reads a file character by character, until the end of file is reached:
 <?php $file=fopen("welcome.txt","r")
 or exit("Unable to open file!");
while (!feof($file))
 { echo fgetc($file); }
 fclose($file); ?>

PHP Include

Server Side Includes (SSI)
You can insert the content of one PHP file into another PHP file before the server executes it, with the include() or require() function.
The two functions are identical in every way, except how they handle errors:
  •     include() generates a warning, but the script will continue execution
  •     require() generates a fatal error, and the script will stop
These two functions are used to create functions, headers, footers, or elements that will be reused on multiple pages.
Server side includes saves a lot of work. This means that you can create a standard header, footer, or menu file for all your web pages. When the header needs to be updated, you can only update the include file, or when you add a new page to your site, you can simply change the menu file (instead of updating the links on all your web pages).
PHP include() Function
The include() function takes all the content in a specified file and includes it in the current file.
If an error occurs, the include() function generates a warning, but the script will continue execution.
Example 1
Assume that you have a standard header file, called “header.php”. To include the header file in a page, use the include() function:
<html>
<body>
<?php include(“header.php”); ?>
<h1>Welcome to my home page!</h1>
<p>Some text.</p>
</body>
</html>
Example 2
Assume we have a standard menu file, called “menu.php”, that should be used on all pages:
<a href=”index.php”>Home</a>
<a href=”about.php”>About Us</a>
<a href=”contact.php”>Contact Us</a>
If you look at the source code of the page above (in a browser), it will look like this:
<html>
<body>
<div>
<a href=”index.php”>Home</a>
<a href=”about.php”>About Us</a>
<a href=”contact.php”>Contact Us</a>
</div>
<h1>Welcome to my home page!</h1>
<p>Some text.</p>
</body>
</html>
PHP include_once() Function
The include_once statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the include statement, with the only difference being that if the code from a file has already been included, it will not be included again. As the name suggests, it will be included just once.
include_once may be used in cases where the same file might be included and evaluated more than once during a particular execution of a script, so in this case it may help avoid problems such as function redefinitions, variable value reassignments, etc.
PHP require() Function
The require() function is identical to include(), except that it handles errors differently.
If an error occurs, the include() function generates a warning, but the script will continue execution. The require() generates a fatal error, and the script will stop.
Error Example include() Function
<html>
<body>
<?php
include(“wrongFile.php”);
echo “Hello World!”;
?>
</body>
</html>
Error message:
Warning: include(wrongFile.php) [function.include]:
failed to open stream:
No such file or directory in C:\home\website\test.php on line 5
Warning: include() [function.include]:
Failed opening ‘wrongFile.php’ for inclusion
(include_path=’.;C:\php5\pear’)
in C:\home\website\test.php on line 5
Hello World!
Notice that the echo statement is executed! This is because a Warning does not stop the script execution.
Error Example require() Function
Now, let’s run the same example with the require() function.
<html>
<body>
<?php
require(“wrongFile.php”);
echo “Hello World!”;
?>
</body>
</html>
Error message:
Warning: require(wrongFile.php) [function.require]:
failed to open stream:
No such file or directory in C:\home\website\test.php on line 5
Fatal error: require() [function.require]:
Failed opening required ‘wrongFile.php’
(include_path=’.;C:\php5\pear’)
in C:\home\website\test.php on line 5
The echo statement is not executed, because the script execution stopped after the fatal error.
It is recommended to use the require() function instead of include(), because scripts should not continue after an error.
PHP require_once() Function
The require_once statement is identical to require except PHP will check if the file has already been included, and if so, not include (require) it again.