My PHP Reference by mozammel06



                                                  My PHP Reference: 
                  Array Declaration:                                      Array Reading: 
$array_name=array();                                     print $array_name[number]; 

Example: $name=array(“razib”,”sajib”,”habib”)            Example:  for($a=0;$a>3;$a++)  
                   $Number = array(10, 20, 30, 40);      { print $name[$a]; } 

Declaration:      $number = array();                     # Key may be string, or number. if number, that is 
                                                         called scalar, and if string that is Associative array 
$number[]="Autumn";             $seasons[1]="Autumn";
$number[]=20;                   $seasons[2]=20;          $num[razib]=20; $num[sajib]="Sajib Ahmed"; 
$number[]="Spring";             $seasons[3]="Spring";
                                                         $num["sultan"]="tania sultana"; 
                                $seasons[4]=25;          $num[maruf]="marufbd"; 
it will be start from 0,1,2,

print $num[maruf]."<br>".$num[razib]. "<br>".$num[sajib]." and <br>".$num[sultan]; must be visited later, because here is some problems.  

The count( ) function is useful when you want to return how many elements are in your array. You
can then use this in a for loop. Here's an example we used earlier, only this time with the count

$seasons = array("Autumn", "Winter", "Spring", "Summer");

$array_count = count($seasons);

for ($key_Number = 0; $key_Number < $array_count; $key_Number++) {
print $seasons[$key_Number];

To get how many elements are in the array, we used this:

$array_count = count($seasons);

Using array_rand() Function You can grab a random key from an array. This could be useful in
games of chance. Here's a simple script that simulates a single dice throw:


$numbers = array(1 => 1, 2 => 2, 3 => 3, 4 => 4, 5 => 5, 6 => 6);
$random_key = array_rand($numbers, 1);
print $random_key;


The function that returns the random key is this:

array_rand($numbers, 1);

ucwords() Function converts Lower Case to Upper Case for First Later: (bill gates to Bill Gates)

example: $full_name="bill gates";      convert to upper case:  $full_name = ucwords($full_name); 

strtoupper( ) : this function used to convert all string lower case to upper case.
strtolower( ) : this function used to convert all string upper case to lower case.
Array Looping: foreach statement are used for array looping,

Example: $number=array(0,1,2,3,4,5,6,7,8,9); foreach($number as $temp) { print $temp; } here,
$number is that array in which we want to looping. and $temp is a the variable in which the array key
and value of $number are stored temporarily while the loop be finished.


#The single quote ( ‘ )  sign can’t be used in string, if string are bound by two( ‘ )sign as: 
$name=’mozammel’s cat’; 

This is wrong, we must use double quote (“) or \’ replacing the single quote. If we want display ( \ ) in 
the last position of a string, as $name=’mozammel\’  then, we must use this form 

Some Important Function: 
           Function Name                                                Works
strtoupper( )                         this function used to convert all string lower case to upper case.

strtolower( )                         this function used to convert all string upper case to lower case.

ucwords()                             Function converts Lower Case to Upper Case for First Later: (bill
                                      gates to Bill Gates)example: $full_name="bill gates";      convert to 
first later lower to upper case       upper case:  $full_name = ucwords($full_name);

strlen( )                             Counting how many characters is in string.  
                                      $char_num=strlen($name); This function displays number of 
and                                   string including white space. But if we want without(excluding) 
                                      white space, we must use trim() function initially. Example: 
trim()                                $name=trim(” mozammel “);    $char_num=strlen($name);   print 
Know the number of character          $char_num;
of a string  
                                      the trim( ) function removes any blank spaces from the left and right of 
                                      a string 

                                      ltrim( ), removes space from the beginning of a string; the second one,  
                                      rtrim( ), removes space from the end of a string
str_shuffle( )                        This function used to display randomly arranged character from a string.
                                      Ex: $name=”mozammel”; $full_name=str_shuffle($name);
Random function 

$_SERVER["HTTP_USER_AGENT             $agent = $_SERVER["HTTP_USER_AGENT"]; print $agent;      The
"];                                   $_SERVER["HTTP_USER_AGENT"];used to display browser info

strops()                              $name = "bill gates"; $letter_position = strpos($name, "i");
                                      The strops() function are used to find character position in a
                                      string. It shows the position from 0, here the answer is 1
chr( )                                Convert an ASCII value to a its equivalent character

ord( )                                Find out what the ASCII value of a character is 

echo( )                               An alternative to the print statement 

similar_text( )                       Tells you how similar two strings of text are:   $name1=”mozammel”; 
                                      $name2=”mozammal”;  $check=similar_text($name1, $name2, 
similar string testing                $percent);   print($percent . "% correct"); 
$_REQUEST                             $_REQUEST can be used in for $_GET and $_POST Method, This 
                                      Function Contains the content of $_GET , $_POST and $_COOKIE. 

                                      A cookie is often used to identify a user. A cookie is a small file that the 
What is a Cookie?                     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 Creat a Cookie?                setcookie(name, value, expire, path, domain);
setcookie();                          $expire=time()+60*60*24*30;
                                      setcookie("user", "Alex Porter", $expire);
The setcookie() function must         ?> <html>...... // here we declare a cookie named “user”
appear before the <html> tag.         value “Alex Porter” and Expire in “60*60*24*30”


                                     $_COOKIE[ ];        variable is used to retrieve a cookie value.
How to Retrieve a Cookie 
                                     echo $_COOKIE["user"]; // Print a cookie
$_COOKIE[ ];                         print_r($_COOKIE); // A way to view all cookies
How to Delete a Cookie?              // set the expiration date to one hour ago for deleting Cookie.
                                     setcookie("user", "", time()-3600);
We have to declare expiration        ?>
date in the past.                    // When deleting a cookie you should assure that the expiration
                                     date is in the past
file_exists()                        file_exists() function checks the availability of desire file on
                                     desire directory. The argument will be name_with_path ie:
move_uploaded_file()                 move_uploaded_file() function used to move a uploaded file
                                     one place to another place

strpos()                             strpos() this function used to search a character in a string. if
                                     found, it will return the first position of character. If not, it will return
                                     False value

User Define Function: 
Declaration of user define                Declaration:  function function_name() { statement; }   
function:  making and calling             Ex1: function man() {  
                                          $man="mozammel haque";   
                                          print $man; } 
                                          function calling:   // just call function by man(); 
NB: The variable that is used in 
                                          function man() {  
function must be declared inside of 
                                          $man="mozammel haque";   
function Ex1 , 
                                          print $man; }   
If the variable is declared outside of    man();   //when function is called, it will work as defined in 
function, then we must use that           two { } 
variable as an argument of function       ex2:  $man="mozammel haque";   
that is created by us. See Ex2             function man($man) {  
                                          print $man; }   
When Two argument if function:            <?php
                                          function name($first, $last) 
                                          {   print $first." Mozammel ".$last;  } 
                                          name(Md, Haque);  ?>      
                                                                      //it will print on desktop Md Mozammel Haque
Returning the value from a                <?php
function for using next time              function add($x, $y) 
                                          {  $z=$x+$y;     return $z; } 
                                          $f=add(3,5);    print $f; 
                                          print "<br/>"; 
Return Value 
                                          print add(5,5);   
                                           ?>     //it returned data of $z variable and reused in function 
                                          function foo() { 
Nesting a Function                          function bar()   { 
                                              echo "I don't exist until foo() is called.\n0"; }  } 
declaring function in a function          // We can't call bar() before calling foo() function, because 


                                       bar() is in other function foo(), so foo() must be called first
                                       // Now we can call bar(),because foo() is called first, so foo() is 
                                       executed and then bar() can be executed easily. 
This Script is used to check the       <?php
text box are blank or filled:          $man=trim("mozammel haque");   
                                        function man($man)  {  if($man=="")  { 
                                       print "Blank Text Detected"; }  
                                        else { print "Text is OK";} 
                                       } man($man); ?> 

Working with File: 
this function used to read             $file_contents = readfile("dictionary.txt");
contect/text from any file.            print $file_contents;
file_get_contents()                    ?>
                                       this program will read text from dictionary.txt file, and prints it
this function also used to read
                                       to the display. it can be used as
contect/text from any file as
readfile();                            $file_to_read = "dictionary.txt";
                                       print readfile($file_to_read);

 have to learn                


fgetcsv()                              <?PHP 
                                       $file_handle = fopen("widgets.csv", "r"); 
                                       while (!feof($file_handle) ) { 
this function used to show data from   $line_of_text = fgetcsv($file_handle, 1024); 
a cvs file named widgets.csv. from     print $line_of_text[0] . $line_of_text[1]. $line_of_text[2] . 
same file locations on server          "<BR>"; 
                                       the cvs file have only 3 column here.
realpath()                             <?PHP 
                                       $absolute_path = realpath("fileDir.php"); 
this function used to show file
                                       print "Absolute path is: " . $absolute_path; 
directory with name  
                                       here this program shows the directory of filedir.php
dirname()                              <?PHP 
                                       $dir = dirname("folder/myphp/fileDir.php"); 
Get the Directory, but not the file
                                       print "directory is: " . $dir . "<BR>"; 
                                       Get the Directory, but not the file name 
basename()                             <?PHP 
                                       $bas = basename("folder/myphp/fileDir.php"); 
Get the Filename only 
                                       print "File Name is: " . $bas . "<BR>"; 
                                       Get the Filename only 



Working with Include File: 
Include(“file_name”) is a built in       <?php include("header.php"); ?> the function used in the 
function that includes any php file in a body of a php file at a div. Example:  <div class="leftmenu"> 
php page, It includes all of code of     <?php include("left_menu.php"); ?> </div>  here, we include 
file, then it is executed.               a left_menu file at the leftmenu div in body. 

require() is a built in function like as      NS: If any Error Occurred  during including a file by include() 
include() function that includes any          function , It shows an error message (only Warning), but other 
php file in a php page, It includes all       code then are Executed. 
of code of file, then it is executed. 
                                              NS: But in the require() function, If any Error Occurred  during 
                                              including a file by require() function , It shows  error message 
                                              Warning and Fatal Error, and Execution are stopped Here.  


Working with Upload File: 
                                   $_FILES[“key1”][“key2”]  Array used to upload a file Client to Server 
By using the global PHP        Here Key1 is the form's input name and the Key2 can be either
$_FILES array you can          "name", "type", "size", "tmp_name" or "error". Like this:
upload files from a client        • $_FILES["file"]["name"] - the name of the uploaded file
computer to the remote server.    • $_FILES["file"]["type"] - the type of the uploaded file
                                          •   $_FILES["file"]["size"] - the size in bytes of the uploaded file
                                          •   $_FILES["file"]["tmp_name"] - the name of the temporary
                                              copy of the file stored on the server
                                          •   $_FILES["file"]["error"] - the error code resulting from the
                                              file upload 
Upload File Form Script:           up_form.php:
                                   <form enctype="multipart/form‐data" action="upload.php" 
In these Script, up_form.php       method="post"> 
Named Form Select a file and       <label for="file"> Select a File</label> 
send it into Post Method,          <input type="file" name="file" value="file" id="file" /> 
then the upload.php file           <input type="submit" name="submit" value="Submit"> 
Executes it. And Stored in         </form> 
Server.                            upload.php:
                                   if ($_FILES["file"]["error"] > 0) 
                                     {   echo "Error: " . $_FILES["file"]["error"] . "<br />";  } 
                                   else  { 
                                     echo "Upload: " . $_FILES["file"]["name"] . "<br />"; 
                                     echo "Type: " . $_FILES["file"]["type"] . "<br />"; 
                                     echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />"; 
                                     echo "Stored in: " . $_FILES["file"]["tmp_name"]; 
                                     }  ?>       

Form Script:                       <?php 
(Secured/Restricted)               if((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == 
                                   "image/jpeg") || ($_FILES["file"]["type"] == "image/png") || 
In this Script, the file that’s 
                                   ($_FILES["file"]["type"] == "image/jpg") || ($_FILES["file"]["type"] == 
extension is .gif .jpg .jpeg 
                                   "image/pjpeg")) && ($_FILES["file"]["size"] < 240000)) { 
and .png can be uploaded if 
that is less than 240kb in       if($_FILES["file"]["error"] >0)  {  print "File Could not be uploaded?";  } 
size.                            else { 

                                   print "File Name". $_FILES["file"]["name"]."<br/>"; 
                                   print "File Type". $_FILES["file"]["type"]."<br/>"; 


                                   print "File Size". $_FILES["file"]["size"]."<br/>"; 
                                   print "File Path". $_FILES["file"]["tmp_name"]."<br/>"; 
                                   } }   else {print "File Upload Error".$_FILES["file"]["error"]; } 

Form Script:                       <?php 
(Secured/Restricted with           if((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == 
File Saving System)                "image/jpeg") || ($_FILES["file"]["type"] == "image/png") || 
                                   ($_FILES["file"]["type"] == "image/jpg") || ($_FILES["file"]["type"] == 
                                   "image/pjpeg")) && ($_FILES["file"]["size"] < 240000)) { 
In this Script, the file that’s    if($_FILES["file"]["error"] >0)  {  print "File Could not be uploaded?";  } 
extension is .gif .jpg .jpeg 
                                   else { 
and .png can be uploaded if 
that is less than 240kb in         print "File Name". $_FILES["file"]["name"]."<br/>"; 
size. And Store in                 print "File Type". $_FILES["file"]["type"]."<br/>"; 
“/upload/ ” path after php 
                                   print "File Size". $_FILES["file"]["size"]."<br/>"; 
file path in server. 
                                   print "File Path". $_FILES["file"]["tmp_name"]."<br/>"; 
                                   if (file_exists("upload/" . $_FILES["file"]["name"])) 
Here we used two function:        { 
                                         echo $_FILES["file"]["name"] . " <h4> File Already Exists.<h4> "; 
file_exists() and                        } 
move_uploaded_file()                   else 
                                         "upload/" . $_FILES["file"]["name"]); 
                                         echo "File Stored in: " . "upload/" . $_FILES["file"]["name"];   
                                         }      //file name only 
                                     echo "Invalid file"; 



Working with Date and Time: 
date();                                 <?php 
                                        $today = date('d‐m‐y');   // '-' sign can be replaced by another sign ':' 
this function used to display date
                                        print $today; 
on Browser. the argument must
be used in this function for getting    ?> 
date formate
                                        Day of the week Characters for the date( ) function

                                             Character              Meaning                      Example
Day of the week Characters
for the date( ) function                        d        Day of the month                   05, 09, 14, 31
                                                D        The day in text format             Mon, Wed, Sun
                                                 j       Like 'd', but without the zeros 5, 9, 14, 31

                                        l (lowercase L) Like 'D' but not shortened          Monday, Sunday
                                                         Ordinal ending for the day of st nd
                                                S                                      1 , 2 , 20th
                                                         the month


                                                     Numeric value for day of         0 is Sunday; 6 is
                                                     week                             Saturday
                                            W        Week number of the year          12th day of the year
                                          z     Numeric day of the year        0 to 365
                                     NOTE: W is available in PHP version 4.1.0 and above
Year Characters for the date( )      Year Characters for the date( ) function
                                          Character                Meaning                    Example
                                                 L       Is it a Leap Year?             1 if yes; 0 if no
                                                 Y       4 digit year value             2006, 2007
                                                 y       2 digit year value             06, 07

Time Characters for the date(        Time Characters for the date( ) function
) function
                                         Character                  Meaning                    Example
                                             a        Morning or Afternoon?                 am or pm

                                             A        Like 'a' but uppercase                AM or PM
                                             g        12 hour format – no leading zeros 1, 9, 12
                                             G        24 hour format – no leading zeros 0, 15, 23
                                             h        12 hour format – with zeros           01, 09, 12
                                             H        24 hour format – with zeros           00, 09, 23
                                             i        minutes                               00 to 59
                                           s     seconds                                    00 to 59
Other Characters for the date(       Other Characters for the date( ) function
) function
                                         Character              Meaning                     Example
                                            O         Greenwich Meantime offset +0300

                                            T         Time zone of the computer GMT, EST
                                                      Full formatted date and time Tue, 28 Feb 2006
                                                      using RFC 2822               15:22:23 +0300


Delete Record From Table: 
Delete data    $SQL = "DELETE FROM AddressBook WHERE First_Name = 'Bill' AND Surname = 'Gates'"; 

               //this code will delete specified name from addressbook table.  you can use this code also. 

               $SQL = "DELETE FROM AddressBook WHERE ID = '7' "; 

               $SQL="Delete from php where id='2'"; 




PHP Mail Function: 
mail();                  mail(to,subject,message,headers,parameters)


                           $to = ""; 
                           $subject = "Test mail"; 
                           $message = "Hello! This is a simple email message."; 
                           $from = ""; 
                           $headers = "From:" . $from; 
                           echo "Mail Sent."; 

                           <html> <body> 
                           if (isset($_REQUEST['email'])) 
                           //if "email" is filled out, send email 
                             //send email 
                             $email = $_REQUEST['email'] ;   $subject = $_REQUEST['subject'] ; 
                             $message = $_REQUEST['message'] ; 
                             mail("", "$subject", 
                             $message, "From:" . $email); 
                             echo "Thank you for using our mail form";   } 
                           //if "email" is not filled out, display the form 
                             {   echo "<form method='post' action='mailform.php'> 
                             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> 



Session Variable Starting: 
session_start()  session_start() must define before <html> tag

visitor counter  <?php    session_start(); if(isset($_SESSION['a'])) 
session_start()  $_SESSION['a']=$_SESSION['a']+1;  else  $_SESSION['a']=1; 
                 echo "Views=". $_SESSION['a'];    ?>   // $_SESSION['a'] means session variable declaring 
Session           ?php 
Destroy           unset($_SESSION['views']); 
                  ?>       //Session Destroy 

                  ?>           //Session Destroy using session_destroy() function 

Login Check:      <?PHP  //this script use to check if the user is Logged in or Not 
check if the      if (!(isset($_SESSION['login']) && $_SESSION['login'] != '')) { 
user is Logged 
                            header ("Location: login.php"); } ?> 
in or Not 
                  //this script works allows the user who are logged in, and redirect a logged out or 
                  not logged in user to login page. 
Login:            if ($num_rows > 0)  //this script used to login and session start See login Script File 
                  {  session_start(); 
                  }  else  { session_start(); $_SESSION['login']=''; 


                  print "Invalid Login Information"; 

Logout:           <?php    //this script used to logout and session destroy See logout Script File 
                  session_destroy();   ?> 


Working With MySQL Database: 
                      Sorting the Results
                      You can sort the results of the SELECT query by using the following clause at the end of
                      the statement
                      (and the optional ascending or descending qualifier):
                      SELECT * FROM tablename WHERE field1=value1 ORDER BY field2 ASC|DESC
                      Limiting the Results
                      If you would like to limit the results returned from your query, you can modify your
                      SELECT statement
                      like this:
                      SELECT * FROM tablename WHERE field1=value1
                      ORDER BY field2 ASC
                      LIMIT offset, number_of_rows_to_be_returned
mysql_connect()       mysql_connect(“host”,”user”,”pass”) 

                      This function are used to connect with mysql database. 


mysql_select_db()  mysql_select_db(“db”,”link”)

                      This function are used to Select a Database from  mysql server. 




Taking value from a form and send it to a variable: 
<body bgcolor="#66CCdb">    <!—used for only colored background ‐‐> 
<form method="post" name="cal" action="cal.php"> 
Value1: <input type="text" name="value1" size="6" value=""><br><br> 
Value2: <input type="text" name="value2" size="6" value=""><br><br> 
<input type="submit" name="submit" value="submit">  
 print "The Valu for".$value1."x".$value2."=".$total;  



#Data Taking from a Form and Sending it into a Database: (db name: php, table:std) 
<body bgcolor="#66CCdb">    <!—used for only colored background ‐‐> 
<h1>Welcome to Student Database Entry:<br></h1> 
<form method="post" name="form1" action="std_form.php"> 
Enter Student Name:<input type="text" name="name" size="35" value=""><br><br> 
Roll:<input type="text" name="roll" size="10" value="" > <br><br> 
Marks Details: <br><br> 
Bangla: <input type="text" name="bangla" size="6" value=""><br><br> 
English: <input type="text" name="english" size="6" value=""><br><br> 
Mathematice:<input type="text" name="math" size="6" value=""><br><br> 
Physics: <input type="text" name="physics" size="6" value=""><br><br> 
Chemistry: <input type="text" name="chemistry" size="6" value=""><br><br> 
Biology: <input type="text" name="biology" size="6" value=""> <br> <br> 
<input type="submit" name="button" value="Submit Data"> 
if(isset($_POST['button']))   //(isset( ) function again, just to check if the user clicked the Submit button.) 
}  ?> 

    $SQL = "INSERT INTO std (id, name, roll, bangla, english, math, physics, chemistry, biology) VALUES 
(' ','$name', '$roll','$bangla','$english','$math','$physics','$chemistry', '$biology')"; 
$result = mysql_query($SQL); 
print "Records added to the database"; 
else { 
print "Database NOT Found "; 



Show Information from an existing database: Using mysql_fetch_assoc() and foreach Loop 

$num_rows=mysql_num_rows($result); // to know number of Rows 
print"There are Currently ".$num_rows." Rows in the Table"; // to print Number of Rows 
print"<table border=1>";   //data printing using table 
while($a_row=mysql_fetch_row($result)) // $a_row is an array where row result stored one by one  
{                                                            // get the array key(row key) and its value from $result to $a_row 
foreach($a_row as $field)   // get the key and its value from $a_row array to $field    (goto array looping) 


Show Information from an existing database:  Using mysql_fetch_assoc() function 
print "<table border=1>"; 
while ($field = mysql_fetch_assoc($result))  
print "<td>". $field['id']."</td>"."<td>". $field['name']."</td>"."<td>". $field['ssc']."</td>"."<td>". 
$field['hsc']."</td>"."<td>". $field['url']."</td>"; 




Extra Comment for My Next time Reference : 

SN                                            COMMENTS

1      eকিট পেজর ডাটা an পেজ িp ট করেত হেল pথম পেজ ভিরেয়বল তরী করা যােব না। পেরর
        পেজ( য পেজ িp ট হেব) ভিরেয়বল তরী করেত হেব, eবং িp ট করেত হেব।

       One Page's input data can be printed in other page if the variable declared in next 
       page where the data be printed. But we can't declare variable in 1st page, It Must be 
       declared in next page 


About this Reference: this reference written for me( But I want to distribute it 
to all. 


To top