PHP Installation XAMPP: Cross – Apache, MySQL, Php, Perl + FileZilla, Tomcat NetBeans: IDE PHP - XAMPP PHP – NetBeans IDE Netbeans- default browser Netbeans – Starts a project PHP – Starting a project Netbeans – Setting a project Basic PHP Syntax • <html> <body> <?php echo "Hello World"; ?> </body> </html> Comment in Php • <html> <body> <?php //This is a comment /* This is a comment block */ ?> </body> </html> PHP Variables • <?php $txt="Hello World!"; $x=16; • echo $txt; ?> • --------------• Hello World! PHP Operators Arithmetic Assignment Comparison Logical String + = == && . (Append) - += != || * -= <> ! / *= > % /= >= ++ %= < -- <= if • <?php $d=date("D"); if ($d=="Fri") echo "Have a nice weekend!"; ?> • <?php $d=date("D"); if ($d=="Fri") echo "Have a nice weekend!"; else echo "Have a nice day!"; ?> if • <?php $d=date("D"); if ($d=="Fri") echo "Have a nice weekend!"; elseif ($d=="Sun") echo "Have a nice Sunday!"; else echo "Have a nice day!"; ?> switch • <?php 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"; } ?> Numeric Arrays • $cars=array("Saab","Volvo","BMW","Toyota"); • -------------or • $cars[0]="Saab"; $cars[1]="Volvo"; $cars[2]="BMW"; $cars[3]="Toyota"; echo $cars[0] . " and " . $cars[1] . " are Swedish cars."; Associative Arrays • ID key => value • $ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34); • -------------------or----------------• $ages['Peter'] = "32"; $ages['Quagmire'] = "30"; $ages['Joe'] = "34"; echo "Peter is " . $ages['Peter'] . " years old."; • ---------------------------------• Peter is 32 years old. Multidimensional Arrays $families = array ( "Griffin"=>array ( "Peter", "Lois", "Megan" ), "Quagmire"=>array ( "Glenn" ), "Brown"=>array ( "Cleveland", "Loretta", "Junior" ) ); Array ( [Griffin] => Array ( [0] => Peter [1] => Lois [2] => Megan ) [Quagmire] => Array ( [0] => Glenn ) [Brown] => Array ( [0] => Cleveland [1] => Loretta [2] => Junior ) ) Multidimensional Arrays • echo "Is " . $families['Griffin'][2] . " a part of the Griffin family?"; • ---------------------------------• Is Megan a part of the Griffin family? While Loops <?php $i=1; while($i<=5) { echo "The number is " . $i . "<br />"; $i++; } ?> The number is 1 The number is 2 The number is 3 The number is 4 The number is 5 Do While Loops <?php $i=1; do { $i++; echo "The number is " . $i . "<br />"; } while ($i<=5); ?> The number is 2 The number is 3 The number is 4 The number is 5 The number is 6 For Loops <?php for ($i=1; $i<=5; $i++) { echo "The number is " . $i . "<br />"; } ?> The number is 1 The number is 2 The number is 3 The number is 4 The number is 5 Foreach Loops <?php $x=array("one","two","three"); foreach ($x as $value) { echo $value . "<br />"; } ?> one two three Create a PHP Function <?php function writeName() { echo "Kai Jim Refsnes"; } echo "My name is "; writeName(); ?> My name is Kai Jim Refsnes Create a PHP Function <?php function writeName($fname) { echo $fname . " Refsnes.<br />"; } echo "My name is "; writeName("Kai Jim"); echo "My sister's name is "; writeName("Hege"); echo "My brother's name is "; writeName("Stale"); ?> My name is Kai Jim Refsnes. My sister's name is Hege Refsnes. My brother's name is Stale Refsnes. Create a PHP Function <?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("Ståle","?"); ?> My name is Kai Jim Refsnes. My sister's name is Hege Refsnes! My brother's name is Ståle Refsnes?i Create a PHP Function <?php function add($x,$y) { $total=$x+$y; return $total; } echo "1 + 16 = " . add(1,16); ?> 1 + 16 = 17 $_GET variable • <form action="welcome.php" method="get"> Name: <input type="text" name="fname" /> Age: <input type="text" name="age" /> <input type="submit" /> </form> • ----------------------------• http://localhost/welcome.php?fname=Peter&age=37 • ----------------------------• Welcome <?php echo $_GET["fname"]; ?>.<br /> You are <?php echo $_GET["age"]; ?> years old! • When using method="get" in HTML forms, all variable names and values are displayed in the URL. $_POST variable • <form action="welcome.php" method="post"> Name: <input type="text" name="fname" /> Age: <input type="text" name="age" /> <input type="submit" /> </form> • -----------------------------------• Welcome <?php echo $_POST["fname"]; ?>!<br /> You are <?php echo $_POST["age"]; ?> years old. • Information sent from a form with the POST method is invisible to others and has no limits on the amount of information to send. • However, because the variables are not displayed in the URL, it is not possible to bookmark the page. $_REQUEST Variable • Welcome <?php echo $_REQUEST["fname"]; ?>!<br /> You are <?php echo $_REQUEST["age"]; ?> years old. • ---------• The predefined $_REQUEST variable contains the contents of both $_GET, $_POST, and $_COOKIE. • The $_REQUEST variable can be used to collect form data sent with both the GET and POST methods. PHP Date() Function • date(format [, timestamp]) • <?php echo date("Y/m/d") . "<br />"; echo date("Y-m-d"); ?> • 2011/11/17 2011-11-17 PHP Date() Function • 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); ?> • Tomorrow is 2011/11/18 PHP include() Function • <html> <body> <?php include("header.php"); ?> <h1>Welcome to my home page!</h1> <p>Some text.</p> </body> </html> PHP include() Function 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> <div class="leftmenu"> <?php include("menu.php"); ?> </div> <h1>Welcome to my home page.</h1> <p>Some text.</p> </body> </html> PHP File Handling • Reading a File Line by Line <?php $file = fopen("welcome.txt", "r") or exit("Unable to open file!"); //Output a line of the file until the end is reached while(!feof($file)) { echo fgets($file). "<br />"; } fclose($file); ?> PHP File Handling • Reading a File Character by Character <?php $file=fopen("welcome.txt","r") or exit("Unable to open file!"); while (!feof($file)) { echo fgetc($file); } fclose($file); ?> PHP File Upload • Create an Upload-File Form <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> Create The Upload Script • upload_file.php <?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"]; } ?> Save uploaded File • upload_file.php <?php // Upload file and Display result 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"]; } ?> Create a Cookie • setcookie(name, value, expire, path, domain); • <?php setcookie("user", "Alex Porter", time()+3600); ?> • <?php $expire=time()+60*60*24*30; setcookie("user", "Alex Porter", $expire); ?> • 60 sec * 60 min * 24 hours * 30 days Retrive a Cookie • <?php if (isset($_COOKIE["user"])) echo "Welcome " . $_COOKIE["user"] . "!<br />"; else echo "Welcome guest!<br />"; ?> Delete a Cookie • <?php // set the expiration date to one hour ago setcookie("user", "", time()-3600); ?> PHP Session Variables • Starting a PHP Session • Before you can store user information in your PHP session, you must first start up the session. • Note: The session_start() function must apear BEFORE the <html> tag: • <?php session_start(); ?> <html> <body> </body> </html> PHP Session Variables • <?php session_start(); // store session data $_SESSION['views']=1; ?> • <?php //retrieve session data echo "Pageviews=". $_SESSION['views']; ?> PHP Session Variables • <?php session_start(); if(isset($_SESSION['views'])) $_SESSION['views']=$_SESSION['views']+1; else $_SESSION['views']=1; echo "Views=". $_SESSION['views']; ?> PHP Destroying a Session • <?php session_destroy(); ?> • Free a session variable <?php unset($_SESSION['views']); ?> PHP mail() Function • <?php $to = "someone@example.com"; $subject = "Test mail"; $message = "Hello! This is a simple email message."; $from = "someonelse@example.com"; $headers = "From:" . $from; mail($to,$subject,$message,$headers); echo "Mail Sent."; ?> PHP mail() Function • <?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 our mail form"; } else //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>"; } ?> Error Handling • <?php if(!file_exists("welcome.txt")) { die("File not found"); } else { $file=fopen("welcome.txt","r"); } ?> Error Handling • <?php //error handler function function customError($errno, $errstr) { echo "<b>Error:</b> [$errno] $errstr<br />"; echo "Ending Script"; die(); } //set error handler set_error_handler("customError",E_USER_WARNING); //trigger error $test=2; if ($test>1) { trigger_error("Value must be 1 or below",E_USER_WARNING); } ?> Error Handling • <?php //create function with an exception function checkNum($number) { if($number>1) { throw new Exception("Value must be 1 or below"); } return true; } //trigger exception in a "try" block try { checkNum(2); //If the exception is thrown, this text will not be shown echo 'If you see this, the number is 1 or below'; } //catch exception catch(Exception $e) { echo 'Message: ' .$e->getMessage(); } ?> • Message: Value must be 1 or below Filter & Sanitize <?php if(!filter_has_var(INPUT_POST, "url")) { echo("Input type does not exist"); } else { $url = filter_input(INPUT_POST, "url", FILTER_SANITIZE_URL); } ?> •Check if the "url" input of the "POST" type exists •If the input variable exists, sanitize (take away invalid characters) and store it in the $url variable •"http://www.csuååohioøø.edu/ •http://www.csuohio.edu/ MySQL Workbench • http://wb.mysql.com/ Connect / Close a DB • mysql_connect(servername,username,password); • <?php $con = mysql_connect("localhost", "root", "pass"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_close($con); ?> Create a Database • if (mysql_query("CREATE DATABASE my_db",$con)) { echo "Database created"; } else { echo "Error creating database: " . mysql_error(); } Create a Table • // Create table mysql_select_db("my_db", $con); $sql = "CREATE TABLE Persons ( FirstName varchar(15), LastName varchar(15), Age int )"; // Execute query mysql_query($sql,$con); Create a Table • mysql_select_db("my_db", $con); $sql = "CREATE TABLE Persons ( personID int NOT NULL AUTO_INCREMENT, PRIMARY KEY(personID), FirstName varchar(15), LastName varchar(15), Age int )"; mysql_query($sql,$con); Insert a Table • mysql_select_db("my_db", $con); mysql_query("INSERT INTO Persons (FirstName, LastName, Age) VALUES ('Peter', 'Griffin', '35')"); mysql_query("INSERT INTO Persons (FirstName, LastName, Age) VALUES ('Glenn', 'Quagmire', '33')"); Insert Data From a Form Into a Database • <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> Insert Data From a Form Into a Database • 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"; Select Data From a Database 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"); while($row = mysql_fetch_array($result)) { echo $row['FirstName'] . " " . $row['LastName']; echo "<br />"; } mysql_close($con); ?> Display the Result in an HTML 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"); echo "<table border='1'> <tr> <th>Firstname</th> Firstname <th>Lastname</th> Glenn </tr>"; while($row = mysql_fetch_array($result)) Peter { echo "<tr>"; echo "<td>" . $row['FirstName'] . "</td>"; echo "<td>" . $row['LastName'] . "</td>"; echo "</tr>"; } echo "</table>"; mysql_close($con); ?> Lastname Quagmire Griffin The WHERE clause • <?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 />"; } ?> Update Data In a Database • <?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); ?> Delete Data In a Database • <?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); ?>