Presentation is loading. Please wait.

Presentation is loading. Please wait.

APACHE & PHP (except Accessing PHP from SQL

Similar presentations


Presentation on theme: "APACHE & PHP (except Accessing PHP from SQL"— Presentation transcript:

1 APACHE & PHP (except Accessing PHP from SQL
APACHE & PHP (except Accessing PHP from SQL. Please see last slide for reference material) UNIT 5

2 Apache : Installation, Configuration, Basic Security

3 Outline Introduction Why Apache ? Installation Configuration
Running Apache Basic Security

4 Introduction A basic web server works as follows :
It is a program that runs on a host computer . It waits for a request from web browser/client for objects it has in its possession Upon receiving the request , it retrieves the requested information and sends it to the client. The objects it can serve include HTML documents, plain text, images, sounds, video and other data.

5 Introduction Apache is the most popular web server on the internet, running approximately 60% of all web servers. This is the default web server on Red Hat, SuSE, and Debian systems and is well known in industry for its flexibility and performance.

6 Introduction Installing and maintaining is easy and ranks far below and DNS in complexity & difficulty of administration. Its free and open source and full source code is available from Apache group site at .

7 Why Apache ? Apache is popular because Apache is highly configurable .
It is extensible (for e.g. mod_perl and mod_php3 can be added) . Supports virtual hosts or multi homed servers . It is free and open source .

8 Installation Apache is included with most Linux distributions. On a machine installed with recent version of Linux, chances are Apache is already installed and running. Processor status can be checked to see if its running by using the command machine1$ ps –ef | grep httpd

9 Installation If one wishes to download the source code and compile it then, Execute the configure script included with the distribution to detect type of system used and set up appropriate makefiles. use --prefix option to specify where in ones directory tree the Apache server should live.

10 Installation For example : % ./configure --prefix=/etc/httpd
Default modules can be used or some features may be included or removed by invoking -enable-module= and -disable-module= options to configure .

11 Installation Some modules like asis, autoindex, env may be disabled for security reasons. A complete list of modules can be viewed at src/configuration file or After executing configure run make and make install to actually compile and install the appropriate files .

12 Configuration All configuration files are in conf directory ( /etc/httpd/conf). The files that are to be examined and customized are httpd.conf httpd.conf is used to set the TCP port (usually port 80), location of log files, and various network and performance parameters

13 Security Modifying the Default Header :
A hacker can exploit a web server by the information it sends in its header ( version, machine type, its built-up etc) . Its always better to modify the default header by changing the lines that reveals this information in src/include/httpd.h file .

14 Security Upgrading old software when necessary.
Protecting Web Data with IP Restrictions : Apache can be configured to allow restricted IP addresses only. This can be done by modifying .htaccess

15 Security Using HTTP Authentication :
HTTP user authentication restricts access to a particular directory and subdirectories of the web server . A browser implements authentication by prompting a dialog box for the user to type his username/password.

16 Security Using Secure HTTP Connections :
The Secure Socket Layer (SSL) should be used to minimize the likelihood that a hacker can snoop a username/password. SSL not only encrypts the data before it is transferred to the web site, but also it decrypts the data received from the web site, thus securing the data transfers.

17 PHP BASICS

18 11.1 Origin and Uses of PHP Developed by Rasmus Lerdorf in 1994
PHP is a server-side scripting language, embedded in XHTML pages PHP has good support for form processing PHP can interface with a wide variety of databases

19 11.2 Overview of PHP When a PHP document is requested of a server, the server will send the document first to a PHP processor The result of the processing is the response to the request Two modes of operation Copy mode in which plain HTML is copied to the output Interpret mode in which PHP code is interpreted and the output from that code sent to output The client never sees PHP code, only the output produced by the code PHP has typical scripting language characteristics Dynamic typing, untyped variables Associative arrays Pattern matching Extensive libraries

20 11.3 General Syntactic Characteristics
PHP code is contained between the tags <?php and ?> Code can be included with the PHP include include(“table2.inc”); When a file is included, the PHP interpreter reverts to copy mode Thus, code in an include file must be in <?php and ?> tags All variable names in PHP begin with $ and continue as usual for variables Variable names are case sensitive However keywords and function names are not case sensitive

21 11.3 PHP Syntax One line comments can begin with # or // and continue to the end of the line Multi-line comments can begin with /* and end with */ PHP statements are terminated with semicolons Curly braces are used to create compound statements Braces cannot define blocks with logically scoped variables, unless it is the body of a function

22 11.4 Primitives, Operations, Expressions
Four scalar types: boolean, integer, double, string Two compound types: array, object Two special types: resource and NULL

23 11.4 Variables Variables are not declared except in order to specify scope or lifetime A variable that has not been assigned a value is unbound and has the value NULL NULL is coerced to 0 if a number is needed, to the empty string if a string is needed Both of these coercions count as boolean FALSE

24 11.4 Integer Type PHP distinguishes between integer and floating point numeric types Integer is equivalent to long in C, that is, usually 32 bits

25 11.4 Double Type Literal double type numeric values include a period and/or the exponent sign: either e or E Double type values are stored internally as double precision floating point values

26 11.4 String Type Characters in PHP are one byte
String literals are enclosed in single or double quotes Double quoted strings have escape sequences interpreted and variables interpolated Single quoted strings have neither escape sequence interpretation nor variable interpolation A literal $ sign in a double quoted string must be escaped with a backslash, \ Double-quoted strings can cover multiple lines, the included end of line characters are part of the string value

27 11.4 Boolean Type The boolean type has two values :TRUE and FALSE
Other type values are coerced as needed by context, for example, in control expressions The integer value 0, the empty string and the literal string “0” all count as false NULL counts as false The double value 0.0 counts as false. Beware, however, that double calculations rarely result in the exact value 0.0

28 11.4 Arithmetic Operators and Expressions
PHP supports the usual operators supported by the C/C++/Java family Integer divided by integer results in integer if there is no remainder but results in double if there is a remainder 12/6 is 2 12/5 is 2.4 A variety of numeric functions is available: floor, ceil, round, srand, abs, min, max

29 11.4 String Operations String catenation is indicated with a period
Characters are accessed in a string with a subscript enclosed in curly braces Many useful string functions are provided strlen gives the length of a string strcmp compares two strings as strings chop removes whitespace from the end of a string strpos() Returns the position of the first occurrence of a string inside another string (case-sensitive) Substr strtolower strtoupper

30 11.4 Assignment Operators The assignment operators used in C/C++/Java are supported in PHP

31 11.5 Output The print function is used to send data to output
print takes string parameters, PHP coerces as necessary The C printf function is also available The first argument to printf is a string with interspersed format codes A format code begins with % followed by a field width and a type specifier Common types specifiers are s for string, d for integer and f double Field width is a single integer to specify the number of characters (minimum) used to display the value or two integers separated by a period to indicate field width and decimal places for double values printf(“x = %5d is %s\n”, $x, $size); Displays $x as an integer and $size as a string

32 11.6 Relational Operators PHP has the usual comparison operators: >, < <=, >=, == and != PHP also has the identity operator === This operator does not force coercion The regular comparisons will force conversion of values as needed

33 11.6 Boolean Operators PHP supports &&, || and ! as in C/C++/Java
The lower precedence version and and or are provided The xor operator is also provided

34 11.6 Selection Statements PHP provides an I with almost the same syntax as C/C++/Java The only difference is the elseif (note, not elsif as in Perl) The switch statement is provided with syntax and semantics similar to C/C++/Java The case expressions are coerced before comparing with the control expression break is necessary to prevent execution from flowing from one case to the next

35 11.6 Loop Statements PHP provides the while and for and do-while as in JavaScript

36 11.7 Arrays Arrays in PHP combine the characteristics of regular arrays and hashes An array can have elements indexed numerically. These are maintained in order An array, even the same array, can have elements indexed by string. These are not maintained in any particular order The elements of an array are, conceptually, key/value pairs

37 11.7 Array Creation & Access
Two ways of creating an array Assigning a value to an element of an array Using the array function Create a numerically indexed array array(23, ‘xiv’, “bob”, 777); Create an array with string indexes array(“x” => “xerxes”, “y” => “ytrbium”) Array elements are accessed by using a subscript in square brackets

38 11.7 Functions for Dealing with Arrays
The unset function can be used to remove an array or an element of an array The array_keys function returns a list of the keys of an array The array_values returns a list of values in an array The array_key_exists function returns true if a given key is actually present in a given array is_array determines if its argument is an array implode converts an array of strings to a single string, separating the parts with a specified string explode converts a string into a list of strings by separating the string at specified characters

39 11.7 Arrays as Stacks PHP provides the array_push function that appends its arguments to a given array The function array_pop removes the last element of a given array and returns it

40 11.7 Iterating Through an Array
The foreach statement has two forms for iterating through an array foreach (array as scalar_variable) loop body foreach (array as key => value) loop body The first version assigns each value in the array to the scalar_variable in turn The second version assigns each key to key and the associated value to value in turn In this example, each day and temperature is printed $lows = array("Mon" => 23, "Tue" => 18, "Wed" => 27); foreach ($lows as $day => $temp) print("The low temperature on $day was $temp <br />");

41 11.8 General Characteristics of Functions
Function syntax function name([parameters]) { ... } The parameters are optional, but not the parentheses Function names are not case sensitive A return statement causes the function to immediately terminate and return a value, if any, provided in the return A function that reaches the end of the body without executing a return, returns no value

42 11.8 Parameters A formal parameter, specified in a function declaration, is simply a variable name If more actual parameters are supplied in a call than there are formal parameters, the extra values are ignored If more formal parameters are specified than there are actual parameters in a call then the extra formal parameters receive no value PHP defaults to pass by value Passing by reference was deprecated in PHP and was removed in PHP You should therefore not use this feature other than on legacy websites, and even there you are recommended to rewrite code that passes by reference, because it will halt with a fatal error on newer versions of PHP.

43 11.8 The Scope of Variables A variable defined in a function is, by default, local to the function A global variable of the same name is not visible in the function Declaring a variable in a function with the global declaration means that the functions uses the global variable of that name The usual lifetime of a local variable is from the time the function begins to execute to the time the function returns

44 PHP Global Variables - Superglobals
Several predefined variables in PHP are "superglobals", which means that they are always accessible, regardless of scope - and you can access them from any function, class or file without having to do anything special. The PHP superglobal variables are: $GLOBALS $_SERVER $_REQUEST $_POST $_GET $_COOKIE $_SESSION echo $_SERVER['PHP_SELF']; echo "<br>"; echo $_SERVER['SERVER_NAME']; echo "<br>"; echo $_SERVER['HTTP_HOST']; echo "<br>"; echo $_SERVER['HTTP_REFERER']; echo "<br>"; echo $_SERVER['HTTP_USER_AGENT']; echo "<br>"; echo $_SERVER['SCRIPT_NAME'];

45 STRINGS & REGULAR EXPRESSIONS

46 preg-match() preg(regex, string) searches for the pattern described in regex within the string string. It returns false if no match was found.

47 remember DOS? DOS had the * character as a wildcard. If you said
DIR *.EXE It would list all the files ending with .EXE Thus the * wildcard would mean “all characters except the dot” Similarly, you could say DEL *.* to delete all your files

48 regular expression Is nothing but a fancy wildcard.

49 pattern The regular expression describes a pattern of characters.
Patters are common in other circumstances. Query: ‘Krichel Thomas’ in Google Query: ‘"Thomas Krichel"’ in Google Dates are of the form yyyy-mm-dd.

50 pattern matching We say that a regular expression matches the string if an instance of the pattern described by the regular expression can be found in the string. If we say “matches in the string” may make it a little more clearer. Sometimes people also say that the string matches the regular expression.

51 metacharacters Instead of just giving the star * special meaning, in a regular expression all the following have special meaning \ ^ $ . | ( ) * + { } ? [ ] Collectively, these characters are knows as metacharacters. They don't stand for themselves but they mean something else. For example DEL *.EXE does not mean: delete the file "*.EXE". It means delete anything ending with .EXE.

52 metacharacters We are somehow already familiar with metacharacters.
In XML < means start of an element. To use < literally, you have to use < In PHP the "\n" does not mean backslash and then n. It means the newline character.

53 simple regular expressions
Characters that are not metacharacters just simply mean themselves ‘good’ does not match in ‘Good Bear’ ‘d B’ matches in ‘Good Bear’ ‘dB’ does not match in ‘Good Bear’ ‘Beer ’ does not match in ‘Good Bear’ If there are several matches, the pattern will match at the first occurrence. ‘o’ matches in ‘Good Beer’

54 the backslash \ quote If you want to match a metacharacter in the string, you have to quote it with the backslash ‘a 6+ pack’ does not match in ‘a 6+ pack’ ‘a 6\+ pack’ does match in ‘a 6+ pack’

55 anchor metacharacters ^ and $
^ matches at the beginning of the string. $ matches at the end of the string. ‘keeper’ matches in ‘bearkeeper’ ‘keeper$’ matches in ‘bearkeeper’ ‘^keeper’ does not match in ‘bearkeeper’ ‘^$’ matches in ‘’ Note that in a double quoted-string an expression starting with $ will be replaced by the variable's string value (or nothing if the variable has not been set).

56 character classes We can define a character class by grouping a list of characters between [ and ] ‘b[ie]er’ matches in ‘beer’ ‘b[ie]er’ matches in ‘bier’ ‘[Bb][ie]er’ matches in ‘Bier’ Within a class, metacharacters need not be escaped. In the class only -, ] and ^ are metacharacters.

57 - in the character class
Within a character class, the dash - becomes a metacharacter. You can use to give a range, according to the sequence of characters in the character set you are using. It’s usually alphabetic ‘be[a-e]r’ matches in ‘beer’ ‘be[a-e]r’ matches in ‘becr’ ‘be[a-e]r’ does not match in ‘befr’ If the dash - is the last character in the class, it is treated like an ordinary character.

58 File Handling with PHP

59 Files and PHP File Handling Data Storage Manipulating uploaded files
Though slower than a database Manipulating uploaded files From forms Creating Files for download

60 Open/Close a File A file is opened with fopen() as a “stream”, and PHP returns a ‘handle’ to the file that can be used to reference the open file in other functions. Each file is opened in a particular mode. A file is closed with fclose() or when your script ends.

61 File Open Modes ‘r’ Open for reading only. Start at beginning of file.
Open for reading and writing. Start at beginning of file. ‘w’ Open for writing only. Remove all previous content, if file doesn’t exist, create it. ‘a’ Open writing, but start at END of current content and creates the file if necessary ‘a+’ Open for reading and writing, start at END and create file if necessary.

62 File Open/Close Example
<?php // open file to read $toread = fopen(‘some/file.ext’,’r’); // open (possibly new) file to write $towrite = fopen(‘some/file.ext’,’w’); // close both files fclose($toread); fclose($towrite); ?>

63 Now what..? If you open a file to read, you can use more in-built PHP functions to read data.. If you open the file to write, you can use more in-built PHP functions to write..

64 Reading Data There are two main functions to read data:
fgets($handle,$bytes) Reads up to $bytes of data, stops at newline or end of file (EOF) fread($handle,$bytes) Reads up to $bytes of data, stops at EOF.

65 Reading Data We need to be aware of the End Of File (EOF) point..
feof($handle) Whether the file has reached the EOF point. Returns true if have reached EOF.

66 Data Reading Example $handle = fopen('people.txt', 'r');
while (!feof($handle)) { echo fgets($handle, 1024); echo '<br />'; } fclose($handle);

67 Data Reading Example $handle = fopen('people.txt', 'r');
while (!feof($handle)) { echo fgets($handle, 1024); echo '<br />'; } fclose($handle); $handle = fopen('people.txt', 'r'); Open the file and assign the resource to $handle

68 Data Reading Example $handle = fopen('people.txt', 'r');
while (!feof($handle)) { echo fgets($handle, 1024); echo '<br />'; } fclose($handle); while (!feof($handle)) { echo fgets($handle, 1024); echo '<br />'; } While NOT at the end of the file, pointed to by $handle, get and echo the data line by line

69 Data Reading Example $handle = fopen('people.txt', 'r');
while (!feof($handle)) { echo fgets($handle, 1024); echo '<br />'; } fclose($handle); Close the file fclose($handle);

70 File Open shortcuts.. There are two ‘shortcut’ functions that don’t require a file to be opened: $lines = file(filename) Reads entire file into an array with each line a separate entry in the array. $str = file_get_contents(filename) Reads entire file into a single string.

71 Writing Data To write data to a file use: fwrite($handle,$data)
Write $data to the file.

72 Data Writing Example $handle = fopen('people.txt', 'a');
fwrite($handle, “\nFred:Male”); fclose($handle);

73 Write new data (with line break after previous data)
Data Writing Example $handle = fopen('people.txt', 'a'); fwrite($handle, '\nFred:Male'); fclose($handle); Open file to append data (mode 'a') $handle = fopen('people.txt', 'a'); fwrite($handle, “\nFred:Male”); Write new data (with line break after previous data)

74 SYSTEM CALLS

75 exec — Execute an external program
string exec ( string $command [, array $output [, int $return_var ]] )

76 Parameters command-The command that will be executed. output - If the output argument is present, then the specified array will be filled with every line of output from the command. Trailing whitespace, such as \n, is not included in this array. return_var - If the return_var argument is present along with the output argument, then the return status of the executed command will be written to this variable.

77 <?php // outputs the username that owns the running php/httpd process // (on a system with the "whoami" executable in the path) echo exec('whoami'); ?>

78 DAY 5

79 COOKIES & SESSIONS

80 How to create variables storing values across php scripts’ calls?
. Client-server connection is not permanent => Cannot be saved in program memory There are many clients connecting simultaneously => Cannot be saved in file (you cannot identify clients as well sometimes)

81 Different mechanisms of the same solution
Cookies Cookies are a mechanism for storing data in the remote browser and thus tracking or identifying return users. Sessions Session support in PHP consists of a way to preserve certain data across subsequent accesses. This enables you to build more customized applications and increase the appeal of your web site.

82 What is a Cookie? A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests for a page with a browser, it will send the cookie too. With PHP, you can both create and retrieve cookie values.

83

84 How to Create a Cookie The setcookie() function is used to create cookies. Note: The setcookie() function must appear BEFORE the <html> tag. setcookie(name, [value], [expire], [path], [domain], [secure][httponly]); This sets a cookie named "uname" - that expires after ten hours. <?php setcookie("uname", $name, time()+36000); ?> <html> <body> …

85 The setcookie parameters
name The name of the cookie. This is the name that your server will use to access the cookie on subsequent browser requests. value The value of the cookie, or the cookie’s contents. This can contain up to 4 KB of alphanumeric text. expire (Optional.) Unix timestamp of the expiration date. Generally, you will probably usetime() plus a number of seconds. If not set, the cookie expires when the browser closes. path (Optional.) The path of the cookie on the server. If this is a / (forward slash), the cookie is available over the entire domain, such as If it is a subdirectory, the cookie is available only within that subdirectory. The default is the current directory that the cookie is being set in, and this is the setting you will normally use. domain (Optional.) The Internet domain of the cookie. If this is .webserver.com, the cookie is available to all of webserver.com and its subdomains, such as and images.webserver.com. secure (Optional.) Whether the cookie must use a secure connection ( If this valueis TRUE, the cookie can be transferred only across a secure connection. The default is FALSE. httponly (Optional; implemented since PHP version ) Whether the cookie must use the HTTP protocol. If this value is TRUE, scripting languages such as JavaScript cannot access the cookie. (Not supported in all browsers.) The default is FALSE.

86 How to Retrieve a Cookie Value
To access a cookie you use $_COOKIE array Tip: Use the isset() function to find out if a cookie has been set. <html> <body> <?php if (isset($_COOKIE[“uname”])) echo "Welcome " . $uname . "!<br />"; else echo "You are not logged in!<br />"; ?> </body> </html>

87 How to Delete a Cookie It will expire or
Cookies must be deleted with the same parameters as they were set with. If the value argument is an empty string (""), and all other arguments match a previous call to setcookie, then the cookie with the specified name will be deleted from the remote client.

88 What is a Session? The session support allows you to register arbitrary numbers of variables to be preserved across requests. A visitor accessing your web site is assigned an unique id, the so-called session id. This is either stored in a cookie on the user side or is propagated in the URL.

89 How to Create a Session The session_start() function is used to create sessions. <?php session_start(); ?>

90 How to Retrieve a Session Value
Register Session variable session_register('var1','var2',...); // will also create a session PS:Session variable will be created on using even if you will not register it! Use it <?php session_start(); if (!isset($_SESSION['count'])) $_SESSION['count'] = 0; else $_SESSION['count']++; ?>

91 How to Delete a Session Value
session_unregister(´varname´); How to destroy a session: session_destroy()

92 Using Cookies Cookies are small pieces of data that a server sends to a browser for storage. When a browser contacts a server, it sends along any cookies for that server under the variable $_COOKIES. Similarly, a server can set one or more cookies on the browser for retrieval at a later time.

93 Session Variables Effectively, session variables are cookies that remain active only while the browser is actively interacting with the server. When time elapses, or when you close your browser, the session variables disappear. (If cookies are not allowed by a user, then information for sessions may be placed in a query string at the end of a URL.)


Download ppt "APACHE & PHP (except Accessing PHP from SQL"

Similar presentations


Ads by Google