php - php hypertext preprocessor
- Details
- Last Updated: Friday, 13 September 2019 06:58
- Published: Saturday, 24 August 2019 11:46
- Hits: 1146
PHP Hypertext Preprocessor (PHP) : is a programming language that allows web developers to create dynamic content that interacts with databases. PHP is basically used for developing web based software applications. PHP is the most popular scripting language used on servers. The php pgm to run is embedded in html code. When we don't want o have static html pages, we use php to generate dynamic html cod. This php script to generate dynamic webpage is run on server, and then once the html code is generated, it is sent to browser for display.
PHP is open source, and has C like syntax. It was created in 1994, and was originally called Personal Home Page (php). php is most used language for website coding, so it will suffice to learn just this language for building websites with dynamic content. If you want to build static website, just knowing HTML and CSS will suffice, but static websites are not easy to maintain, change, and are not used anymore (except for very small websites).
Official website for php. Here you can find lots of php doc and tutorial: http://php.net
other good tutorial is from w3schools: https://www.w3schools.com/php/
Installation:
On linux mint, we'll use APT cmd to install php. Latest stable version f php is 7.2.PhP is cripting language, and so can scripts written in php with php interpreter. However, we want php to be able to connect to MySQL database, and as well as communicate with web server pgm to send it the contents to display. So, along with php, we install helper packages.
sudo apt install php libapache2-mod-php php-mysql => This installs php 7.2 + extra modules for it to talk to apache2 and mysql.
It installs these pkg on my system (All pkg installed are 7.2 version, and there are no other versions installed):
no versions: php, libapache2-mod-php, php-mysql, php-common => These pkg w/o version number actually point to 7.2 version
7.2 versions: php7.2, libapache2-mod-php7.2, php7.2-mysq, php7.2-common, php7.2-cli, php7.2-json, php7.2-apcache, php7.2-readline => these pkg with version number 7.2 are the actual pkg installed.
which php => shows /usr/bin/php as php binary location. This is a softlink to binary php7.2 stored here.
php -v => shows php version num as 7.2
There are lots of php modules available. PEAR (PHP Extension and Application Repository is, collection of various useful PHP packages.
Running php: There are various ways to run php. php is mostly used for server side scripting, where it geberates html o/p. It can also be used as cmd line script, to generate any kind of o/p. We will talk about few common ways to run php:
1. Interactive shell: on linux terminal, we can run php script with php interpreter. Just like any other scripting language, we can open php shell and run php interactively:
php -a => opens php interactive shell. Now we can type any php cmd on php cmd line terminal.
php> echo 2+3; => echo cmds work fine in php
5
php> exit
2. php file: we can have php script in a file, and pass that script to php interpreter, just like with other scripting languages.
test.php => create this file, and put below code in this file (.php extension is not necessary when writing code to run on php cmd line interpreter, it' needed only when running on webserver)
!#/usr/bin/php => 1st line indicates that interpreter used should be php
<?php => Any php code needs to be within "<?php" and "?>" tags. This tell the php engine to execute this code as php code. Anything outside this is treated as regular text, and php engine will just print it on screen as is. So if we omit these tags, php code will not execute at all and will just output the code on screen. It's important to have no space in these tags "<?php" and "?>", (i.enot like "<? php") or else they are not recognized as valid tags. Note: these tags were not needed in interactive shell, as php understands that it'sinteractive session, so every code entered is valid php code.
echo "Hello \n"; => simple echo stmt
phpinfo(); => This is a very useful function provided by php, which provides a lot of info abut php engine that was used to run this script. It is also used to validate if php is installed correctly and is running fine.
?>
any garabge text =>Anything written outside php tags is printed as is on screen. php engine doesn't even look at this and ignores it completely (as it's outside the php tags)
Now, after saving the script, change the permission to executable => chmod 755 test.php
./test.php => prints "Hello". If the 1st line (!#/usr/bin/php) in php file above is omitted, then we need to type "php test.php"
3. webserver script: We can have php file that we can pass to a webserver. Once php is installed on your machine, apache webserver on same m/c is able to access it, w/o doing anything more. The server finds out that this file needs to be interpreted by PHP because we used the ".php" extension, which the server is configured to pass on to PHP. So, .php extension is very important here, as w/o that, the webserver won't know what to do with this file. php files can have regular html code or any text in it. php parser looks for php code inside php tags, and does whatever is asked of it. Parsing in this manner allows PHP to be embedded in all sorts of different documents, as everything outside of a pair of opening and closing tags is ignored by the PHP parser. Then it returns the final generated file (replacing code within php tags with the output of the script) to server engine, which sends it to the browser.
If we have apache installed, we'll see a default file here: /var/www/html/index.html
IF we open browser, and type "127.0.0.1" in the browser address, we'll see default ubuntu page show up (see in apache tutorial section). Now if we put some other file here named test.php, and access it via addr "127.0.0.1/test.php" in the browser, it will be sent to apache server, which will pass it to php engine (since it has .php extension), We can copy below code in test.php file (we'll need to open this file preceeding it with sudo, since only root has permission to edit in this dir).
sudo emacs /var/www/html/test.php
<html>
<head>
<title>PHP Test</title>
</head>
<body>
<p>** Outside : before php **</p>
<?php echo '<p>Hello World</p>'; ?>
<p>** Outside : after php **</p>
</body>
</html>
Now, on accessing addr "127.0.0.1/test.php", we will see "Hello World" printed on browser, as the php code has been parsed by php engine. We'll also see text with "** ... **" that's outside php tags.
PHP syntax: We'll be talking about php syntax when used as webserver script. Just like any other language, php file is parsed by parser, which parses tokens and looks for var defn, operators, std keywords, functions, etc. language defines data types as number, string, etc. Variables store different data, belonging to one of these data types. We have operators to operate on these var. We have conditional stmt to get pgm to take diff execution paths.
1. Any PHP file needs to have a .php extension for webserver to recognize it and pass it to php interpreter. php file can have any text in it, but anything within php tags (<?php and ?>) needs to be valid php code, and that is the only code that will be parsed by the php engine. Php syntax refers to php code inside these tags.
2. If php contains only php code, and nothing else, then closing php tags (?>) can be omitted.
3. Each php stmt ends with semicolon ";", (except for the tags. tags imply continuation of stmt, so no ; used. same for stmt like "if else" which are 1 stmt, so no ; used except inside { } which may have multiple stmt in them).
3. comments: C style (// for single line and /* ... */ for multi line) of comments supported. PHP also supports scripting language type single line comment (starting with #).
4. case sensitivity: php variables are case sensitive, but std keywords, class, functions are not case sensitive.For ex, $book and $Book are different, but "when" and "WhEn" are same.
5. whitespaces in php serve as a separator for tokens, so that the interpreter can parse the file for tokens. However, it seems tolerant of non-whitespaces also (i.e ( a < b ) and (a<b) both seem to work ).Not sure, how lenient it is with whitespaces, but it's a good idea to always have whitespaces.
6. variables: variables are specified with $ sign in front of var name. var name can only contain alphanumeric char and a underscore (A-Z, 0-9, a-z, _), and must can't start with a number. variables are case sensitive. We do not specify data type (i.e int, char, etc) of var, php automatically assigns it based on it's value. Thus, it's called loosely typed language, and is similar to almost all other scripting languages, which never assign data types. However, in php 7, data type declaration can be added using "strict" keyword.
php supports following data type:
- string: sequence of char inside single or double quotes. ex: $str = "my name"; MAny builtin func can be used to manipulate string. ex: strlen("Hello world!"); => returns length of string as 12.
- integer: $x=435; php func var_dump($x) returns var type and value.
- float: $x=4.23; php func var_dump($x) returns var type and value.
- boolean: 2 values "true orTRUE" and "false or FALSE". $x=true; NOTE: there is no quotes around this (As $x="true" makes $x a string, and not boolean). booleans are usedin conditional stmt
- array:stores multiple values in single var.ex: $cars = array("Volvo","BMW","Toyota"); $cars[0] refers to "volvo", so on. can also be assigned as $cars[2]="BM", Many func available to manipulate arrays.ex: count($cars), sort($cars), etc.
- associative arrays: similar to perl associative arrays, used to store key/value pair. ex: $age = array("Jim" => "25", "Joe" => "35"); now $age['Jim'] refers to value "25". This can also be assigned as $cars['Joe']="maruti"; We can loop thru associative arrays using foreach. function print_r($age) explained below, will print array's all key/value pairs w/o going thru "for" loop for each array element.
- associative arrays: similar to perl associative arrays, used to store key/value pair. ex: $age = array("Jim" => "25", "Joe" => "35"); now $age['Jim'] refers to value "25". This can also be assigned as $cars['Joe']="maruti"; We can loop thru associative arrays using foreach. function print_r($age) explained below, will print array's all key/value pairs w/o going thru "for" loop for each array element.
- object: An object is a data type which stores data and information on how to process that data. We use "class" for this, just like in other Object oriented languages.
- NULL: Null is a special data type which can have only one value: NULL. Any variable is created without a value is automatically assigned a value of NULL. ex: $x=NULL;
The scope of var (i.e places where it can be called or referenced) is of 3 types:
- global: var declared outside of any function have global scope, and can be accessed only outside the function (so not truly global, as var not available within the function). However, re declaring these var with "global" var inside the function allows these var to be used within the function.
- superglobals: there are various predefined superglobal var, that can be accessed anywhere on php code.There are lots of them, and each of these var store useful info in an associative array. ex: $_SERVER superglobal => holds information about headers, paths, and script locations. ex: $_SERVER['HTTP_HOST'] => Returns the Host header from the current request
- local: var declared within a function have local scope, and can only be acccessed within that function.
- static: this is still a local var declared within a func, but we can declare it to be static, which will prevent the var from getting deleted when exiting the func. So, next time func is called, value of the var from last time is still preserved.
7. operators: php divides operators in following groups:
- arithmetic operators: used on numerical values. +, -, *, /, % (modulus), ** (exponentiation)
- assignment opeartors: used to assign values to var. =, +=, -=, *=, /=, %= (a +=b is same as a=a+b)
- comparison operators: ==, === (both equal and same type), !=, !==, <, >, <=, >=
- increment/decrement operator: ++$x (pre increment, increment $x first, then return $x), $x++ (post increment, return $x first, then increment $x), --$x, $x--
- logical operators: and (same as &&), or (Same as ||), xor, ! (not). ex: $a = $x and $y; $b = !$a; $c = $a || $b;
- string operators: . (Concatenation), .=(conctenation assignment, $a .= $b is same as $a = $a . $b). ex: $c = $a . $b (concatenates string $a and $b, to form new string $c, with no space in b/w $a and $b)
- array operators: +, ==, ===, !=, !== these operators same as comparison but apply to array and check key/value pair match. + implies union of 2 arrays
- conditional assignment: ?= (if else) same as in C language
8. conditional stmt:
- if else: ex: if ($cond != 0) { echo "name"; $c=$a; ... }. if-elseif: ex: if (..) { ... } elseif (...) { ... } else { ... } => these don't have semicolon as if else are just 1 big stmt. Inside { }, we should have ; for each stmt. else, elseif are all optional.
- switch: to select one of many blocks of code
- loops: while, do while, for, foreach
9. display: various inbuilt functions avalable to display on scrren. i.e. echo(), print(), print_r().
echo and print are used to display values/text. Both can be used with or w/o parentheses (i.e print "a"; or print("a");). echo works same way as linux echo. ex: echo "My $name"; echo "me" . $name . "and"; print syntax same as echo. One diff is that print returns a value of 1, while echo doesn't return any value. So, print can be used in expressions. Both stmt can contain html markup code in them (i.e print "<b> Hi </b>";). prinrt_r() is used to display values in nice human readable format. print_r can be used to display associative arrays, w/o going thru "for" loop. eg print_r($age); where $age is an associative array.
10. functions: besides the built in functions, we can define our own function using "function" keyword. ex: function myfunc ($a) { ...return $c; }. Now myfunc can be called as myfunc(5); or $a=myfunc("hello"); Functions may or may not have a return value.
php forms:
- $_REQUEST
- $_POST
- $_GET']
Php cookies and sessions: good link here: http://shiflett.org/articles/the-truth-about-sessions
cookies:
A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's computer. Cookie is a human readable text file. Each time the same computer requests a page with a browser, it will send the cookie too. The server reads these cookies and determines various info about the user stored in cookies. These cookies need to be stored in client's computer by the server in the very beginning. With PHP, you can both create and retrieve cookie values. It is upon the browser to accept or decline cookies. Some websites demand that you agree to store cookies, or they refuse to show you the webpage.
setcookie(name) => this func sets cookie name. other optional parameters as cookie value, expiry time, etc may be set too, If expiry time not set, then cookie destroyed on closing the browser or that tab of browser.
ex: setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); This has expiration time in future = 86400 * 30 sec = 30 days from current time. (since 1 day = 86400 seconds). To delete a cookie, set it's expiration time in past. setcookie should be the very first thing to do in any php file, before we write out any html code using <html> tag.
superglobal var $_COOKIE stores the value of cookie. i.e $_COOKIE[$name] gives the value of cookie with name $name.
ex: if ( isset($_COOKIE[$cookie_name])) { echo "Value is: " . $_COOKIE[$cookie_name]; } //function isset checks if $_COOKIE[name] is null or has any value
Note: The value of the cookie is automatically URLencoded when sending the cookie, and automatically decoded when received (to prevent URLencoding, use setrawcookie()
instead).
how cookies work:
So, the way cookie's work, is when a browser calls www.xyz.com/index,php, it causes the webserver to process index.php file. index.php has setcookie() function before any <html> tag in the file. This setcookie function is written as some conditional stmt, so that if that request is coming from a client computer for the first time, only then this setcookie func is called. The cookie values are sent by client, in the HTTP header of the request (header has lot of other info also, besides cookie info). $_COOKIE var extracts and stores these cookie values. Depending on whether the header sent by client has "cookie values" in it or not, $_COOKIE may contain these values or be empty.
ex: if (count ($_COOKIE) == 0) { setcookie ... } else {read cookie values from request sent by browser} => this cmd sets cookie only if number of cookies stored in $_COOKIE var is 0. This code sits before any <html> tag.
This causes the cookie to be set if it was already empty, so that the next response sent by server (which is actually the response to this request sent by client), will include these cookie name/value pairs in the HTTP header of response. NOTE: $_COOKIE stores cookie values that come in the request header of client. If client header doesn't have these cookie values in it, $_COOKIE will be null. Several copies of index.php may be running on the server at the same time, since many clients may be connecting to the same server, but each of them has their own copy running, and stores the cookie value received from header of client response in superglobal var $_COOKIE. So, $_COOKIE value is unique for each client connection, even though the same index.php script is running for all clients. If there is some other script as welcome.php running on server, it will have it's own unique values stored in $_COOKIE depending on what the browser sent it. If browser sent same cookie value for other scripts, then $_COOKIE will have same value for other script too.
We can check the request header sent by the client by opening "web developer" in the "open menu" icon on far right of "firefox" web browser. Within "web developer", we will see "storage inspector". Clicking this will open a new section on bottom of that firefox page. Here we will see a lot of tabs along with "storage" tab. Clicking on storage tab will show couple of sections on right side, one of which is "ccokies". Clicking on "cookies" will show all the cookie values stored by that website on this computer.
If we click on "network" tab instead of "storage" tab, we'll see all the http request/response sent/received by the user computer, time it took, etc. This request/response has multiple lines. First line is the request/response line. 2nd line is required header "Host". After that we can have multiple optional headers. One of such optional headers is "Cookie" for request, and "Set-Cookie" for response. A very good site explaining this is here: http://shiflett.org/articles/the-truth-about-sessions. If we click on the latest http request sent by the browser (shown at the bottom of all requests in the "network" tab of firefox), it will show the http request header sent by the client, as well as the http response header received by the client (which was sent by the webserver after processing the http request sent by the client). In request header, we should see a "Cookie" as one of the headers being sent. It should have name/value pair, if the cookie is set on client's m/c already. If the client m/c is visiting this website for first time, then this info may be absent from http request header. Similarly in the response header sent by webserver, we'll see a "Set-Cookie" header being sent (if setcookie function was called in the php script run by the server, for that request). If setcookie function was not called, then this header will be absent from response. This is a very good way to debug and understand how cookies are being sent and received.
Sessions:
Once the cookie name/value pair is set on user m/c, the cookie is stored on user's computer for ever, until it expires. Sometimes, we do not want the info to be stored for ever. We want info to be stored when the user visits our webserver using a browser, and remain stored, until the user closes the browser or that tab of browser. Also, cookie have another problem, where cookies are stored on user's computer, which makes it a security hole. Cookies do not allow info to be accessed across all pages of a website (or they have to be passed individually to each page, and we have little control on which pages can or cannot access these cookie variables).
These issues are resolved via a session. sessions are similar to cookies in many aspects. session is basically treating website as an application started by a particular user. It stores info related to that user across all pages of a website, so that all pages can uniquely identify the user. It does this by setting a user-key cookie on the user's computer. This cookie name is "PHPSESSID" and it has value that looks something like this: 765487cf34ert8dede5a562e4f3a7e12. It's expiry is set to "session" (i.e expires when user closes the browser or tab). Then, when a session is opened on another page, it scans the computer for this cookie. If there is a match, it accesses that session, if not, it starts a new session.
A session is started with the session_start()
function. This causes cookie "PHPSESSID" to be stored with a large random value on user's m/c. This cookie is just like any other cookie, and can be read via $_COOKIE["PHPSESSID"]. IThis cookie is used to uniquely identify the connection of this website to the user's m/c. f this cookie was already set, then session_start() function doesn't set it, but just reads it. Once session_start() function is called, and a session has been started, other session var can now be set. Session variables are set with the PHP global variable: $_SESSION (i.e $_SESSION["user"] = "Matt"); Now we can access this session var "user" in any other script too, by reading $_SESSION["user"]. session_start() function needs to be put before any <html> tags. It's put in all the pages, wherever we need to access these session var. As explained above, session_start() doesn't always start a new session (it starts new session only if it finds no user-key match on reading PHPSESSID cookie),
PHP session expire on closure of window/tab of browser. They also have a default timeout limit of 1440 sec (24 min). So, if session is inactive for more than 24 min, the session var $_SESSION gets unset (i.e it stores nothing). Note that the cookie PHPSESSID still remains valid, and can be read in any php script even after timeout, as long as the browser/tab is not closed.
ex: Below we show 2 scripts. Both scripts can access the same session var.
script_1.php
<?php session_start(); ?> // PHPSESSID cookie is set with random key, if not already set
<html>
<body>
<?php $_SESSION["userName"] = "raj"; // $_SESSION superglobal var is set in this script, but is accessible from any script. This var is set to this value only for this PHPSESSID cookie.
print_r($_SESSION); ?>
</body>
</html>
script_2.php
<?php session_start(); ?> // PHPSESSID cookie is not set here, since the script finds this cookie on user m/c already set. So, it reads the cookie session value, and on a match, starts the same session as in script_1.php
<html>
<body>
<?php
if (isset($_SESSION['$userName'])) {
echo "Your session is running " . $_SESSION['$userName'];
}
?>
</body>
</html>
sql database:
php allows to connect to and manipulate database. We'll talk about mysql database connections via php scripts. Read mysql tutorial section before reading this section. Before php5, MySQL extension was used to connect to MySQL db, but from php5 onwards, MySQLi (MySQL improved) and PDO (PhP data objects) extensions provided (MySQL was deprecated in 2012). MySQLi can only connect to MySQL db, but PDO can connect to many other db too. However, PDO is more complex, so we'll concentrate on MySQLi only.
MySQLi is object oriented, but supports procedural calls too (i.e can work like a function call too, for folks who don't like to code in object oriented format). We'll focus on using mysqli as a function as that's easier to learn.
The PHP functions for use with MySQL have the following general format −
mysqli_function(value,value,...);
The second part of the function name is specific to the function, usually a word that describes what the function doest The following are two of the common functions:
$connect = mysqli_connect($servername, $username, $passwd); //connects to a db. It has return value of link identifier of mysql db server on success, and FALSE on fail. This link identifier is used to perform any operation on this mysql db server
mysqli_query($connect,"SQL statement"); //performs operations on db
NOTE: we can connect to mysql server only with the username who is listed as user in "user" table of "sql" database. If we haven't added any user to mysql server previously,
then root is the only user allowed. However, if I try to connect to mysql from php script as "root" user, I get an "access denied error" for user "root@localhost".So, add another user to
php, and connect as that user.
ex: The php script below very useful to check if your browser can connect to mysql db on a server. This should be the first script to run on any 3rd party webhost server, on which you have your website and mysql db hosted.
<?php
$servername = "localhost"; //name of server, if running on same m/c, use localhost
$username = "username"; //any valid username other than "root"
$password = "password"; //password for that user
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection.
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
//create database
$sql = "CREATE DATABASE myDB";
if (mysqli_query($conn, $sql)) {
echo "Database created successfully";
} else {
echo "Error creating database: " . mysqli_error($conn);
}
//create/insert etc .. any sql cmd can be issued to this db
$sql = "CREATE TABLE MyGuests ( ..., )"; //or "INSERT INTO ....,
if (mysqli_query($conn, $sql)) {
echo "operation successful";
} else {
echo "Error in operation: " . mysqli_error($conn);
}
//queries on db, requires other functions (as mysqli_num_rows(), mysqli_fetch_assoc(), etc) to process and display results of query
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
---------------------------------------------