Friday, September 24, 2010

Introduction to PHP

PHP is a powerful tool for making dynamic and interactive Web pages.
PHP runs on different platform like Windows,Linux,Unix etc.
PHP compatible with almost all servers used today all over the world like IIS,Apache.
You can Download it for FREE from official website : http://www.php.net/downloads.php

What is PHP?
  • PHP stands for PHP: Hypertext Preprocessor
  • PHP is a server-side scripting language, like ASP
  • PHP scripts are executed on the server
  • PHP supports many databases (MySQL,Oracle etc.)
  • PHP is an open source software
  • PHP is free to download and use
What is MySql?
  • MySQL is a database server
  • MySQL is ideal for both small and large applications
  • MySQL supports standard SQL
  • MySQL compiles on a number of platforms
  • MySQL is free to download and use
PHP combined with MySQL are cross-platform (you can develop in Windows and serve on a Unix platform)

What do you need next?

If your server supports PHP you don't need to do anything.
Just create some .php files in your web directory, and the server will parse them for you. Because it is free, most web hosts offer PHP support.
However, if your server does not support PHP, you must install PHP.
Here is a link to a good tutorial from PHP.net on how to install PHP5: http://www.php.net/manual/en/install.php

Download MySql Database For Free:

Download MySQL for free here: http://www.mysql.com/downloads/index.html

Download Apache Server:

Download MySQL for free here: http://www.mysql.com/downloads/index.html

 

    Thursday, September 23, 2010

    Overview Of Software Engineering

    What is Software Engineering?

    The term Software Engineering first appeared in the 1968 NATO Software Engineering Conference and was meant to provoke thought regarding the current "Software Crisis" as the time.

    “state of the art of developing quality software on time and within budget"

    Trade-off between perfection and physical constraints
    • SE has to deal with real-world issues
    State of the art!
    • Community decides on “best practice”+ life-long education 

      Software Development Activity:


    Steps
    Description
    Requirements Collection Establish Customer Needs
    Analysis Model And Specify the requirements-“What”
    Design Model And Specify a Solution –“Why”
    Implementation Construct a Solution In Software
    Testing Validate the solution against the requirements
    Maintenance Repair defects and adapt the solution to the new requirements

    Planning:

    • The important task in creating a software product is extracting the requirements or requirements analysis. Customers typically have an abstract idea of what they want as an end result, but not what software should do. Incomplete, ambiguous, or even contradictory requirements are recognized by skilled and experienced software engineers at this point. Frequently demonstrating live code may help reduce the risk that the requirements are incorrect.
    •  Once the general requirements are gleaned from the client, an analysis of the scope of the development should be determined and clearly stated. This is often called a scope document. 

    Design:
    • Domain Analysis is often the first step in attempting to design a new piece of software, whether it be an addition to an existing software, a new application, a new subsystem or a whole new system. Assuming that the developers (including the analysts) are not sufficiently knowledgeable in the subject area of the new software, the first task is to investigate the so-called "domain" of the software. The more knowledgeable they are about the domain already, the less work required. Another objective of this work is to make the analysts, who will later try to elicit and gather the requirements from the area experts, speak with them in the domain's own terminology, facilitating a better understanding of what is being said by these experts. If the analyst does not use the proper terminology it is likely that they will not be taken seriously, thus this phase is an important prelude to extracting and gathering the requirements. If an analyst hasn't done the appropriate work confusion may ensue: "I know you believe you understood what you think I said, but I am not sure you realize what you heard is not what I meant."


    Specification:
    • Specification is the task of precisely describing the software to be written, possibly in a rigorous way. In practice, most successful specifications are written to understand and fine-tune applications that were already well-developed, although safety-critical software systems are often carefully specified prior to application development. Specifications are most important for external interfaces that must remain stable.A good way to determine whether the specifications are sufficiently precise is to have a third party review the documents making sure that the requirements and Use Cases are logically sound. 

    Architecture:
    • The architecture of a software system or software architecture refers to an abstract representation of that system. Architecture is concerned with making sure the software system will meet the requirements of the product, as well as ensuring that future requirements can be addressed. The architecture step also addresses interfaces between the software system and other software products, as well as the underlying hardware or the host operating system.

    Implementation:
    • Implementation is the part of the process where software engineers actually program the code for the project.

    Testing:
    • Software testing is an integral and important part of the software development process. This part of the process ensures that bugs are recognized as early as possible.

    Documentation:
    • Documenting the internal design of software for the purpose of future maintenance and enhancement is done throughout development. This may also include the authoring of an API, be it external or internal.

    Deployment and Maintenance:
    •  Deployment starts after the code is appropriately tested, is approved for release and sold or otherwise distributed into a production environment.
    • Maintenance and enhancing software to cope with newly discovered problems or new requirements can take far more time than the initial development of the software. It may be necessary to add code that does not fit the original design to correct an unforeseen problem or it may be that a customer is requesting more functionality and code can be added to accommodate their requests. It is during this phase that customer calls come in and you see whether your testing was extensive enough to uncover the problems before customers do. If the labor cost of the maintenance phase exceeds 25% of the prior-phases' labor cost, then it is likely that the overall quality, of at least one prior phase, is poor. In that case, management should consider the option of rebuilding the system (or portions) before maintenance cost is out of control..

    Wednesday, September 22, 2010

    About web URL

    What is WWW?

    • It stands for World Wide Web.
    • Web address are URL(Universal Resource Locator)
    • A server address and a path to a particular file.
    • URLs are often redirected to other places
    Example of URL:
    • http://students.myclass.com/classes/PHP&MYSQL/index.html
     In above URL,
    • Protocol : Http://
    • Web Server : Students
    • Domain : myclass.com
    • Path : /classes/PHP&MYSQL/ (dir(floders))
    • File : index.html
    • File Extension : .HTML(Hyper Text Markup Langague)

    Monday, September 20, 2010

    Web Programming

    Clients and Server
    •  Web programming languages are usually classified as server-side or client-side. Some languages, such as JavaScript, can be used as both client-side and server-side languages, but most Web programming languages are server-side languages. 
    • The client is the Web browser, so client-side scripting uses a Web browser to run scripts. The same script may produce different effects when different browsers run it. 
    • A Web server is a combination of software and hardware that outputs Web pages after receiving a request from a client. Server-side scripting takes place on the server. If you look at the source of a page created from a server-side script, you'll see only the HTML code the script has generated. The source code for the script is on the serverand doesn't need to be downloaded with the page that's sent back to the client.
    • Web Programming Languages:
    1. PHP
    2. ASP
    3. Perl
    4. Java Script

    Client/Server Interaction

    For Web pages, the client requests a page the server returns it:there’s no permanent connection, just a short conversation.
    Details of the conversation are specified by HTTP.










    Server-Side
    •   PHP is a Server-side language
    •  Even though it is embedded in HTML files much like the client-side Javascriptlanguage, PHP is server-side and all PHP tags will be replaced by the server before anything is sent to the web browser. 


    • So, if the HTML file contains any PHP(or any script langauge) code,  Then user will get just simple html code.

            
                 

      Saturday, September 18, 2010

      PHP Platform

      PHP Platforms
      • PHP can be installed on any web server: Apache, IIS, Netscape, etc…
      • PHP can be installed on any OS: Unix, Linux, Windows, MacOS, etc…
      • XAMPP is a free and open source cross-platform web server package, consisting mainly of the Apache HTTP Server, MySQL database, andinterpreters for scripts written in the PHP andPerlprogramming languages.
      • It is used as a development tool, to allow website designers and programmers to test their work on their own computers without any access to the Internet. 
      • XAMPP's name is an acronym for:
        X (meaning cross-platform)
        Apache HTTP Server
        MySQL
        PHP
        Perl
      • LAMP package is used for Linux OS.
      • WAMP package is used for Windows OS
         

      Friday, September 17, 2010

      Difference between php4 and php5

      1. Unified constructor and Destructor.
      2. Exception has been introduced.
      3. New error level named E_STRICT has been introduced.
      4. Now we can define full method definitions for a abstract class.
      5. Within a class we can define class constants.
      6. We can use the final keyword to indicate that a method cannot be overridden by a child.
      7. Public, private and protected method introduced.
      8. Magic methods has been included.
      9. We can pass value by reference.

      Wednesday, September 15, 2010

      PHP Syntax

      PHP Syntax

      You cannot view the PHP source code by selecting "View source" in the browser -you will only see the output from the PHP file, which is plain HTML. This is because the scripts are executed on the server before the result is sent back to the browser.

      Basic PHP Syntax

      • A PHP scripting block can be placed anywhere in the document.
      • On servers with shorthand support enabled you can start a scripting block with .
      • However, for maximum compatibility, we recommend that you use the standard form rather than the shorthand form.
      • A PHP file normally contains HTML tags, just like an HTML file, and some PHP scripting code.
      • Each code line in PHP must end with a semicolon. The semicolon is a separator and is used to distinguish one set of instructions from another.
      • There are two basic statements to output text with PHP: echo andprint. In the example above we have used the echo statement to output the text"Hello World".
      Comments in PHP
      • Comments are use to ignore code or codes of line from the execution on the server. 
      • In PHP 2 types of comments are available.
      • Single line comment, Multiline comment.
      • Single line comments can be given by // or #.
      • Multiline comment can be given by /*..........*/.

      Sunday, September 12, 2010

      PHP Variable



      • Variable is name to the memory location.its a one kind of container which hold any type of data to perform operation on it. php variables doesn't need to specify which type of variable we would like to declare.
      • Variables are used for storing values, such as numbers, strings or function results, so that they can be used many times in a script.
      • When a variable is set it can be used over and over again in your script.
      • All variables in PHP start with a $ sign symbol.
      • Example : $var_name = value;New PHP programmers often forget the $ sign at thebeginning of the variable. In that case it will not work.
      • PHP is a Loosely Typed Language so, In PHP a variable does not need to be declared before being set.
      • PHP automatically converts the variable to the correct data type, depending on how they are set.
      • In a strongly typed programming language, you have to declare (define) the type and name of the variable before using it.
      • In PHP the variable is declared automatically when you use it.
      • Example : $value=25 


        Rules for Constructing PHP variable:
        • Must always begin with a dollar-sign ($).
        • Generally start with a letter and can contain letters, numbers, and underscore characters “_”.
        • Values can be numbers, strings, boolean, etc....
        • Names are case sensitive.
        • value gets change as the program executes.


        PHP supports eight primitive data types :

        Four scalar types:
        • Boolean
        • Integer
        • Float
        • String
        Two compound types:
        • Array
        • Object
        Two special types:
        • Resource
        • Null




              Saturday, September 11, 2010

              PHP Operators

              • Operators are used to operate on values.
              • There are in php Arithmetic operators,Logical operator,Assignment operator,Comparison operator are available.
              Arithmetic Operator :
              Arithmetic operators are used to perform some arithmetic operation on with the variable in the task.
              Operator Description Example Result
              + Addition x=2,x+2 4
              - Subtraction x=2,5-x 3
              * Multiplication x=4,x*5 20
              / Division 15/5,5/2 3,2.5
              % Modulus 5%2,10%8 1,2
              ++ Increment x=5,x++ 6
              -- Decrement x=5,x-- 4

              Assignment Operator :
              Assignment operator is used to assign value to the variable.

              operator Example Is the same
              = x=y x=y
              += x+=y x=x+y
              -= x-=y x=x-y
              *= x*=y x=x*y
              /= x/=y x=x/y
              .= x.=y x=x.y
              %= x%=y x=x%y

              Comparison Operator:
              Comparison operators used to compare two variable with operator which will mostly used in conditions where return value will be true or false.
              Operator Description Example
              == Is equal to 5==8 returns False
              != Is not equal 5!=8 returns True
              > Is greater than 5>8 returns False
              < Is less than 5<8 returns True
              >= Is greater than or equal to 5>=8 returns False
              <= Is less than or equal to 5<=8 returns True

              Logical Operator:
              Logical operators are use to make condition which will return true or false.
              Operator Description Example
              && And x=2,y=3,(x<10 && y>1)Returns True
              || OR x=50,y=3,(x<10 || y>1)Returns False
              ! NOT x=50,y=3,(x!=y)Returns True

              Thursday, September 9, 2010

              Conditional Statements

              Very often when you write code, you want to perform different actions for different decisions.
              You can use conditional statements in your code to do this.
              if...else statement -use this statement if you want to execute a set of code when a condition is true and another if the condition is not true.
              else if statement -is used with the if...else statement to execute a set of code if one of several condition are true.

              PHP If & Else Statements

              The If...Else Statement:
              If you want to execute some code if a condition is true and another code if a condition is false, use the if....else statement.

              Syntax:
              • if (condition ) code to be executed if condition is true; else code to be executed if condition is false; 
              Example :

              $d=date("D");
              if ($d=="Fri")
              echo "Have a nice weekend!";
              else
              echo "Have a nice day!";


              If more than one line should be executed if a condition is true/false, the lines should be enclosed within curly braces:


              $d=date("D");
              if ($d=="Fri")
              {
              echo "Hello!
              ";
              echo "Have a nice weekend!";
              echo "See you on Monday!";
              }


              The Else....If Statement:

              If you want to execute some code if one of several conditions are true use the else if statement.


              Syntax:

              • if (condition)
                code to be executed if condition is true;
                else if(condition)
                code to be executed if condition is true;
                else
                code to be executed if condition is false;



              PHP Switch Statement


              The Switch statement in PHP is used to perform one of several different actions based on one of several different conditions.
              If you want to select one of many blocks of code to be executed,use the Switch statement.
              The switch statement is used to avoid long blocks of if..else if..else code.

              Syntax:

              switch (expression)
              {
              case label1:
              code to be executed if expression = label1;
              break;
              case label2:
              code to be executed if expression = label2;
              break;
              default:
              code to be executed
              if expression is different
              from both label1 and label2;
              }

              Example:

              switch ($x)
              {
              case 1:
              echo "Number 1";
              break;
              case 2:
              echo "Number 2";
              break;
              case 3:
              echo "Number 3";
              break;
              default:
              echo "No number between 1 and 3";
              }









              Sunday, September 5, 2010

              PHP Loops

              • PHP loops also called iteration.
              • Iteration or looping is a way to execute a block of program statements more than once.
              • we will use the for statement to create loops.
              • The for loop is generally controlled by counting.
              • There is an index variable that you increment or decrement each time through the loop.
              • When the index reaches some limit condition, then the looping is done and we continue on in the code.

              Why do we want loops in our code?

              • Do something for a given number of times or for every object in a collection of objects.
              • For every radio button in a form, see if it is checked.
              • For every month of the year, charge $100 against the balance.
              • Calculate the sum of all the numbers in a list.
              • Many loops are counting loops.
              • They do something a certain number of times.






































              PHP Looping :

              Looping statements in PHP are used to execute the same block of code a specified number of times.
              Very often when you write code, you want the same block of code to run a number of times. You can use looping statements in your code to perform this.

              In PHP we have the following looping statements:


              • While -loops through a block of code if and as long as a specified condition is true.
              • do...while -loops through a block of code once, and then repeats the loop as long as a special condition is true.
              • For -loops through a block of code a specified number of times.
              • For each-loops through a block of code for each element in an array 


              The while Statement:

              The while statement will execute a block of code if and as long as a condition is true.


              Syntax:
              while (condition)
              code to be executed;


              Example:
              The following example demonstrates a loop that will continue to run as long as the variable i is less than, or equal to 5. i will increase by 1 each time the loop runs:

              $i=1;
              while($i<=5)
              {
              echo "The number is " . $i . "
              ";
              $i++;
              }


              The do...while Statement :


               The do...while statement will execute a block of code at least once-it then will repeat the loop as long asa condition is true.


              Syntax:

              do
              {
              code to be executed;
              }
              while (condition);

              Example:

              The following example will increment the value of i at least once, and it will continue incrementing the variable i as long as it has a value of less than 5:

              $i=0;
              do
              {
              $i++;
              echo "The number is " . $i . "
              ";
              }
              while ($i<5);


              The for Statement :


               The for statement is used when you know how many times you want to execute a statement or a list of statements.



              Syntax

              for (initialization; condition; increment)
              {
              code to be executed;
              }


              Note:The for statement has three parameters. The first parameter initializes variables, the second parameter holds the condition, and the third parameter contains the increments required to implement the loop. If more than one variable is included in the initialization or the increment parameter, they should be separated by commas. The condition must evaluate to true or false.


              Example

              The following example prints the text "Hello World!" five times:

              for ($i=1; $i<=5; $i++)
              {
              echo "Hello World!
              ";
              }


              The foreach Statement:

              The for eachstatement is used to loop through arrays.
              For every loop, the value of the current array element is assigned to $value (and the array pointer is moved by one) -so on the next loop, you'll be looking at the next element.


              Syntax

              foreach(array as value)
              {
              code to be executed;
              }


              Example

              The following example demonstrates a loop that will print the values of the given array:

              $arr=array("one", "two", "three");
              foreach($arras $value)
              {
              echo "Value: " . $value . "
              ";
              }

              Saturday, September 4, 2010

              PHP Functions

              The real power of PHP comes from its functions.
              • In PHP -there are more than 700 built-in functions available.
              • A function is a block of code that can be executed whenever we need it.

              Creating PHP functions:
              • All functions start with the word "function()".
              • Name the function -It should be possible to understand what the function does by its name. The name can start with a letter or underscore (not a number) .
              • Add a "{"-The function code starts after the opening curly brace.
              • Insert the function code.
              • Add a "}"-The function is finished by a closing curly brace.

              Example
              A simple function that writes my name when it is called:

              functionwriteMyName()
              {
              echo "Hello World";
              }

              writeMyName();




              The output of the code above will be:
              Hello world!


              PHP Functions -Adding parameters


              Our first function (writeMyName()) is a very simple function. It only writes a static string.
              To add more functionality to a function, we can add parameters. A parameter is just like a variable.
              You may have noticed the parentheses after the function name, like:writeMyName(). The parameters are specified inside the parentheses.


              Example

              functionwriteMyName($fname)
              {
              echo $fname. "Refsnes.
              ";
              }
              echo "My name is ";
              writeMyName("Kai Jim");echo "My name is ";
              writeMyName("Hege");echo "My name is ";
              writeMyName("Stale");

              The output of the code above will be:
              My name is Kai JimRefsnes.
              My name isHege Refsnes.
              My name is StaleRefsnes



               

              PHP Functions -Return values 
              Functions can also be used to return values. 


              Example:

              function add($x,$y)
              {
              $total = $x + $y;
              return $total;
              }
              echo "1 + 16 = " . add(1,16);


              The output of the code above will be:
               
               1 + 16 = 17 



               
               































              Friday, September 3, 2010

              Difference between echo and print

              Speed : There is a difference between the two, but speed-wise it
              should be irrelevant which one you use. echo is marginally faster  

              Expression : print() behaves like a function in that you can do:
              $ret = print "Hello World"; And $ret will be 1. That means that print
              can be used as part of a more complex expression where echo cannot.

              Example:
              $b ? print "true" : print "false";

              Parameter(s).  : The grammar is: echo expression [, expression[,expression] ... ] But echo ( expression, expression ) is not valid.
              This would be valid: echo ("howdy"),("partner"); the same as: echo
              "howdy","partner";
              So, echo without parentheses can take multiple parameters, which get
              concatenated:

              echo "and a ", 1, 2, 3; // comma-separated without parentheses
              echo ("and a 123"); // just one parameter with parentheses
              print() can only take one parameter:
              print ("and a 123");
              print "and a 123";

              Thursday, September 2, 2010

              Sessions and Cookies in PHP

              PHP Cookies :

              • A message given to a Web browser by a Web server. The browser stores the message in a text file. The message is then sent back to the server each time the browser requests a page from the server.
              • A cookie is often used to identify a user

              What is a Cookie?
              • A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too. With PHP, you can both create and retrieve cookie values.

              How to Create a Cookie?

              The setcookie() function is used to set a cookie.

              Note:The setcookie() function must appear BEFORE the tag.

              Syntax:
              setcookie(name, value, expire, path, domain);



              Set Cookies:- 
              setcookie("user","tom",time()+3660);
              echo "cookie is set";

              Retrieve Cookies:-
              echo "Cookie value is ".$_COOKIE['user'];


              Note: The value of the cookie is automatically URL encoded when sending the cookie, and automatically decoded when received (to prevent URLencoding, use set raw cookie() instead).



              How to Retrieve a Cookie Value?
              The PHP $_COOKIE variable is used to retrieve a cookie value.

              In the example below, we retrieve the value of the cookie named "user" and display it on a page:

              Example :
              echo $_COOKIE["user"];

              In the following example we use the isset() function to find out if a cookie has been set:
              Example:
              if (isset($_COOKIE["user"]))
              echo "Welcome " . $_COOKIE["user"] . "!";
              else
              echo "Welcome guest!";



              How to Delete a Cookie?
              When deleting a cookie you should assure that the expiration date is in the past.

              Example:
              setcookie("user", "", time()-3600);




              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.


              PHP Session Variables

              • When you are working with an application, you open it, do some changes and then you close it. This is much like a Session. The computer knows who you are. It knows when you start the application and when you end. But on the internet there is one problem: the web server does not know who you are and what you do because the HTTP address doesn't maintain state.
              • A PHP session solves this problem by allowing you to store user information on the server for later use (i.e. username, shopping items, etc). However, session information is temporary and will be deleted after the user has left the website. If you need a permanent storage you may want to store the data in a database.
              • Sessions work by creating a unique id (UID) for each visitor and store variables based on this UID. The UID is either stored in a cookie or is propagated in the URL.
              • A PHP session solves this problem by allowing you to store user information on the server for later use (i.e. username, shopping cart items, etc). However, this session information is temporary and is usually deleted very quickly after the user has left the website that uses sessions. 
              • It is important to ponder if the sessions' temporary storage is applicable to your website. If you require a more permanent storage you will need to find another solution, like a MySQL database.
              • Sessions work by creating a unique identification (UID) number for each visitor and storing variables based on this ID. This helps to prevent two users' data from getting confused with one another when visiting the same webpage.

                Note: If you are not experienced with session programming it is not recommended that you use sessions on a website that requires high-security, as there are security holes that take some advanced techniques to plug. 
              Starting a PHP Session
              • Before you can begin storing user information in your PHP session, you must first start the session. When you start a session, it must be at the very beginning of your code, before any HTML or text is sent.







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

              Storing a Session Variable :
              • The correct way to store and retrieve session variables is to use the PHP $_SESSION variable:
              Example:
              session_start();
              $_SESSION['views']=1; //Storing value in session variable.
              echo "Pageviews=". $_SESSION['views']; //Retriving the value of session variable.

              Destroying a Session :
              • If you wish to delete some session data, you can use the unset()or the session_destroy() function.
              • The unset() function is used to free the specified session variable.
              Example:
              unset($_SESSION['views']);

              You can also completely destroy the session by calling the session_destroy() function.
              session_destroy();
              Note:session_destroy() will reset your session and you will lose all your stored session data.


              Understanding session
              • This piece of code does one of two things. If the user does not already have a session, it creates a new session -or -if the user does already have a session it connects to the existing session file. When a new session is created, PHP session management generates a session identifier that consists of a random 32 hex digit string and creates an empty session file on the server with the  name sess_ followed by the session identifier. It also includes a set-cookie in the response and a session cookie in the browser with the value of the session identifier. This means that any subsequent request to the server will include this session identifier allowing PHP to connect to the appropriate session file.
              • session_start();

              PHP String

              • A string variable is used to store and manipulate a piece of text. 
              • String variables are used for values that contains character strings.
              • After creating a string we can manipulate it. A string can be used directly in a function or it can be stored in a variable.
              Below, the PHP script assigns the string "Hello World" to a string variable called $txt:

              $txt="Hello World"; echo $txt;
              output : HelloWorld

              The Concatenation Operator
              • There is only one string operator in PHP.
              • The concatenation operator (.)is used to put two string values together.
              • To concatenate two variables together, use the dot (.) operator.
              Example:
              $txt1="Hello World";
              $txt2="1234";
              echo $txt1 . " " . $txt2;

              output:
              Hello World 1234

              If we look at the code above you see that we used the concatenation operator two times. This is because we had to insert a third string.
              Between the two string variables we added a string with a single character, an empty space, to separate the two variables.

              Using the strlen() function

              • The strlen() function is used to find the length of a string.
              Example:
              echo strlen("Hello world!");

              output:
              12
              The length of a string is often used in loops or other functions, when it is important to know when the string ends. (i.e. in a loop, we would want to stop the loop after the last character in the string)


              Using the strpos() function 
              • The strpos() function is used to search for a string or character within a string.
              • If a match is found in the string, this function will return theposition of the first match. If no match is found, it will return FALSE.
              Example:
              echo strpos("Hello world!","world");


              output:
              6
              As you see the position of the string "world" in our string is position 6. The reason that it is 6, and not 7, is that the first position in the string is 0, and not 1.


              Commonly used String Functions

              • addslashes—Quote string with slashes.
              • explode —Split a string by string.
              • implode —Join array elements with a string.
              • join —Alias of implode().
              • md5 —Calculate the md5 hash of a string.
              • nl2br —Inserts HTML line breaks before all new lines in a string.
              • str_split —Convert a string to an array.
              • strcmp—Binary safe string comparison.
              • print —Output a string.
              • strtolower—Make a string lowercase.
              • strtoupper—Make a string uppercase.
              • trim —Strip whitespace(or other characters) from the beginning and end of a string.




              PHP Headers

              • HTTP is the protocol (the set of 'rules') for transferring data (e.g. HTML in web pages, pictures, files) between web servers and client browsers, and usually takes place on port80. This is where the 'http://' in website URLs comes from. 
              • Headers can be separated into two broad types: Request the headers that your browser sends to the server when you request a file, and Response headers that the server sends to the browser when it serves the file.
              PHP header(): The Basics
              • Using this function, you can make your scripts send headers of your choosing to the browser, and create some very useful and dynamic results. However, the first thing you need to know about the header() function is that you have to use it before PHP has sent any output (and therefore its default headers).























              Redirecting with the Refresh header

              • While you can sometimes get away with supplying a relative URL for the value, according to the HTTP specification, you should really use an absolute URL.
              • One mistake that is easy to make with the Location header is not calling exit directly afterwards (you may not always want to do this, but usually you do). The reason this is a mistake is that the PHP code of the page continues to execute even though the user has gone to a new location. In the best case, this uses system resources unnecessarily. In the worst case, you may perform tasks that you never meant to.

              Example :
              header('Refresh:10;url=http://www.mysite.com/otherpage.php');
              echo'Youwillberedirectedin10seconds';

              • The Refresh redirects users like the Location header does, but you can add a delay before the user is redirected. For example, the following code would redirect the user to a new page after displaying the current one for 10 seconds



              Serving different types of files and generating dynamic content using the Content-Type header:



              The Content-Type header tells the browser what type of data the server is about to send. Using this header, you can have your PHP scripts output anything from plaintext files to images or zip files. The table below lists frequently-used MIME types:

              You can do several interesting things with this. For example, perhaps you want to send the user a pre-formatted text file rather than HTML:


              Example : header('content-Type:text/plain');



              Or perhaps you'd like to prompt the user to download the file, rather than viewing it in the browser. With the help of the Content-Dispositionheader, it's easy to do, and you can even suggest a file name for the user to use:

              Example:
              header('Content-Type:application/octet-stream');
              header('Content-Disposition: attachment; '.'filename="plain_text_file.txt"'); 

              PHP Array

              An array can store one or more values in a single variable name.

              What is an array?
              • When working with PHP, sooner or later, you might want to createmany similar variables.
              •  Instead of having many similar variables, you can store the dataas elements in an array.
              • Each element in the array has its own ID so that it can be easily accessed.
              Types of Array:
              1. Numeric Array
              2. Associative Array
              3. Multidimensional Array
              1) Numeric Array:
              • A numeric array stores each element with a numeric ID key.
              • There are different ways to create a numeric array:
              Example 1
              In this example the ID key is automatically assigned:
              $names = array("Peter","Quagmire","Joe");

              Example 2
              In this example we assign the ID key manually:
              $names[0] = "Peter";
              $names[1] = "Quagmire";
              $names[2] = "Joe";



              2) Associative Arrays:

              • An associative array, each ID key is associated with a value.
              • When storing data about specific named values, a numerical array is not always the best way to do it.
              • With associative arrays we can use the values as keys and assign values to them.
              Example 1
              In this example we use an array to assign ages to the different persons:
              $ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34);


              Example 2
              This example is the same as example 1, but shows a different way of creating the array:
              $ages['Peter'] = "32";
              $ages['Quagmire'] = "30";
              $ages['Joe'] = "34";




              3) Multidimensional Arrays:
              • In a multidimensional array, each element in the main array can also be an array. And each element in the sub-array can be an array, and so on.
              Example
              In this example we create a multidimensional array, with automatically assigned ID keys:
              $families = array
              (
              "Griffin"=>array
              (
              "Peter",
              "Lois",
              "Megan"
              ),
              "Quagmire"=>array
              (
              "Glenn"
              ),
              "Brown"=>array
              (
              "Cleveland",
              "Loretta",
              "Junior"
              )
              );

              PHP Date Function

              • The PHP date() function is used to format a time or a date.
              • The PHP date() function formats a timestamp to a more readable date and time.
              Syntax:
              • date(format,timestamp)
              • Parameter        Description
                FormatRequired. Specifies the format of the timestamp
                TimestampOptional. Specifies a timestamp. Default is the current date andtime (as a timestamp)

              PHP Date -What is a Timestamp?
              A timestamp is the number of seconds since January 1, 1970 at 00:00:00 GMT. This is also known as the Unix Timestamp.














              PHP Date -Format the Date
              The first parameter in the date() function specifies how to format the date/time. It uses letters to represent date and time formats. Here are some of the letters that can be used:

              • d -The day of the month (01-31)
              • m -The current month, as a number (01-12)
              • Y -The current year in four digits
              Example:
              echo date("Y/m/d");
              echo date("Y.m.d");
              echo date("Y-m-d");

              Output:
              2009/07/11
              2009.07.11
              2009-07-11

              PHP Date -Adding a Timestamp
              • The second parameter in the date() function specifies a timestamp. This parameter is optional. If you do not supply a timestamp, the current time will be used.
              • In our next example we will use themktime() function to create a timestamp for tomorrow.
              • The mktime() function returns the Unix timestamp for a specified date.
              Syntax:
              • mktime(hour,minute,second,month,day,year,is_dst) 
              • To go one day in the future we simply add one to the day argument of mktime().
              Example:
              $tomorrow =mktime(0,0,0,date("m"),date("d")+1,date("Y"));
              echo "Tomorrow is ".date("Y/m/d", $tomorrow);

              Output:
              Tomorrow is 2006/07/12

              Wednesday, September 1, 2010

              PHP Include

              Server Side Includes (SSI) are used to create functions, headers, footers, or elements that will be reused on multiple pages.

              Server Side Includes
              • You can insert the content of a file into a 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. The include() function generates a warning (but the script will continue execution) while the require() function generates a fatal error (and the script execution will stop after the error).
              • These two functions are used to create functions, headers, footers, or elements that can be reused on multiple pages.
              • This can save the developer a considerable amount of time. This means that you can create a standard header or menu file that you want all your web pages to include. When the header needs to be updated, you can only update this one 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 web pages).
              • Include_once and require_once is also use for include any file into your code.
              • But the difference between include and include_once is in include if there is any error in include file there is no effect on the code where it isincluded but in include_once there is effect in the code if there is any error.

























              It is recommended to use the require() function instead of include(), because scripts should not continue executing if files are missing or misnamed.