Web Technology - Overview of PHP Data Types and Concepts (Jntu-Anantapur)
G.PULLAIAH COLLEGE OF ENGINEERING & TECHNOLOGY KURNOOLSUB: WEB TECHNOLOGIES (R09)UNIT-3Important Points about PHP: PHP stands for PHP: Hypertext Preprocessor PHP is a server-side scripting language that is embedded in HTML. It is used to manage dynamic content, databases, session tracking, even build entire e-commerce sites, like ASP 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 PHP supports a large number of major protocols such as POP3, IMAP, and LDAP. PHP4 added support for Java and distributed object architectures (COM and CORBA), making n-tier development a possibility for the first time. What exactly PHP: ü 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" ü PHP runs on different platforms (Windows, Linux, Unix, etc.) ü PHP is compatible with almost all servers used today (Apache, IIS, etc.) ü PHP is case sensitive Common uses of PHP: · PHP performs system functions, i.e. from files on a system it can create, open, read, write, and close them. · PHP can handle forms, i.e. gather data from files, save data to a file, thru email you can send data, return data to the user. · You add, delete, and modify elements within your database thru PHP. · Access cookies variables and set cookies. · Using PHP, you can restrict users to access some pages of your website. · It can encrypt data. Characteristics of PHPFive important characteristics make PHP's practical nature possible: 1. Simplicity 2. Efficiency 3. Security 4. Flexibility 5. Familiarity PHP Installation:ü Download PHP for free here: http://www.php.net/downloads.php PHP Environment SetupIn order to develop and run PHP Web pages three vital components need to be installed on your computer system. Web Server - PHP will work with virtually all Web Server software, including Microsoft's Internet Information Server (IIS) but then most often used is freely availble Apache Server. Download Apache for free here: http://httpd.apache.org/download.cgi Database - PHP will work with virtually all database software, including Oracle and Sybase but most commonly used is freely available MySQL database. Download MySQL for free here: http://www.mysql.com/downloads/index.html PHP Parser - In order to process PHP script instructions a parser must be installed to generate HTML output that can be sent to the Web Browser. Apache Configuration for PHPApache uses httpd.conf file for global settings, and the .htaccess file for per-directory access settings. Older versions of Apache split up httpd.conf into three files (access.conf, httpd.conf, and srm.conf), and some users still prefer this arrangement. Apache server has a very powerful, but slightly complex, configuration system of its own. Learn more about it at the Apache Web site: www.apache.org The following section describe settings in httpd.conf that affect PHP directly and cannot be set elsewhere. If you have standard installation then httpd.conf will be found at /etc/httpd/conf: Timeout This value sets the default number of seconds before any HTTP request will time out. If you set PHP's max_execution_time to longer than this value, PHP will keep grinding away but the user may see a 404 error. In safe mode, this value will be ignored; you must use the timeout value in php.ini instead DocumentRoot DocumentRoot designates the root directory for all HTTP processes on that server. It looks something like this on Unix:
You can choose any directory as document root. AddType The PHP MIME type needs to be set here for PHP files to be parsed. Remember that you can associate any file extension with PHP like .php3, .php5 or .htm.
Action You must uncomment this line for the Windows apxs module version of Apache with shared object support:
or on Unix flavors:
AddModule You must uncomment this line for the static module version of Apache.
PHP Syntax:Note: PHP code is executed on the server, and the plain HTML result is sent to the browser. A PHP scripting block always starts with <?php and ends with ?>. A PHP scripting block can be placed anywhere in the document. Each code line in PHP must end with a semicolon. The semicolon is a separator and is used to distinguish one set of instructions from another. There are two basic statements to output text with PHP: echo and print The file must have a .php extension PHP tags can be represented in 4 ways 1. Canonical PHP tags:Eg: <?php...... ?> 2. Short-open (SGML-style) tags:Eg: <?...?> 3. ASP-style tags:Eg: <%...%> 4. HTML script tags:Eg : <script language="PHP">...</script> Comment Lines in PHP: Note: Comment lines are used in the program to understand the code There are two commenting formats in PHP:
PHP Variables: A variable is used to store information. Variables are used for storing values, like text strings, numbers or arrays. When a variable is declared, it can be used over and over again in your script. All variables in PHP start with a $ sign symbol. The correct way of declaring a variable in PHP: Eg: $var_name = value; Eg: creating a variable containing a string, and a variable containing a number:
PHP is a Loosely Typed Language:In PHP, a variable does not need to be declared before adding a value to it.you do not have to tell PHP which data type the variable is PHP automatically converts the variable to the correct data type, depending on its value. Naming Rules for VariablesA variable name must start with a letter or an underscore "_" A variable name can only contain alpha-numeric characters and underscores (a-z, A-Z, 0-9, and _ ) A variable name should not contain spaces. If a variable name is more than one word, it should be separated with an underscore ($my_string), or with capitalization ($myString) PHP String Variables: A string variable is used to store and manipulate text.String Variables in PHP:String variables are used for values that contain characters.the PHP script assigns the text "Hello World" to a string variable called $txt: Eg: <?php The output of the code above will be: Hello World PHP data types:A data type refers to the type of data a variable can store. PHP has eight (8) different data types you can work with. These are: PHP has eight data types: Scalar types
Compound types
Special types
Boolean values:In PHP the boolean data type is a primitive data type having one of two values: True or False. This is a fundamental data type.
The script uses a random integer generator to simulate our case. $r = rand(0, 1); The rand() function returns a random number from the given integer boundaries. In our case 0 or 1. $male = $r ? True: False; We use the ternary operator to set a $male variable. The variable is based on the random $r value. If $r equals to 1, the $male variable is set to True. If $r equals to 0, the $male variable is set to False. if ($male) { echo "We will use name John\n"; } else { echo "We will use name Victoria\n"; } We print the name. The if command works with boolean values. If the variable $male is True, we print the "We will use name John" to the console. If it has a False value, we print the other string. The following script shows some common values that are considered to be True or False. For example, empty string, empty array, 0 are considered to be False. <?php class Object {}; var_dump((bool) ""); var_dump((bool) 0); var_dump((bool) -1); var_dump((bool) "PHP"); var_dump((bool) array(32)); var_dump((bool) array()); var_dump((bool) "false"); var_dump((bool) new Object()); var_dump((bool) NULL); ?> In this script, we inspect some values in a boolean context. The var_dump()function shows information about a variable. The (bool) construct is called casting. In its casual context, the 0 value is a number. In a boolean context, it is False. The boolean context is when we use (bool) casting, when we use certain operators (negation, comparison operators) and when we use if/else, while keywords. $ php boolean.php bool(false) bool(false) bool(true) bool(true) bool(true) bool(false) bool(true) bool(true) bool(false) Here is the outcome of the script. Integers Integers are a subset of the real numbers. They are written without a fraction or a decimal component. Integers fall within a set Z = {..., -2, -1, 0, 1, 2, ...} Integers are infinite. In computer languages, integers are primitive data types. Computers can practically work only with a subset of integer values, because computers have finite capacity. Integers are used to count discrete entities. We can have 3, 4, 6 humans, but we cannot have 3.33 humans. We can have 3.33 kilograms. Integers can be specified in three different notations in PHP. Decimal, hexadecimal and octal. Octal values are preceded by 0, hexadecimal by 0x. <?php $var1 = 31; $var2 = 031; $var3 = 0x31; echo "$var1\n"; echo "$var2\n"; echo "$var3\n"; ?> We assign 31 to three variables using three notations. And we print them to the console. $ php notation.php 31 25 49 The default notation is the decimal. The script shows these three numbers in decimal. Integers in PHP have a fixed maximum size. The size of integers is platform dependent. PHP has built-in constants to show the maximum size of an integer. $ uname -mo i686 GNU/Linux $ php -a Interactive shell php > echo PHP_INT_SIZE; 4 php > echo PHP_INT_MAX; 2147483647 php > On my 32bit Ubuntu system, an integer value size is four bytes. The maximum integer value is 2147483647. In Java and C, if an integer value is bigger than the maximum value allowed, integer overflow happens. PHP works differently. In PHP, the integer becomes a float number. Floating point numbers have greater boundaries. <?php $var = PHP_INT_MAX; echo var_dump($var); $var++; echo var_dump($var); ?> We assign a maximum integer value to the $var variable. We increase the variable by one. And we compare the contents. $ php boundary.php int(2147483647) float(2147483648) As we have mentioned previously, internally, the number becomes a floating point value. In Java, the value after increasing would be -2147483648. This is where the term integer overflow comes from. The number goes over the top and becomes the smallest negative integer value assignable to a variable. If we work with integers, we deal with discrete entities. We would use integers to count apples. <?php # number of baskets $baskets = 16; # number of apples in each basket $apples_in_basket = 24; # total number of apples $total = $baskets * $apples_in_basket; echo "There are total of $total apples \n"; ?> In our script, we count the total amount of apples. We use the multiplication operation. $ php apples.php There are total of 384 apples Floating point numbers Floating point numbers represent real numbers in computing. Real numbers measure continuous quantities. Like weight, height or speed. Floating point numbers in PHP can be larger than integers and they can have a decimal point. The size of a float is platform dependent. We can use various syntax to create floating point values. <?php $a = 1.245; $b = 1.2e3; $c = 2E-10; $d = 1264275425335735; var_dump($a); var_dump($b); var_dump($c); var_dump($d); ?> In this example, we have two cases of notations, that are used by scientists to denote floating point values. Also the $d variable is assigned a large number, so it is automatically converted to float type. $ php floats.php float(1.245) float(1200) float(2.0E-10) float(1264275425340000) This is the output of the above script. According to the documentation, floating point numbers should not be tested for equality. We will show an example why. $ php -a Interactive shell php > echo 1/3; 0.333333333333 php > $var = (0.333333333333 == 1/3); php > var_dump($var); bool(false) php > In this example, we compare two values that seem to be identical. But they yield unexpected result. Let's say a sprinter for 100m ran 9.87s. What is his speed in km/h? <?php # 100m is 0.1 km $distance = 0.1; # 9.87s is 9.87/60*60 h $time = 9.87 / 3600; $speed = $distance / $time; echo "The average speed of a sprinter is $speed \n"; ?> ü In this example, it is necessary to use floating point values. $speed = $distance / $time; ü To get the speed, we divide the distance by the time. $ php sprinter.php The average speed of a sprinter is 36.4741641337 This is the output of the sprinter script. 36.4741641337 is a floating point number. Strings ü String is a data type representing textual data in computer programs. Probably the single most important data type in programming. ü Since string are very important in every programming language, we will dedicate a whole chapter to them. Here we only drop a small example. <?php $a = "PHP "; $b = 'PERL'; echo $a, $b; echo "\n"; ?> ü We can use single quotes and double quotes to create string literals. $ php strings.php PHP PERL ü The script outputs two strings to the console. The \n is a special sequence, a new line. The effect of this character is like if you hit the enter key when typing text. Arrays ü Array is a complex data type which handles a collection of elements. Each of the elements can be accessed by an index. In PHP, arrays are more diverse. Arrays can be treated as arrays, lists or dictionaries. In other words, arrays are all what in other languages we call arrays, lists, dictionaries. ü Because collections are very important in all computer languages, we dedicate two chapters to collections - arrays. Here we show only a small example. <?php $names = array("Jane", "Lucy", "Timea", "Beky", "Lenka"); print_r($names); ?> The array keyword is used to create a collection of elements. In our case we have names. The print_r function prints a human readable information about a variable to the console. $ php init.php Array ( [0] => Jane [1] => Lucy [2] => Timea [3] => Beky [4] => Lenka ) Output of the script. The numbers are indeces by which we can access the names. Objects So far, we have been talking about built-in data types. Objects are user defined data types. Programmers can create their data types that fit their domain. More about objects in chapter about object oriented programming, OOP. Resources Resources are special data types. They hold a reference to an external resource. They are created by special functions. Resources are handlers to opened files, database connections or image canvas areas. NULL There is another special data type - NULL. Basically, the data type means non existent, not known or empty. In PHP, a variable is NULL in three cases:
<?php $a; $b = NULL; $c = 1; unset($c); $d = 2; if (is_null($a)) echo "\$a is null\n"; if (is_null($b)) echo "\$b is null\n"; if (is_null($c)) echo "\$c is null\n"; if (is_null($d)) echo "\$d is null\n"; ?> ü In our example, we have four variables. Three of them are considered to be NULL. We use the is_null() function to determine, if the variable is NULL. $ php null.php $a is null $b is null $c is null The Concatenation Operatorü There is only one string operator in PHP. ü The concatenation operator (.) is used to put two string values together. ü To concatenate two string variables together, use the concatenation operator:
The output of the code above will be: Hello World! What a nice day! The strlen() function:ü The strlen() function is used to return the length of a string. Let's find the length of a string: Eg: <?php The output of the code above will be: 12 The strpos() function:ü The strpos() function is used to search for a character/text within a string.Let's see if we can find the string "world" in our string: Eg: <?php The output of the code above will be: 6(position starts with ZERO) Note: if match is found then it return character position other wise returns FALSE PHP Operators:PHP Operators This section lists the different operators used in PHP. Arithmetic Operators
Assignment Operators
Comparison Operators
Logical Operators
Conditional operators:
PHP supports following three decision making statements:
The If...Else StatementIf you want to execute some code if a condition is true and another code if a condition is false, use the if....else statement. Syntax
ExampleThe following example will output "Have a nice weekend!" if the current day is Friday, otherwise it will output "Have a nice day!":
If more than one line should be executed if a condition is true/false, the lines should be enclosed within curly braces:
The ElseIf StatementIf you want to execute some code if one of several conditions are true use the elseif statement Syntax
ExampleThe following example will output "Have a nice weekend!" if the current day is Friday, and "Have a nice Sunday!" if the current day is Sunday. Otherwise it will output "Have a nice day!":
The Switch StatementIf you want to select one of many blocks of code to be executed, use the Switch statement. The switch statement is used to avoid long blocks of if..elseif..else code. Syntax
ExampleThe switch statement works in an unusual way. First it evaluates given expression then seeks a lable to match the resulting value. If a matching value is found then the code associated with the matching label will be executed or if none of the lables match then statement will will execute any specified default code.
PHP supports following four loop types.
We will discuss about continue and break keywords used to control the loops execution. The for loop statementThe for statement is used when you know how many times you want to execute a statement or a block of statements. Syntax
The initializer is used to set the start value for the counter of the number of loop iterations. A variable may be declared here for this purpose and it is tradional to name it $i. ExampleThe following example makes five iterations and changes the assigned value of two variables on each pass of the loop:
This will produce following result:
The while loop statementThe while statement will execute a block of code if and as long as a test expression is true. If the test expression is true then the code block will be executed. After the code has executed the test expression will again be evaluated and the loop will continue until the test expression is found to be false. Syntax
ExampleThis example decrements a variable value on each iteration of the loop and the counter increments until it reaches 10 when the evaluation is false and the loop ends.
This will produce following result:
The do...while loop statementThe do...while statement will execute a block of code at least once - it then will repeat the loop as long as a condition is true. Syntax
ExampleThe following example will increment the value of i at least once, and it will continue incrementing the variable i as long as it has a value of less than 10:
This will produce following result:
The foreach loop statementThe foreach statement is used to loop through arrays. For each pass the the value of the current array element is assigned to $value and the array pointer is moved by one and in the next pass next element will be processed. Syntax
ExampleTry out following example to list out the values of an array.
This will produce following result:
The break statementThe PHP break keyword is used to terminate the execution of a loop prematurely. The break statement is situated inside the statement block. If gives you full control and whenever you want to exit from the loop you can come out. After coming out of a loop immediate statement to the loop will be executed. ExampleIn the following example condition test becomes true when the counter value reaches 3 and loop terminates.
This will produce following result:
The continue statementThe PHP continue keyword is used to halt the current iteration of a loop but it does not terminate the loop. Just like the break statement the continue statement is situated inside the statement blokc containing the code that the loop executes, preceded by a conditional test. For the pass encountering continue statement, rest of the loop code is skipped and next pass starts. ExampleIn the following example loop prints the value of array but for which condition bceoms true it just skip the code and next valuye is printed.
This will produce following result
PHP Arrays:ü An array stores multiple values in one single variable. ü A variable is a storage area holding a number or text. The problem is, a variable will hold only one value. ü An array is a special variable, which can store multiple values in one single variable. If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this:
ü However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300? ü The best solution here is to use an array! ü An array can hold all your variable values under a single name. And you can access the values by referring to the array name. ü Each element in the array has its own index so that it can be easily accessed. In PHP, there are three kind of arrays:
Numeric Arraysü A numeric array stores each array element with a numeric index. ü There are two methods to create a numeric array. 1. In the following example the index are automatically assigned (the index starts at 0): $cars=array("Saab","Volvo","BMW","Toyota"); 2. In the following example we assign the index manually:
ExampleIn the following example you access the variable values by referring to the array name and index:
The code above will output: Saab and Volvo are Swedish cars. Associative ArraysAn associative array, each ID key is associated with a value. When storing data about specific named values, a numerical array is not always the best way to do it. With associative arrays we can use the values as keys and assign values to them. Example 1In this example we use an array to assign ages to the different persons: $ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34); Example 2This example is the same as example 1, but shows a different way of creating the array:
The ID keys can be used in a script:
The code above will output: Peter is 32 years old. Multidimensional ArraysIn a multidimensional array, each element in the main array can also be an array. And each element in the sub-array can be an array, and so on. ExampleIn this example we create a multidimensional array, with automatically assigned ID keys:
The array above would look like this if written to the output:
Example 2Lets try displaying a single value from the array above:
The code above will output: Is Megan a part of the Griffin family? PHP Strings:ü They are sequences of characters, like "PHP supports string operations". Following are valid examples of string
ü Singly quoted strings are treated almost literally, whereas doubly quoted strings replace variables with their values as well as specially interpreting certain character sequences.
This will produce following result:
There are no artificial limits on string length - within the bounds of available memory, you ought to be able to make arbitrarily long strings. Strings that are delimited by double quotes (as in "this") are preprocessed in both the following two ways by PHP:
The escape-sequence replacements are:
String Concatenation Operator To concatenate two string variables together, use the dot (.) operator:
This will produce following result:
If we look at the code above you see that we used the concatenation operator two times. This is because we had to insert a third string. Between the two string variables we added a string with a single character, an empty space, to separate the two variables. Using the strlen() function The strlen() function is used to find the length of a string. Let's find the length of our string "Hello world!":
This will produce following result:
The length of a string is often used in loops or other functions, when it is important to know when the string ends. (i.e. in a loop, we would want to stop the loop after the last character in the string) Using the strpos() function The strpos() function is used to search for a string or character within a string. If a match is found in the string, this function will return the position of the first match. If no match is found, it will return FALSE. Let's see if we can find the string "world" in our string:
This will produce following result:
As you see the position of the string "world" in our string is position 6. The reason that it is 6, and not 7, is that the first position in the string is 0, and not 1. PHP Functions:ü The real power of PHP comes from its functions. ü In PHP, there are more than 700 built-in functions. A function is a piece of code which takes one more input in the form of parameter and does some processing and returns a value. You already have seen many functions like fopen() and fread() etc. They are built-in functions but PHP gives you option to create your own functions as well. There are two parts which should be clear to you:
In fact you hardly need to create your own PHP function because there are already more than 1000 of built-in library functions created for different area and you just need to call them according to your requirement. Please refer to PHP Function Reference for a complete set of useful functions. Creating PHP Function: Its very easy to create your own PHP function. Suppose you want to create a PHP function which will simply write a simple message on your browser when you will call it. Following example creates a function called writeMessage() and then calls it just after creating it. Note that while creating a function its name should start with keyword function and all the PHP code should be put inside { and } braces as shown in the following example below:
This will display following result:
PHP Functions with Paramters: PHP gives you option to pass your parameters inside a function. You can pass as many as parameters your like. These parameters work like variables inside your function. Following example takes two integer parameters and add them together and then print them.
This will display following result:
Passing Arguments by Reference: It is possible to pass arguments to functions by reference. This means that a reference to the variable is manipulated by the function rather than a copy of the variable's value. Any changes made to an argument in these cases will change the value of the original variable. You can pass an argument by reference by adding an ampersand to the variable name in either the function call or the function definition. Following example depicts both the cases.
This will display following result:
PHP Functions retruning value: A function can return a value using the return statement in conjunction with a value or object. return stops the execution of the function and sends the value back to the calling code. You can return more than one value from a function using return array(1,2,3,4). Following example takes two integer parameters and add them together and then returns their sum to the calling program. Note that return keyword is used to return a value from a function.
This will display following result:
Setting Default Values for Function Parameters: You can set a parameter to have a default value if the function's caller doesn't pass it. Following function prints NULL in case use does not pass any value to this function.
This will produce following result:
Dynamic Function Calls: It is possible to assign function names as strings to variables and then treat these variables exactly as you would the function name itself. Follwoing example depicts this behaviour.
This will display following result:
PHP Forms and User Input:The PHP $_GET and $_POST variables are used to retrieve information from forms, like user input. PHP Form HandlingThe most important thing to notice when dealing with HTML forms and PHP is that any form element in an HTML page will automatically be available to your PHP scripts. ExampleThe example below contains an HTML form with two input fields and a submit button:
When a user fills out the form above and click on the submit button, the form data is sent to a PHP file, called "welcome.php": "welcome.php" looks like this:
Output could be something like this: Welcome John! The PHP $_GET and $_POST variables will be explained in the next chapters. Form ValidationUser input should be validated on the browser whenever possible (by client scripts). Browser validation is faster and reduces the server load. You should consider server validation if the user input will be inserted into a database. A good way to validate a form on the server is to post the form to itself, instead of jumping to a different page. The user will then get the error messages on the same page as the form. This makes it easier to discover the error. PHP Files & I/OExplain following functions related to files:
Opening and Closing Files The PHP fopen() function is used to open a file. It requires two arguments stating first the file name and then mode in which to operate. Files modes can be specified as one of the six options in this table.
If an attempt to open a file fails then fopen returns a value of false otherwise it returns a file pointer which is used for further reading or writing to that file. After making a changes to the opened file it is important to close it with the fclose() function. The fclose() function requires a file pointer as its argument and then returns true when the closure succeeds or false if it fails. Reading a file Once a file is opend using fopen() function it can be read with a function called fread(). This function requires two arguments. These must be the file pointer and the length of the file expressed in bytes. The files's length can be found using the filesize() function which takes the file name as its argument and returns the size of the file expressed in bytes. So here are the steps required to read a file with PHP.
The following example assigns the content of a text file to a variable then displays those contents on the web page.
Writing a file A new file can be written or text can be appended to an existing file using the PHP fwrite()function. This function requires two arguments specifying a file pointer and the string of data that is to be written. Optionally a third intger argument can be included to specify the length of the data to write. If the third argument is included, writing would will stop after the specified length has been reached. The following example creates a new text file then writes a short text heading insite it. After closing this file its existence is confirmed using file_exist() function which takes file name as an argument
|
No comments:
Post a Comment