Friday 21 April 2017

PHP Notes

The Characteristics of PHP:-
-----------------------------------
1.PHP is a high level programming language.
2.It is a server-side scripting language.
We write the PHP script with mixing of other languages in web-designing.
3. PHP is a case-sensitive language.
4. Here every line ends with a semicolon(;).
5. We are using multiple webservers to run the PHP applications like Apache Tomcat, IIS, WampServer.

In the sameway zazoumini webserver etc.

Syntax of PHP Script:-
-------------------------------
<?php

statements;

?>

How to use PHP syntax in HTML?
------------------------------------------
<HTML>
       <HEAD>
<TITLE>....</TITLE>
       </HEAD>
      <BODY>
<?php

statements;

?>
      </BODY>
</HTML>



example 1:
-------------
<? php
       echo "Hello.. The First PHP Program";
?>

-> Echo is a keyword

Variable Declaration:-
--------------------------
1. PHP variables must start with a letter or underscore "_".
2. PHP variables may only be comprised of alpha-numeric characters and underscores. a-z, A-Z, 0-9, or _ .
3.Variables with more than one word should be separated with underscores.
eg: $my_variable
4.Variables with more than one word can also be distinguished with capitalization.
e: $myVariable
5. A variable is name.  It can store values.  Later these values will perform operations depends on variable

name.
6. In PHP, we can write any name as variable except reserve words.
7. Every variable name starts with a "$" symbol.
eg: $x=200;


Outputting a String:-
-------------------------
To output a string, use PHP "echo". You can place either a string variable or you can use

quotes.
eg:

<html>
<head>
     <title>ECHO Demo</title>
</head>
<body bgcolor=tan text=green>

<?php

$myString = "Hello!";
echo "<center>".$myString;
echo "<h5>Welcome To PHP World!</h5>";
?>
</body>
</html>


Operators:-
---------------
There are many operators used in PHP, so we have separated them into the following categories to make it

easier to learn them all.

1.Assignment Operators
2.Arithmetic Operators
3.Comparison Operators
4.String Operators
5.Combination Arithmetic & Assignment Operators

Assignment Operators:-
------------------------------
Assignment operators are used to set a variable equal to a value or set a variable to another

variable's value. Such an assignment of value is done with the "=", or equal character.
Example:
$my_var = 4;
$another_var = $my_var;

Note:Now both $my_var and $another_var contain the value 4. Assignments can also be used in

conjunction with arithmetic operators.

Arithmetic Operators:-
-----------------------------

Operator    English Example
---------------------------------------------------------
+ Addition 2 + 4
- Subtraction 6 - 2
* Multiplication 5 * 3
/ Division 15 / 3
% Modulus 43 % 10

eg:

<html>
<head>
<title>Arithematic Operators Demo</title>
</head>
<body bgcolor=yellow>

<?php
$addition = 2 + 4;
$subtraction = 6 - 2;
$multiplication = 5 * 3;
$division = 15 / 3;
$modulus = 5 % 2;
echo "<h2>"."Perform addition: 2 + 4 = ".$addition."<br />";
echo "Perform subtraction: 6 - 2 = ".$subtraction."<br />";
echo "Perform multiplication:  5 * 3 = ".$multiplication."<br />";
echo "Perform division: 15 / 3 = ".$division."<br />";
echo "Perform modulus: 5 % 2 = " . $modulus
. ". Modulus is the remainder after the division operation has been performed.
In this case it was 5 / 2, which has a remainder of 1.";
?>
------------------------------------------------------------------------------------------------

3.Comparison Operators:-
-----------------------------------
Comparisons are used to check the relationship between variables and/or values.

Assume: $x = 4 and $y = 5;

Operator English Example Result
-------------------------------------------------------------------------------
==   Equal To $x == $y false
!=   Not Equal To $x != $y true
<   Less Than $x < $y   true
> Greater Than $x > $y   false
<=   Less Than or Equal To $x <= $y   true
>=   Greater Than or Equal To $x >= $y   false

String Operators:-
-----------------------
As we have already seen  "Echo" , the period "." is used to add two strings together, or more

technically, the period is the concatenation operator for strings.

eg:
$a_string = "Hello";
$another_string = " Billy";
$new_string = $a_string . $another_string;
echo $new_string . "!";

Combination Arithmetic & Assignment Operators:-
-------------------------------------------------------------------

In programming it is a very common task to have to increment a variable by some fixed

amount. The most common example of this is a counter. Say you want to increment a counter by 1

$counter = $counter + 1;

However, there is a shorthand for doing this.

$counter += 1;

This combination assignment/arithmetic operator would accomplish the same task. The

downside to this combination operator is that it reduces code readability to those programmers who are

not used to such an operator. Here are some examples of other common shorthand operators. In general,

"+=" and "-=" are the most widely used combination operators.

Operator English Example Equivalent Operation
----------------------------------------------------------------------------------------------------------
+= Plus Equals $x += 2; $x = $x + 2;
-= Minus Equals   $x -= 4; $x = $x - 4;
*= Multiply Equals $x *= 3; $x = $x * 3;
/= Divide Equals x /= 2; $x = $x / 2;
%= Modulo Equals $x %= 5; $x = $x % 5;
.= Concatenate Equals $my_str.="hello"; $my_str = $my_str . "hello";

Pre/Post-Increment & Pre/Post-Decrement:-
----------------------------------------------------------

This may seem a bit absurd, but there is even a shorter shorthand for the common task of adding 1 or

subtracting 1 from a variable. To add one to a variable or "increment" use the "++" operator:

$x++; Which is equivalent to $x += 1; or $x = $x + 1;
To subtract 1 from a variable, or "decrement" use the "--" operator:

$x--; Which is equivalent to $x -= 1; or $x = $x - 1;
In addition to this "shorterhand" technique, you can specify whether you want to increment before the

line of code is being executed or after the line has executed. Our PHP code below will display the

difference.

Example:
------------
<html>
<head>
<title>Pre/Post Increment/Decrement Demo</title>
</head>
<body bgcolor=tan>
<?php
$x = 4;
echo "<h2>"."The value of x with post-plusplus = " . $x++;
echo "<br /> The value of x after the post-plusplus is " . $x;
$x = 4;
echo "<br />The value of x with with pre-plusplus = " . ++$x;
echo "<br /> The value of x after the pre-plusplus is " . $x;
?>


Output:
----------
The value of x with post-plusplus = 4
The value of x after the post-plusplus is = 5
The value of x with with pre-plusplus = 5
The value of x after the pre-plusplus is = 5

HTML Code:
------------------
<!-- This is an HTML Comment -->

PHP Comment Syntax: Single Line Comment:-
-----------------------------------------------------------
While there is only one type of comment in HTML, PHP has two types. The first type we will

discuss is the single line comment. The single line comment tells the interpreter to ignore everything that

occurs on that line to the right of the comment. To do a single line comment type "//" or "#" and all text to

the right will be ignored by PHP interpreter.

Example:
------------
<html>
<head>
<title>PHP Comments</title>
</head>
<body bgcolor=tan>
<?php
echo "<h2>"."<font color=green>"."Hello World!"; // This will print out Hello World!
echo "<br />Psst...You can't see my PHP comments!"; // echo "nothing";
// echo "My name is Humperdinkle!";
# echo "I don't do anything either";
#echo "Happy Diwali";
?>

PHP Comment Syntax: Multiple Line Comment:-
----------------------------------------------------------------
Similiar to the HTML comment, the multi-line PHP comment can be used to comment out large

blocks of code or writing multiple line comments. The multiple line PHP comment begins with " /* " and

ends with " */ ".

Example:
------------
<html>
<head>
<title>PHP MultipleLine Comment</title>
</head>
<body bgcolor=tan>
<?php
/* This Echo statement will print out my message to the
the place in which I reside on.  In other words, the World. */
echo "Hello World!";
/* echo "My name is Humperdinkle!";
echo "No way! My name is Uber PHP Programmer!";
*/
?>
</body>
</html>





example 2: Adding two Numbers:-
-------------------------------------------
         <?php
$x=200;
$y=300;
$z=$x+$y;
echo "The Sum of x and y is  ",$z;
            ?>

example 3: How to use HTML Tags in Middle of PHP ?
----------------------------------------------------------------------
<html>
        <head>
 
       </head>
        <body bgcolor="yellow">
             <h1>Variable Demo</h1>
             <hr>
<?php
$x=5;
$y=3;
$x=$x + $y;
$y=$x - $y;
$x=$x - $y;
echo "After swapping x value is: ", $x."<br>";
echo "After swapping y value is: ", $y."<br>";
?>
          </body>
</html>

Control Structures:-
------------------------
There are three Control Structures
1. Conditional Control Structures
2. Looping Control Structures
3. Non-Conditional Control Structures.

1. Conditional Control Structures:-
-------------------------------------------
example on If Condition
------------------------------
<?php
     
      $x=200;
`      if($x == 200)
echo "The x value is 200";
?>

Comments in PHP:
------------------------
Single Line  - //
Multi Line - /* ........ */

If - Else:-
---------

       <?php
$x=200;
$y=300;
if($x > $y)
                        //echo "x is big"
    print(" x is big");
else
    print("y is big");
          ?>


If - Elseif:-
-------------

       <?php
$x=200;
$y=300;
if($x > $y)
                        //echo "x is big"
    print(" x is big");
else
    print("y is big");
          ?>


Switch Case:-
--------------------
<?php
$x=100;
$ch;

switch($ch)
{
case 1:
if($x  % 2 == 0)
{
echo $x."Even No  ";
}
else
{
echo $x."Odd No  ";
}
break;

case 2:
if($x>18)
echo $x."You are Major";
else
echo $x."You are Minor";
break;

case 3:
if($x % 4 == 0)
echo $x." is a Leap Year  ";
else
echo $x." is not a leap year";
default:
echo "Invalid Choice..";

?>

---------------------------------------------------------------------------------------------------------

Using Switch Case:
----------------------------
<html>
<head>
<title>Swich Case Demo</title>
</head>
<body bgcolor=green text=white>
<?php
$destination = "Tokyo";
echo "<h2>"."Traveling to $destination<br />";
switch ($destination){
case "Las Vegas":
echo "Bring an extra $500";
break;
case "Amsterdam":
echo "Bring an open mind";
break;
case "Egypt":
echo "Bring 15 bottles of SPF 50 Sunscreen";
break;
case "Tokyo":
echo "Bring lots of money";
break;
case "Caribbean Islands":
echo "Bring a swimsuit";
break;
}

?>
-------------------------------------------------------------------------------------

Write a program SNO,Sname, Marks of 3 subjects M,P,C,Total and Average.

Prg:
-----
<?php
$sno=1;
$sname="Ravi;
$M=96;
$P=94;
$C=92;
$Total=$M+$P+$C;
&Avg=$Total/3;

if($M>=35 && $P>=35 && $C>=$c)
{
echo "Pass";
    if($Avg>=50)
    {
echo "First Class";
    }
    else if($Avg <50)
                       {
echo "Second Class";
          }    
}
else
echo"Fail";
?>


Looping Control Structures:
-----------------------------------
While Loop:
--------------

<html>
      <head>
<title>While Loop Demo</title>
      </head>
      <body>
<?php
$i=10;
while($i<=10)
{
echo"<h2>".$i."<br>";
$i++;
}
?>
      </body>
</html>


-----------------------------------------------------------------------------------------
Array:-
--------
        Array is a variable which can store multiple values in a single varible.  It is also called homogeneous

data elements.  That means it stores a same type of values.

There are three types of arrays.
i. Numerical Array
ii. Associated Array
iii. Multi-Dimensional Array.

i. Numerical Array:-
-----------------------
A Numerical array, the array index format is numericals.  It can store any kind of data.

eg:1

      <?php
$arr=array("Ravi","Kiran","Kishore");
print($arr[0]." is Good boy"."<br>");
print("Age of  ".$arr[2]." is 20 years");
      ?>
------------------------------------------------------------------------------------
eg:2

       <?php
$arr[0]="Ravi";
$arr[1]="Kiran";
$arr[2]="Kishore";
$c=Count($arr);
                          for($i=0;$i<$c;$i++)
     {
print("<h2>".$arr[i]."<br>"."<h2>");
     }
     $d=date("D,M,Y");
    print("<h4>"."Today's Date is",$d);
    ?>

-----------------------------------------------------------------------------------------
ii.Associated Array:
------------------------
An associate array, an array index key associated with value.

eg:1
     <?php
ages["sri"]="20";
ages["kiran"]="24";
ages["anil"]="22";
echo"Sri is ".$ages['sri']."years old";
      ?>

How to write Multi Structures?
---------------------------------------
<?php
$x[0]="100";
$x[1]="200";
$x[2]="300";
$x[3]="400";
$x[4]="500";
?>

<html>
      <head>
<title>MultiStructures</title>
      </head>
<body bgcolor="cyan">
<h2 align="center">This is Multi Structure Demo</h2>
<hr>
<?php
  <!-- $a=count($arr);
$b=count($x);
$p=1;
$s=0;
echo "<h3>";
for($i=0;$i<$a;$i++)
{
$p=$p * $arr[$i];
}
print("The Product of First Array: ".$p."<br>");

for($j=0;$i<$b;$i++)
{
$s=$s+$x[$j];
}
print("The Sum of Second Array is: ".$s);
?>
</body>
</html>

----------------------------------------------------------------------------------------------------
PHP - Functions:-
-----------------------
A function is just a name we give to a block of code that can be executed whenever we need it.

i.Always start your function with the keyword function
ii.Remember that your function's code must be between the "{" and the "}"
iii.When you are using your function, be sure you spell the function name correctly

Syntax:
---------
<?php
function myCompanyMotto()
{
statements;
}
?>

Example:-
--------------
<html>
<head>
<title>Function Demo</title>
</head>
<body bgcolor=tan text=blue>
<?php
function myCompanyMotto(){
    echo "<h2>"."We deliver quantity, not quality!<br />";
}
echo "<h3>"."Welcome to Tizag.com <br />";
myCompanyMotto();
echo "Well, thanks for stopping by! <br />";
echo "and remember... <br />";
myCompanyMotto();
?>
</body>
</html>

----------------------------------------------------------------------------------------------------------
PHP Functions - Parameters:-
----------------------------------------
<html>
<head>
<title>Function Parameters Demo</title>
</head>
<body bgcolor=yellow text=blue>
<?php
function myGreeting($firstName){
    echo "<h2>"."Hello there ". $firstName . "!<br />";
}
myGreeting("Jack");
myGreeting("Ahmed");
myGreeting("Julie");
myGreeting("Charles");
?>
</body>
</html>
----------------------------------------------------------------------------------------------------------

Functions with Multiple Parameters:
-------------------------------------------------

<html>
<head>
<title>Functions with Multiple Parameters Demo</title>
</head>
<body bgcolor=cyan text=blue>
<?php
function myGreeting($firstName, $lastName){
    echo "<h2>"."Hello there ". $firstName ." ". $lastName ."!<br />";
}
myGreeting("Jack", "Black");
myGreeting("Ahmed", "Zewail");
myGreeting("Julie", "Roberts");
myGreeting("Charles", "Schwab");
?>
</body>
</html>

------------------------------------------------------------------------------------------------
Functions with Returning Values:
------------------------------------------------
<html>
<head>
<title>Functions with Returning Values</title>
</head>
<body bgcolor=green text=white>
<?php
function mySum($numX, $numY){
    $total = $numX + $numY;
    return $total;
}
$myNumber = 0;
echo "<h2>"."Before the function, myNumber = ". $myNumber ."<br />";
$myNumber = mySum(3, 4); // Store the result of mySum in $myNumber
echo "After the function, myNumber = " . $myNumber ."<br />";
?>
</body>
</html>

---------------------------------------------------------------------------------------------------------
Array:
---------
An array is a group of homogeneous elements.

Example:
------------
<html>
<head>
<title>Array Demo</title>
</head>
<body bgcolor=blue text=white>
<?php
$employee_array[0] = "Bob";
$employee_array[1] = "Sally";
$employee_array[2] = "Charlie";
$employee_array[3] = "Clare";

echo "<h2>"."Two of my employees are ". $employee_array[0] . " & " . $employee_array[1];

echo "<br />Two more employees of mine are ". $employee_array[2] . " & " . $employee_array[3];

?>
</body>
</html>
-----------------------------------------------------------------------------------------------------
PHP - Associative Arrays:-
-------------------------------------
In an associative array a key is associated with a value. If you wanted to store the salaries of

your employees in an array, a numerically indexed array would not be the best choice. Instead, we could

use the employees names as the keys in our associative array, and the value would be their respective

salary.

Example:-
-----------------
<html>
<head>
<title>Associative Array Demo</title>
</head>
<body bgcolor=tan text=blue>
<?php
$salaries["Bob"] = 2000;
$salaries["Sally"] = 4000;
$salaries["Charlie"] = 600;
$salaries["Clare"] = 0;

echo "<h2>"."Bob is being paid - $" . $salaries["Bob"] . "<br />";
echo "Sally is being paid - $" . $salaries["Sally"] . "<br />";
echo "Charlie is being paid - $" . $salaries["Charlie"] . "<br />";
echo "Clare is being paid - $" . $salaries["Clare"];
?>
</body>
</html>

-----------------------------------------------------------------------------------------------------
Syntax of While Loop:-
--------------------------------
while ( conditional statement is true)
{
//do this code;
}


Example on While Loop:
----------------------------------

<html>
<head>
<title>While Loop Demo</title>
</head>
<body bgcolor=violet text=blue>
<?php
$brush_price = 5;
$counter = 10;

echo "<h3>"."<table border=\"1\" align=\"center\">";
echo "<tr><th>Quantity</th>";
echo "<th>Price</th></tr>";
while ( $counter <= 100 ) {
echo "<tr><td>";
echo "<h4>".$counter;
echo "</td><td>";
echo "<h4>".$brush_price * $counter;
echo "</td></tr>";
$counter = $counter + 10;
}
echo "</table>";
?>
</body>
</html>

-----------------------------------------------------------------------------------------------------------

Syntax of  For Loop:
------------------------------
for ( initialize a counter; conditional statement; increment a counter)
{
do this code;
}

Example:-
-------------

<html>
<head>
<title>ForLoop Demo</title>
</head>
<body bgcolor=purple text=white>
<?php
$brush_price = 5;

echo "<table border=\"1\" align=\"center\">";
echo "<tr><th>Quantity</th>";
echo "<th>Price</th></tr>";
for ( $counter = 10; $counter <= 100; $counter += 10) {
echo "<tr><td>";
echo "<h4>".$counter;
echo "</td><td>";
echo "<h4>".$brush_price * $counter;
echo "</td></tr>";
}
echo "</table>";
?>
</body>
</html>

--------------------------------------------------------------------------------------------------
Using Foreach
-----------------------
Note:-
---------
The operator "=>" represents the relationship between a key and value. You can imagine that

the key points => to the value. In our example we named the key $key and the value $value. However, it

might be easier to think of it as $name and $age. Below our example does this and notice how the output is

identical because we only changed the variable names that refer to the keys and values.

Example:
-------------
<html>
<head>
<title>Foreach Demo</title>
</head>
<body bgcolor=cyan text=blue>
<?php
$employeeAges;
$employeeAges["Lisa"] = "28";
$employeeAges["Jack"] = "16";
$employeeAges["Ryan"] = "35";
$employeeAges["Rachel"] = "46";
$employeeAges["Grace"] = "34";

foreach( $employeeAges as $key => $value){
echo "<h2>"."Name: $key, Age: $value <br />";
}
?>
</body>
</html>

--------------------------------------------------------------------------------------------------
Using Do While
-----------------------
Example:
-------------

<html>
<head>
<title>Do While Demo</title>
</head>
<body bgcolor=pink>
<?php
$x = 10;
do {
echo "<h2>".$x."<br/>";
$x=$x-1;
} while ($x >= 1);
?>
</body>
</html>

-----------------------------------------------------------------------------------------------
Example on Do While:
--------------------------------
<html>
<head>
<title>Do While Demo</title>
</head>
<body bgcolor=pink>
<?php
$x = 0;
do {
echo "<center>"."<h2>"."Happy Diwali";
} while ($x > 1);
?>
</body>
</html>
-----------------------------------------------------------------------------------------------------------
PHP FILES:-
===========
The file "testFile.txt" should be created in the same directory where this PHP code resides.

PHP will see that "testFile.txt" does not exist and will create it after running this code.

$ourFileName = "testFile.txt";

Here we create the name of our file, "testFile.txt" and store it into a PHP String variable

$ourFileName.

$ourFileHandle = fopen($ourFileName, 'w') or die("can't open file");

This bit of code actually has two parts. First we use the function fopen and give it two

arguments: our file name and we inform PHP that we want to write by passing the character "w".

Second, the fopen function returns what is called a file handle, which will allow us to

manipulate the file. We save the file handle into the $ourFileHandle variable.

fclose($ourFileHandle);

We close the file that was opened. fclose takes the file handle that is to be closed.


Creating a File:-
-----------------------
<?php
$ourFileName = "testFile.txt";
$ourFileHandle = fopen($ourFileName, 'w') or die("can't open file");
fclose($ourFileHandle);
?>

Writing a File:
---------------------

<?php
$myFile = "testFile.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = "Aptech Computer Education \n";
fwrite($fh, $stringData);
$stringData = "Dwarakanagar\n";
fwrite($fh, $stringData);
fclose($fh);
?>

Reading a File:-
------------------------
<?php
$myFile = "testFile.txt";
$fh = fopen($myFile, 'r');
$theData = fread($fh, 6);
fclose($fh);
echo $theData;
?>

Deleting Data from the File:-
----------------------------------------
<?php
$myFile = "testFile.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
fclose($fh);
?>

PHP - File Write: Appending Data:-
-----------------------------------------------
<?php
$myFile = "testFile.txt";
$fh = fopen($myFile, 'a') or die("can't open file");
$stringData = "Happy Dasara\n";
fwrite($fh, $stringData);
$stringData = "Happy Diwali\n";
fwrite($fh, $stringData);
fclose($fh);
?>

------------------------------------------------------------------------------------------------------------
PHP - File Open: Truncate:-
-------------------------------------
To erase all the data from our testFile.txt file we need to open the file for normal writing. All

existing data within testFile.txt will be lost.

Example:
------------
<?php
$myFile = "testFile.txt";
$fh = fopen($myFile, 'w');
fclose($fh);
?>

PHP - Different Ways to Open a File:-
--------------------------------------------------
Read: 'r'
-----------
Open a file for read only use. The file pointer begins at the front of the file.

Write: 'w'
-------------
Open a file for write only use. In addition, the data in the file is erased and you will begin

writing data at the beginning of the file. This is also called truncating a file, which we will talk about more

in a later lesson. The file pointer begins at the start of the file.

Append: 'a'
---------------
Open a file for write only use. However, the data in the file is preserved and you begin will

writing data at the end of the file. The file pointer begins at the end of the file.

-------------------------------------------------------------------------------------------------

PHP Form Handling:
====================
The most important thing to notice when dealing with HTML forms and PHP is that any form element in

an HTML page will automatically be available to your PHP scripts.

Create a html file (sample.html)
-------------------------------------------
<html>
<body bgcolor=yellow>

<form action="welcome.php" method="post">
Name: <input type="text" name="fname">
<br><br>
Age: <input type="text" name="age">
<br><br>
<input type="submit">
</form>

</body>
</html>

Create a PHP File (welcome.php)
------------------------------------------------
<html>
<body>

Welcome <?php echo $_POST["fname"]; ?>!<br>
You are <?php echo $_POST["age"]; ?> years old.

</body>
</html>

Note:
----------
Save both files in C:\wamp\www\Uma.
Execute html file.


The $_GET Variable:
================
The predefined $_GET variable is used to collect values in a form with method="get"

Information sent from a form with the GET method is visible to everyone (it will be displayed in the

browser's address bar) and has limits on the amount of information to send.

HTML FIle:
------------------------
<html>
<body bgcolor=yellow>

<form action="phpget.php" method="get">
Name: <input type="text" name="fname">
<br><br>
Age: <input type="text" name="age">
<br><br>
<input type="submit">
</form>

</body>
</html>

----------------------------------------------------------------------
phpget.php
---------------------------------------------------------------
<html>
<body bgcolor=cyan>
Welcome <?php echo $_GET["fname"]; ?>.<br>
You are <?php echo $_GET["age"]; ?> years old!

</body>
</html>
==================================================
The $_POST Variable
=========================================
The predefined $_POST variable is used to collect values from a form sent with method="post".

Information sent from a form with the POST method is invisible to others and has no limits on the

amount of information to send.

Note: However, there is an 8 MB max size for the POST method, by default (can be changed by setting the

post_max_size in the php.ini file).

Example of HTML File:
---------------------------------------------
<html>
<body bgcolor=green>
<form action="phppost.php" method="post">
Name: <input type="text" name="fname">
<br><br>
Age: <input type="text" name="age">
<br><br>
<input type="submit">
</form>
</body>

<html>
     
---------------------------------------------------
phppost.php
----------------------------------

<html>
<body bgcolor=violet>

Welcome <?php echo $_POST["fname"]; ?>!<br>
You are <?php echo $_POST["age"]; ?> years old.

</body>
</html>

PHP Date() :
===================
The required format parameter in the date() function specifies how to format the date/time.

Here are some characters that can be used:

d - Represents the day of the month (01 to 31)
m - Represents a month (01 to 12)
Y - Represents a year (in four digits)

Example:
---------------------------------
<html>
<body bgcolor=blue text=white>

<?php
echo "<h2>".date("Y/m/d") . "<br>";
echo date("Y.m.d") . "<br>";
echo date("Y-m-d");
?>
</body>
<html>
======================================
PHP Date() - Adding a Timestamp:
===============================
The optional timestamp parameter in the date() function specifies a timestamp. If you do not specify a

timestamp, the current date and time will be used.

The mktime() function returns the Unix timestamp for a date.

The Unix timestamp contains the number of seconds between the Unix Epoch (January 1 1970 00:00:00

GMT) and the time specified.

Example:
-------------------
<html>
<body bgcolor=green text=white>
<?php
$tomorrow = mktime(0,0,0,date("m"),date("d")+1,date("Y"));
echo "<h2 align=center>"."Tomorrow is ".date("Y/m/d", $tomorrow);
?>
</body>
</html>

==============================================
PHP include and require Statements
==============================================
In PHP, you can insert the content of one PHP file into another PHP file before the server executes it.

The include and require statements are used to insert useful codes written in other files, in the flow of

execution.

Include and require are identical, except upon failure:
------------------------------------------------------------------

1. require will produce a fatal error (E_COMPILE_ERROR) and stop the script
include will only produce a warning (E_WARNING) and the script will continue
So, if you want the execution to go on and show users the output, even if the include file is missing, use

include. Otherwise, in case of FrameWork, CMS or a complex PHP application coding, always use require

to include a key file to the flow of execution. This will help avoid compromising your application's security

and integrity, just in-case one key file is accidentally missing.

Including files saves a lot of work. This means that you can create a standard header, footer, or menu file

for all your web pages. Then, when the header needs to be updated, you can only update the header

include file.

Example - 1(y3.php)
--------------------------------------------------------------
<html>
<body>

<?php include 'y3.php'; ?>
<h1>Welcome to my home page!</h1>
<p>Some text.</p>

</body>
</html>

----------------------------------------------------------------------------------------
Example - 2 (menu.php)
---------------------------------
echo '<a href="/default.php">Home</a>
<a href="/tutorials.php">Tutorials</a>
<a href="/references.php">References</a>
<a href="/examples.php">Examples</a>
<a href="/about.php">About Us</a>
<a href="/contact.php">Contact Us</a>';

-----------------------------------------------------------------------
y4.php
------------------------------------------------
<html>
<body>

<?php include 'menu.php'; ?>
<h1>Welcome to my home page!</h1>
<p>Some text.</p>

</body>
</html>
-----------------------------------------------------------------------------------

Example - 3(vars.php)
-------------------------------------------------------
<?php
$color='red';
$car='Indigo';
?>
------------------------------------------------------------
y5.php
----------------------------------------------
<html>
<body>

<h1>Welcome to my home page.</h1>
<?php include 'vars.php';
echo "I have a $color $car"; // I have a red BMW
?>

</body>
</html>

===========================================

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.

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


Example I (cookie.php)
-------------------------------------------
<?php
setcookie("user", "Uma", time()+3600);
?>

<html>
<body bgcolor=tan text=green>
<h1>Cookie is Created..</h1>
</body>
</html>

-----------------------------------------
cookie1.php
-----------------------------------
<?php
// Print a cookie
echo $_COOKIE["user"];

// A way to view all cookies
print_r($_COOKIE);
?>

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.

Starting a PHP Session:
---------------------------------
 The session_start() function must appear BEFORE the <html> tag.

eg:
<?php session_start(); ?>

<html>
<body>

</body>
</html>

Storing a Session Variable:(Example)
----------------------------------------------------
<?php
session_start();
// store session data
$_SESSION['views']=1;
?>

<html>
<body>

<?php
//retrieve session data
echo "Pageviews=". $_SESSION['views'];
?>

</body>
</html>

Uploading Files:
=================================
A PHP script can be used with a HTML form to allow users to upload files to the server.

Initially files are uploaded into a temporary directory and then relocated to a target destination by a PHP

script.


Example:
--------------------
uploadfile1.html
------------------------
<html>
<head>
<title>File Uploading Form</title>
</head>
<body bgcolor=cyan text=blue>
<h3>File Upload:</h3>
Select a file to upload: <br />
<form action="fileupload2.php" method="post" enctype="multipart/form-data">
<input type="file" name="file" size="50" />
<br />
<input type="submit" value="Upload File" />
</form>
</body>
</html>


fileupload2.php
----------------------------
<?php
error_reporting(0);
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>";
move_uploaded_file($_FILES["file"]["tmp_name"],
      "upload/" . $_FILES["file"]["name"]);
      echo "Stored in: " . "upload/" . $_FILES["file"]["name"];

  }
?>


Strings in PHP
==================
Example 1
-----------------

<?php
$txt="Hello world!";
echo $txt;
?>

Example 2
----------------------

<?php
$txt1="Hello world!";
$txt2="What a nice day!";
echo $txt1 . " " . $txt2;
?>

Example 3
----------------------
<?php
echo strlen("Hello world!");
?>

Example 4
----------------------
<?php
echo strpos("Hello world!","world");
?>

Example 5
----------------------

<?php
$string1="Hello World";
$string2="1234";
echo $string1 . " " . $string2;
?>

Example 6
----------------------
<?php
$myString = "My apple is red";
echo str_replace("red", "blue", $myString);
?>


Example 7
----------------------
<?php
$myString = "hello";
echo strtoupper($myString);
?>


==============================================
Object Oriented Programming Concepts
===============================================
 Standard Structure of Program in OOPS:-

class
Object
objective
1.Data Members
2.Member Functions



Class:-
---------
In a PHP program the "class"  keyword denotes class name.
(or)
Class is nothing but collection of data and functions.

(or)

In object oriented programming a class can be an abstract data type, blue print or template. You could

consider the name of a class as noun like name of a person, place or thing. For example Fruit is a class,

where apple, orange are the object of this class.


Objective:-
---------------
It is a invisible and it is the end result of an application which can be achieved using data

members and member functions. Objective means end result of the programme.


Object:-
------------
It is a instance of a class which can be gives the reference to its.
(or)

Object is nothing but instance of class.



   OOPS:- Object Oriented Programming System
--------------------------------------------------------------
1.Encapsulation
2.Data Abstraction
3.Polymorphism
4.Inheritance

1.Data Encapsulation:-
----------------------------
The union of data and functions into objects is known as Data Encapsulation.
(or)

Details of what a class contains need not be visible to other classes and objects that use it.

Instead, only specific information can be made visible and the others can be hidden.  This is achieved

through encapsulation, also called data hiding.  Both abstraction and encapsulation are complementary to

each other.

Data Abstraction:-
------------------------

We can give restricting the data, to set a number of functions.
(or)
It gives security.
(or)

Abstraction is the feature of extracting only the required information from objects.  For

example, consider a television as an object.  It has a manual stating how to use the television.  However,

this manual does not show all the technical details of television, thus giving only an abstraction to the

user.

Polymorphism:-
---------------------

It is ability to take more than one form.
(or)
Use of something for different purposes.
(or)

Polymorphism is the ability to behave differently in different situations.  It is basically seen in

programs where you have multiple method declared with the same name but with diferent parameters and

different behavior.


Inheritance:-
----------------
Relation between two classes.
(or)
Object of one class can acquire the properties of  another class.
(or)

Inheritance is the process of creating a new class based on the attributes and methods of an

existing class.  The existing class is called the base class whereas the new calss created is called the derived

class.  This is very important concept of objet-oriented programming as it helps to reuse the inherited

attributes and methods.

Base Class:-
---------------
It is a old class or parent class

Derived Class:-
--------------------
It is a new class or child class which can acquire the properties from base class.


Example 1:(oopsprg6.php)
------------------------------------------

<?php

class A

{

public function disp()
{

echo "Inside the class<br/>";

}
}

$a=new A();

$a->disp();

A::disp();

?>

-----------------------------------------------------------------------------
Example 2:(oopprg1.php)
----------------------------------------------------------------

<html>
<head>
<title>Class and Object</title>
</head>
<body bgcolor=green text=white>

<?php
class Test
{
public function display()
{
        echo "<h2>We just created and object!"."<br>";           echo "

This is my First Class and Object..";
    }
public function disp()
{
echo "<br><h2>This is my Second Function</h2>";
}
}
$Test = new Test();
$Test->display();
$Test->disp();
?>
</body>
</html>

--------------------------------------------------------------------------------------
Example 3.(oops1.php)
---------------------------------------

<html>
<head>
<title>Classes and Objects</title>
</head>
<body bgcolor=green text=white>
<?php
class SimpleClass
{

public $var = 'This is my Instance Variable';

 
public function displayVar()
{
echo $this->var;
    }
}

$SimpleClass = new SimpleClass();
$SimpleClass->displayVar();
?>
</body>
</html>

-----------------------------------------------------------------------
Example 4(oops4.php)
-------------------------------------------------------------------
<html>
<head>
<title>Class and Object</title>
</head>
<body bgcolor=green text=white>
<?php
class Image
 {
    public function Image()
 {
        echo "<h2>We just created and object!"."<br>";
        echo " This is my First Class and Object..";
    }
}
$image = new Image();
?>
</body>
</html>

===================================================
Inheritance (Example5  oopsprg9.php)
=======================================
<?php

class One

{

public function printItem($string)

{

echo 'This argument is passing from '.$string.'<br/>';

}

}

class Two extends One

{

}

$baseObj=new One();

$childObj=new Two();

$baseObj->printItem("Base");

$childObj->printItem("Child");

?>
------------------------------------------------------------------------------
Example6(oopsprg10.php)
---------------------------------------------------------------------------
<?php

class One
{

private $string;

public function mutator($arg)
{

$this->string=$arg;
}

public function accessor()
{

echo "Value is: ".$this->string;}}

$one=new One();

$one->mutator("roseindia");

$one->accessor();

?>
=================================================
Using static keyword:Example7    ooprg11.php
==================================================


<?php
//Example of PHP Static Variables & Methods :

class One
{

private static $var=0;


static function disp()
{

print self::$var;
}
}

One::disp();

?>

 -----------------------------------------------------------------------
Exmple8 (oopsprg12.php)
-----------------------------------------------------------------------

<?php
//abstract class

abstract class One
{

public function disp()
{

echo "Inside the parent class<br/>";

}

}

class Two extends One
{

public function disp()
{

echo "Inside the child class<br/>";

}

}

class Three extends One
{

//no method is declared

}

$two=new Two();

echo "<b>Calling from the child class Two:</b><br/>";

$two->disp();

echo "<b>Calling from the child class Three:</b><br/>";

$three=new Three();

$three->disp();

?>
-------------------------------------------------------------------------

Example9 (oopsprg3.php)
---------------------------------------------------------------

<?php

abstract class One{

abstract function disp();

}

class Two extends One{

public function disp(){

echo "Inside the child class<br/>";

}

}

class Three extends One{

public function disp(){

echo "Inside the child class 2<br/>";}

}

$two=new Two();

echo "<b>Calling from the child class Two:</b><br/>";

$two->disp();

echo "<b>Calling from the child class Three:</b><br/>";

$three=new Three();

$three->disp();

?>
-----------------------------------------------------------------
Example10    (oopsprg14.php)
--------------------------------------------------------------
<?php

interface Inter
{

const a="This is constant value";

public function disp();
}

class A implements Inter
{

function show()
{

echo self::a."<br/>";
}

public function disp()
{

echo "Inside the disp function";
}
}

$a=new A();

$a->show();

$a->disp();

?>
-------------------------------------------------------------------
Constructor:   Example11  (oopsprg.php)
======================================
<html>
<head>
<title>Class and Object</title>
</head>
<body bgcolor=blue text=white>

<?php
class Test
{
public function Test()
{
        echo "<h2>This is a Constructor..!"."<br>";
    }
public function disp()
{
echo "<br><h2>This is Normal Function..</h2>";
}
public function display()
{
    echo " <br><h2>TThis is another Normal Function..";
    }

}
$T = new Test();
$T->disp();
$T->display();

?>
</body>
</html>

-------------------------------------------------------------------------------
Example12  (oopsprg7.php)
--------------------------------------------------------------------------
//Constructor

<?php

class ParentClass
{

function __construct()
{

print "In parent class <br/>";
}
}

class ChildClass extends ParentClass
{

function __construct()
{

parent::__construct();

print "In child class";
}
}

$obj1=new ParentClass();

$obj2=new ChildClass();

?>

======================================================

What is MySQL?
==================
1. MySQL is a database server
2. MySQL is ideal for both small and large applications
3. MySQL supports standard SQL
4. MySQL compiles on a number of platforms
5. MySQL is free to download and use





Database Programs in PHP
========================
Database - MySql
Database Name- Uma
Table - employ
Columns - eno, ename, basic

Retrieving Records:
--------------------------------

<?php
$con = mysql_connect("localhost","root","");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("uma", $con);

$result = mysql_query("SELECT * FROM employ ") or die('error at Sql');

echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>";

while($row = mysql_fetch_array($result))
  {
  echo "<tr>";
  echo "<td>" . $row['eno'] . "</td>";
  echo "<td>" . $row['ename'] . "</td>";
  echo "<td>" . $row['basic'] . "</td>";
  echo "</tr>";
  }
echo "</table>";

mysql_close($con);
?>

=============================================
Inserting Records:
=========================================
<html>
<head>
<title>Insert data into database</title>
</head>
<body>
<?php


$con = mysql_connect("localhost","root","");
if (!$con)
 {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("uma", $con);

// The SQL statement is built

$strSQL = "INSERT INTO employ(";

$strSQL = $strSQL . "eno, ";
$strSQL = $strSQL . "ename, ";
$strSQL = $strSQL . "basic) ";

$strSQL = $strSQL . "VALUES(";

$strSQL = $strSQL . "500, ";

$strSQL = $strSQL . "'Anil', ";

$strSQL = $strSQL . "30000)";

// The SQL statement is executed
mysql_query($strSQL) or die (mysql_error());

// Close the database connection
mysql_close();
?>

<h1>The Record is Inserted!</h1>
</body>
</html>

=================================================
Updating Records
=================================================
<html>
<head>
<title>Update data in database</title>

</head>
<body>

<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
  die('Could not connect: ' . mysql_error());
}

mysql_select_db("uma", $con);

// The SQL statement is built
$strSQL = "Update employ set ";
$strSQL = $strSQL . "ename= 'Anil', ";
$strSQL = $strSQL . "basic= 44454 ";

$strSQL = $strSQL . "Where eno = 101";

// The SQL statement is executed
mysql_query($strSQL);

// Close the database connection
mysql_close();
?>

<h1>The database is updated!</h1>
</body>
</html>

================================================
Deleting Records
=============================================

<html>
<head>
<title>Delete data in the database</title>
</head>
<body>

<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
  die('Could not connect: ' . mysql_error());
}

mysql_select_db("uma", $con);

// The SQL statement that deletes the record
$strSQL = "DELETE FROM employ WHERE eno= 500";
mysql_query($strSQL);

// Close the database connection
mysql_close();
?>

<h1>Record is deleted!</h1>

</body>
</html>
====================================================
Filters in PHP
=========================================
fileter1.php
============================================
<?php
$int = 123;

if(!filter_var($int, FILTER_VALIDATE_INT))
  {
  echo("Integer is not valid");
  }
else
  {
  echo("Integer is valid");
  }
?>
===================================================
filte2.php
==================================================

<?php
if(!filter_has_var(INPUT_POST, "email"))
  {
  echo("Input type does not exist");
  }
else
  {
  if (!filter_input(INPUT_POST, "email", FILTER_VALIDATE_EMAIL))
    {
    echo "E-Mail is not valid";
    }
  else
    {
    echo "E-Mail is valid";
    }
  }
?>

==================================================
filterx.php
================================================
<?php
error_reporting(0);

?>
<form method="post" action="filter2.php">
<input type=text name=email>
<input type="submit" value="Submit">
</form>

<a href="filter2.php?email=eswar1251x@gmail.com">clickme </a>

======================================================
Networking :
=====================================
Example(network1.php)
---------------------------------------
<?php
echo gethostbyaddr('192.168.1.100');
echo gethostbyaddr('192.168.0.1');
?>

-------------------------------------------------------
Example(network2.php)
---------------------------------------------------------
Code:
<?php
echo gethostbyname('gmail.com');
?>
-----------------------------------------------
Example(network3.php)
---------------------------------------------------------
<?php
echo getservbyname('http', 'tcp');
?>
------------------------------------------------
Example(network4.php)
--------------------------------------------------
<?php
echo getprotobyname(81);
echo getprotobyname('icmp');
?>
================================================
Mailing
===============================================
Example (mail1.php)
---------------------------------------------------------------------
<?php
$to = "umaataptech@gmail.com";
$subject = "Test mail from PHP";
$message = "Hello! This is a simple email message from PHP";
$from = "umaataptech@gmail.com";
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);
echo "Mail Sent.";
?>
--------------------------------------------------------------------------------------
Example (mail2.php)
----------------------------------------------------------------------------
<html>
<body>

<?php
if (isset($_REQUEST['email']))
//if "email" is filled out, send email
  {
  //send email
  $email = $_REQUEST['email'] ;
  $subject = $_REQUEST['subject'] ;
  $message = $_REQUEST['message'] ;
  mail("umaataptech@gmail.com", "Subject: $subject", $message, "From: $email" );
  echo "Thank you for using our mail form";
  }
else
//if "email" is not filled out, display the form
  {
  echo "<form method='post' action=''>
  Email: <input name='email' type='text'><br>
  Subject: <input name='subject' type='text'><br>
  Message:<br>
  <textarea name='message' rows='15' cols='40'>
  </textarea><br>
  <input type='submit'>
  </form>";
  }
?>

</body>
</html>
=======================================================

1 comment:

PHP Notes

The Characteristics of PHP:- ----------------------------------- 1.PHP is a high level programming language. 2.It is a server-side scrip...