Вы находитесь на странице: 1из 79

www.ardentcollaborations.

com

Ardent Collaborations
LAMP refers to a solution stack of software,
usually free and open source software, used to
run dynamic Web sites or servers. The original
expansion is as follows:
Linux - operating system;
Apache - the Web server;
MySQL - the database management system
PHP - what is PHP?

Ardent Collaborations
 PHP is a widely-used general-purpose scripting
language that is especially suited for Web
development and can be embedded into HTML.
<body>
 <?php
phpinfo();
         ?>
</body>
the code is executed on the server, generating
HTML which is then sent to the client. The client
would receive the results of running that script, but
would not know what the underlying code was.
There are three main areas where PHP scripts are
used.
 Server-side scripting. This is the most traditional
and main target field for PHP. You need three things
to make this work. The PHP parser, a web server
and a web browser.
 Command line scripting. You can make a PHP script
to run it without any server or browser. You only
need the PHP parser to use it this way.
 Writing desktop applications. PHP is probably not
the very best language to create a desktop
application with a graphical user interface, but if
you know PHP very well, and would like to use some
advanced PHP features in your client-side
applications you can also use PHP-GTK to write
such programs.
 PHP can be used on all major operating systems.
 PHP has also support for most of the web servers
today.
 you also have the choice of using procedural
programming or object oriented programming, or a
mixture of them.
 With PHP you are not limited to output HTML. PHP's
abilities includes outputting images, PDF files and
even Flash movies (using libswf and Ming)
generated on the fly.
 One of the strongest and most significant features
in PHP is its support for a wide range of databases.
Rasmus Lerdorf, who wrote the original Common Gateway Interface binaries,

Andi Gutmans and Zeev Suraski, who rewrote the parser that formed PHP 3
And developed the famous Zend Engine.

Ardent Collaborations
PHP originally stood for Personal Home Page.
It began in 1994 as a set of Common Gateway
Interface binaries written in the C programming
language by the Rasmus Lerdorf.
He created these Personal Home Page Tools to
maintain his personal homepage.

Ardent Collaborations
Lerdorf released PHP publicly on June 8, 1995
named PHP version 2
The syntax was similar to Perl but was more
limited, simpler, and less consistent.

Ardent Collaborations
Zeev Suraski and Andi Gutmans, two Israeli
developers at the Technion IIT, rewrote the
parser in 1997 and formed the base of PHP 3
They changed the name to Hypertext
Preprocessor.
The development team officially released PHP/FI
2 in November 1997.
The official launch of PHP 3 came in June 1998

Ardent Collaborations
Suraski and Gutmans then started a new rewrite
of PHP's core, producing the Zend Engine in
1999.
On May 22, 2000, PHP 4, powered by the Zend
Engine 1.0, was released.
On July 13, 2004, PHP 5 was released, powered
by the new Zend Engine II.
In 2008, PHP 5 became the only stable version
under development.
PHP 6.0 will be launched very soon.

Ardent Collaborations
The Zend Engine is an open source scripting
engine (a Virtual Machine), commonly known for
the important role it plays in the web automation
language PHP.

Ardent Collaborations
• To activate recognition for short tags, short_open_tag is set
to "On" in php.ini
(C:\wamp\bin\apache\apache2.2.6\bin\php.ini)
• To activate recognition for the ASP style tags, asp_tags is set
to "On"

Ardent Collaborations
PHP supports eight primitive types.
Four scalar types:
 boolean
 integer
 float (floating-point number, or double)
 string
Two compound types:
 array
 object
And finally two special types:
 resource
 NULL
This is the simplest type. A boolean expresses a
truth value. It can be either TRUE or FALSE (case
insensitive)
the following values are considered FALSE:
 the boolean FALSE itself
 the integer 0 (zero)
 the float 0.0 (zero)
 the empty string, and the string "0"
 an array with zero elements
 an object with zero member variables (PHP 4 only)
 the special type NULL
◦ Every other value is considered TRUE
 An integer is a number of the set Z = {...,
-2, -1, 0, 1, 2, ...}.
 <?php
$a = 1234; // decimal number
$a = -123; // a negative number
$a = 0123; // octal number (equivalent to 8
3 decimal)
$a = 0x1A; // hexadecimal number (equival
ent to 26 decimal)
?>
◦ If an invalid digit is given in an octal integer (i.e.
8 or 9), the rest of the number is ignored.
 Floating point numbers (also known as
"floats", "doubles", or "real numbers") can be
specified using any of the following syntaxes:
 <?php
$a = 1.234; 
$b = 1.2e3; 
$c = 7E-10;
?>
A string is series of characters.
A string literal can be specified in four different
ways:
◦ single quoted ‘aaa’
◦ double quoted “aaa”
◦ heredoc syntax
 $str = <<<HDS
Example of string
HDS;
◦ nowdoc syntax
 <<<'EOT'

Note: A nowdoc is specified similarly to a heredoc,


but no parsing is done inside a nowdoc.
 A resource is a special variable, holding a reference
to an external resource.
 resource variables hold special handlers to opened
files, database connections etc.

 The special NULL value represents a variable with


no value. NULL is the only possible value of type
NULL.
 A variable is considered to be null if:
 it has been assigned the constant NULL.
 it has not been set to any value yet.
 it has been unset().
Type casting in PHP works much as it does in C: the
name of the desired type is written in parentheses
before the variable which is to be cast.
The casts allowed are:
 (int), (integer) - cast to integer
 (bool), (boolean) - cast to boolean
 (float), (double), (real) - cast to float
 (string) - cast to string
 (array) - cast to array
 (object) - cast to object
 (unset) - cast to NULL (PHP 5)
 Sometimes it is convenient to be able to
have variable variable names. That is, a
variable name which can be set and used
dynamically.
<?php
$a = 'hello';
$$a = 'world';
echo "$a ${$a}";
echo "<br>$a $hello";
?>
Changing Type with settype()
<?
Knowing Type with gettype() $undecided = 3.14;
<? print gettype( $undecided );
$testing = 5; // double
print gettype( $testing ); print " -- $undecided<br>"; // 3.14
// integer settype( $undecided, string );
print "<br>"; print gettype( $undecided ); // string
$testing = "five"; settype( $undecided, boolean );
print gettype( $testing ); print "<br>".gettype( $undecided );
// string // boolean
?> print " -- $undecided<br>"; // 1
?>

Ardent Collaborations
• Variables offer a flexible way of storing
data. You can change their values and the
type of data they store at any time. If,
however, you want to work with a value that
you do not want to alter throughout your
script's execution, you can define a
constant.
– define( "CONSTANT_NAME", 42 );
e.g.
define ( "USER", "Gerald" );
print "Welcome ".USER;
Note: There is $ in constant.

Ardent Collaborations
function some_function( $argument1, $argument2 )
{
// function code here
}
<?php
function bighello()
{
print "<h1>HELLO!</h1>";
}
bighello();
?>

Ardent Collaborations
• A Variable Declared Within a Function Is
Unavailable Outside the Function
• Variables Defined Outside Functions Are
Inaccessible from Within a Function by Default.
• Accessing Global Variables with the global
Statement.
<?php
$life = 420;
function meaningOfLife()
{
global $life;
print "The meaning of life is $life<br>";
}
meaningOfLife();
?>

Ardent Collaborations
<?php <?php
$num_of_calls = 0; function andAnotherThing( $txt )
function andAnotherThing( $txt ) {
{ static $num_of_calls = 0;
global $num_of_calls; $num_of_calls++;
$num_of_calls++;
print "<h1>$num_of_calls. $txt</h1>"; print "<h1>$num_of_calls. $txt</h1>";
} }
andAnotherThing("Widgets"); andAnotherThing("Widgets");
print("We build a fine range of print("We build a fine range of
widgets<p>"); widgets<p>");
andAnotherThing("Doodads"); andAnotherThing("Doodads");
print("Finest in the world<p>"); print("Finest in the world<p>");
?> ?>

Ardent Collaborations
• print (), echo() – may be used as a function.
• Max()
• Min()
• Abs(-100)
• round(13.64) //14
• Rand() //create random number
• Ceil(12.3) // 13
• Floor(12.3) //12
• include(“url")
• require(“url”)

Ardent Collaborations
The two constructs are identical in every way
except how they handle failure. They both
produce a Warning, but require() results in a
Fatal Error.
• An array is a list variable. That is, a variable
that contains multiple elements indexed by
numbers or strings. It enables you to store,
order, and access many values under one
name.
• Each item in an array is commonly referred
to as an element. Each element can be
accessed directly via its index. An index to
an array element can be either a number or
a string.
• By default, array elements are indexed by
number starting at zero

Ardent Collaborations
1. Defining Arrays with the array() Function
$users = array ("Raja", "Rohan", "Rohit",
"Ritesh" );
print "$users[2]";
1. Defining or Adding to Arrays with the
Array Identifier
$users[ ] = " Bert";
$users[ ] = " Sharon";
$users[ ] = " Betty";
$users[ ] = " Harry";
print "$users[2]";

Ardent Collaborations
Arrays indexed by strings are known as associative
arrays.
1. Defining Associative Arrays with the array()
Function
$character = array
(name=>"bob",occupation=>"superhero",age=>30);
print $character[age];
1. Directly Defining or Adding to an Associative
Array
$character[name] = "bob";
$character[occupation] = "superhero";
$character[age] = 30;
print $character[occupation];

Ardent Collaborations
Arrays that contain arrays as their elements
are known as multidimensional arrays.
<?php
$characters = array ( array ( name=>"bob",
occupation=>"superhero", age=>30, specialty=>"x-ray
vision" ),
array ( name=>"sally", occupation=>"superhero",
age=>24, specialty=>"superhuman strength" ),
array ( name=>"mary", occupation=>"arch villain",
age=>63, specialty=>"nanotechnology" )
);
print $characters[0][occupation];
// prints "superhero"
?>

Ardent Collaborations
• We can access an element of an array by
using its index:
• print $user[4]
• count() returns the number of elements in an
array.
$users = array ("Bert", "Sharon",
"Betty", "Harry" );
print $users[count($users)− 1];

Ardent Collaborations
• Syntax:
foreach( $array as $temp ){
//...
}
• Example:

$users = array ("Bert", "Sharon",


"Betty", "Harry" );
foreach ( $users as $val ) {
print "$val<br>";
}

Ardent Collaborations
• Syntax:
foreach( $array as $key=>$value ){
//...
}
• Example:
$character = array
(name=>"bob",occupation=>"superhero",age=>30);
foreach ( $character as $key=>$val ) {
print "$key = $val<br>";
}

Ardent Collaborations
• Joining Two Arrays with array_merge()
– accepts two or more arrays and returns a merged array combining all
their elements.
$first = array("a", "b", "c");
$second = array(1,2,3);
$third = array_merge( $first, $second );
foreach ( $third as $val ){
print "$val<BR>";
}

• Adding Multiple Variables to an Array with array_push()


– accepts an array and any number of further parameters and returns the
total number of elements in the array it transforms.
$first = array("a", "b", "c");
$total = array_push( $first, 1, 2, 3 );
print "There are $total elements in \$first<P>";
foreach ( $first as $val ){
print "$val<BR>";
}

Ardent Collaborations
• Removing the First Element of an Array with array_shift()
– removes and returns the first element of an array
$an_array = array("a", "b", "c");
while ( count( $an_array) )
{
$val = array_shift( $an_array);
print "$val<BR>";
print "there are ".count($an_array)." elements in \$an_array <br>";
}

• Slicing Arrays with array_slice()


– accepts an array as an argument, a starting position (offset), and an
(optional) length and returns a new array.
$first = array("a", "b", "c", "d", "e", "f");
$second = array_slice($first, 2, 3);
foreach ( $second as $var ){
print "$var<br>";
}

Ardent Collaborations
• Sorting Numerically Indexed Arrays with sort()
$an_array = array("x","a","f","c");
sort( $an_array);
foreach ( $an_array as $var ){
print "$var<BR>";
}
• Sorting an Associative Array by Value with asort()
$first = array("first"=>5,"second"=>2,"third"=>1);
asort( $first );
foreach ( $first as $key => $val ){
print "$key = $val<BR>";
}
• Sorting an Associative Array by Key with ksort()
– ksort( $first );

Ardent Collaborations
• When PHP processes a page, it checks for
GET, POST, Cookie, Server and Environment
variables, this information is collectively
known as EGPCS.
• It creates an array called $GLOBALS
foreach ( $GLOBALS as $key=>$value ){
print "$key == $value<br>";
}

Ardent Collaborations
PHP creates 5 global arrays:
1. $HTTP_GET_VARS or $_GET
2. $HTTP_POST_VARS or $_POST
3. $HTTP_COOKIE_VARS or $_COOKIE
4. $HTTP_SERVER_VARS or $_SERVER
5. $HTTP_ENV_VARS or $_ENV

Ardent Collaborations
For fetching request data, we have global arrays
like $_GET, $_POST etc.
Response is sent by the server to the client.
header() is used to send a raw HTTP header.

Syntax:
void header ( string $string [, bool $replace=
true [, int $http_response_code ]] )

Ardent Collaborations
 There are two special-case header calls
◦ "HTTP/“
 used to figure out the HTTP status code to send.
 header("HTTP/1.0 404 Not Found");
◦ "Location:“
 returns a REDIRECT (302) status code to the browser.
 header("Location: http://www.example.com/");
◦ Can be used in some other ways also.
 An example:
 <?php
// We'll be outputting a PDF
header('Content-type: application/pdf');

// It will be called downloaded.pdf
header('Content-
Disposition: attachment; filename="downloaded.pdf"');

// The PDF source is in original.pdf
readfile('original.pdf');
?>
 Word:
◦ header("Content-type: application/msword");
◦ header("Content-Disposition:
attachment;Filename=document_name.doc");

 Excel:
◦ header("Content-type: application/vnd.ms-excel");
◦ header("Content-Disposition:
attachment;Filename=document_name.xls");
 extension=php_pdf.dll
◦ Add this line in the php.ini file to create pdf in
runtime.
◦ An example:
 Click here
$server = "localhost";
$username = "root";
$password = "";
$database = “ardent";

@mysql_connect ($server, $username,


$password) OR die ('Could not connect to
MySQL: ' . mysql_error() );
@mysql_select_db ($database) OR die ('Could
not select the database: ' . mysql_error() );

Ardent Collaborations
//connect
$sql = "INSERT INTO std VALUES(1,'Rohit','Kolkata')"
;
$results = mysql_query ( $sql);
if($results)
{
echo "Added";
}
else
{
echo "Sorry, There is a temporary problem, Try
again.". mysql_error();
}

Ardent Collaborations
$sql = "SELECT * from std";
$result = mysql_query($sql);

while ($row = mysql_fetch_array($result)) {


echo "$row[roll]";
echo "$row[name] ";
echo "$row[addr] ";
}

Ardent Collaborations
 Include() and require() function enables us
to incorporate files into your PHP
documents.
 include_once() and require_once()
includes the file only once.

Ardent Collaborations
 Checking for Existence with
file_exists()
 is_file() for checking it is a file or not.
 is_dir() for checking it is a directory or
not.

 Other Functions:
◦ is_readable()
◦ is_writable
◦ is_executable

Ardent Collaborations
 Determining File Size with filesize()
 last accessed time with fileatime().
e.g.
$atime = fileatime( "test.txt" );
print "test.txt was last accessed on ";
print date("D d M Y g:i A", $atime);

 the modification date of a file with the


function filemtime()

Ardent Collaborations
) : create a file
touch(

If the file already exists, the contents are not


disturbed, but the modification date is updated
to the time at which the function executed.
e.g. touch("myfile.txt");
unlink() :remove an existing file.
e.g. unlink("myfile.txt");

Ardent Collaborations
fopen()
fopen() requires a string containing the file path,
followed by a string containing the mode in which the
file is to be opened.
read ('r'), write ('w'), and append ('a').

Modes:

for reading:
$fp = fopen( "test.txt", 'r' );
for writing: $fp = fopen( "test.txt", 'w' );
for appending : $fp = fopen( "test.txt", 'a' );

Ardent Collaborations
 Line by Line: fgets(file pointer, no of bytes)
 Reading Arbitrary Amounts of Data
from a File with fread()
 feof(file pointer) tells the end of file
while ( ! feof( $fp ) ) {
$line = fgets( $fp, 1024 );
print "$line<br>";
}

Ardent Collaborations
 fgetc(file pointer) reads a character
fseek(file pointer, int offset)

change the current


position within a file.

Ardent Collaborations
 $fp = fopen( "test.txt", "w" )
 $fp = fopen( "test.txt", "a" )
◦ fwrite()
◦ fputs()
Both of them accepts a file pointer and a string.

Ardent Collaborations
The integer returned by time() represents the
number of seconds elapsed since
midnight GMT on January 1, 1970. This
moment is known as the UNIX epoch, and
the number of seconds that have elapsed since
then is referred to as a time stamp.

Ardent Collaborations
Getdate()
returns an
associative
array

Ardent Collaborations
<?php
$date_array = getdate(time()+330*60); // no
argument passed so today's date will be used
print_r($date_array);

print "<hr>Today's date: $date_array[mday]/


$date_array[mon]/ $date_array[year]<p>";
?>

Ardent Collaborations
Date() returns string

Ardent Collaborations
returns a time stamp that you can then use with
date() or getdate().
mktime() accepts up to six integer arguments
in the following order:
 hour
 minute
 second
 month
 day of month
 year

Ardent Collaborations
Checkdate() accepts three integers:
month, day, and year.
checkdate() returns true if the date is
valid.

Ardent Collaborations
@mail( $to, $subject, $message, $headers )
$to =email id
$subject = subject of the mail
$message = body of the mail
$headers = "From: st@ardentcollaborations.com\r\nReply-
To: st@ardentcollaborations.com";

It returns true, if mail sent successfully.

Ardent Collaborations
<form enctype="multipart/form-data"
action="uploader.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE"
value="100000" />
Choose a file to upload: <input
name="uploadedfile" type="file" /><br />
<input type="submit" value="Upload File" />
</form>
For binary data enctype must be multipart/form-
data

Ardent Collaborations
the uploaded file exists in a temporary storage
area on the server. If the file is not moved to a
different location it will be destroyed! To save
our precious file we are going to need to make
use of the $_FILES associative array.

Ardent Collaborations
It has two parameter, first s the form's input name and
the second index can be either "name", "type", "size",
"tmp_name" or "error". Like this:

$_FILES["file"]["name"] - the name of the uploaded file


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

Ardent Collaborations
move_uploaded_file($_FILES['uploadedfile']
['tmp_name'], $target_path)

$target_path is the location where to save the


file

Ardent Collaborations
$target_path = "uploads/";
$target_path = $target_path . $_FILES['uploadedfile']
['name'];
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'],
$target_path))
echo "<br>The file ". $_FILES['uploadedfile']['name']. "
has been uploaded";
else
echo "<br>There was an error uploading the file, please
try again!";

Ardent Collaborations
Print a string using
 print
 echo
 printf

Ardent Collaborations
Ardent Collaborations
<?php
$r=rand(0,255);
$g=rand(0,255);
$b=rand(0,255);
?>

<body bgcolor=<?php printf("#%x%x%x",$r,


$g,$b); ?> >

Ardent Collaborations
 chr() Return a specific character by ASCII
 string convert_uuencode ( string $data ):
encodes a string using the uuencode
algorithm.
 string convert_uudecode ( string $data ):
decodes a uuencoded string

Ardent Collaborations
 crypt — One-way string encryption
(hashing): return an encrypted string using
the standard Unix DES-based encryption
algorithm.
<?php
$password = crypt('mypassword');
if (crypt($user_input, $password) == $password) {
echo "Password verified!";
}
?>

Ardent Collaborations
md5() — Calculate the md5 hash of a string:
Calculates the MD5 hash of str using the RSA
Data Security
sha1 — Calculate the sha1 hash of a string:
Calculates the sha1 hash of str using the US
Secure Hash Algorithm 1.
hash — Generate a hash value (message digest):
it takes 2 args ( string $algo , string $data).

Ardent Collaborations
Join array elements with a glue string.

$array = array('Rohit', 'Sharma', 'Kolkata');


$comma_separated = join(",", $array);
echo $comma_separated; //
Rohit,Sharma,Kolkata

Ardent Collaborations
Returns an array of strings, each of which is a
substring of string formed by splitting it on
boundaries formed by the string delimiter .

$str = "Rohit,Sharma,Kolkata";
$ar=explode("," , $str);
print_r($ar);

Ardent Collaborations
 trim() - Strip whitespace (or other characters)
from the beginning and end of a string
 ltrim() - Strip whitespace (or other
characters) from the beginning of a string
 rtrim() - Strip whitespace (or other
characters) from the end of a string

Ardent Collaborations
 str_replace: Replace all occurrences of the
search string with the replacement string
 str_ireplace — Case-insensitive version of
str_replace().

 str_replace ( $search , $replace , $subject)

Ardent Collaborations
Pad a string to a certain length with another
string
string str_pad ( string $input , int $pad_length [, string
$pad_string= " " [, int $pad_type= STR_PAD_RIGHT ]] )
This functions returns the input string padded on the left,
the right, or both sides to the specified padding length. If
the optional argument pad_string is not supplied, the input
is padded with spaces, otherwise it is padded with
characters from pad_string up to the limit.
Optional argument pad_type can be STR_PAD_RIGHT,
STR_PAD_LEFT, or STR_PAD_BOTH. If pad_type is not
specified it is assumed to be STR_PAD_RIGHT.

Ardent Collaborations
string str_repeat ( string $input , int $multiplier )

Returns input repeated multiplier times.


<?php
echo str_repeat("-=", 10);
?>

Ardent Collaborations

Вам также может понравиться