PHP: Hypertext Preprocessor, Is A Widely Used, General-Purpose Scripting Language That
PHP: Hypertext Preprocessor, Is A Widely Used, General-Purpose Scripting Language That
was originally designed for web development, to produce dynamic web pages. It can be
embedded into HTML and generally runs on a web server, which needs to be configured
to process PHP code and create web page content from it. It can be deployed on most
web servers and on almost every operating system and platform free of charge.
• It is easy to learn
• It blends well with HTML
• PHP has a vast library of functions and APIs
• You can rapidly create Web applications and database-backed applications
• It is cross-platform capable
• But after these many good aspects also php had a lots issue, but the major areas
are solved with php5.
Generally PHP code you can write anywhere in the HTML page, but PHP code should
be written within the tags - <?php ?> or <? ?>
For using the second method You have to activate “short_open_tag” from php.ini file.
<html>
<head>
<title>My First PHP Page</title>
</head>
<body>
<?php
echo "Hello World!";
?>
</body>
</html>
Generally echo or print can be used for printing any output to the browser.
Note: Every line of PHP code should ends with a semicolon (;).
1. Include:
<?php
include("sample.php");
echo "Hello World!";
?>
2. Require:
<?php
require("noFileExistsHere.php");
echo "Hello World!";
?>
If the file is exists both code will add the file to your webpage, but if the file is not
exists then in the 1st case it will through a warning but execute the following code and
in the 2nd case it will throw a fatal error stop executing the rest.
Like the other programming languages php also has if, if-else, elseif and switch
statement.
For checking the conditions if, if else, elseif are used. You can use switch statement in
place of if, elseif, else.
<?php <?php
$no = 3 $no = 3;
If ($no == 1){ switch ($no ){
echo "The No is 1"; case 1:
} else if ($no == 2) { echo "The No is 1";
echo "The No is 2"; break;
} else if ($no == 3) { case 2:
echo "The No is 3"; echo "The No is 2";
} else { break;
echo " The No is greater than 3"; case 3:
} echo "The No is 3";
?> break;
default:
echo "The No is greater
than 3";
break;
}
?>
PHP Forms:
Now we are in form control. Here some form methods has to be cleared.
• Form method
There are 2 methods used in php, POST and GET. POST method passes
the values of the fields through backend when GET method passes the
value through URL. So for the security reason POST is vastly used (in
general case).
If we are using POST method then we have to retrieve the value with
$_POST or $_REQUEST.
And if we are using GET method then we have to retrieve the value with
$_GET or $_REQUEST.
• Form action
In which page form fields’ value should be passed. (You can use same
page or same page with different action also.)
• Different types of buttons
1. Input type submit (on click the form will be submitted automatically)
2. Input type image (same as above)
3. Input type button (You have to submit the form manually.)
<html><body>
<form action="sample.php" method="post">
<select name="item">
<option value="Paint">Paint</option>
<option value="Brushes">Brushes</option>
<option value="Erasers">Erasers</option>
</select>
Quantity: <input name="quantity" type="text" />
<input type="submit” value="submit" />
</form>
</body></html>
<?php
$item=$_REQUEST ['item']; or $item=$_POST['item'];
$quantity =$_REQUEST [‘quantity’]; or $quantity =$_POST[' quantity '];
?>
<html><body>
<form action="sample.php" method="get">
<select name="item">
<option value="Paint">Paint</option>
<option value="Brushes">Brushes</option>
<option value="Erasers">Erasers</option>
</select>
Quantity: <input name="quantity" type="text" />
<input type="submit” value="submit" />
</form>
</body></html>
<?php
$item=$_REQUEST ['item']; or $item=$_GET['item'];
$quantity =$_REQUEST [‘quantity’]; or $quantity =$_GET[' quantity '];
?>
PHP Array
$emp[0] = "Bob";
$emp[1] = "Sally";
$emp[2] = "Charlie";
$emp[3] = "Clare";
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.
$salaries["Bob"] = 2000;
$salaries["Sally"] = 4000;
$salaries["Charlie"] = 600;
$salaries["Clare"] = 0;
From the above array you can get the value and the respected employee name from a
single array only.
And on the other hand if you want to get the name who is getting 2000 Rs , that you can
find like this:
$emp=array_keys($salaries, "2000");
echo $emp[0];
Output: Bob
For more inbuilt functions refer: http://php.net/
PHP Loops:
Example:
$employeeAges;
$employeeAges["Lisa"] = "28";
$employeeAges["Jack"] = "16";
$employeeAges["Ryan"] = "35";
$employeeAges["Rachel"] = "46";
$employeeAges["Grace"] = "34";
4. PHP - Do While
A "do while" loop is a slightly modified version of the while loop.
On the other hand, a do-while loop always executes its block of code at least
once. This is because the conditional statement is not checked until after the
contained code has been executed.
The difference between while and Dowhile loop is shown in the down example:
$cookies = 0;
while($cookies > 1){
echo "statement exicuted";
}
Output: Nothing
$cookies = 0;
do {
echo "statement exicuted";
} while ($cookies > 1);
A function is just a name we give to a block of code that can be executed whenever we
need it. The main usability of function is you can call that block of code from any place
and any no of times.
Now in the below 2 examples you can see the plain functions as well as the functions
with parameters.
<?php
function go(){
echo "Function called";
}
echo "Welcome to freshersworld.com <br />";
go();
?>
Output:
Welcome to freshersworld.com
Function called
Output:
Hi Amit
Hi Ahmed
Database Connection and handling db queries
PHP can connect to more all less all databases. But with PHP mainly mysql is used.
Here we are showing the connection pattern between PHP and mysql.
?>
Example:
But when you are getting a result set from a query some additional functions are needed
to get the values. This is needed for select query because it returns a result set.
The functions are mysql_fetch_assoc, mysql_fetch_row, mysql_num_rows etc.
Mysql_num_rows is used to fetch the no of rows in the result set.
Example: (assume that xyz table has id, name and salary field)
OR
In file handling mainly we have to use create, open, read, write, append, delete, truncate
and file upload.
For creation, writing and truncate in file the use is same. If the file is present then it will
open that file only otherwise it will create a new file. If the file is present then at the time
of opening it clears the data in it and opens a blank file.
$file_name = "sample.txt";
$file_handle = fopen($file_name, 'w') or die("can't open file");
fclose($file_handle);
fopen function has 2 arguments – the first argument is the file name and the 2nd one is in
which mode you want to open a file . In the above example ‘w’ stands for the mode
write.
• 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.
• Read/Write: 'r+'
Opens a file so that it can be read from and written to. The file pointer is at the
beginning of the file.
• Write/Read: 'w+'
This is exactly the same as r+, except that it deletes all information in the file when
the file is opened.
• Append: 'a+'
This is exactly the same as r+, except that the file pointer is at the end of the file.
File Upload:
PHP file upload can be done through a file field from a form. But for uploading a file you
have to be very clear that in the destination folder you have proper permission. Another
important thing is that for uploading a file in form tag you have to add some additional
properties (enctype="multipart/form-data").
</form>
<?php
$file_name = $_FILES["photo"]["name"];
$new_file_name="/photo/". file_name;
move_uploaded_file($_FILES["photo"]["tmp_name"], $new_file_name);
?>
By using $_FILES["photo"]["type"] you can get the extension of the file also. There are
other syntaxes are also there to find the size of a file.
PHP Strings:
In PHP there are a lot of string functions. Some common PHP string functions are
strpos(), str_replace, implode, explode, substr etc.
The reference of the string functions You can get:
http://php.net/manual/en/ref.strings.php
Advanced PHP:
The date function uses letters of the alphabet to represent various parts of a typical date
and time format.
Example:
<?php
echo date("m/d/y");
?>
• r: Displays the full date, time and timezone offset. It is equivalent to manually
entering date("D, d M Y H:i:s O")
Time:
Day:
• d: Day of the month with leading zeroes. Values are 01 through 31.
• j: Day of the month without leading zeroes. Values 1 through 31
• D: Day of the week abbreviations. Sun through Sat
• l: Day of the week. Values Sunday through Saturday
• w: Day of the week without leading zeroes. Values 0 through 6.
• z: Day of the year without leading zeroes. Values 0 through 365.
Month:
Year:
PHP sessions:
A PHP session solves this problem by allowing you to store user information on the
server for later use (i.e. username etc). However, this session information is temporary
and is usually deleted very quickly after the user has left the website that uses sessions.
In the below example we will try to find out the page hit for a single user:
<?php
session_start();
if(isset($_SESSION['views']))
$_SESSION['views'] = $_SESSION['views']+ 1;
else
$_SESSION['views'] = 1;
Simply the session variables are working like the global variables throughout the
site for a specific time.
PHP Cookies:
PHP Cookies are variables which are stored in client side, this improves the
performance because server is not hitting for these values. But this is not that much
secure to use as it stored in client side.
Example:
<?php
$one_day = 60 * 60 * 24 * 1 + time();
?>
<?php
?>
As you know the main popularity of PHP is that it blends well with any HTML front-end
design and you can create the php block in any place.
For an example think you are asked to fetch all the values of previous xyz table. Here is
the example how you are going to produce such output.
ID Name Salary
1 Amit 5000
2 Vikash 3000
3 Asit 12000
4 Manish 55000
<html>
<head>
<title>Sample Coding</title>
</head>
<body>
<td width="17%">ID</td>
<td width="44%">Name</td>
<td width="39%">Salary</td>
</tr>
<?php
while($result = mysql_fetch_assoc($query))
{
?>
<tr style="text-align:center">
</tr>
<?php
?>
</table>
</body>
</html>
Now be very sure at the time of real-time coding you are following the naming
conventions (Means your variable name, function name, page name etc should
reflect the description of it).
And another aspect is performance, for this try to hit the server as minimal as
possible.