0% found this document useful (0 votes)
4 views

Practical PHP File

The document is a lab manual for a Bachelor of Computer Applications program, focusing on programming in PHP. It includes an index of practical exercises, an introduction to PHP, its features, and instructions on how to run PHP programs using XAMPP. The manual also provides detailed steps for installing XAMPP and starting PHP programming with practical examples.

Uploaded by

bp110673
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Practical PHP File

The document is a lab manual for a Bachelor of Computer Applications program, focusing on programming in PHP. It includes an index of practical exercises, an introduction to PHP, its features, and instructions on how to run PHP programs using XAMPP. The manual also provides detailed steps for installing XAMPP and starting PHP programming with practical examples.

Uploaded by

bp110673
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

Bachelor of Computer Applications

(Computer Science and Engineering)

Session 2022-23

Lab Manual

Programming in PHP laboratory

UGCA 1938

I.K. Gujral Punjab Technical University

Main campus, Kapurthala


INDEX

S.No Title Pg no.


1 Take values from user and compute sum, subtraction, multiplication, division and 11
exponent of value of the variables.
2 Write a program to find area of following shapes: circle, rectangle, triangle, square 12
trapezoid and parallelogram.
3 Compute and print roots of quadratic equation. 13
4 Write a program to determine whether triangle is isosceles or not. 14
5 Print multiplication table of a number input by user. 14
6 Calculate sum of natural number from one to n number. 15
7 Print Fibonacci series up to n number e.g. 0 1 1 2 3 5 8 13 21…..n 16
8 Write a program to find the factorial of any number. 16
9 Determine prime number within a specific range. 17
10 Write a program to compute, the Average and Grade of students marks. 18
11 Compute addition, subtraction and multiplication of a matrix. 18
12 Count total number of vowels in a word “Develop & Empower Individuals”. 20
13 Determine whether a string is palindrome or not? 21
14 Display word after sorting in alphabetical order. 21
15 Check whether a number is in a given range using function. 23
16 Write a program accepts a string and calculates number of upper case letters and 23
lower case letters available in that string.
17 Design a program to reverse a string word by word. 24
18 Write a program to create a login form. On submitting the form, the user should 24
navigate to profile page.
19 Design front page of a college or department using graphic method. 26
20 Write a program to upload and download files. 26

1
Introduction to PHP
PHP stand for Hypertext processor. It is a server side scripting language, and a powerful tool for
making dynamic and interactive web pages. PHP is widely used, free, and efficient. PHP files can
contain text, html, css, javascript and php code. PHP files are saved with .php extension.

• PHP can generate dynamic page content


• PHP can create, open, read, write, delete, and close files on the server
• PHP can collect form data
• PHP can send and receive cookies
• PHP can add, delete, modify data in your database
• PHP can be used to control user-access
• PHP can encrypt data

PHP Features
As PHP can do anything related to server-side programming which contains the backend of any web
page,
it holds a lot of unique features within it. The main purpose of PHP design is web development.
Let us look into some of the unique features of PHP:
• Simple, Familiar and ease of use: Its popularly known for its simplicity, familiarity and easy to
learn the language as the syntax is similar to that of ‘C’ or Pascal language.
So the language is very logical and well organized general-purpose programming language. Even
people with a normal programming background can easily understand and capture the use of
language. PHP is very advantageous for new users as its a very reliable, fluent, organized, clean,
demandable and efficient.
The main strength of PHP is the availability of rich pre-defined functions. The core distribution
helps the developers implement dynamic websites very easily with secured data. PHP applications
are very easy to optimize.
• Loosely typed language: PHP encourages the use of variables without declaring its data types.
So this is taken care at the execution time depending on the value assigned to the variable. Even
the variable name can be changed dynamically.
• Flexibility: PHP is known for its flexibility and embedded nature as it can be well integrated
with HTML, XML, Javascript and many more. PHP can run on multiple operating systems
like Windows, Unix, Mac OS, Linux, etc. The PHP scripts can easily run on any device like
laptops, mobiles, tablets, and computer. It is very comfortably integrated with various
Databases. Desktop applications are created using advanced PHP features. The executable PHP
can also be run on command-line as well as directly on the machine. Heavyweight applications
can be created without a server or browser.
It also acts as an excellent interface with relational databases.
• Open Source: All PHP frameworks are open sources, No payment is required for the users and
its completely free. User can just download PHP and start using for their applications or projects.
Even in companies, the total cost is reduced for software development providing more
reliability and flexibility.
It supports a popular range of databases like MySQL, SQLite, Oracle, Sybase, Informix, and
PostgreSQL.
PHP provides libraries to access these databases to interact with web servers. Developers are free
to post errors, inspect codes and can contribute to code as well as bug fixing. Many frameworks
like Codeignitor, Zend Framework, CakePHP make use of PHP.

2
Even many popular content management systems like WordPress, Joomla and Drupal use PHP
as prime language. Because of the above reasons many web hosting companies and Internet
Service providers prefers PHP.
• Cross-platform compatibility: PHP is multi-platform and known for its portability as it can run
on any operating System and windows environments. The most common are XAMPP
(Windows, Apache Server, MySQL, Perl, and PHP) and LAMP
(Linux, Apache, MySQL, PHP). As PHP is platform-independent, it’s very easy to integrate
with various databases and other technologies without re-implementation. It effectively saves a
lot of energy, time and money.
• Error reporting and exceptions: PHP supports much errors reporting constants to generate
errors and relevant warnings at run time. For
example E_ERROR, E_WARNING, E_PARSE, E_STRICT.
PHP5 supports exception handling which is used to throw errors which can be caught at any time.
• Active community support: PHP is very rich with many diverse online community developers
to help beginners for web-based applications. These worldwide volunteers contribute many
features as well as new versions for PHP libraries. Even they contribute a translation in different
languages to help out programmers. There is a bundle of third-party open-source libraries which
provide basic functionalities. Even the documentation given by the official site helps in
implementing new features providing access to a variety of creative imagination.
• Fast and efficient performance: Users generally prefer fast loading websites.
For any web development, speed becomes an important aspect which is taken care of by PHP.
PHP scripts are faster than other scripting languages like ASP.NET, PERL, and JSP. The
memory manager of PHP 7 is very optimized and fast as compared to older versions of PHP. Even
connecting to the database and loading of required data from tables, are faster than other
programming languages. It provides a built-in module for easy and efficient database management
system. The high speed of PHP is advantageous for users for its server administration and mail
functionality. Also, it supports session management and removing of unwanted memory
allocation.
• Maintenance: When dealing with big projects, maintenance of code is also an important aspect
of the web development process. There are many PHP frameworks for example MVC (Model
View Controller) which makes development and maintenance of code easier. Files belonging to
the different module are maintained separately.
• Third-party application support and security: Many PHP’s predefined functions support data
encryption options keeping it more secure. Even the users can use third-party applications to
secure data.
• Real time access monitoring: PHP also provides a summary of user’s recent logging accesses.
• Memory and CPU usage information: PHP can provide memory usage information from
functions like memory_get_usage() or memory_get_peak_usage(), which can help the
developers optimize their code. In the similar way, the CPU power consumed by any script can
be retrieved for further optimization.
• Object oriented features: PHP supports object-oriented programming features, resulting in
increased speed and introducing added features like data encapsulation and inheritance at many
levels.
• Magic Constants: PHP provides many built-in magic methods starting with __(double
underscore) which are called during specific events.
For example directory path
(__DIR__), class name (__CLASS__), namespace (__NAMESPACE__), function name
(__FUNCTION__), method name (__METHOD__), line number (__LINE__), file path
(__FILE__).

3
• Regular expression: PHP provides regular expression functions with parsing and pattern
matching methods.
• PDO Class: PHP Data Objects are created by PDO class which gives a good abstraction layer
for database drivers. The PDO Classes are enriched with functions which are database
independent. It means the same functions are used for similar actions for different databases
without re-development as long as it supports PDO. In this way, the application becomes more
portable saving lot of time and effort. Use of PDO helps the application from SQL injection
attacks.
Additional Features:
The feature list is endless. The other features of PHP are manipulation of images using GD
library, make remote connections using cURL, handling file system, managing user sessions,
track sessions, Use of SimpleXML Class which reads and write XML files through objects,
support of cookies and sessions, shell command-line execution, compression of ZIP archives,
use of Ajax.

How to run PHP programs ?

XAMPP is a Web development tool, created by Apache, that makes it easy to run PHP (Personal
Home Pages) scripts on your computer locally. Installation of XAMPP Server on windows is easy as
compared to manual installation of a web server and PHP required a lot of in-depth configuration
knowledge. XAMPP package installs MySQL, FileZilla, Mercury, Perl, and Tomcat along with Web
Server and PHP, with these applications you can test the full website on your desktop. You don’t
need to upload it every time on an online Web server.
Step 1: First of all, open the Apache Friends website and download XAMPP for Windows, and
install it.
Step 2: Start the XAMPP Program Control Panel. Click on the “Start” button next to the “Apache”
to start your Apache Web Server. Also, start “MySQL” if your PHP programs depend on a MySQL
database to run.

How to run PHP programs ?

4
Step 3: Place your PHP files in the “htdocs” folder located under the “XAMPP” folder on your drive
(i.e. C/D/E etc). The initial path is “your_drive_letter:\xampp\htdocs” for your Web server. Make
sure that your PHP files are saved as a “.php” file extension.
Example: The “demo.php” file is saved in the htdocs folder.
• PHP

<!DOCTYPE html>

<html>
<body>
<h1>Hello GFG </h1>

<?php
echo "Hello geeksforgeeks";
?>
</body>
</html>

How to run PHP programs ?

Step 4: Open up any web browser and enter “localhost/filename”. This will open the list of all the
files and folders stored under the “htdocs” folder on your computer. Click on the link to a PHP file
and open it to run a program.
Example: The file “demo.php” file is placed inside the “htdocs” folder. If you want to run it, open
any web browser and enter “localhost/demo.php” and press enter.

5
Installing XAMPP

Our XAMPP tutorial will take you through the installation process for the software package on
Windows. If you’re using Linux or Mac OS X, then the steps listed below for the installation process
may differ.

Step 1: Download
XAMPP is a release made available by the non-profit project Apache Friends. Versions with PHP
5.5, 5.6, or 7 are available for download on the Apache Friends website.

Step 2: Run .exe file


Once the software bundle has been downloaded, you can start the installation by double clicking on
the file with the ending .exe.

Step 3: Deactivate any antivirus software


Since an active antivirus program can negatively affect the installation process, it’s recommended to
temporarily pause any antivirus software until all XAMPP components have successfully been
installed.

Before installing XAMPP, it is advisable to disable the anti-virus program temporarily


Step 4: Deactivate UAC
User Account Control (UAC) can interfere with the XAMPP installation because it limits writing
access to the C: drive, so we recommend you deactivate this too for the duration of the installation
process. To find out how to turn off your UAC, head to the Microsoft Windows support pages.

User account control can affect the installation of XAMPP


Step 5: Start the setup wizard
After you’ve opened the .exe file (after deactivating your antivirus program(s) and taken note of the
User Account Control, the start screen of the XAMPP setup wizard should appear automatically.
Click on ‘Next’ to configure the installation settings.

6
You can start the setup on the startup screen
Step 6: Choose software components
Under ‘Select Components’, you have the option to exclude individual components of the XAMPP
software bundle from the installation. But for a full local test server, we recommend you install using
the standard setup and all available components. After making your choice, click ‘Next’.

In the dialog window entitled 'select components', you can choose the software components before
installation

7
Step 7: Choose the installation directory
In this next step, you have the chance to choose where you’d like the XAMPP software packet to be
installed. If you opt for the standard setup, then a folder with the name XAMPP will be created under
C:\ for you. After you’ve chosen a location, click ‘Next’.

For the next step, you need to select the directory where XAMPP should be installed
Step 8: Start the installation process
Once all the aforementioned preferences have been decided, click to start the installation. The setup
wizard will unpack and install the selected components and save them to the designated directory.
This process can take several minutes in total. You can follow the progress of this installation by
keeping an eye on the green loading bar in the middle of the screen.

8
According to the default settings, the selected software components are unpacked and installed in the
target folder
Step 9: Windows Firewall blocking
Your Firewall may interrupt the installation process to block the some components of the XAMPP.
Use the corresponding check box to enable communication between the Apache server and your
private network or work network. Remember that making your XAMPP server available for public
networks isn’t recommended.

Step 10: Complete installation


Once all the components are unpacked and installed, you can close the setup wizard by clicking on
‘Finish’. Click to tick the corresponding check box and open the XAMPP Control Panel once the
installation process is finished.

By clicking on 'finish', the XAMPP Setup Wizard is completed

The XAMPP Control Panel

Controls for the individual components of your test server can be reached through the XAMPP
Control Panel. The clear user interface logs all actions and allows you to start or stop individual
modules with a single. The XAMPP Control Panel also offers you various other buttons, including:

• Config: allows you to configure the XAMPP as well as the individual components

9
• Netstat: shows all running processes on the local computer
• Shell: opens a UNIX shell
• Explorer: opens the XAMPP folder in Windows Explorer
• Services: shows all services currently running in the background
• Help: offers links to user forums
• Quit: closes the XAMPP Control Panel

In the Control Panel, you can start and stop individual modules
Starting modules

Individual modules can be started or stopped on the XAMPP Control Panel through the corresponding
buttons under ‘Actions’. You can see which modules have been started because their names are
highlighted green under the ‘Module’ title.

10
Practical 1
Take values from user and compute sum, subtraction, multiplication, division and exponent of value
of the variables.
Sol.
<form action="p1.php >" method=post>
<label>Enter number: </label>
<input type="number" name="number1" >
<label>Enter number: </label>
<input type="number" name="number2">
<input type="submit" value="Show Result" name="res">
</form>
P1.php
<?php
if (isset($_POST[res])) {
$number1 = $_POST['number1'];
$number2 = $_POST['number2'];
echo $number1 . " + " . $number2 . " = " . $number1 + $number2 . "<br>";
echo $number1 . " - " . $number2 . " = " . $number1 - $number2 . "<br>";
echo $number1 . " X " . $number2 . " = " . $number1 * $number2 . "<br>";
echo $number1 . " / " . $number2 . " = " . $number1 / $number2 . "<br>";
echo $number1 . " ** " . $number2 . " = " . $number1 ** $number2 . "<br>";
}
?>
OutPut:

11
Practical 2
Write a program to find area of following shapes: circle, rectangle, triangle, square trapezoid and
parallelogram.
<?php
$pi = 3.14;
$rad = 3;
echo "Area of circle is: " . $pi * $rad * $rad . "<br>";
$wid = 23;
$len = 12;
echo "Area of rectangle is: " . $wid * $len . "<br>";
$height = 3;
$breadth = 6;
echo "Area of triangle is: " . ($height * $breadth) / 2 . "<br>";
$side = 4;
echo "Area of square is: " . $side * $side . "<br>";
echo "Area of trapezoid is: " . ($side + $breadth / 2) * $height . "<br>";
echo "Area of parallelogram is: " . $breadth * $height;
?>

OutPut:

12
PRACTICAL - 3
Compute and print roots of quadratic equation.
<?php
function roots($a, $b, $c) {
$D = $b*$b - 4*$a*$c;
if ($D >= 0){
$x1 = (-$b + sqrt($D))/(2*$a);
$x2 = (-$b - sqrt($D))/(2*$a);
echo "Roots are: $x1, $x2 \n";
} else {
$x1 = -$b/(2*$a);
$x2 = sqrt(-$D)/(2*$a);
echo "Roots are: $x1 ± $x2 i \n";
}
}
echo "Equation is x*x+5x+4=0\n";
roots(1,5,4);
echo "\nEquation is x*x+4x+5=0\n";
roots(1,4,5);
?>

13
PRACTICAL-4
Write a program to determine whether a triangle is isosceles or not?
<?php
$a=10;
$b=12;
$c=10;

if($a==$b || $b==$c || $a==$c){


echo"The triangle is isosceles.";
}
else{
echo"The triangle is not isosceles.";
}
?>
OUTPUT:

PRACTICAL-5
Print multiplication table of a number input by the user.
<?php
$num = readline("Enter the number: ");
echo "Multiplication table of ",$num," is\n\n";
for ($i = 1; $i <= 10; $i++) {
echo "\t", $num, " x ", $i, " = ", $num * $i, "\n";
}
?>

14
OUTPUT :

PRACTICAL-6
Calculate sum of natural numbers from one to n number.
<?php
$num = readline("Enter the n number: ");
$n = $num;
$sum = 0;
while ($n >= 0) {
$sum = $sum + $n;
$n--;
}
echo "Sum of $num number is: $sum";
?>
OUTPUT:

15
PRACTICAL-7
Print Fibonacci series up to n numbers e.g. 0 1 1 2 3 5 8 13 21…..n
<?php
function Fibonacci($n){
$num1 = 0;
$num2 = 1;

$counter = 0;
while ($counter < $n){
echo ' '.$num1;
$num3 = $num2 + $num1;
$num1 = $num2;
$num2 = $num3;
$counter = $counter + 1;
}
}
$n = 20;
Fibonacci($n);
?>
OUTPUT:

PRACTICAL-8
Write a program to find the factorial of any number.
<?php
$num = 4;
$factorial = 1;
for ($x=$num; $x>=1; $x--)
{
$factorial = $factorial * $x;

16
}
echo "Factorial of $num is $factorial";
?>
OUTPUT:

PRACTICAL-9
Determine prime numbers within a specific range.
<?php
function check_prime($num)
{
if ($num == 1)
return 0;
for ($i = 2; $i <= $num/2; $i++)
{
if ($num % $i == 0)
return 0;
}
return 1;
}
$num = 47;
$flag_val = check_prime($num);
if ($flag_val == 1)
echo "It is a prime number";
else
echo "It is a non-prime number"
?>
OUTPUT:

17
PRACTICAL-10
Write a program to compute, the Average and Grade of students marks.
<?php
$marks = 40;
if ($marks>=60)
{
$grade = "First Division";
}
else if($marks>=45)
{
$grade = "Second Division";
}
else if($marks>=33)
{
$grade = "Third Division";
}
else
{
$grade = "Fail";
}
echo "Student grade: $grade";
?>
OUTPUT:

PRACTICAL-11
Compute addition, subtraction and multiplication of a matrix.
<?php
$a = array(array(1,2,3),array(4,5,6),array(7,8,9));
$b = array(array(7,8,9),array(4,5,6),array(1,2,3));
$m=count($a);
$n=count($a[2]);

18
$p=count($b);
$q=count($b[2]);
echo "the first matrix :"."\n";
for ($row = 0; $row < $m; $row++) {
for ($col = 0; $col < $n; $col++)
echo " ".$a[$row][$col];
echo "\n";
}
echo "the second matrix :"."\n";
for ($row = 0; $row < $p; $row++) {
for ($col = 0; $col < $q; $col++)
echo " ".$b[$row][$col];
echo "\n";
}
echo "the transpose for the first matrix is:"."\n";
for ($row = 0; $row < $m; $row++) {
for ($col = 0; $col < $n; $col++)
echo " ".$a[$col][$row];
echo "\n";
}
echo "the addition of matrices is:"."\n";
for ($row = 0; $row < 3; $row++) {
for ($col = 0; $col < 3; $col++)
echo " ".$a[$row][$col]+$b[$row][$col]." ";
echo "\n";
}
echo "the subtraction of matrices is:"."\n";
for ($row = 0; $row < 3; $row++) {
for ($col = 0; $col < 3; $col++)
echo " ".$a[$row][$col]-$b[$row][$col]." ";
echo "\n";
}
echo " The multiplication of matrices: \n";
$result=array();
for ($i=0; $i < $m; $i++) {
for($j=0; $j < $q; $j++){
$result[$i][$j] = 0;
for($k=0; $k < $n; $k++)
$result[$i][$j] += $a[$i][$k] * $b[$k][$j];
}
}
for ($row = 0; $row < $m; $row++) {
for ($col = 0; $col < $q; $col++){
echo " ".$result[$row][$col];
}
echo "\n";
}
?>
OUTPUT:

19
PRACTICAL-12
Count total number of vowels in a word “Develop & Empower Individuals”.
<?php
$count=0;
$a="“Develop & Empower Individuals";
for($i=0;$i<strlen($a);$i=$i+1)
{
if($a{$i}=='a'||$a{$i}=='e'||$a{$i}=='i'||$a{$i}=='o'||$a{$i}=='u') //here $a{i} will return the
character for ith position
{
$count=$count+1;
}
}
echo "The number of vowels are:".$count;
?>
OUTPUT:

20
PRACTICAL-13
Determine whether a string is palindrome or not?
<?php
function Palindrome($string){
if (strrev($string) == $string){
return 1;
}
else{
return 0;
}
}
$original = "ANURADHA";
if(Palindrome($original)){
echo "Palindrome";
}
else {
echo "Not a Palindrome";
}
?>
OUTPUT:

PRACTICAL-14
Display word after Sorting in alphabetical order.
<?php
$string = "hijdeafgbc";
//convert string to array
$str_arr = str_split($string);
//sort into alphabetical order using sort() php function
sort($str_arr);
//convert array to string again
print implode($str_arr);
?>

21
OUTPUT:

PRACTICAL-15
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Practical 15</title>
</head>
<body>
<form action="" method="post">
Range:<br>
Start: <input type="number" name="start"><br>
End: <input type="number" name="end"><br><br>
Find: <input type="number" name="num1"><br>
<input type="submit" name="Results" value="Results">
</form>
<?php
function find_num($start, $end, $value){
$find=false;
for($i=$start;$i<=$end;$i++){
if($value==$i){$find=true;}
}
return $find;
}
if(isset($_POST['Results']))
{
$r=$_POST['start'];

22
$e=$_POST['end'];
$n=$_POST['num1'];
$result=find_num($r,$e,$n);
if($result){
echo"<br> The value is present.";
}
else{
echo"<br> The value is not present.";
}
}
?>
</body>
</html>
OUTPUT:

PRACTICAL-16
Write a program accepts a string and calculates number of upper case letters and lower case letters
available in that string.
<?php
function Countt($str)
{
$upper = 0;
$lower = 0;
for ($i = 0; $i < strlen($str); $i++)
{
if ($str[$i] >= 'A' && $str[$i] <= 'Z')
$upper++;
if ($str[$i] >= 'a' && $str[$i] <= 'z')

23
$lower++;
}
echo "Upper case letters: " , $upper,"\n" ;
echo "Lower case letters : " ,$lower,"\n" ;
}
$str = "#GeeKs01fOr@gEEks07";
Countt($str);
?>

OUTPUT:

PRACTICAL-17
Design a program to reverse a string word by word.
<?php
$inpStr = "CodeSpeedy Technologies Hello There";
$inpStrArray = explode(" ", $inpStr); #converting string to array
$revArr = array_reverse($inpStrArray); #reversing the array
echo "The reversed string words are: " . $revStr = implode(" ", $revArr);
?>
OUTPUT:

Practical 18
Write a program to create a login form. On submitting the form, the user should navigate to profile
page.
<!DOCTYPE html>
<html lang="en">
<head>

24
<title>Practical 18</title>
</head>
<body>
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post">
<div><label for="username">Enter Your Username: </label><input type="text"
name="username"></div>
<div><label for="pass">Enter Your Password: </label><input type="password"
name="pass"></div>
<div><button type="submit">Login</button></div>
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$conn = mysqli_connect("localhost", "root", "", "dbname");
if (!$conn) {
die("Error" . mysqli_connect_error());
}
$username = $_POST["username"];
$password = $_POST["pass"];
$sql = "Select * from registration where username='$username' && password='$password'";
$result = mysqli_query($conn, $sql);
$num = mysqli_num_rows($result);
if ($num == 1) {
header("Location: profile.php");
} else {
$showError = "error!!";
}
}
?>
</body>
</html>

25
Practical 19
Design front page of a college or department using graphic method.
<?php
$im = imagecreate(450, 350);
imagecolorallocate($im, 200, 20, 20);
$text_color = imagecolorallocate($im, 255, 255, 255);
imagestring($im, 5, 140, 100, "Punjabi Tech University", $text_color);
imagestring($im, 5, 80, 160, "University That Encorage Thinking", $text_color);
imagepng($im, "demoimage.png");
imagedestroy($im);
?>
<img src="demoimage.png" alt="this is my image">
OutPut:

Practical 20
Write a program to upload and download files.
Main file:
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">

26
<input type="submit" value="Upload Image" name="submit">
</form>
<p>Click on the image to download it.
<p>
<a href="uploads/prac15.png" download>
<img src="uploads/prac15.png" alt="Image" width="294" height="142">
</a>
Upload file:
<?php
$target_dir = "uploads/";
$target_file = $target_dir.basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}

if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}

27
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". htmlspecialchars( basename( $_FILES["fileToUpload"]["name"])). " has been
uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
OutPut:

28

You might also like