Você está na página 1de 16

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.

Why PHP is so popular?

Some of the reasons of the popularity of PHP are:

• 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.

Some important things to note down.

• Basically “wamp” or “lamp” is used for php execution.


(Both are the combinations of apache, mysql and PHP )
• All the php configurations are stored in php.ini file.
• For Your system current settings You can see by phpinfo()
• Sometime User has to activate some properties for php.ini file. Like
short_open_tag, max execution time, graphics library support etc. All these terms
are described below. After changing the config file user has to restart the server
to effect the following changes.
• Apache configuration file is httpd.conf.

• All of your PHP projects should be inside “www” directory of wamp.


PHP Basics:

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.

For a simple example:

<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 (;).

Include a external file through PHP

There are 2 ways to include a file through PHP.

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.

Condition checking in PHP (if, if-else, elseif, switch)

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.

If, elseif, else Switch

<?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.)

Here is a example of a form with post method:

<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>

In sample.php page we can get the value like this:

<?php
$item=$_REQUEST ['item']; or $item=$_POST['item'];
$quantity =$_REQUEST [‘quantity’]; or $quantity =$_POST[' quantity '];
?>

Here is a example of a form with get method:

<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>

In sample.php page we can get the value like this:

<?php
$item=$_REQUEST ['item']; or $item=$_GET['item'];
$quantity =$_REQUEST [‘quantity’]; or $quantity =$_GET[' quantity '];
?>

PHP Array

The simple array in php looks like:

$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.

echo "Bob is being paid – Rs.” $salaries["Bob"] . "<br />";

Output: Bob is being paid – Rs.2000

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:

In PHP we use these 4 loops:

1. PHP - While Loop


The function of the while loop is to do a task over and over as long as the
specified conditional statement is true. This logical check is the same as the one
that appears in a PHP if statement to determine if it is true or false. Here is the
basic structure of a PHP while loop:

while ( conditional statement is true){


//do this code;
}

2. PHP - For Loop


The basic structure of the for loop is as follows:

for ( initialize a counter; conditional statement; increment a counter){


do this code;
}

Example:

for ( $i = 10; $i <= 100; $i += 10)


{
echo $i;
}

3. PHP - For Each


The concept of for each loop is something new in php. While a For Loop and
While Loop will continue until some condition fails, the For Each loop will
continue until it has gone through every item in the array.

$employeeAges;
$employeeAges["Lisa"] = "28";
$employeeAges["Jack"] = "16";
$employeeAges["Ryan"] = "35";
$employeeAges["Rachel"] = "46";
$employeeAges["Grace"] = "34";

foreach( $employeeAges as $key => $value){


echo "Name: $key, Age: $value <br />";
}

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);

Output: statement executed


PHP Functions:

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.

Example 1: (plain functions without parameters)

<?php
function go(){
echo "Function called";
}
echo "Welcome to freshersworld.com <br />";
go();
?>

Output:
Welcome to freshersworld.com
Function called

Example 2: (plain functions with parameters)


<?php
function myGreeting($firstName){
echo "Hi ". $firstName. "<br />";
}
myGreeting("Amit");
myGreeting("Ahmed");
?>

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.

Below is the syntax for mysql database connection.


<?php

$link = mysql_connect('server name', ‘username’, 'password');

$db_selected = mysql_select_db(‘database name’, $link);

?>

In PHP every database query should be sent through a function “mysql_query”.

Example:

$Sample_query = mysql_query(“delete from xyz where id=6”);

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)

$Sample_query = mysql_query(“select * from xyz where id=6”);


$result = mysql_fetch_assoc($Sample_query);
$salary = $result[‘salary’];
$name = $result[‘name’];

OR

$Sample_query = mysql_query(“select * from xyz where id=6”);


$result = mysql_fetch_row($Sample_query);
$salary = $result[2];
$name = $result[1];
$id = $result[0];

Example for mysql_num_rows:

$Sample_query = mysql_query(“select * from xyz”);


$no_of_rows = mysql_num_rows($Sample_query);
File handling In PHP:

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.

Here is the description of different modes.

• 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.

Some advanced modes:

• 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").

See the example below:

<form action="" method="post" name="form1" enctype="multipart/form-data">

<input name="photo" type="file"/>

</form>

The php code for upload:

<?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.

From here you can rename a file to store in server.

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:

PHP date and time-

In PHP time() function returns the current timestamp.

Timestamp: A timestamp is the number of seconds from January 1, 1970 at 00:00.


Otherwise known as the Unix Timestamp, this measurement is a widely used standard
that PHP has chosen to utilize.

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");

?>

Important arguments passed through the date function.

Important Full Date and Time:

• 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:

• a: am or pm depending on the time


• A: AM or PM depending on the time
• g: Hour without leading zeroes. Values are 1 through 12.
• G: Hour in 24-hour format without leading zeroes. Values are 0 through 23.
• h: Hour with leading zeroes. Values 01 through 12.
• H: Hour in 24-hour format with leading zeroes. Values 00 through 23.
• i: Minute with leading zeroes. Values 00 through 59.
• s: Seconds with leading zeroes. Values 00 through 59.

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:

• m: Month number with leading zeroes. Values 01 through 12


• n: Month number without leading zeroes. Values 1 through 12
• M: Abbreviation for the month. Values Jan through Dec
• F: Normal month representation. Values January through December.
• t: The number of days in the month. Values 28 through 31.

Year:

• L: 1 if it's a leap year and 0 if it isn't.


• Y: A four digit year format
• y: A two digit year format. Values 00 through 99.

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;

echo "views = ". $_SESSION['views'];


?>

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:

Creation of cookies (use setcookie(name, value, expiration) function)

<?php

//Calculate 1 days in the future

//seconds * minutes * hours * days + current time

$one_day = 60 * 60 * 24 * 1 + time();

setcookie('name', 'Amit', $one_day);

?>

Fetching cookies values

<?php

Echo “Your name is “.$_COOKIE[‘name’];

?>

Merging the UI with the PHP code

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.

The sample output is looks like –

ID Name Salary
1 Amit 5000
2 Vikash 3000
3 Asit 12000
4 Manish 55000

The sample code for the above output:

<html>

<head>

<title>Sample Coding</title>

</head>

<body>

<table width="50%" border="1" cellspacing="0" cellpadding="5">

<tr style="font-weight:bold; text-align:center">

<td width="17%">ID</td>

<td width="44%">Name</td>

<td width="39%">Salary</td>

</tr>

<?php

$query = mysql_query("select * from xyz");

while($result = mysql_fetch_assoc($query))

{
?>

<tr style="text-align:center">

<td><?php echo $result['id']; ?></td>

<td><?php echo $result['name']; ?></td>

<td><?php echo $result['salary']; ?></td>

</tr>

<?php

?>

</table>

</body>

</html>

2 Important things to note down:

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.

Você também pode gostar