Unit Third
Unit Third
We can create and use forms in PHP. To get form data, we need to use PHP superglobals $_GET and $_POST. The
form request may be get or post. To retrieve data from get request, we need to use $_GET, for post request $_POST.
<html>
<body>
<input type="submit">
</form>
</body>
</html>
Let's see a simple example to receive data from get request in PHP
1. <?php
2. $name=$_GET["name"];//receiving name field value in $name variable
3. echo "Welcome, $name";
4. ?>
The data passed through post request is not visible on the URL browser so it is secured. You can send large amount
of data through post request.
Let's see a simple example to receive data from post request in PHP
1. <?php
2. $name=$_POST["name"];//receiving name field value in $name variable
3. $password=$_POST["password"];//receiving password field value in $password variable
4.
5. echo "Welcome: $name, your password is: $password";
6. ?>
Output:
$GLOBALS
$_SERVER
$_REQUEST
$_POST
$_GET
PHP $GLOBALS
$GLOBALS is a PHP super global variable which is used to access global variables from anywhere in the PHP
script (also from within functions or methods).
PHP stores all global variables in an array called $GLOBALS[index]. The index holds the name of the variable.
The example below shows how to use the super global variable $GLOBALS:
Example
<?php
$x = 75;
$y = 25;
function addition() {
$GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y'];
}
addition();
echo $z;
?>
PHP $_SERVER
$_SERVER is a PHP super global variable which holds information about headers, paths, and script locations.
The example below shows how to use some of the elements in $_SERVER:
Example
<?php
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'];
?>
PHP $_REQUEST
PHP $_REQUEST is a PHP super global variable which is used to collect data after submitting an HTML form.
The example below shows a form with an input field and a submit button. When a user submits the data by clicking
on "Submit", the form data is sent to the file specified in the action attribute of the <form> tag. In this example, we
point to this file itself for processing form data. If you wish to use another PHP file to process form data, replace that
with the filename of your choice. Then, we can use the super global variable $_REQUEST to collect the value of the
input field:
Example
<html>
<body>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input field
$name = $_REQUEST['fname'];
if (empty($name)) {
echo "Name is empty";
} else {
echo $name;
}
}
?>
</body>
</html>
PHP $_POST
PHP $_POST is a PHP super global variable which is used to collect form data after submitting an HTML form with
method="post". $_POST is also widely used to pass variables.
The example below shows a form with an input field and a submit button. When a user submits the data by clicking
on "Submit", the form data is sent to the file specified in the action attribute of the <form> tag. In this example, we
point to the file itself for processing form data. If you wish to use another PHP file to process form data, replace that
with the filename of your choice. Then, we can use the super global variable $_POST to collect the value of the
input field:
Example
<html>
<body>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input field
$name = $_POST['fname'];
if (empty($name)) {
echo "Name is empty";
} else {
echo $name;
}
}
?>
</body>
</html>
PHP $_GET
PHP $_GET is a PHP super global variable which is used to collect form data after submitting an HTML form with
method="get".
<html>
<body>
</body>
</html>
When a user clicks on the link "Test $GET", the parameters "subject" and "web" are sent to "test_get.php", and you
can then access their values in "test_get.php" with $_GET.
Example
<html>
<body>
<?php
echo "Study " . $_GET['subject'] . " at " . $_GET['web'];
?>
</body>
</html>
Superglobal Arrays
The PHP Superglobals are a handful of arrays that provide to a PHP script global access to data originating
externally. Whereas PHP scripts contain variables that are local to that script and functions may have variables that
are only accessible within that function therefore the PHP Superglobals represent data coming from URLs, HTML
forms, cookies, sessions, and the Web server itself.
$HTTP_GET_VARS, $HTTP_POST_VARS, etc., served these same purposes but the PHP superglobal variables
are better in that they can also be accessed within any functions (i.e., they have global scope).
$_GET
The $_GET Superglobal represents data sent to the PHP script in a URL. This applies both to directly accessed
URLs (e.g., http://www.example.com/page.php?id=2) and form submissions that use the GET method.
$_POST
The $_POST Superglobal are used to send data to the PHP script via HTTP POST. This is normally a form with a
method of POST.
$_COOKIE
The $_COOKIE Superglobal represents data available to a PHP script via HTTP cookies.
$_REQUEST
$_SESSION
The $_SESSION Superglobal represents data available to a PHP script that has previously been stored in a session.
$_SERVER
The $_SERVER Superglobal represents data available to a PHP script from the Web server itself. Common uses of
$_SERVER is to refer to the current PHP script ($_SERVER[‘PHP_SELF’]), the path on the server to that script,
the hostname, and so on.
$_ENV
The $_ENV Superglobal represents data available to a PHP script from the environment in which PHP is running.
$_FILES
The $_FILES Superglobal represents data available to a PHP script from HTTP POST file uploads. Using $_FILES
is the currently preferred way to handle uploaded files in PHP.
It is possible, but not recommended, to import fields from a form submission into global variables. This behavior
was once the default for PHP. Although it was useful for quick scripts, it represented a security risk, with the
prospect of user-submitted values overwriting script variables. You can change the new default by altering
the php.ini file. You can also import user input explicitly with the import_request_variables() function. This function
requires a string representing the types to import and another optional but advisable string that adds a prefix to all
imported variable names. The types argument can be any combination of g, p and c, standing for get, post,
and cookies, respectively. If you only use one or two of these letters, then only the corresponding parameters are
imported. The order is important in that earlier types are overwritten by later ones. That is, with the
string gp, get variables are overwritten by post variables of the same name. Suppose an input element
called username is submitted via the get method:
<input type="text" name="username" />
This line would create a global variable called $import_username, containing the user-submitted value for
the username field. All other fields submitted would be similarly imported.
You can also import user input explicitly with the import_request_variables() function. This function requires a
string representing the types to import and another optional but advisable string that adds a prefix to all imported
variable names.
The examples so far enable us to gather information from HTML elements that submit a single value per element
name. This leaves us with a problem when working with SELECT elements. These elements make it possible for the
user to choose multiple items. If we name the SELECT element with a plain name
the script that receives this data will only have access to a single value corresponding to this name. We can change
this behavior by renaming any elements of this kind so that its name ends with an empty set of square brackets.
You can add PHP tags to your HTML Page. You simply need to enclose the PHP code with the PHP starts tag <?
php and the PHP end tag ?>. The code wrapped between these two tags is considered to be PHP code, and it will be
executed on the server-side before the requested file is sent to the client browser.
Syntax:
<html>
</html>
Example
<html>
<head>
<style>
h1 {
color: green;
</style>
</head>
<body>
<center>
<h1>Welcome To
GFG</h1>
<p>
<?php
echo "Complete
<strong>Portal</strong> for
Geeks."
?>
<br><br>
<?php
?>
</p>
</center>
</body>
</html>
Output:
Syntax:
<input type="hidden">
Example:
<html>
<head>
<title>
</title>
<style>
h1 {
color: green;
body {
text-align: center;
</style>
</head>
<body>
<h1>
GeeksforGeeks
</h1>
<h3>
</h3>
<form action="#">
</form>
</body>
</html>
Output:
Redirection in PHP
Redirection from one page to another in PHP is commonly achieved using the following two ways:
The header() function is an inbuilt function in PHP which is used to send the raw HTTP (Hyper Text Transfer
Protocol) header to the client.
Syntax:
Parameters: This function accepts three parameters as mentioned above and described below:
$replace: This parameter is used to hold the replace parameter which indicates the header should replace a previous
similar header, or add a second header of the same type. It is optional parameter.
$http_response_code: This parameter hold the HTTP response code.
<?php
// Redirect browser
header("Location: https://www.geeksforgeeks.org");
exit;
?>
Syntax
1. resource fopen ( string $filename , string $mode [, bool $use_include_path = false [, resource $context ]] )
Example
1. <?php
2. $handle = fopen("c:\\folder\\file.txt", "r");
3. ?>
Syntax
Example
<?php
fclose($handle);
?>
Example
<?php
$filename = "c:\\myfile.txt";
fclose($handle);//close file
?>
Output
Syntax
Example
<?php
fclose($fp);
?>
Output
Syntax
Example
<?php
unlink('data.txt');
?>
The directory functions allow you to retrieve information about directories and their contents.
Installation
The PHP directory functions are part of the PHP core. No installation is required to use these functions.
Function Description
<?php
// Change directory
chdir("images");
echo getcwd();
?>
Result:
/home/php
/home/php/images
<?php
chroot("/path/to/chroot/");
// Get current directory
echo getcwd();
?>
Result:
<?php
$dir = "/images/";
if (is_dir($dir)){
if ($dh = opendir($dir)){
closedir($dh);
?>
Result:
filename: cat.gif
filename: dog.gif
filename: horse.gif
$d = dir(getcwd());
$d->close();
?>
Result:
Handle: Resource id #2
Path: /etc/php
filename: .
filename: ..
filename: ajax.gif
filename: books.xml
filename: cdcatalog.xml
filename: cd_catalog.xml
filename: default.asp
filename: demo_array.asp
filename: demo_array.htm
...
...
...
<?php
echo getcwd();
?>
Result:
/home/php
<?php
$dir = "/images/";
if (is_dir($dir)){
if ($dh = opendir($dir)){
closedir($dh);
?>
Result:
filename: cat.gif
filename: dog.gif
filename: horse.gif
$dir = "/images/";
if (is_dir($dir)){
if ($dh = opendir($dir)){
closedir($dh);
?>
Result:
filename: cat.gif
filename: dog.gif
filename: horse.gif
Open a directory, list its files, reset directory handle, list its files once again, then close:
<?php
$dir = "/images/";
if (is_dir($dir)){
if ($dh = opendir($dir)){
}
rewinddir();
closedir($dh);
?>
Result:
filename: cat.gif
filename: dog.gif
filename: horse.gif
filename: cat.gif
filename: dog.gif
filename: horse.gif
<?php
$dir = "/images/";
$a = scandir($dir);
$b = scandir($dir,1);
print_r($a);
print_r($b);
?>
Result:
Array
[0] => .
[1] => ..
Array
[4] => ..
[5] => .
If the new name specified by the user already exists, the rename() function overwrites it. The old name of the file
and the new name specified by the user are sent as parameters to the rename() function and it returns True on
success and a False on failure.
Syntax:
oldname : It is a mandatory parameter which specifies the old name of the file or directory.
newname : It is a mandatory parameter which specifies the new name of the file or directory.
Return Value:
The rename() function generates a Warning if the newname already exists while renaming a directory.
The wrapper used in oldname must match the wrapper used in newname.
If the destination filesystem doesn’t permit chown() or chmod() system calls to be made on files, then rename()
function may generate Warnings.
Examples:
$new_name = "newgfg.txt" ;
Syntax:
Parameters: The copy() function in PHP accepts two parameters which are source and destination.
Examples:
Output : true
$destfile = 'user01/Desktop/admin/geeksforgeeks.txt';
Output : true
However, with ease comes danger, so always be careful when allowing file uploads!
In your "php.ini" file, search for the file_uploads directive, and set it to On:
file_uploads = On
Next, create an HTML form that allow users to choose the image file they want to upload:
<!DOCTYPE html>
<html>
<body>
</form>
</body>
</html>
Using file_get_contents() function: The file_get_contents() function is used to read a file into a string. This
function uses memory mapping techniques that are supported by the server and thus enhances the performance
making it a preferred way of reading the contents of a file.
Syntax:
$start, $max_length)
Example 1: This example illustrates the use of file_get_contents() function to read the file into a string.
<?php
$url = 'https://media.geeksforgeeks.org/wp-content/uploads/gfg-40.png';
$file_name = basename($url);
if (file_put_contents($file_name, file_get_contents($url)))
else
?>
PHP Imagecreate( ) Function
Image create ( ) function is another inbuilt PHP function mainly used to create a new image. The function returns the
given image in a specific size. We need to define the width and height of the required image. Instead of the image
create ( ) function, we can also use other creative functions like imagecreatetruecolor( ), which is a better alternative
as it will return a better image quality.
Syntax
1 $ width This parameter is used to define the image's width that we want to display. Mandatory
2 $ height This parameter is used to define the height of the image that we want to display Mandatory
The image creates ( ) function returns the resource identifier of an image on successful execution of the program and
FALSE on a failed attempt.
<!DOCTYPE html>
<html lang="en">
<head>
<title>PHP</title>
</head>
<body>
<?php
Imagepng($image);
Imagedestroy($image);
?>
</body>
</html>
Output
PHP Imagecreate( ) FunctionHere in this program, we have declared various variables like $image to define the
size of the image that we require, $background color to define the color of background we require, $text color to
define the color of text we require. We have used the image string ( ) function to declare the string we want to
display as an image. To display the output of the image, we have used an inbuilt PHP command header and
imagepng to display on the browser.
Computer graphics is an art of drawing pictures on computer screens with the help of programming. It involves
computations, creation, and manipulation of data. In other words, we can say that computer graphics is a rendering
tool for the generation and manipulation of images.
The primary output device in a graphical system is the video monitor. The main element of a video monitor is the
Cathode Ray Tube CRT, shown in the following illustration.
The operation of CRT is very simple −
The electron beam passes through focusing and deflection systems that direct it towards specified positions on the
phosphor-coated screen.
When the beam hits the screen, the phosphor emits a small spot of light at each position contacted by the electron
beam.
It redraws the picture by directing the electron beam back over the same screen points quickly.
There are two ways Random scan and Raster scan by which we can display an object on the screen.
Raster Scan
In a raster scan system, the electron beam is swept across the screen, one row at a time from top to bottom. As the
electron beam moves across each row, the beam intensity is turned on and off to create a pattern of illuminated spots.
Picture definition is stored in memory area called the Refresh Buffer or Frame Buffer. This memory area holds the
set of intensity values for all the screen points. Stored intensity values are then retrieved from the refresh buffer and
“painted” on the screen one row scan line at a time as shown in the following illustration.
Each screen point is referred to as a pixel picture element. At the end of each scan line, the electron beam returns to
the left side of the screen to begin displaying the next scan line.
Raster Scan
In this technique, the electron beam is directed only to the part of the screen where the picture is to be drawn rather
than scanning from left to right and top to bottom as in raster scan. It is also called vector display, stroke-writing
display, or calligraphic display.
Picture definition is stored as a set of line-drawing commands in an area of memory referred to as the refresh display
file. To display a specified picture, the system cycles through the set of commands in the display file, drawing each
component line in turn. After all the line-drawing commands are processed, the system cycles back to the first line
command in the list.
Random-scan displays are designed to draw all the component lines of a picture 30 to 60 times each second.
Random Scan
Computer Graphics has numerous applications, some of which are listed below −
Computer graphics user interfaces GUIs − A graphic, mouse-oriented paradigm which allows the user to interact
with a computer.
Engineering drawings − mechanical, electrical, civil, etc. - Replacing the blueprints of the past.
Typography − The use of character images in publishing - replacing the hard type of the past.
Architecture − Construction plans, exterior sketches - replacing the blueprints and hand drawings of the past.