Unit1 WT
Unit1 WT
Introduction to PHP:
Simplicity
Declaring variables,
Efficiency
data types, arrays, strings,
operators, expressions, Security
controlstructures, Flexibility
functions, Familiarity
Reading data from web form controls like text boxes, radio buttons, lists etc., All PHP code must be included inside one of the three special markup tags are recognized
Handling File Uploads. Connecting to database (MySQL as reference), executing by the PHP Parser.
simple queries,handling results,
Handling sessions and cookies
File Handling in PHP: File operations like opening, closing, reading, writing,
appending, deleting etc. on text and binary files, listing directories.
As we have mentioned previously, internally, the number becomes a floating point value.
var_dump(): The PHP var_dump() function returns the data type and value.
PHP Doubles or 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 syntaxes to create floating point values.
The $d variable is assigned a
<?php large number, so it is
$a = 1.245; automatically converted to
$b = 1.2e3; float type.
$c = 2E-10;
$d = 1264275425335735;
var_dump($a);
var_dump($b);
var_dump($c);
var_dump($d);
?> This is the output of beside scrip
PHP Boolean
A Boolean represents two possible states: TRUE or FALSE.
$x = true; $y = false;
Booleans are often used in conditional testing.
<?php
$male = False;
$r = rand(0, 1);
$male = $r ? True: False; if
($male) {
echo "We will use name John\n";
} else {
echo "We will use name Victoria\n";
} ?> ?> output: 6
Tip: The first character position in a string is 0 (not 1).
The script uses a random integer generator to simulate our case. $r = rand(0, 1);
Replace Text within a String
The rand( ) function returns a random number from the given integer boundaries 0 or 1.
The PHP str_replace() function replaces some characters with some other characters in a
$male = $r? True: False;
string. The example below replaces the text "world" with "Dolly":
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.
PHP Strings
String is a data type representing textual data in computer programs. Probably the single
most important data type in programming.
<?php
$a = "PHP ";
$b = 'PERL';
echo $a . $b; ?>
Output: PHP PERL
We can use single quotes and double quotes to create string literals.
The script outputs two strings to the console. The \n is a special sequence, a new line.
The escape-sequence replacements are −
\n is replaced by the newline character
\r is replaced by the carriage-return
character \t is replaced by the tab
character
\$ is replaced by the dollar sign itself ($)
\" is replaced by a single double-quote (")
\\ is replaced by a single backslash (\)
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:
<?php
$txt1="Hello Kalpana!";
$txt2="What a nice day!"; echo
$txt1 . " " . $txt2;
?> O/P: Hello Kalpana! What a nice day!
Search for a Specific Text within a String
The PHP strpos() function searches for a specific text within a string. If a match is found,
the function returns the character position of the first match. If no match is found, it
will return FALSE. The example below searches for the text "world" in the string "Hello
world!":
Example
<?php
echo strpos("Hello world!", "world");
$my_var = null;
Example A variable that has been assigned NULL has the following properties −
<?php It evaluates to FALSE in a Boolean context.
echo str_replace("world", "Kalpana", "Hello world!"); It returns FALSE when tested with IsSet() function.
?> Output: Hello Kalpana!
The strlen() function: Tip: If a variable is created without a value, it is automatically assigned a value of NULL.
The strlen() function is used to return the length of a string. Let's find the length of a string: Variables can also be emptied by setting the value to NULL:
Eg: <?php
echo strlen("Hello world!"); ?> The output of the code above will be: 12 Example1
<?php
PHP Array $x = "Hello world!";
Array is a complex data type which handles a collection of elements. Each of the elements $x = null; var_dump($x);
can be accessed by an index. An array stores multiple values in one single variable. In the ?>
following example $cars is an array. The PHP var_dump() function returns the data type
and value: PHP Resource
Example The special resource type is not an actual data type. It is the storing of a reference to
<?php functions and resources external to PHP. A common example of using the resource data
$cars = array("Volvo","BMW","Toyota"); type is a database call. Resources are handlers to opened files, database connections or
print_r($cars); image canvas areas. We will not talk about the resource type here, since it is an advanced
var_dump($cars); topic.
?> constant() function
The array keyword is used to create a collection of elements. In our case we have names.
As indicated by the name, this function will return the value of the constant. This is useful
The print_r function prints human readable information about a variable to the console.
when you want to retrieve value of a constant, but you do not know its name, i.e. It is
stored in a variable or returned by a function.constant() example
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 traditional to name it $i.
Example
The following example makes five iterations and changes the assigned value of two
variables on eachpass
` of the loop −
Example
This 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.
<html>
<body>
<?php { </body> </html>
$i = 0; code to be executed; This will produce the following result −
} Value is 1
Example Value is 2
$num = 50; while( Value is 3
$i < 10) Try out beside example to list out the
values of an array. Value is 4
{ Value is 5
$num--;
$i++;
}
echo ("Loop stopped at i = $i and num = $num" );
?> </body> </html>
This will produce the following result –
Syntax
Example
The 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 −
<html> }while( $i < 10 );
<body> echo ("Loop stopped at i = $i" );
<?php ?>
$i = 0; $num = 0; do{ </body>
$i++; </html>
O/P: Loop stopped at i = 10
<html> <html>
<head> <head>
<title>Dynamic Function Calls</title> <title>Dynamic Function Calls</title>
</head> </head>
<body> <body>
<?php <?php
function sayHello() function add($x,$y) The PHP default variable $_PHP_SELF is used for the PHP script name and when you
{ { click "submit" button then same PHP script will be called and will produce followingresult
echo "Hello<br />"; echo "addition=" . ($x+$y);
} } The method = "POST" is used to post user data to the server script.
$function_holder = "sayHello"; $function_holder = "add"; PHP Forms and User Input:
$function_holder(); $function_holder(20,30); The PHP $_GET and $_POST variables are used to retrieve information from forms, like
?> </body> </html> ?> </body> </html> user input.
Output: Hello PHP - GET & POST Methods
Output: addition=50 There are two ways the browser client can send information to the web server.
PHP Default Argument Value The GET Method
The following example shows how to use a default parameter. If we call the function The POST Method
setHeight() without arguments it takes the default value as argument: Before the browser sends the information, it encodes it using a scheme called URL
encoding or URL Parameters. In this scheme, name/value pairs are joined with equal
Example
<?php
function setHeight($minheight = 50) { echo
"The height is : $minheight \t"; signs and different pairs are separated by the ampersand.
}
The GET Method
setHeight(350);
The GET method sends the encoded user information appended to the page request. The
setHeight(); // will use the default value of 50
setHeight(135);
setHeight(80);
?> page and the encoded information are separated by the ?character.
O/P: 350 50 135 80 The GET method produces a long string that appears in your server logs, in the browser's
Location: box.
PHP -Web Concepts and Reading data from WEB The GET method is restricted to send upto 1024 characters only.
Identifying Browser & Platform Never use GET method if you have password or other sensitive information to be sent
to the server.
PHP creates some useful environment variables that can be seen in the phpinfo.php GET can't be used to send binary data, like images or word documents, to the server.
page that was used to setup the PHP environment. One of the environment variables set by The PHP provides $_GET associative array to access all the sent information using GET
PHP is HTTP_USER_AGENT which identifies the user's browser and operating system. method.
Using HTML Formwith name validation in PHP: test.php
$_GET is an array of variables passed to the current script via the URL parameters.
$_POST is an array of variables passed to the current script via the HTTP POST method.
The data in a MySQL database are stored in tables. A table is a collection of related data, and it consists of columns and
rows.
Databases are useful for storing information categorically. A company may have a database with the following tables:
Employees
Products
Customers
Orders
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
You will need special CREATE privileges to create or to delete a MySQL database.
<?php The SQL query must be quoted in PHP
$servername = "localhost"; String values inside the SQL query must be quoted
$username = "username"; Numeric values must not be quoted
$password = "password"; The word NULL must not be quoted
// Create connection
$conn = new mysqli($servername, $username, $password); <?php
// Check connection $servername = "localhost";
if ($conn->connect_error) { $username = "username";
die("Connection failed: " . $conn->connect_error); $password = "password";
} $dbname = "myDB";
$conn->close();
?> Here is the detail of all the arguments −
Name − This sets the name of the cookie and is stored in an environment variable
The SELECT statement is used to select data from one or more tables: called HTTP_COOKIE_VARS. This variable is used while accessing cookies.
Value − This sets the value of the named variable and is the content that you
SELECT column_name(s) FROM table_name actually want to store.
Expiry − This specify a future time in seconds since 00:00:00 GMT on 1st Jan 1970.
<?php After this time cookie will become inaccessible. If this parameter is not set then
$servername = "localhost"; cookie will automatically expire when the Web Browser is closed.
$username = "username"; Path − This specifies the directories for which the cookie is valid. A single forward
$password = "password";
$dbname = "myDB";
slash character permits the cookie to be valid for all directories.
Domain − This can be used to specify the domain name in very large domains and
// Create connection must contain at least two periods to be valid. All cookies are only valid for the host
$conn = new mysqli($servername, $username, $password, $dbname); and domain which created them.
// Check connection Security − This can be set to 1 to specify that the cookie should only be sent by
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error); secure transmission using HTTPS otherwise set to 0 which mean cookie can be sent
} by regular HTTP.
Following example will create two cookies name and age these cookies will be expired
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql); after one hour.
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
PHP -Cookies
Cookies are text files stored on the client computer and they are kept of use tracking
purpose. PHP transparently supports HTTP cookies.
There are three steps involved in identifying returning users −
Server script sends a set of cookies to the browser. For example name, age, or
identification number etc.
Browser stores this information on local machine for future use.
When next time browser sends any request to web server then it sends those cookies
information to the server and server uses that information to identify the user.
Setting Cookies with PHP
PHP provided setcookie() function to set a cookie. This function requires upto six
arguments and should be called before <html> tag. For each cookie this function has to be
Accessing Cookies with PHP
PHP provides many ways to access cookies. Simplest way is to use either $_COOKIE or Deleting Cookie with PHP
$HTTP_COOKIE_VARS variables. Following example will access all the cookies set in above Officially, to delete a cookie you should call setcookie() with the name argument only but
example. this does not always work well, however, and should not be relied on.
You can use isset() function to check if a cookie is set or not. It is safest to set the cookie with a date that has already expired –
PHP - Session
When you work with an application, you open it, do some changes, and then you close it.
This is much like a Session.
Session ID is stored as a cookie on the client box or passed along through URL's.
The values are actually stored at the server and are accessed via the session id from your
cookie. On the client side the session ID expires when connection is broken.
Session variables solve this problem by storing user information to be used across
multiple pages (e.g. username, favorite color, etc). By default, session variables last until
the user closes the browser.
Session variable values are stored in the 'superglobal' associative array '$_SESSION'
File Handling in PHP: File operations like opening, closing, r Open a file for read only. File pointer starts at the beginning of the file
reading, writing, appending, deleting etc. on text and binary
files, listing directories. w Open a file for write only. Erases the contents of the file or creates a new file if it doesn't exist. F
a Open a file for write only. The existing data in file is preserved. File pointer starts at the end of
PHP Manipulating Files x Creates a new file for write only. Returns FALSE and an error if file already exists
PHP has several functions for creating, reading, uploading, and editing files. r+ Open a file for read/write. File pointer starts at the beginning of the file
w+ Open a file for read/write. Erases the contents of the file or creates a new file if it doesn't exist.
a+ Open a file for read/write. The existing data in file is preserved. File pointer starts at the end o
PHP readfile() Function x+ Creates a new file for read/write. Returns FALSE and an error if file already exists
The readfile() function reads a file and writes it to the output buffer.
Assume we have a text file called "webdictionary.txt", stored on the server, that looks like PHP Read File - fread()
this:
The fread() function reads from an open file.
AJAX = Asynchronous JavaScript and XML
The first parameter of fread() contains the name of the file to read from and the second
CSS = Cascading Style Sheets
parameter specifies the maximum number of bytes to read.
HTML = Hyper Text Markup Language
PHP = PHP Hypertext Preprocessor
The following PHP code reads the "webdictionary.txt" file to the end:
SQL = Structured Query Language
SVG = Scalable Vector Graphics
XML = EXtensible Markup Language fread($myfile,filesize("webdictionary.txt"));
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!"); The fclose() requires the name of the file (or a variable that holds the filename) we want to
echo fread($myfile,filesize("webdictionary.txt")); close:
fclose($myfile);
?>
<?php
$myfile = fopen("webdictionary.txt", "r");
// some code to be executed.... PHP Create File - fopen()
fclose($myfile);
?> The fopen() function is also used to create a file. Maybe a little confusing, but in PHP, a file is
created using the same function used to open files.
If you use fopen() on a file that does not exist, it will create it, given that the file is opened
PHP Read Single Line - fgets() for writing (w) or appending (a).
The fgets() function is used to read a single line from a file. $myfile = fopen("testfile.txt", "w")
The example below outputs the first line of the "webdictionary.txt" file:
PHP Write to File - fwrite()
The fwrite() function is used to write to a file.
Example
The first parameter of fwrite() contains the name of the file to write to and the second
parameter is the string to be written.
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!"); The example below writes a couple of names into a new file called "newfile.txt":
echo fgets($myfile);
fclose($myfile);
?> <?php
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = "John Doe\n";
fwrite($myfile, $txt);
PHP Read Single Character - fgetc() $txt = "Jane Doe\n";
fwrite($myfile, $txt);
fclose($myfile);
The fgetc() function is used to read a single character from a file.
?>
The example below reads the "webdictionary.txt" file character by character, until end-of-file
is reached: PHP Append Text
You can append data to a file by using the "a" mode. The "a" mode appends text to the end of
Example the file, while the "w" mode overrides (and erases) the old content of the file.
In the example below we open our existing file "newfile.txt", and append some text to it
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
// Output one character until end-of-file <?php
while(!feof($myfile)) { $myfile = fopen("newfile.txt", "a") or die("Unable to open file!");
echo fgetc($myfile); $txt = "Donald Duck\n";
} fwrite($myfile, $txt);
fclose($myfile); $txt = "Goofy Goof\n";
?> fwrite($myfile, $txt);
fclose($myfile);
?>
PHP Delete File - unlink() opendir() Opens a directory handle
In PHP, the unlink() function is used to delete a file from the file system. It accepts a readdir() Returns an entry from a directory handle
single argument, which is the path to the file that needs to be deleted.
rewinddir() Resets a directory handle
Here is the syntax of the unlink() function:
scandir() Returns an array of files and directories of a specified directory
bool unlink ( string $filename [, resource $context ] )
In this example, we first check if the file exists using the file_exists() function. If the
file exists, we attempt to delete it using the unlink() function. If the unlink() function
returns true, we display a success message. If it returns false, we display an error
message.
It is important to note that the unlink() function permanently deletes the file, so be
careful when using it. Once a file is deleted using unlink(), it cannot be recovered.
Conclusion
File handling in PHP involves opening, reading, writing, and manipulating files stored on
a file system.
The fopen() function is used to open a file for reading, writing, or appending.
The fwrite() function is used to write to a file, while the fread() function is used to read
from a file.
The fgets() function can be used to read a single line from a file.
The fclose() function should be used to close a file after reading or writing to it.