1 / 46

PHP

PHP. Dynamic Web programming. MySQL Connection Function. Here is a function that automates connecting to a certain database. Save it in a separate file e.g. ConnectToDB.inc function db_Connect ($db="") { global $ dbhost , $ dbuser , $ dbpass ;

dympna
Download Presentation

PHP

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. PHP Dynamic Web programming

  2. MySQLConnection Function • Here is a function that automates connecting to a certain database. • Save it in a separate file e.g. ConnectToDB.inc • function db_Connect($db="") { • global $dbhost, $dbuser, $dbpass; • $dbcnx = @mysql_connect($dbhost, $dbuser, $dbpass) • or die("The site database appears to be down."); • if ($db!="" and !@mysql_select_db($db)) • die("The site database is unavailable."); • return $dbcnx; • }It is a good practice to write these statements in a function and separate file. • Include this file and call the function wherever you want to connect to database. • <? Include(“ConnectToDB.inc"); ?>

  3. MySQL Connection Function • <?php • include ("ConnectToDB_n.php"); • $result=db_connect('test_data') ; • print ('Connection successfully <br>'); • $result = mysql_query ('SELECT * FROM students WHERE age<25'); • while ($row = mysql_fetch_array($result)) • { • echo $row["first"]; //echo $row[0] • echo $row["age"]."<br>" ; //echo $row[1] • } • ?>

  4. MySQL Connection Function • <?php • include ("ConnectToDB_n.php"); • $result=db_connect('test_data') ; • $result = mysql_query ("CREATE TABLE addressbook ( • id INT not null AUTO_INCREMENT, • first varchar (30) not null, • last varchar (30) not null, • email varchar(50) not null, • PRIMARY KEY (id), INDEX (id), UNIQUE (id))"); • if ($result) print ('Creation successfully <br>'); • mysql_query ("INSERT INTO addressbook VALUES ('1','Ivan','Dimitrov','ivanwww@swu.bg')") ; • mysql_query ("INSERT INTO addressbook VALUES ('2','Maria','Stoyanova','mariawww@swu.bg')") ; • mysql_query ("INSERT INTO addressbook VALUES ('3','Dimitar', 'Kalev','dimitarwww@swu.bg')") ; • print ('Insertion successfully <br>'); ?>

  5. Adding Actionable Hyperlinks 1/2) • <table> • <tr> • <th>First Name</th> <th>Last Name</th> <th>Email</th> • <th>Actions</th> • </tr> • <?php • $conn = mysql_connect("localhost", "root", “"); • mysql_select_db("AddressBook", $conn); • $result = mysql_query("select * from contacts"); • while ($row = mysql_fetch_array($result)) { • print “<td>" . $row["LastName"] . "</td>"; • print “<td>" . $row["email"] . "</td>"; • print “<td><a href='remove.php?id=".$row["ID"]."'> • Remove </a></td>"; • print "</tr>"; } • mysql_close($conn);

  6. Adding Actionable Hyperlinks 2/2) • <?php • $cid = $_GET['id']; • $conn = mysql_connect("localhost", "root", “"); • mysql_select_db("AddressBook", $conn); • $query = "DELETE FROM Contacts WHERE id={$cid}"; • mysql_query($query); • If(mysql_affected_rows($query) ) { • print mysql_affected_rows($query).“ row(s) Deleted • successfully"; • } • ?>

  7. Secure Configuration • Don’t run MySQL as administrator/root. • Run it as a user created specifically for this purpose. Don’t use this account for anything else. • Don’t access web database with root user. • Create a separate admin account for each database for reading and writing from PHP script. • Disallow access to port 3306 (or whatever port you have MySQL running on) except from trusted hosts.

  8. Accounts and Privileges • All MySQL accounts should have a password, especially root. • Grant users the minimum level of privilege required to do their job. • Principle of Least Privilege • Set permissions on the database directories so that only appropriate user can access them. • Only the root user should have access to the mysql database, which contains privilege information.

  9. Using Encryption • Don’t Don t store application passwords in plaintext in the database. (Use hashing mechanisms) • PHP has an in built sha1() function that calculates hashing scheme of a string. • The result of sha1() can not be translated back into the original string. • This makes it a good way to store password. • $safe_password=sha1($password);

  10. HTTP is stateless • A fundamental characteristic of Web is: - The stateless interaction between browsers and web servers - Each HTTP request sent to a web server is independent of any other request. • Applications that require complex user interaction can't be implemented as a series of unrelated, stateless web pages. • An often-cited example is a shopping cart in which items are added to the cart while searching or browsing an on-line store. The state of the shopping cart (the selected items) needs to be stored somewhere to be displayed when the user visits the order page.

  11. HTTP is stateless • There are three ways to build an application that keeps state: - Variables can be passed between scripts as query string appended with the URL. - Variables can be stored in the browser at client-side as cookies and then can be included with each request. - variables can be stored on the server as session variables

  12. Passing Variables Between Scripts • The simplest way is to add the variables to the url: www.seecs.edu.pk/myscript.php?variable=value • You can chain these variables using an ampersand. • myscript.php?variable1=value1&variable2=value2&… • As per normal you can access these variables easily. You just need to use $_GET array, and access variables through their names. E.g • $var1 = $_GET[“variable1”];

  13. URL encoding This can lead to problems as you can’t have certain characters in url’s– spaces for example, more ampersands, colons and so on. • To deal with this php has the urlencode() function.Thisconverts all those problem characters into their url friendly counterparts. E.g. • <? • $str = urlencode(“script.php?name=T.J.&lastname=O’Reilly”); • print “<A HREF=$str>link</A>”; • ?> • <A HREF=script.php%3Fname%3DT. + J.%26lastname%3DO%27Reilly>link </A>

  14. Cookies • Setting and playing around with cookies can be a fun and useful way to save data on a user's hard drive. • It can successfully store valuable information which may be helpful the next time they come to the site. • Its fairly simple to set up, and even easier to read. To use it, you have to remember some guidelines…

  15. Guidelines • You have to put the cookie code before you print out any other HTML in your script. • 2. The cookie will not be evident on the page until its refreshed, or the user visits the page again (It is sent with the current page data) • Here's the code to set a variable: • <? • setcookie (“loginName", “Jimbo"); • ?> VARIABLE NAME VALUE

  16. Cookie Expiration • Now, the next time someone visits this page, or any other PHP page that cookie variable will be available. • However by default this cookie will expire when the user turns his browser off. • To extend the time to expire, set in seconds as the next field. For example: • <? • setcookie (“loginName", “jimbo", time()+3600); • ?> EXPIRES IN 1 HOUR

  17. Time Conversion table • 1 minute - 60s • 1 hour - 3600s • 1 day - 86400s • 1 week - 604800s • 1 fortnight - 1209600s • 1 month - 2419200s • 3 month - 7257600s • 1 year - 29030400s

  18. Reading Cookie Information • The cookies for the web domain your page is in will be automatically loaded into PHP. • You can get at them via two arrays: $HTTP_COOKIE_VARS[“loginName"]; • or $_COOKIE[“loginName”]; • So to display the cookie data on screen all you need is: • <? • print $_COOKIE[“loginName”] • ?>

  19. Practical Cookies : User Prefs • User_prefs.php • <?php • if(!$_COOKIE["body_color"]) • { • setcookie("body_color", "#000000", time()+3600); • setcookie("text_color", "#FFFF00", time()+3600); • } • ?> • <HTML> • <BODY BGCOCLR = <?php echo $COOKIE ["body_color"]?> text=<?php • echo $COOKIE [“text_color"]?>> • Hello buddy • </BODY> • <HTML>

  20. Multiple Cookies • It is not a problem to have multiple cookies -save it, here is a code example: • <? • setcookie (“loginName", “admin"); • setcookie (“password", “student"); • setcookie (“hits", “3"); • print $_COOKIE[“loginName”].”<BR>”; • print $_COOKIE[“password”].”<BR>”; • print $_COOKIE[“hits”].”<BR>”; • ?>

  21. Deleting Cookies – Reading • There are two ways of deleting cookies. The traditional way • <? • setcookie ("cookie", "", time()-86400); • ?> • Or simply by setting the cookie as nothing: • <? • setcookie ("cookie"); • ?>

  22. Don’t use multiple cookies • As such it is viewed as bad coding to use more than one cookie, and so people tend to store all variables they need in ONE cookie. • This is easy in PHP because of the explode() and implode() commands.

  23. Exploding Cookies • Before you can also use implode and explode. • $info[0] = “admin”; • $info[1] = “student”; • $cookie = implode($info, “-”); • setcookie (“myCookie", $cookie, time()+86400); • And you can take them out as follows: • $cookie = $_COOKIE[‘myCookie']; • $info = explode($cookie, “-”); • Of course you need to remember that element 0 of the info array is the username and element 1 is the password. But this way you can build up huge cookies.

  24. Problems with Cookies • Not only are cookies painful to code. • It may seem a surprisingly low statistic, but Cookies are about 30% unreliable on the web right now and it's getting worse. • More and more web browsers are starting to come with security and privacy settings and people browsing the net these days are starting to frown upon Cookies because they store information on their local computer that they do not want stored there.

  25. PHP Maintaining state • We now have two ways of maintaining state – of keeping variables common between scripts. - Adding variables to the url - Storing variables in cookies • Neither are satisfactory. One is incredibly clumsy the other out of synch. Your cookie is always one step behind because you send it out with each page. • So whats the answer? Sessions!

  26. The Session Solution • PHP has a great set of functions that can achieve the same results of Cookies and more without storing information on the user's computer. • PHP Sessions store the information on the web server in special files. • These files are connected to the user's web browser via the server and a special ID called a "Session ID". • This is nearly 99% flawless in operation and it is virtually invisible to the user.

  27. What is a Session? • Session: An abstract concept to represent a series of HTTP requests and responses exchanged between a specific Web browser and a specific Web server. • Session concept is very useful for Web based applications to pass and share information from one Web page (request) to another Web page (request). • Since the current design of HTTP protocol does not support session concept, all Web server side scripting technologies, including PHP, have designed their own way to support session concept. • The key design element of session support is about how to identify a session and how to maintain the session ID (identification). • One common way to maintain the session ID is use the cookie technology. 

  28. What is a Session? • The session concept should be managed by the server. • When the first request comes from a browser on a client host, the server should create a new session, and assigns a new session ID. • The session ID will be then send back to the same browser as a cookie. • The browser will remember this ID, and send the ID back to the server in the subsequent requests. • When the server receives a request with a session ID in them, it knows this is a continuation of an existing session. • When the server receives a request from a browser on a new client host (request without a session ID), the server should not only create a new session ID, it should also create a new session object associated with the new session ID. • This session object should become the storage place for different requests of the same session to store and share information.

  29. PHP's Session Support • Like JavsServer Page (JSP), PHP manages the session ID with as a cookie, a GET variable, or a POST variable. • It offer a built-in array as the session object, and a number of built-in functions to allow the PHP script to interact with the session: • $_SESSION - A built-in array to store and share variables for the session. • session_start() - A built-in function to create a new session or resume an existing session based on the current session id that's being passed via a request, such as GET, POST, or a cookie. • session_name() - A built-in function to set and get the session name. • session_id() - A built-in function to set and get the session ID. • session_destroy() - A built-in function to destroy all variables stored in $_SESSION.

  30. Session Start • The correct way to start a session is using the session_start() command. • We must include this statement at the start of every script of our site that we want to be able to use session variables in. • <? • session_start(); • print “We have started our session:"; • ?> • This is essential and an easy thing to forget.

  31. A common error • Just like Cookies you MUST call the session_start() function before anything is output y to your web browser. • This is absoultey important because you will get some ugly errors by PHP that will say something like this: • <? • echo “This is incorrect and will cause an error:"; • session_start(); • ?> • Generates the error: • Warning: Cannot send session cookie - headers already sent by (output started at session_header_error/session_error.php:2) in session_header_error/session_error.php on line 3

  32. Assigning Variables • <? // start the session • session start () ; • print “Registering a session"; • // Get the user's input from the form for example • $data = $_POST[‘data']; • // Create a new Session variable. You can skip this step. A variable can be automatically registered when you assign it a value. • session_register('name'); • // way of putting data into the variable. If variable ‘name’ is not already registered, then it will be automatically registered and assigned a value here. • $_SESSION['name'] = $data; ?>

  33. Sessions on Multiple Pages • The first thing you MUST do on each page you want to access a session variable is to start the session. • That may not sound right to you because "We already started the session on the last page." • That's true, but we need to keep the "connection" going between our session because they do not have persistent connections like MySQL does.

  34. A Multiple Page Session • <? • // start the session • session_start(); • print “In this script we use session variables”; • print “that we created in the previous script<br>”; • // display the session variable • print “Hi there $_SESSION[‘name’] everything is working • fine! <br>”; • ?>

  35. Unregistering Session Variables • With PHP Sessions, we have the ability to simply remove a single session variable without dumping our entire session and rebuilding it. • The function is called session_unregister() • Here's how we unregister a single session variables and leave the rest intact. • session_unregister('name');

  36. Destroying a Whole Session • Why might it be necessary to destroy a session when the session will get destroyed when the user closes their browser? • Well, Imagine that you had a session you were using to determine if the user was logged into your site based upon a username and password - anytime you have a login feature, to make the users feel better, you should have a logout feature as well. • That's where session_destroy() may be useful – it will delete the session files and clears any trace of that session.

  37. Practical Sessions : Hit Counter • What we're about to do here is: - start your session - register a variable called "count“ - assign a value of 1 to it on the first page. - Then, we're going to increment the counter as we go through the website. - We’re also going to provide a reset page

  38. Hit Counter – counter page • hit_counter.php • <? • session_start(); • if (!$_SESSION[‘count’]) // or if(isset($_SESSION[“count”])) • session_register('count'); • if($_SESSION['count'] == 0) • $_SESSION['count'] = 1; • else • $_SESSION['count']++; • ?> • You’ve visited <?=$_SESSION['count']?> pages so far!<br> • <a href=“hit_counter.php">Increment Your Counter!</a><br> • <a href=“reset.php">Reset Your Counter!</a><br>

  39. Hit Counter – Reset Page • reset_counter.php • <? • session_start(); • session_register('count'); • $_SESSION['count'] = 1; • ?> • You’ve visited <?=$_SESSION['count']?> pages so far!<br><a href=“hit_counter.php">Increment Your Counter!</a><br><a href=“reset_counter.php">Reset Your Counter!</a><br>

  40. Viewing Your Session ID • Every Session has a unique Session ID. A session ID looks like some chatting guru collapsed on the keyboard. • There's a function in PHP called session_id() that allows you to display the current session ID or utilize it however you need. • <? • session_start(); • echo "Your session ID is <B>". session_id() ."</B>"; • ?> • This will simply display something like: • Your session ID is Bd315d2ed59dfa1c2d0fb0b0339c758d

  41. Practical Sessions : User Prefs • User_prefs.php • if((!$_SESSION[“body_color”])||(!$_SESSION[“text_color”])) { • $_SESSION[“body_colour”] = “#000000”; • $_SESSION[“text_colour”] = “#FFFFFF”; • } • ?> • <HTML> • <BODY BGCOLOR=<?=$_SESSION[“body_colour”]?> • TEXT=<?=$_SESSION[“body_colour”] ?> >

  42. Session Problem • When you click your back button to make changes in the form, you have to click the REFRESH button on that page to get the information that you posted back into the form. • • This only works about 50% of the time. The other 50% the users information is lost • • This can be horrific for users… but there is a simple solution. • Enter this right below the session_start() of each script: • header("Cache-control: private");

  43. Discussion of Prefs • Now this is all great at the moment but we do have a problem – a session automatically closes when a user shuts his web browser. • If that person has spent hours setting all their user preferences and they disappear when the browser is closed you aren’t going to get many repeat users. • So while sessions maintain state over a visit we need someway of storing data between visits…. • One solution is to store such valuable user preferences in the databasefor repeated users. • And when these users come again to visit your site, simply fetch these values from database and assign them to session variables.

  44. Redirection • Just like Cookies and Sessions, you MUST call the header() function before anything is output to your web browser. Otherwise you will get a famous error message i.e. Headers already sent etc. • <?php • header(“Location: http://www.example.com/”); • ?> • <?php • header(“Location: myApp/login.php”); • ?>

  45. Web Mail Systems • Its easy to send emails in php too. • Mail() function uses SMTP (Simple Mail Transfer Protocol) to send emails automatically from inside your scripts. • To receive and process mail PHP can use the IMAP protocols (we won’t go into this). • PHP comes with the IMAP library and this can be used for POP and NNTP (news) connections.

  46. Sending a mail… • <? • $email = “falak.nawaz@seecs.edu.pk"; • $title = “More SPAM!”; • $message = “This is my first\n PHP mail message”; • $from = "From: falak@msn.com\n"; • mail($email, $title, $message, $from); • ?> • http://www.learnphp.org/tutorials/Creating-a-PHP-Login-Script-23270.html • http://sephiroth.it/tutorials/flashPHP/authentication/index.php

More Related