Vous êtes sur la page 1sur 21

PHP?

PHP stands for PHP: Hypertext Preprocessor PHP is a server-side scripting language PHP scripts are executed on the server PHP supports many databases (MySQL, Oracle, ODBC, etc.) PHP is an open source software PHP is free to download and use What is a PHP File? PHP files can contain text, HTML tags and scripts PHP files are returned to the browser as plain HTML PHP files have a file extension of ".php", ".php3", or ".phtml" Why PHP? PHP runs on different platforms (Windows, Linux, Unix, etc.) PHP is compatible with almost all servers used today (Apache, IIS, etc.) PHP is FREE to download from the official PHP resource. PHP is easy to learn and runs efficiently on the server side Basic PHP Syntax A PHP script always starts with <?php and ends with ?>. A PHP script can be placed anywhere in the document.
General Syntax :

<?php ?> HiVBJPP.php <html> <body> <?php echo "Hi.. VBJPP"; ?> </body> </html>

Comments in PHP
<html> <body> <?php //No one passed in WAD H..Ha..Ha..

/* This is a comment block */ ?> </body> </html>

PHP Variables
Rules for PHP variable names:

Variables in PHP starts with a $ sign, followed by the name of the variable The variable name must begin with a letter or the underscore character A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ) A variable name should not contain spaces Variable names are case sensitive (y and Y are two different variables)

<?php $txt="ADI!"; $x=16; ?>

PHP Variable Scope


local global static parameter


Local scope <?php $a = 5; // global scope function myTest() { echo $a; // local scope } myTest(); ?>

Global Scope
<?php $a = 5; $b = 10; function myTest() { global $a, $b; $b = $a + $b; } myTest(); echo $b; ?>

<?php $a = 5; $b = 10; function myTest() { $GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b']; } myTest(); echo $b; ?>

The Concatenation Operator


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

strlen()
<?php echo strlen("Om Sai"); ?>

strpos()
<?php echo strpos("Om Sai","Sai"); ?>

Arithmetic Operators
+ * / % .

Assignment Operators
= -= *= /= %= .=

Incrementing/Decrementing Operators Comparison Operators


++, -== === != <> !== > < <= >=

Array Operators Logical Operators


And Or Xor && || ! + == === != <> !==

if Statement
<html> <body> <?php $d=date("D"); if ($d=="Sun") echo "Have a nice weekend!"; ?> </body> </html> <html> <body> <?php $d=date("D"); if ($d=="Sun") { echo "Hello!<br />"; echo "Have a nice weekend!"; echo "See you on Monday!"; } ?> </body> </html>

The if...elseif....else Statement

<html> <body> <?php $d=date("D"); if ($d=="Sat") echo "Have a nice weekend!"; elseif ($d=="Sun") echo "Have a nice Sunday!"; else echo "Have a nice day!"; ?> </body> </html>

The PHP Switch Statement


<html> <body> <?php $x=1; switch ($x) { case 1: echo "Number 1"; break; case 2: echo "Number 2"; break; case 3: echo "Number 3"; break; default: echo "No number between 1 and 3"; } ?> </body> </html>

Array Numeric Arrays


$My=array("Om "," Sai "," Ram "," Adi "); Manully : $My[0]="Om"; $My[1]="Sai"; $My[2]="Ram"; $My[3]="Adi"; <?php $cars[0]=" Om "; $cars[1]=" Sai "; $cars[2]=" Ram "; $cars[3]=" Adi "; echo $cars[0] . " and " . $cars[1] . " are Swedish cars."; ?> $ages = array("Om"=>32, "Sai"=>30, "Ram"=>34); $ages['Om'] = "32"; $ages['Sai'] = "30"; $ages['Ram'] = "34"; <?php $ages['Om'] = "32"; $ages['Sai'] = "30"; $ages['Ram'] = "34"; echo "God " . $ages[Sai] . "years old."; ?>

Associative Arrays

Multidimensional Arrays
$families = array ( "A"=>array ( "B", "C", "D" ), "K"=>array ( "L" ), "R"=>array ( "S", "T", "U" ) );

2nd Way: Array ( [A] => Array ( [0] => B [1] => C [2] => D ) [K] => Array ( [0] => L ) [R] => Array ( [0] => S [1] => T [2] => U ) ) echo "Is " . $families['A'][2] . " a part of the As family?";

PHP Loops while


<html> <body> <?php $i=1; while($i<=5) { echo "The number is " . $i . "<br />"; $i++; } ?> </body> </html>

do...while
<html> <body> <?php $i=1; do { $i++; echo "The number is " . $i . "<br />"; } while ($i<=5); ?> </body> </html>

foreach for
<html> <body> <?php for ($i=1; $i<=5; $i++) { echo "The number is " . $i . "<br />"; } ?> </body> </html> <html> <body> <?php $x=array("one","two","three"); foreach ($x as $value) { echo $value . "<br />"; } ?> </body> </html>

PHP Functions
Syntex: function functionName() { code to be executed; } <html> <body> <?php

function writeName() { echo "Sai "; } echo "I Believe in "; writeName(); ?> </body> </html>

Adding parameters
<html> <body> <?php function writeName($fname) { echo $fname . " .<br />"; } echo "My name is "; writeName("Adi"); echo "My Studied "; writeName("M.Tech"); echo "Got "; writeName("8.40"); ?> </body> </html>

<html> <body> <?php function writeName($fname,$punctuation) { echo $fname . " Refsnes" . $punctuation . "<br />"; } echo "My name is "; writeName("Kai Jim","."); echo "My sister's name is "; writeName("Hege","!"); echo "My brother's name is "; writeName("Stle","?"); ?> </body> </html>

Add two numbers <html> <body> <?php function add($x,$y) { $total=$x+$y; return $total; } echo "1 + 16 = " . add(1,16); ?> </body> </html>

PHP Form Handling


$-POST[] <html> <body> <form action="welcome.php" method="post"> Name: <input type="text" name="fname" /> Age: <input type="text" name="age" /> <input type="submit" /> </form> $_ GET[]

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

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

$_REQUEST
The $_REQUEST variable can be used to collect form data sent with both the GET and POST methods. Welcome <?php echo $_REQUEST["fname"]; ?>!<br /> You are <?php echo $_REQUEST["age"]; ?> years old.

PHP Date() Function


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

characters, like"/", ".", or "-" can also be inserted between the letters to add additional formatting: <?php echo date("Y/m/d") . "<br />"; echo date("Y.m.d") . "<br />"; echo date("Y-m-d"); ?> mktime(hour,minute,second,month,day,year,is_dst) <?php $tomorrow = mktime(0,0,0,date("m"),date("d")+1,date("Y")); echo "Tomorrow is ".date("Y/m/d", $tomorrow); ?> O/P Tomorrow is 2009/05/12

Server Side Includes (SSI)


Insert the content of one PHP file into another PHP file before the server executes it, with the include() or require() function.

include() generates a warning, but the script will continue execution require() generates a fatal error, and the script will stop

These two functions are used to create functions, headers, footers, or elements that will be reused on multiple pages. Server side includes saves a lot of work. can create a standard header, footer, or menu file for all our web pages. When the header needs to be updated, you can only update the include file.

include()
<html> <body> <?php include(header.php); ?> <h1>Welcome to my home page!</h1> <p>Some text.</p> </body> </html>

Menu.php <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> <html> <body> <?php include("menu.php"); ?> <h1>Welcome to my home page.</h1> <p>Some text.</p> </body> </html> Include Gives Only warning Require gives Fatal Error

require()
<html> <body> <?php require("wrongFile.php"); echo "May be error"; ?> </body> </html>

File Handling
Rights : r, r+, W, W+, a, a+, x, x+ FOPEN() <html> <body> <?php $file=fopen("welcome.txt","r") ; ?> </body> </html> FCLOSE() <?php $file = fopen("test.txt","r"); //some code to be executed fclose($file); ?>

Reading a File Line by Line


<?php

Reading a File Character by Character


<?php

$file = fopen("welcome.txt", "r"); while(!feof($file)) { echo fgets($file). "<br />"; } fclose($file); ?>

$file=fopen("welcome.txt","r"); while (!feof($file)) { echo fgetc($file); } fclose($file); ?>

File Upload
<html> <body> <form action="upload_file.php" method="post" enctype="multipart/form-data"> <label for="file">Filename:</label> <input type="file" name="file" id="file" /> <br /> <input type="submit" name="submit" value="Submit" /> </form> </body> </html>

Upload Script
<?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"]; } ?> using the global PHP $_FILES array you can upload files from a client computer to the remote server.

Saving the Uploaded File


<?php if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/jpeg")) && ($_FILES["file"]["size"] < 20000)) { if ($_FILES["file"]["error"] > 0) { echo "Return Code: " . $_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 "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />"; if (file_exists("upload/" . $_FILES["file"]["name"])) { echo $_FILES["file"]["name"] . " already exists. "; } else { move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]); echo "Stored in: " . "upload/" . $_FILES["file"]["name"]; } } } else { echo "Invalid file"; } ?>

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

Create a Cookie
setcookie(name, value, expire, path, domain); <?php setcookie("Adi", "All time", time()+3600); ?> <html>

<?php $expire=time()+60*60*24*30; setcookie("Adi", "All time", $expire); ?> <html>

Retrieve a Cookie
<?php // Print a cookie echo $_COOKIE["user"]; // A way to view all cookies print_r($_COOKIE); ?>

<html> <body> <?php if (isset($_COOKIE["user"])) echo "Welcome " . $_COOKIE["user"] . "!<br />"; else echo "Welcome guest!<br />"; ?> </body> </html>

If Browser does not support Cookies then you have to pass the value using Usual Manner(Get,POST)

PHP Emails
<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("someone@example.com", $subject , $message, "From:" . $email); echo "Thank you for using mail form"; } else { 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>

PHP Database mysql_connect(servername,username,password); Servername : Optional (loaclhost : 3306) Username : for D/B Password : For D/B

<?php $con = mysql_connect("localhost","Adi","Omsai"); if (!$con) { die('Could not connect: ' . mysql_error()); } // some code ?>

Close connection <?php $con = mysql_connect("localhost","Adi","Omsai"); if (!$con) { die('Could not connect: ' . mysql_error()); } // some code mysql_close($con); ?>

Create Databse CREATE DATABASE database_name <?php $con = mysql_connect("localhost","Adi","Omsai"); if (!$con) { die('Could not connect: ' . mysql_error()); } if (mysql_query("CREATE DATABASE my_db",$con)) { echo "Database created"; } else { echo "Error creating database: " . mysql_error(); } mysql_close($con); ? Create Table <?php $con = mysql_connect("localhost","peter","abc123"); if (!$con) { Primary Key $sql = "CREATE TABLE Persons ( personID int NOT NULL AUTO_INCREMENT, PRIMARY KEY(personID),

die('Could not connect: ' . mysql_error()); } // Create database if (mysql_query("CREATE DATABASE my_db",$con)) { echo "Database created"; } else { echo "Error creating database: " . mysql_error(); } // Create table mysql_select_db("my_db", $con); $sql = "CREATE TABLE Persons ( FirstName varchar(15), LastName varchar(15), Age int )"; mysql_query($sql,$con); // Execute Query mysql_close($con); ?>

FirstName varchar(15), LastName varchar(15), Age int )"; mysql_query($sql,$con);

Insert data from Form <html> <body> <form action="insert.php" method="post"> Firstname: <input type="text" name="firstname" /> Lastname: <input type="text" name="lastname" /> Age: <input type="text" name="age" /> <input type="submit" /> </form> </body> </html> <?php $con = mysql_connect("localhost","Adi","Omsai"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("my_db", $con);

$sql="INSERT INTO Persons (FirstName, LastName, Age) VALUES ('$_POST[firstname]','$_POST[lastname]','$_POST[age]')" if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); } echo "1 record added"; mysql_close($con); ?>

Select Dta from Databse <?php $con = mysql_connect("localhost","Adi","Omsai"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("my_db", $con);

Display in Table <?php $con = mysql_connect("localhost","peter","abc123"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("my_db", $con);

$result = mysql_query("SELECT * FROM Persons"); $result = mysql_query("SELECT * FROM Persons"); while($row = mysql_fetch_array($result)) { echo $row['FirstName'] . " " . $row['LastName']; echo "<br />"; } mysql_close($con); ?> echo "<table border='1'> <tr> <th>Firstname</th> <th>Lastname</th> </tr>"; while($row = mysql_fetch_array($result)) { echo "<tr>"; echo "<td>" . $row['FirstName'] . "</td>"; echo "<td>" . $row['LastName'] . "</td>"; echo "</tr>"; } echo "</table>"; mysql_close($con); ?> Order By <?php $con = mysql_connect("localhost","peter","abc123"); if (!$con) { die('Could not connect: ' . mysql_error());

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

} mysql_select_db("my_db", $con); $result = mysql_query("SELECT * FROM Persons WHERE FirstName='Peter'"); while($row = mysql_fetch_array($result)) { echo $row['FirstName'] . " " . $row['LastName']; echo "<br />"; } ?>

} mysql_select_db("my_db", $con); $result = mysql_query("SELECT * FROM Persons ORDER BY age"); while($row = mysql_fetch_array($result)) { echo $row['FirstName']; echo " " . $row['LastName']; echo " " . $row['Age']; echo "<br />"; } mysql_close($con); ?> Delete Data <?php $con = mysql_connect("localhost","peter","abc123"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("my_db", $con); mysql_query("DELETE FROM Persons WHERE LastName='Griffin'"); mysql_close($con); ?>

Update Data <?php $con = mysql_connect("localhost","peter","abc123"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("my_db", $con); mysql_query("UPDATE Persons SET Age=36 WHERE FirstName='Peter' AND LastName='Griffin'"); mysql_close($con); ?>

Mysql (Access Connectivity) <html> <body> <?php $link=mysql_connect("localhost","root",""); if(!$link) { echo "Server is not found",mysql_error(); } $db=mysql_select_db("spc",$link); if(!$db) {

echo "Database is not found",mysql_error(); } $sql="SELECT * FROM tut"; $rs=mysql_query($sql); $num=mysql_numrows($rs); if (!$rs) {exit("No data found");} echo "<table><tr>"; echo "<th>Name</th>"; echo "<th>Subject</th></tr>"; $i=0; while($i<$num) { $name=mysql_result($rs,$i,"nam"); $subject=mysql_result($rs,$i,"Subject"); echo "<tr><td>$name</td>"; echo "<td>$subject</td></tr>"; $i++; } mysql_close($link); echo "</table>"; ?> </body> </html>