Thursday, December 24, 2009

PHP Tutorial- Working with Forms

PHP comprises of a very powerful feature of handling HTML forms. The basic concept in this is that any form element in an HTML page will automatically be available in the PHP scripts.


Creating Forms


The forms in PHP are created in the same way as they were created in HTML. The most important thing in this that any form element in an HTML page will be available to the PHP script.










Example

<html>


<body>


<form action="action.php" method="POST">
Enter your name:
<input type="text" name="name" />
Enter your age: <input type="text" name="age" />
<input type="submit" />
</form>  
</body>
</html>

 


 In the above example the HTML page contains two fields of input type and a submit button. When the user fills in the forma and hits the submit button then the “action.php” file will be called. The purpose of action and method in the form tag will be explained later.


Submitting Data


After designing a form, the first step is to set up the form to submit its data to the PHP script. The submission of data is done through the action attribute of the <form> tag. When a form is submitted, the web server executes the PHP script and passes to it the values which were submitted in the submission. This attribute defines the URL to which the data is submitted.










Example
If the PHP script is called “welcome.php” then the <form> tag would be like:   <form action=”welcome.php” method=”POST”>  
 


Post and Get Operations


There are two methods that can be used while creating a form in HTML. These methods are post and get.  










Example

<form action=”welcome.php” method=”POST”>  


Or  


<form action=”welcome.php” method=”GET”>  

 



The get and the post method do the same thing. If no method is specified then the default method is taken as GET by the web server.   The get method puts the contents of the form right in the URL. This method has certain disadvantages. The first one being that there is a limit that how much data can be sent through the form using the get method. It depends on the web server’s operating system and software and many systems have a limit of 256 characters. The second thing is that individual get queries may be stored in the web server’s logs   The post method was created to correct the inadequacies of the get method. Firstly, the information that is sent through the post method is not visible in the URL. Secondly, the data cannot be deciphered by looking into the web server logs. The limit on the amount of data that can be sent from a form is not as small as that of get.      


Cookies  


A cookie is used to identify a user. A cookie is a small file that is embedded by the server on the user’s computer. In this when the same computer requests for a page with a browser, it will send the cookie too. Each cookie consists of a name, value, expiry date, and host and path information. The size of an individual cookie is limited to 4 KB. With PHP, cookie values can be created and retrieved.


Creating Cookie


The setcookie() function is used to create cookies. The setcookie() function should be called before any other content is sent to the browser. The setcookie() function appears before the HTML tag. The setcookie() function accepts the cookie name, cookie value, expiry date, path, and domain. All the arguments to this function are optional apart from the cookie name parameter.  










Syntax
Setcookie(name, value, expire, path, domain);
 









Example
<?php setcookie("usal", $sal, time()+3600); ?>   <html> <body>   <p> A cookie was set on this page! The cookie will be active when the client has sent the cookie back to the server. </p>   </body> </html>  
 


In the above a example a cookie named usal was set with the setcookie() function. This cookie will expire in one hour as the parameter of time given in the function is set to 1 hour.


Retrieving a Cookie Value


When a cookie is set, then the cookie name is used as a variable by PHP. To access the cookie the cookie name has to be referred as a variable.  








Example

<html>


<body>
<?php if (isset($_COOKIE[" usa))
echo "Welcome " . $_COOKIE["usal"] . "!<br />";
else
echo "You are not logged in!<br />"; ?>
</body>
</html>

PHP Tutorial- Operators

By now, you must have started writing those scripts and started working on PHP. Now, it’s time for you to learn about the operators available in PHP. An operator is something in which one or more values are fed and it gives another value as a result.

In general there are three types of operators:

  • Unary – it operates on only one value.

  • Binary – it operates on two or more than two values.

  • Ternary – it is used to select between two expressions depending on the third one.
There are many types of operators in PHP; some of them are useful but some are not. In this tutorial we will be studying about the most useful operators in PHP, which are:
  • Arithmetic operators

  • Assignment operators

  • Comparison operators

  • Logical operators
Arithmetic Operators
Addition (+)
$a=20;
$b=10;
$c=$a+$b;
Result = 30
Subtraction (-)
$a=15;
$b=10;
$c=$a-$b;
Result = 5
Multiplication (*)
$a=5;
$b=2;
$c=$a*$b;
Result = 10
Division (/)
$a=30;
$b=2;
$c=$a/$b;
Result = 15
Modulus (%)
$a=5;
$b=2;
$c=$a%$b;
Result = 1
Increment (++)
$a=5;
$a++;
Result = 6
Decrement (--)
$a=5;
$a--;
Result = 4

PHP Tutorial- Functions

In this chapter you will be getting technical know how of functions. Functions are useful in any type of programming language. Whenever you want to use a particular piece of code over and over again, it is very useful to put that code in a function. This is done so that the code can be reused easily. Another use of using functions is that whenever there is an error in the code, and then it has to be corrected only at one place; in the function. With the use of functions, the entire code can be understood easily.


Declaring Functions


Creating your own function in your script is a straightforward task. It is like creating a function in any other language. The functions in PHP begin with the keyword"function" which is followed by the function name. Following the function name there is a set of parenthesis which contains the parameters to be passed. These parameters are an optional set of variables passed to the function.









Syntax

function <name of function> ([$var1 [= constant]], [$var2 [= constant]], ...)


{


Body of the function;


}

 

Your First Function


Now that you have got an idea of th2e functions, you are ready to start with functions. In the following example the string "Welcome to vudevelopers!" will be printed five times on the browser with the help of functions. By writing a single code once in a function, we can call the same function again in a script.

















































Example

<html>


<body>


<?php


function fundisp()


{


for($i = 0; $i < 5; $i++)


{


echo "Welcome to vudevelopers!<br/>";


}


}


echo "After this statement the function will be called.<br/><br/>";


fundisp();


echo "<br/>";


echo "This statement is printed after the function has been called.";


echo "<br/>";


?>


</body>


</html>

 
 

Output



Passing Parameters to Functions


In this section we will be discussing about how to pass parameters to a function in PHP. A parameter of a function is a piece of data that a function requires to execute. If we define parameters formally then, function parameters are represented by variable names which are located within the parenthesis of the function definition.


In the following example of passing parameters to functions we will be displaying the string "Welcome to vudevelopers!." The difference that this example has got with the previous example is that, in this example the number of times the text will be displayed is not fixed, rather that number is passed as a parameter when the function is called.


















































Example


<html>


<body>


<?php


function fundisp($num)


{


for($i = 0; $i < $num; $i++)


{


echo "Welcome to vudevelopers!<br/>";


}


}


echo "After this statement the function will be called.<br/><br/>";


fundisp(7);


echo "<br/>";


echo "This statement is printed after the function has been called.";


echo "<br/>";


?>


</body>


</html>


Output


PHP Tutorial- Conditionals and Looping

Conditionals and Looping


In the previous chapters the basics of PHP have been explained. With this you must be well versed with the basic idea of PHP. Now we will be taking a step forward and moving on to the learning of the conditional statements and looping structures. These conditional statements and looping structures give you more flexibility in writing a PHP script.


Conditional Statements


Conditions and conditional statements are a part of every programming language and scripting language. There are times when you want to perform different actions for different decisions. In this you have to use conditional statements, so that the correct decision should be made.


Consider a situation if you want to greet every visitor on your site on 25 th December with Merry Christmas. In order to achieve this you do not have write a code on Christmas displaying Merry Christmas. This can be done well in advance as you can always write a conditional statement that if date is 25 th December then Merry Christmas should be displayed. So, with the help of conditional statements job done, well in advance.


In PHP there are two conditional statements:



  • If then else statement – This statement is used to execute a specific set of code if the condition is true and other set of code should be executed if the condition is false.


  • Switch statement – This statement is used when you want that one of many lines of codes should execute.

If Statement


The “if else” statement is used if one set of code has to be executed when the condition is true and another set of code has to be executed when the condition is false.









Syntax

If (condition)


Statements to be executed if code is true;


else


Statements to be executed if code is false;

 

In the following example x is compared with y. If x is greater than y then it will display x is greater then y else it will display y is greater than x.
































Example


<html>


<body>


<?php


$x=10;


$y=15;


if ($x>$y)


echo "x is greater than y";


Else


echo "y is greater than x";


?>


</body>


</html>

 

 


In the if statement if you want to execute more than one line when the condition is true then those lines should be put in curly braces.

PHP Tutorial- Classes and Objects

Classes and Objects are considered to be the most useful and dynamic aspects of a programming language. In PHP, classes are used extensively and are very useful. The concept of classes allows for better performance and more features.


What is a Class?


The Class in PHP is basically the same as in other languages such as Java. The class definition begins with the keyword class, followed by a class name. The form name can be any name except a reserved word or keyword in PHP. The class name is followed by a pair of curly braces which contain the definition of class members and methods.
























Example of a Class


<?php


Class abc


{


//member functions and variables go here


}


?>


What is an Object?


An Object is an enclosed bundle of variables and functions which is copied from a Class. Objects provide an easy interface and hide a lot of their inner workings. The object sends orders through special functions called methods and they can return information.


While creating a Class, a set of characteristics is laid down. By creating Objects of that type, entities are created that share these characteristics but the Object might initialize them as different values.


 










Example


Suppose there is a class named building. This class would have a characteristic named floor. All the objects of class building would share the characteristics of floor, but some would initialize it to “one”, some to “two”, others to “three” or “four”, and so on.


The benefit of object oriented code is that it is re-useable. In this the classes can be used to create different objects and classes from one project can be used in other projects as well. Child classes can also be created which inherits the properties of the parent classes.


Creating an Instance


To start with, a class having no member functions and variables is not useful. For a class to be completely useful, member functions and variables have to be added in that class.


Let’s take an example of a class with a variable in it.
























Example


<?php


Class abc


{


$a = “Hello!”;


}


?>


The class abc is the basis from which many objects can be instantiated. The new keyword is used to create an object. Now any abc object that is created contains a property called $a with the value of “Hello”. This property can be accessed and even be changed with the help of objects.


In this the -> operator is used to access or change the properties of the object.


In the following example $obj1 and $obj2 are the objects of the class abc. In this $obj2 has been assigned the string “Welcome to vudevelopers!” to its $a property.
















































Example


<html>


<body>


<?php


Class abc


{


var $a = "Hello";


}


$obj1 = new abc();


$obj2 = new abc();


$obj2->a = "Welcome to vudevelopers!";


echo "$obj1->a<br />";


echo "$obj2->a<br />";


?>


</body>


</html>


Output


Extends


Another feature of object oriented programming is used in PHP, which is inheritance. In PHP a class a class can inherit methods, functions and members of other class by using the extends keyword in the declaration. In PHP it is not possible to inherit from multiple classes, a class can inherit from only one base class.


The class from which inheritance is done is called the parent class or base class and the class which inherits is called the child class.


The Keyword Final


The final keyword prevents the child classes from overriding a method. This can be done by prefixing the method with the keyword final. If the complete class is being defined as final then that class cannot be extended.
















Example


 


final class test


{


//methods and functions


}


The class defined above i.e. class test cannot be overloaded as it has been finalized by using the keyword final with it.


Abstract


A new concept of abstract classes and methods has been introduced in PHP5. When a class is defined as abstract then it is not allowed to create the instance of that class. A class that contains at least one abstract method must also be abstract. The methods defined as abstract cannot define the implementation; they just declare the method’s signature.


When a child class is inheriting from an abstract parent class, then all the methods marked abstract in parent class declaration must also be additionally defined by the child class. These methods must be defined with the same or weaker access. This means that if an abstract method is declared as protected in the parent class then it must be declared either as protected or public in the child class.


Static Keyword


When class members or methods are declared as static then there is no need to instantiate that class. These members and methods are accessible without the instantiation of the class. If a member is declared as static then it cannot be accessed by an instantiated class object, but a method declared as static can be accessed by an instantiated class object.


The static declaration of a class must be after the visibility declaration (means that after the member or method has been declared as public, protected, or private).


The static method calls are resolved at compile time and static properties cannot be accessed through the object through the arrow operator (->).


Interfaces


Object interfaces allow the creation of a code which specifies that which method a class must implement, without having to define how these methods have to be handled.


Interfaces are defined in the same way as a class is defined. These interfaces are defined with the keyword “interface”. In the interface the contents of the methods do not have to be defined and all the methods declared in the interface must be declared as public.


Implementation of Interfaces


To implement an interface, the implements operator is used. The methods must be defined before implementation and all the methods in the interface must be implemented within a class.


Exceptions


Exception handling in PHP is similar to that of other programming languages. Within a PHP block of code we can throw, try and catch an exception. There must be at least one catch block in a try block. In this multiple catch blocks can be used to catch different class types. In exception handling the execution will continue after the last catch block has been encountered and exceptions can be thrown within catch blocks.


In exception handling when an exception is thrown, the code following the statement will not be executed rather PHP will attempt to find the first matching catch block. If the exception is not caught then it will result in a fatal error with an uncaught exception message.

PHP Tutorial- An Introduction to PHP

This tutorial moves a step further from the basic HTML, and it will enhance your art of making good web pages with the use of PHP. Until recently, many websites were made only with the use of HTML, but the recent dot com revolution has changed the scenario. In today´s world, more and more scripting languages have come into existence and PHP is one of them. It is the easiest scripting language and yet the most powerful.


You should be having a basic understanding of WWW, HTML, and basics of building web pages before you learn the usage and handling of PHP.


What is PHP?


PHP stands for Hypertext Preprocessor. PHP is an open source server side scripting language that is especially suited for web development and can be embedded into HTML. The PHP scripts are executed on the server, not on the user´s browser, so there are no compatibility issues. PHP supports many databases like MySQL, Oracle, and Sybase. Since PHP is open source software, therefore it is free to download and use. Due to this it is quickly becoming the most famous scripting languages on the internet.


Why PHP?


Many questions must be coming to your mind, like:


Why should I learn a scripting language?


Why should I choose PHP over other languages?




  • Learning a scripting language can open up huge possibilities for your website. With the use of scripts you can add many new interactive features like feedback forms, guest books, message boards, counters and many more advanced features. This will give your website a more professional image.


  • PHP is one of the most powerful scripting languages which run on different platforms. It is compatible to almost all the servers used today. The most striking features of PHP are that it is FREE to download, easy to learn, and runs efficiently on the server side.

What does a PHP File contain?



  • PHP files may contain text, HTML tags and scripts.


  • PHP files are returned to the browser as plain HTML.


  • PHP files have an extension of ".php", ".php3", or ".phtml".

What is needed to run PHP?


PHP is a server side scripting language. This means that, the users will not need to install new software but your web host will need to have PHP set up on their server.


PHP Tutorial- Advanced PHP Topics

Superglobals


In the previous chapters the concept of global variable was explained. A global variable is a variable declared at the top of the script outside the function. This variable is available to the complete script. Superglobal variables are arrays built into PHP. These superglobal variables are populated automatically with useful elements, and they are available in any scope. A superglobal array can be accessed within a function or a method without using the global keyword.


PHP Superglobals



  • $_COOKIE – It contains values provided to the script via HTTP cookies.


  • $_GET – It contains variables submitted to the script using HTTP get method.


  • $_POST – It contains variables submitted to the script using HTTP post method.


  • $_REQUEST – It is a combined array containing values from the $_GET, $_POST, and $_COOKIES superglobal arrays.


  • $_ENV – It contains keys and values set by the script’s shell.


  • $_FILES – It contains information about uploaded files.


  • $_SERVER – It contains variables made available by the server.


  • $GLOBALS – It contains all the global variables associated with the current script.

Instanceof Operator


The instanceof operator in PHP is used to determine whether a given object, the parents of that object, or its implemented interfaces are of a specified object class.









Example

<?php


class X { }


class Y { }


$thing = new X;


if ($thing instanceof X) {


echo 'X';


}


if ($thing instanceof Y) {


echo 'Y';


}


?>

 

Declare


The declare statement is used to set execution directives for a block of code. The syntax of the declare statement is similar to the syntax of other flow control statements.









Syntax

declare (directive)


statement

 

The directive section allows the behavior of the declare block to be set. In this only one directive is recognized, which is the ticks directive.


[ Ticks - A tick is an event that occurs for every N low level statements, which are executed within the declare block. The value of N is specified using the statement ticks = N in the directive section.]


The statement part of the declare block will be executed according to the directives set in the directive block.







Example

<?php


// how to use declare:


// the first way:


declare(ticks=1) {


// entire script here


}


// the second way:


declare(ticks=1);


// entire script here


?>