محمد احمدی نیا ahmadinia.iauk@gmail.com PHP محمد احمدی نیا ahmadinia.iauk@gmail.com
Server-Side Programming language asp, asp.net, php, jsp, perl, cgi، ... Server HTTP Requests URL(../../*.php) Client Web Server Index.php DB Data HTTP Responses(HTML code) Browser compiler query (PHP compiler) DBMS (mysql) data
Client-Side Scripting versus Server-Side Scripting Client-side scripts Validate user input Reduce requests needed to be passed to server Access browser Server-side scripts Executed on server Generate custom response for clients Wide range of programmatic capabilities Access to server-side software that extends server functionality like DBMS
Installing a web server
Hosting a website: Self hosting Install a web server on a computer Local access Using domain <localhost> or IP address 127.0.0.1 Necessary for server-side programming development Global access Register a human-readable domain name Obtain IP address Static: Costs more Dynamic: Needs dynamic DNS system, e.g. http://www.dyndns.com/
Web server architecture LAMP: Most popular—fully open source Linux for operating system Apache for web server MySQL for database PHP for server-side scripting Others: WAMP: Uses Windows for operating system, with Apache, MySQL, and PHP WISA: Full Microsoft package Windows Internet Information Server (IIS) SQL Server (enterprise) or Access (small-scale) ASP or ASP.NET
Apache Web Server Currently the most popular Web server Stability Efficiency Portability Open-source
All-in-one Apache/MySQL/PHP packages EasyPHP (recommended) Includes PHPMyAdmin for administering MySQL database AbriaSoft Merlin Desktop Edition Includes PHPMyAdmin WAMP Server PHP Triad
Requesting XHTML or PHP documents Request PHP documents from Apache Save PHP documents in the www folder for EasyPHP Launch web browser With EasyPHP, right-click on the status bar icon and click “Local Web” Enter PHP document’s location in Address field, starting with http://localhost/ or http://127.0.0.1/
What is 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, Informix, Oracle, Sybase, Solid, PostgreSQL, Generic ODBC, etc.) PHP is an open source software PHP is free to download and use Cross Platform زبانهای برنامه سازی وب
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" زبانهای برنامه سازی وب
Why PHP? Structurally similar to C/C++ Supports procedural and object-oriented paradigm (to some degree) All PHP statements end with a semi-colon Each PHP script must be enclosed in the reserved PHP tag <html> <body> <?php echo "Hello World"; ?> </body> </html> <?php … ?> زبانهای برنامه سازی وب
Comments in PHP Use // to make a single-line comment or /* and */ to make a large comment block. <html> <body> <?php //This is a comment /* This is a comment block */ ?> </body> </html> زبانهای برنامه سازی وب
PHP Variables PHP variables must begin with a “$” sign and then a letter or an underscore "_" Example variables name: $x, $_temp, … Case-sensitive ($Foo != $foo != $fOo) In PHP, a variable does not need to be declared before adding a value to it. <?php $foo = 25; // Numerical variable $bar = “Hello”; // String variable $foo = ($foo * 7); // Multiplies foo by 7 $bar = ($bar * 7); // Invalid expression ?> زبانهای برنامه سازی وب
Echo The PHP command ‘echo’ is used to output the parameters passed to it The typical usage for this is to send data to the client’s web-browser Syntax void echo (string arg1 [, string argn...]) <?php $foo = 25; // Numerical variable $bar = “Hello”; // String variable echo $bar; // Outputs Hello echo $foo,$bar; // Outputs 25Hello echo “5x5=“,$foo; // Outputs 5x5=25 echo “5x5=$foo”; // Outputs 5x5=25 echo ‘5x5=$foo’; // Outputs 5x5=$foo ?> زبانهای برنامه سازی وب
String Variables A string variable is used to store and manipulate text. The concatenation operator (.) is used to put two string values together. <?php $txt="Hello World"; echo $txt; ?> Hello World <?php $txt1="Hello World!"; $txt2="What a nice day!"; echo $txt1 . " " . $txt2; ?> Hello World! What a nice day! زبانهای برنامه سازی وب
Arithmetic Operators Operator Description Example Result + Addition $x=$y+2 $x=7 $y=5 - Subtraction $x=$y-2 $x=3 * Multiplication $x=$y*2 $x=10 / Division $x=$y/2 $x=2.5 % Modulus $x=$y%2 $x=1 ++ Increment $x=++$y $x=6 $y=6 $x=$y++ $x=5 -- Decrement $x=--$y $x=4 $y=4 $x=$y-- زبانهای برنامه سازی وب
Assignment Operators Operator Example Same As = $x=$y += $x+=$y += $x+=$y $x=$x+$y -= $x-=$y $x=$x-$y *= $x*=$y $x=$x*$y .= $x.=$y $x=$x.$y /= $x/=$y $x=$x/$y %= $x%=$y $x=$x%$y زبانهای برنامه سازی وب
Comparison Operators Given that $x=5, the table below explains the comparison operators: Operator Description Example == is equal to $x==8 is false $x==5 is true != is not equal $x!=8 is true > is greater than $x>8 is false < is less than $x<8 is true >= is greater than or equal to $x>=8 is false <= is less than or equal to $x<=8 is true زبانهای برنامه سازی وب
Logical Operators Logical operators are used to determine the logic between variables or values. Given that $x=6 and $y=3, the table below explains the logical operators: Operator Description Example && and ($x < 10 && $y > 1) is true || or ($x==5 || $y==5) is false ! not !($x==$y) is true زبانهای برنامه سازی وب
Conditional Statements If...else Statement if (condition) { code to be executed if condition is true } else { code to be executed if condition is not true } زبانهای برنامه سازی وب
Conditional Statements The Switch Statement switch(n) { case 1: execute code block 1 break; case 2: execute code block 2 break; default: code to be executed if n is different from case 1 and 2 } زبانهای برنامه سازی وب
Arrays Numeric Arrays A numeric array stores each array element with a numeric index. the index are automatically assigned (the index starts at 0) $cars=array("Saab","Volvo","BMW","Toyota"); assign the index manually $cars[0]="Saab"; $cars[1]="Volvo"; $cars[2]="BMW"; $cars[3]="Toyota"; زبانهای برنامه سازی وب
Arrays Associative Arrays An associative array, each ID key is associated with a value. $ages = array("Peter"=>32, "Quagmire"=>" book", "Joe"=>34); $ages['Peter'] = "32"; $ages['Quagmire'] = " book"; $ages['Joe'] = "34"; زبانهای برنامه سازی وب
PHP Loops The for Loop The for loop is used when you know in advance how many times the script should run. for (variable=startvalue;variable<=endvalue;variable=variable+increment) { code to be executed } <?php for ($i=1; $i<=5; $i++) { echo "The number is " . $i . "<br />"; } ?> زبانهای برنامه سازی وب
PHP Loops The while loop The while loop loops through a block of code while a specified condition is true. while (variable<=endvalue) { code to be executed } <?php $i=1; while($i<=5) { echo "The number is " . $i . "<br />"; $i++; } ?> زبانهای برنامه سازی وب
PHP Loops The do...while Loop do { code to be executed } while (variable<=endvalue); <?php $i=1; do { $i++; echo "The number is " . $i . "<br />"; } while ($i<=5); ?> زبانهای برنامه سازی وب
PHP Functions The real power of PHP comes from its functions.In PHP, there are more than 700 built-in functions. Create a PHP Function function functionName() { code to be executed; } <?php function writeName() { echo "Kai Jim Refsnes"; } echo "My name is "; writeName(); ?> زبانهای برنامه سازی وب
PHP Functions Return values <?php function add($x,$y) { $total=$x+$y; return $total; } echo "1 + 16 = " . add(1,16); ?> زبانهای برنامه سازی وب
User Input and Sending Information For using the information and storing them to database requires that transform information between web pages. The PHP $_GET and $_POST variables are used to retrieve information from forms and transform information. زبانهای برنامه سازی وب
Sending Information-Get method The predefined $_GET variable is used to collect values in a form with method="get". Information sent from a form with the GET method displayed in the browser's address bar has limits on the amount of information to send(exceeding 2000 characters). It is possible to bookmark the page. This can be useful in some cases. زبانهای برنامه سازی وب
Sending Information-Get method <a href=http://www.w3schools.com/welcome.php?fname=Peter&age=37 > link to welcome</a> welcome.php : <form action="welcome.php" method=“get"> Name: <input type="text" name="fname" /> Age: <input type="text" name="age" /> <input type="submit" /> </form> <body> Welcome <?php echo $_GET["fname"]; ?>!<br /> You are <?php echo $_GET["age"]; ?> years old. </body> http://www.w3schools.com/welcome.php?fname=Peter&age=37 زبانهای برنامه سازی وب
Sending Information-Post method The predefined $_POST variable is used to collect values from a form sent with method="post". Information sent is invisible to others has no limits on the amount of information to send. However, there is an 8 Mb max size for the POST method, by default(can be changed by setting the post_max_size in the php.ini file). زبانهای برنامه سازی وب
Sending Information-Post method <form action="welcome.php" method=“post"> Name: <input type="text" name="fname" /> Age: <input type="text" name="age" /> <input type="submit" /> </form> welcome.php : <body> Welcome <?php echo $_POST["fname"]; ?>!<br /> You are <?php echo $_POST["age"]; ?> years old. </body> http://www.w3schools.com/welcome.php زبانهای برنامه سازی وب
Date() Function The PHP date() function is used to format a time and/or date. date(format,timestamp) format: Specifies the format of the timestamp (Required) d - Represents the day of the month (01 to 31) m - Represents a month (01 to 12) Y - Represents a year (in four digits) Timestamp: Specifies a timestamp. Default is the current date and time (Optional) <?php echo date("Y/m/d") . "<br />"; echo date("Y.m.d") . "<br />"; echo date("Y-m-d"); ?> 2009/05/11 2009.05.11 2009-05-11 زبانهای برنامه سازی وب
include() Function takes all the content in a specified file and includes it in the current file. <html> <body> <?php include("header.php"); ?> <h1>Welcome to my home page!</h1> <p>Some text.</p> </body> </html> زبانهای برنامه سازی وب
Sending E-mails PHP allows you to send e-mails directly from a script. The PHP mail() Function mail(to,subject,message,headers) Parameter Description to Required. Specifies the receiver / receivers of the email subject Required. Specifies the subject of the email. message Required. Defines the message to be sent. Each line should be separated with a LF (\n). Lines should not exceed 70 characters headers Optional. Specifies additional headers, like From, Cc, and Bcc. The additional headers should be separated with a CRLF (\r\n) زبانهای برنامه سازی وب
Sending E-mails PHP Simple E-Mail <?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."; ?> زبانهای برنامه سازی وب
Sessions A PHP session variable is used to store information about, or change settings for a user session. Session variables hold information about one single user, store them on the server temporary and are available to all pages in one application. Sessions work by creating a unique id (UID) for each visitor and store variables based on this UID. زبانهای برنامه سازی وب
Sessions Starting a PHP Session The code above will register the user's session with the server, allow you to start saving user information, and assign a UID for that user's session. <?php session_start(); ?> <html> <body> </body> </html> Note: The session_start() function must appear BEFORE the <html> tag: زبانهای برنامه سازی وب
Sessions Storing a Session Variable The correct way to store and retrieve session variables is to use the PHP $_SESSION variable: <?php session_start(); // store session data $_SESSION['views']=1; ?> <html> <body> <?php //retrieve session data echo "Pageviews=". $_SESSION['views']; ?> </body> </html> زبانهای برنامه سازی وب
Sessions A simple page-views counter. The isset() function checks if the "views" variable has already been set. <?php session_start(); if(isset($_SESSION['views'])) $_SESSION['views']=$_SESSION['views']+1; else $_SESSION['views']=1; echo "Views=". $_SESSION['views']; ?> زبانهای برنامه سازی وب
Sessions Destroying a Session The unset() function is used to free the specified session variable: session_destroy() function completely destroy the session: <?php unset($_SESSION['views']); ?> <?php session_destroy(); ?> زبانهای برنامه سازی وب
MySQL
MySQL MySQL is the most popular open-source database system. The data in MySQL is stored in database objects called tables. A table is a collection of related data entries and it consists of columns and rows. زبانهای برنامه سازی وب
Database Tables Databases are useful when storing information categorically. A company may have a database with the following tables: "Employees", "Products", "Customers" and "Orders". A database most often contains one or more tables. Each table is identified by a name (e.g. "Customers" or "Orders"). Tables contain records (rows) with data. زبانهای برنامه سازی وب
Database Tables Below is an example of a table called "Persons": زبانهای برنامه سازی وب
Queries A query is a question or a request from database SELECT LastName FROM Persons زبانهای برنامه سازی وب
PHPMyAdmin PHPMyAdmin is used for creating and administering MySQL database زبانهای برنامه سازی وب
Creating Database sample
Creating Table in Database
Type
Length/Values
Table structure Delete Table Perform SQL statement Empty Table
Inserting data into table
Table Browse
Importing Database Browse for file Start record from which row Choose format
MySQL - Connect to a Database Before access data in a database, must create a connection to the database. mysql_connect(servername,username,password); Parameter Description servername Optional. Specifies the server to connect to. Default value is "localhost:3306" username Optional. Specifies the username to log in with. Default value is the name of the user that owns the server process(“root”) password Optional. Specifies the password to log in with. Default is "" زبانهای برنامه سازی وب
MySQL - Connect to a Database Closing a Connection : mysql_close() function <?php $con = mysql_connect("localhost", "root", ""); if (!$con) { die('Could not connect ‘); } // some code mysql_close($con); ?> زبانهای برنامه سازی وب
Query Executation Execute query Select a database mysql_select_db(“databasename", connection name); mysql_select_db("my_db", $con); Execute query mysql_query("command sql”) mysql_query(“select fname from person”); زبانهای برنامه سازی وب
SQL-Insert Into The INSERT INTO statement is used to insert new records in a table. It is possible to write the INSERT INTO statement in two forms. INSERT INTO table_name VALUES (value1, value2, value3,...) INSERT INTO table_name (column1, column2, column3,...) VALUES (value1, value2, value3,...) زبانهای برنامه سازی وب
SQL-Insert Into <?php $con = mysql_connect("localhost",“root",“ "); if (!$con) { die('Could not connect: ‘); } 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')"); mysql_close($con); ?> زبانهای برنامه سازی وب
SQL- Select The SELECT statement is used to select data from a database. SELECT column_name1, column_name2, …, column_name_k FROM table_name where condition Condition is Comparison statement involves Comparison Operators like: = , >, >= , < , <=, <> زبانهای برنامه سازی وب
SQL- Select mysql_fetch_array() function return the first row from the recordset as an array. Each call to mysql_fetch_array() returns the next row in the recordset. <?php $con = mysql_connect("localhost","peter","abc123"); 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); ?> زبانهای برنامه سازی وب
SQL- Select Display the Result in an HTML Table <?php $con = mysql_connect("localhost","peter","abc123"); mysql_select_db("my_db", $con); $result = mysql_query("SELECT * FROM Persons"); 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>"; ?> زبانهای برنامه سازی وب
SQL- Update The UPDATE statement is used to modify data in a table. UPDATE table_name SET column1=value, column2=value2,... WHERE some_column=some_value <?php $con = mysql_connect("localhost","peter","abc123"); mysql_select_db("my_db", $con); mysql_query("UPDATE Persons SET Age = '36' WHERE FirstName = 'Peter' AND LastName = 'Griffin'"); mysql_close($con); ?> زبانهای برنامه سازی وب
SQL- Delete The DELETE statement is used to delete records in a table. DELETE FROM table_name WHERE condition <?php $con = mysql_connect("localhost","peter","abc123"); mysql_select_db("my_db", $con); mysql_query("DELETE FROM Persons WHERE LastName='Griffin'"); mysql_close($con); ?> زبانهای برنامه سازی وب
For more information… http://www.php.net/manual/en/ http://www.w3schools.com/php/default.asp http://www.zend.com/zend/tut/ زبانهای برنامه سازی وب