CIS 388 Internet Programming PHP/MySQL Part 2
Review/Sample PHP Detect IP address (redirect based on local/remote ip address) <?php // <!-- function IPredirect() { $ip = $_SERVER[“REMOTE_ADDR”]; if (substr($ip, 0, 3) == “10.”) { echo’<a href=“local.htm”>Local Link</a>’; } else { echo’<a href=“remote.htm”>Remote Link</a>’; } } // --> ?>
Advanced PHP PHP includes PHP File Handling Including an external php or html file in your PHP page – useful for reusing code/functions in many pages (navigational columns, database connections, session/cookie retrieval and validation etc…) Syntax: include 'filename'; <?php include 'footer.php';?> https://www.w3schools.com/php/php_includes.asp PHP File Handling Open/Read, Create/Modify, and Upload files with PHP https://www.w3schools.com/php/php_file_open.asp fopen(" filename.ext ", “argument") (fread(), fwrite(), and the fclose() are used with fopen) echo readfile(“filename.ext"); (useful for including external data/rss in your page) Uploading files with PHP: https://www.w3schools.com/php/php_file_upload.asp
Advanced PHP PHP Cookies PHP Session Variables PHP cookies are just like cookies in javascript and are used to trore bits of information on the client computer Syntax: setcookie(name, value, expire, path, domain, secure, httponly); "Value is: " . $_COOKIE[$cookie_name]; https://www.w3schools.com/php/php_cookies.asp PHP Session Variables PHP session variables are similar to cookies, they store bits of information on the server, and they are open with each browser “session” that connects to the server. A session is started with the session_start() function. Syntax: $_SESSION[“variablename"] = “value"; "Favorite color is " . $_SESSION["favcolor"] . ".<br>"; https://www.w3schools.com/php/php_sessions.asp
PHP and MySQL PHP allows the web page to get information from and update information stored in a MySQL database Database Connection Code (Object Oriented) <?php $servername = "localhost"; $username = "username"; $password = "password"; // Create connection $conn = new mysqli($servername, $username, $password); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } echo "Connected successfully"; ?> https://www.w3schools.com/php/php_mysql_connect.asp
PHP and MySQL Create Database (*after MySQL Connection) $sql = "CREATE DATABASE myDB"; if ($conn->query($sql) === TRUE) { echo "Database created successfully"; } else { echo "Error creating database: " . $conn->error; } https://www.w3schools.com/php/php_mysql_create.asp Create Table (* after Database Created) $sql = "CREATE TABLE MyTable (ColumnName1 TYPE(),…) if ($conn->query($sql) === TRUE) { echo "Table MyGuests created successfully"; } else { echo "Error creating table: " . $conn->error; } $conn->close(); https://www.w3schools.com/php/php_mysql_create_table.asp
PHP and MySQL Insert Data into Database $sql = "INSERT INTO MyTable (ColumnName1) VALUES (‘samplevalue')"; if ($conn->query($sql) === TRUE) { echo "New record created successfully"; } else { echo "Error: " . $sql . "<br>" . $conn->error; } Select/Display Data from a Database $sql = "SELECT id, ColumnName1 FROM MyTable"; $result = $conn->query($sql); if ($result->num_rows > 0) { // output data of each row while($row = $result->fetch_assoc()) { echo "id: " . $row["id"]. " – Column Value: " . $row[“ColumnName1"]. " "<br>"; } } else { echo "0 results"; }
PHP and MySQL Delete Records from a Database $sql = "DELETE FROM MyTable WHERE id=1"; if ($conn->query($sql) === TRUE) { echo "Record deleted successfully"; } else { echo "Error deleting record: " . $conn->error; } Update Records in a Database $sql = "UPDATE MyTable SET ColumnName1=‘NewValue' WHERE id=1"; if ($conn->query($sql) === TRUE) { echo "Record updated successfully"; } else { echo "Error updating record: " . $conn->error; } SQL Reference: https://www.w3schools.com/sql/sql_quickref.asp
PHP Login Form <form action="" method="post" name="Login_Form"> <table width="400" border="0" align="center" cellpadding="5" cellspacing="1" class="Table"> <?php if(isset($msg)){?> <tr> <td colspan="2" align="center" valign="top"><?php echo $msg;?></td> </tr> <?php } ?> <td colspan="2" align="left" valign="top"><h3>Login</h3></td> <td align="right" valign="top">Username</td> <td><input name="Username" type="text" class="Input"></td> <td align="right">Password</td> <td><input name="Password" type="password" class="Input"></td> <td> </td> <td><input name="Submit" type="submit" value="Login" class="Button3"></td> </table> </form>
PHP Login Authentification Code <?php session_start(); /* Starts the session */ /* Check Login form submitted */ if(isset($_POST['Submit'])){ /* Define username and associated password array */ $logins = array('Alex' => '123456','username1' => 'password1','username2' => 'password2'); /* Check and assign submitted Username and Password to new variable */ $Username = isset($_POST['Username']) ? $_POST['Username'] : ''; $Password = isset($_POST['Password']) ? $_POST['Password'] : ''; /* Check Username and Password existence in defined array */ if (isset($logins[$Username]) && $logins[$Username] == $Password){ /* Success: Set session variables and redirect to Protected page */ $_SESSION['UserData']['Username']=$logins[$Username]; header("location:index.php"); exit; } else { /*Unsuccessful attempt: Set error message */ $msg="<span style='color:red'>Invalid Login Details</span>"; } ?>
PHP Session Variable Check <?php session_start(); /* Starts the session */ if(!isset($_SESSION['UserData']['Username'])){ header("location:login.php"); exit; } ?> Congratulation! You have logged into password protected page. <a href="logout.php">Click here</a> to Logout.
PHP Logout Session <?php session_start(); /* Starts the session */ session_destroy(); /* Destroy started session */ header("location:login.php"); /* Redirect to login page */ exit; ?>
Additional Resources W3 Schools PHP tutorial: https://www.w3schools.com/php/ PHP scripts and code resources: http://www.w3schools.in/php-script/php-login-without-using-database/ http://www.coderslexicon.com/really-simple-php-login-logout-script-example/