Вы находитесь на странице: 1из 43

PROGRAMMING IN PHP

CORE COURSE IX

PROGRAMMING IN PHP

Objective :

To understand the Concepts of PHP and Ajax.

Unit I

Essentials of PHP - Operators and Flow Control - Strings and Arrays.

Unit II

Creating Functions - Reading Data in Web Pages - PHP Browser - Handling


Power.

Unit III

Object-Oriented Programming –Advanced Object-Oriented Programming .

Unit IV

File Handling –Working with Databases – Sessions, Cookies, and FTP

Unit V

Ajax – Advanced Ajax – Drawing Images on the Server.

Text Book:

1. The PHP Complete Reference, Steven Holzner, McGrawHillEducation, 2007

Reference Books:

1. PHP: A Beginner's Guide, Vikram Vaswani, McGraw Hill Education, 2008

*****

23
PROGRAMMING IN PHP (16SCCCA9,16SCCCS9) III BCA / B.Sc (CS)

1. What is PHP?
PHP is a recursive acronym for "PHP: Hypertext Preprocessor". PHP is a server side scripting
language that is embedded in HTML. It is used to manage dynamic content, databases,
session tracking, even build entire e-commerce sites.
2. What are the common usage of PHP?
Common uses of PHP −
 PHP performs system functions, i.e. from files on a system it can create, open, read,
write, and close them.
 PHP can handle forms, i.e. gather data from files, save data to a file, thru email you
can send data, return data to the user.
 You add, delete, modify elements within your database thru PHP.
 Access cookies variables and set cookies.
 Using PHP, you can restrict users to access some pages of your website.
 It can encrypt data.
3. In how many ways you can embed PHP code in an HTML page?
All PHP code must be included inside one of the three special markup tags ate are
recognised by the PHP Parser.

<?php PHP code goes here ?>


<? PHP code goes here ?>
<script language="php"> PHP code goes here </script>
Most common tag is the <?php...?>
4. What is the purpose of php.ini file?
The PHP configuration file, php.ini, is the final and most immediate way to affect PHP's
functionality. The php.ini file is read each time PHP is initialized.in other words, whenever
httpd is restarted for the module version or with each script execution for the CGI version. If
your change isn.t showing up, remember to stop and restart httpd. If it still isn.t showing up,
use phpinfo() to check the path to php.ini.
5. What is escaping to PHP?
The PHP parsing engine needs a way to differentiate PHP code from other elements in the
page. The mechanism for doing so is known as 'escaping to PHP.'
6. What do you mean by having PHP as whitespace insensitive?
7. Whitespace is the stuff you type that is typically invisible on the screen, including spaces,
tabs, and carriage returns (end-of-line characters). PHP whitespace insensitive means that it
almost never matters how many whitespace characters you have in a row.one whitespace
character is the same as many such characters.
8. Is PHP a case sensitive language?
No, PHP is partially case sensitive.
What are the characteristics of PHP variables?
Here are the most important things to know about variables in PHP.
 All variables in PHP are denoted with a leading dollar sign ($).
 The value of a variable is the value of its most recent assignment.
 Variables are assigned with the = operator, with the variable on the left-hand side
and the expression to be evaluated on the right.
 Variables can, but do not need, to be declared before assignment.
 Variables in PHP do not have intrinsic types - a variable does not know in advance
whether it will be used to store a number or a string of characters.
 Variables used before they are assigned have default values.
 PHP does a good job of automatically converting types from one to another when
necessary.
 PHP variables are Perl-like.

1|Valluvar College of Science and Management, Karur.


PROGRAMMING IN PHP (16SCCCA9,16SCCCS9) III BCA / B.Sc (CS)

9. What are the different types of PHP variables?


PHP has a total of eight data types which we use to construct our variables −
 Integers − are whole numbers, without a decimal point, like 4195.
 Doubles − are floating-point numbers, like 3.14159 or 49.1.
 Booleans − have only two possible values either true or false.
 NULL − is a special type that only has one value: NULL.
 Strings − are sequences of characters, like 'PHP supports string operations.'
 Arrays − are named and indexed collections of other values.
 Objects − are instances of programmer-defined classes, which can package up both
other kinds of values and functions that are specific to the class.
 Resources − are special variables that hold references to resources external to PHP
(such as database connections).
10. What are rules for naming a PHP variable?
Rules for naming a variable are following –
 Variable names must begin with a letter or underscore character.
 A variable name can consist of numbers, letters, underscores but you cannot use
characters like + , - , % , ( , ) . & , etc
11. What are the rules for determine the "truth" of any value not already of the
Boolean type?
Here are the rules for determine the "truth" of any value not already of the Boolean type −
 If the value is a number, it is false if exactly equal to zero and true otherwise.
 If the value is a string, it is false if the string is empty (has zero characters) or is the
string "0", and is true otherwise.
 Values of type NULL are always false.
 If the value is an array, it is false if it contains no other values, and it is true
otherwise. For an object, containing a value means having a member variable that
has been assigned a value.
 Valid resources are true (although some functions that return resources when they
are successful will return FALSE when unsuccessful).
 Don't use double as Booleans.
12. What is NULL?
NULL is a special type that only has one value: NULL. To give a variable the NULL value,
simply assign it like this −
$my_var = NULL;
The special constant NULL is capitalized by convention, but actually it is case insensitive;
you could just as well have typed −
$my_var = null;
A variable that has been assigned NULL has the following properties:
It evaluates to FALSE in a Boolean context.
It returns FALSE when tested with IsSet() function.
13. How will you define a constant in PHP?
To define a constant you have to use define() function and to retrieve the value of a
constant, you have to simply specifying its name. Unlike with variables, you do not need to
have a constant with a $.
14. What is the purpose of constant() function?
As indicated by the name, this function will return the value of the constant. This is useful
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.
<?php
define("MINSIZE", 50);
echo MINSIZE; echo constant("MINSIZE"); // same thing as the previous line ?>
Only scalar data (boolean, integer, float and string) can be contained in constants.
What are the differences between PHP constants and variables?
 There is no need to write a dollar sign ($) before a constant, where as in Variable
one has to write a dollar sign.
2|Valluvar College of Science and Management, Karur.
PROGRAMMING IN PHP (16SCCCA9,16SCCCS9) III BCA / B.Sc (CS)

 Constants cannot be defined by simple assignment, they may only be defined using
the define() function.
 Constants may be defined and accessed anywhere without regard to variable
scoping rules.
 Once the Constants have been set, may not be redefined or undefined.
15. What are PHP magic constants?
PHP provides a large number of predefined constants to any script which it runs known as
magic constants.
16. What is the purpose of _LINE_ constant?
_LINE_ − The current line number of the file.
17. What is the purpose of _FILE_ constant?
_FILE_ − The full path and filename of the file. If used inside an include,the name of the
included file is returned. Since PHP 4.0.2, _FILE_ always contains an absolute path whereas
in older versions it contained relative path under some circumstances.
18. What is the purpose of _FUNCTION_ constant?
_FUNCTION_ − The function name. (Added in PHP 4.3.0) As of PHP 5 this constant returns
the function name as it was declared (case-sensitive). In PHP 4 its value is always
lowercased.
19. What is the purpose of _CLASS_ constant?
_CLASS_ − The class name. (Added in PHP 4.3.0) As of PHP 5 this constant returns the class
name as it was declared (case-sensitive). In PHP 4 its value is always lowercased.
20. What is the purpose of _METHOD_ constant?
_METHOD_ − The class method name. (Added in PHP 5.0.0) The method name is returned
as it was declared (case-sensitive).
21. What is the purpose of break statement?
break terminates the for loop or switch statement and transfers execution to the statement
immediately following the for loop or switch.
22. What is the purpose of continue statement?
continue causes the loop to skip the remainder of its body and immediately retest its
condition prior to reiterating.
23. Explain the syntax for 'foreach' loop.
The foreach statement is used to loop through arrays. For each pass the value of the current
array element is assigned to $value and the array pointer is moved by one and in the next
pass next element will be processed.

foreach (array as value)


{
code to be executed;
}

24. What is numeric array?


Numeric array − An array with a numeric index. Values are stored and accessed in linear
fashion.
25. What is associate array?
Associative array − An array with strings as index. This stores element values in association
with key values rather than in a strict linear index order.

3|Valluvar College of Science and Management, Karur.


PROGRAMMING IN PHP (16SCCCA9,16SCCCS9) III BCA / B.Sc (CS)

26. What is Multidimensional array?


Multidimensional array − An array containing one or more arrays and values are accessed
using multiple indices.
27. How will you concatenate two strings in PHP?
To concatenate two string variables together, use the dot (.) operator −
<?php
$string1="Hello World";
$string2="1234";
echo $string1 . " " . $string2;
?>
This will produce following result −
Hello World 1234
28. How will you find the length of a string in PHP?
The strlen() function is used to find the length of a string. Let's find the length of our string
"Hello world!" −

<?php
echo strlen("Hello world!");
?>
This will produce following result −

12
29. How will you locate a string within a string in PHP?
The strpos() function is used to search for a string or character within a string. If a match is
found in the string, this function will return the position of the first match. If no match is
found, it will return FALSE. Let's see if we can find the string "world" in our string −
<?php
echo strpos("Hello world!","world");
?>
This will produce following result −
6
30. How will you get environment variables in PHP?
PHP provides a function getenv() to access the value of all the environment variables.
31. How will you get the browser's details using PHP?
One of the environemnt variables set by PHP is HTTP_USER_AGENT which identifies the
user's browser and operating system.
32. How will you generate random numbers using PHP?
The PHP rand() function is used to generate a random number. This function can generate
numbers with-in a given range. The random number generator should be seeded to prevent
a regular pattern of numbers being generated. This is achieved using the srand() function
that specifiies the seed number as its argument.
33. What is the purpse $_PHP_SELF variable?
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.
34. How will you redirect a page using PHP?
The PHP header() function supplies raw HTTP headers to the browser and can be used to
redirect it to another location. The redirection script should be at the very top of the page to
prevent any other part of the page from loading. The target is specified by the Location:

4|Valluvar College of Science and Management, Karur.


PROGRAMMING IN PHP (16SCCCA9,16SCCCS9) III BCA / B.Sc (CS)

header as the argument to the header() function. After calling this function the exit()
function can be used to halt parsing of rest of the code.
35. How can you display a file download dialog box using PHP?
The HTTP header will be different from the actual header where we send Content-Type as
text/html\n\n. In this case content type will be application/octet-stream and actual file name
will be concatenated alongwith it. For example,if you want make a FileName file
downloadable from a given link then its syntax will be as follows.

#!/usr/bin/perl
# HTTP Header
print "Content-Type:application/octet-stream; name=\"FileName\"\r\n";
print "Content-Disposition: attachment; filename=\"FileName\"\r\n\n";
# Actual File Content
open( FILE, "<FileName" );
while(read(FILE, $buffer, 100) )
{
print("$buffer");
}
36. How will you get information sent via get method in PHP?
The PHP provides $_GET associative array to access all the sent information using GET
method.
37. How will you get information sent via post method in PHP?
The PHP provides $_POST associative array to access all the sent information using POST
method.
38. What is the purpse $_REQUEST variable?
The PHP $_REQUEST variable contains the contents of both $_GET, $_POST, and $_COOKIE.
We will discuss $_COOKIE variable when we will explain about cookies. The PHP $_REQUEST
variable can be used to get the result from form data sent with both the GET and POST
methods.
39. Which function will you use to create an array?
array() − Creates an array.
40. How can you sort an array?
sort() − Sorts an array.
41. What is the difference between single quoted string and double quoted string?
Singly quoted strings are treated almost literally, whereas doubly quoted strings replace
variables with their values as well as specially interpreting certain character sequences.
<?php
$variable = "name";
$literally = 'My $variable will not print!\\n';
print($literally);
print "<br />";
$literally = "My $variable will print!\\n";
print($literally);
?>
This will produce following result −
My $variable will not print!\n
My name will print
42. How will you concatenate two strings?
To concatenate two string variables together, use the dot (.) operator.

5|Valluvar College of Science and Management, Karur.


PROGRAMMING IN PHP (16SCCCA9,16SCCCS9) III BCA / B.Sc (CS)

<?php
$string1="Hello World";
$string2="1234";
echo $string1 . " " . $string2;
?>
This will produce following result −
Hello World 1234
43. What is the use of $_REQUEST variable?
The PHP $_REQUEST variable contains the contents of both $_GET, $_POST, and $_COOKIE.
We will discuss $_COOKIE variable when we will explain about cookies. The PHP $_REQUEST
variable can be used to get the result from form data sent with both the GET and POST
methods.
44. How will you include the content of a PHP file into another PHP file?
There are two PHP functions which can be used to included one PHP file into another PHP
file.
 The include() Function
 The require() Function
45. What is the difference between include() Function and require() Function?
If there is any problem in loading a file then the require() function generates a fatal error
and halt the execution of the script whereas include() function generates a warning but the
script will continue execution.
46. How will you open a file in readonly mode?
The PHP fopen() function is used to open a file. It requires two arguments stating first the
file name and then mode in which to operate. "r" mode opens the file for reading only and
places the file pointer at the beginning of the file.
47. How will you read a file in php?
Once a file is opened using fopen() function it can be read with a function called fread(). This
function requires two arguments. These must be the file pointer and the length of the file
expressed in bytes.

48. How will you get the size of a file in php?


The files's length can be found using the filesize() function which takes the file name as its
argument and returns the size of the file expressed in bytes.
49. How will you check if a file exists or not using php?
File's existence can be confirmed using file_exist() function which takes file name as an
argument.
50. Can you assign the default values to a function parameters?
Yes! You can set a parameter to have a default value if the function's caller doesn't pass it.
51. How will you set cookies using 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 called
separately.
setcookie(name, value, expire, path, domain, security);
52. How will you get cookies using PHP?
PHP provides many ways to access cookies. Simplest way is to use either $_COOKIE or
$HTTP_COOKIE_VARS variables.
6|Valluvar College of Science and Management, Karur.
PROGRAMMING IN PHP (16SCCCA9,16SCCCS9) III BCA / B.Sc (CS)

53. How will you make a check that a cookie is set or not?
You can use isset() function to check if a cookie is set or not.
54. How will you delete a cookie?
To delete a cookie you should call setcookie() with the name argument only.
55. How will you start a session in PHP?
A PHP session is easily started by making a call to the session_start() function.This function
first checks if a session is already started and if none is started then it starts one. It is
recommended to put the call to session_start() at the beginning of the page.
56. How will you access session variables in PHP?
Session variables are stored in associative array called $_SESSION[]. These variables can be
accessed during lifetime of a session.
57. How will you check if session variable is already set or not in PHP?
Make use of isset() function to check if session variable is already set or not.
58. How will you unset a single session variable?
Here is the example to unset a single variable −
<?php
unset($_SESSION['counter']);
?>
59. How will you destroy the session?
A PHP session can be destroyed by session_destroy() function.
60. How will you send an email using PHP?
PHP makes use of mail() function to send an email. This function requires three mandatory
arguments that specify the recipient's email address, the subject of the the message and the
actual message additionally there are other two optional parameters.
mail( to, subject, message, headers, parameters );
61. What is the purpose of $_FILES variable in PHP?
This is a global PHP variable. This variable is an associate double dimension array and keeps
all the information related to uploaded file.
62. How will you access the uploaded file in PHP?
Using $_FILES['file']['tmp_name'] − it provides access to the uploaded file in the temporary
directory on the web server.
63. How will you access the actual name of the uploaded file in PHP?
Using $_FILES['file']['name'] − it provides the actual name of the uploaded file.
64. How will you access the size of the uploaded file in PHP?
Using $_FILES['file']['size'] − it provides the size in bytes of the uploaded file.
65. How will you access the content type of the uploaded file in PHP?
Using $_FILES['file']['type'] − it provides the MIME type of the uploaded file.
66. How will you access the error code associated with file upload in PHP?
Using $_FILES['file']['error'] − it provides the error code associated with this file upload.
67. What is the purpose of $GLOBALS variable in PHP?
$GLOBALS − Contains a reference to every variable which is currently available within the
global scope of the script. The keys of this array are the names of the global variables.

7|Valluvar College of Science and Management, Karur.


PROGRAMMING IN PHP (16SCCCA9,16SCCCS9) III BCA / B.Sc (CS)

68. What is the purpose of $_SERVER variable in PHP?


$_SERVER − This is an array containing information such as headers, paths, and script
locations. The entries in this array are created by the web server. There is no guarantee that
every web server will provide any of these. See next section for a complete list of all the
SERVER variables.
69. What is the purpose of $_COOKIE variable in PHP?
$_COOKIE − An associative array of variables passed to the current script via HTTP cookies.
70. What is the purpose of $_SESSION variable in PHP?
$_SESSION − An associative array containing session variables available to the current
script.
71. What is the purpose of $_PHP_SELF variable in PHP?
$_PHP_SELF − A string containing PHP script file name in which it is called.
72. What is the purpose of $php_errormsg variable in PHP?
$php_errormsg − $php_errormsg is a variable containing the text of the last error message
generated by PHP.
73. How ereg() function works?
ereg() − The ereg() function searches a string specified by string for a string specified by
pattern, returning true if the pattern is found, and false otherwise.
74. How eregi() function works?
eregi() − The eregi() function searches throughout a string specified by pattern for a string
specified by string. The search is not case sensitive.

75. How split() function works?


The split() function will divide a string into various elements, the boundaries of each element
based on the occurrence of pattern in string.
76. How preg_match() function works?
preg_match() - The preg_match() function searches string for pattern, returning true if
pattern exists, and false otherwise.
77. How preg_split() function works?
The preg_split() function operates exactly like split(), except that regular expressions are
accepted as input parameters for pattern.
78. How will you retrieve the error message using Exception class in PHP when error
occured?
Using getMessage() method of Exception class which returns the message of exception.
79. How will you retrieve code of exception using Exception class in PHP when error
occured?
Using getCode() method of Exception class which returns the code of exception.
80. How will you retrieve source filename using Exception class in PHP when error
occured?
Using getFile() method of Exception class which returns source filename.
81. How will you retrieve source line using Exception class in PHP when error
occured?

8|Valluvar College of Science and Management, Karur.


PROGRAMMING IN PHP (16SCCCA9,16SCCCS9) III BCA / B.Sc (CS)

Using getLine() method of Exception class which returns source line.


82. How will you retrieve stack trace using Exception class in PHP when error
occured?
Using getTrace() method of Exception class which returns array of the backtrace.
83. How will you retrieve formated string of trace in PHP when error occured?
Using getTraceAsString() method of Exception class which returns formated string of trace.
84. How will you get the current date and time using PHP?
PHP's time() function gives you all the information that you need about the current date and
time. It requires no arguments but returns an integer.
85. What is the purpose of getdate() function?
The function getdate() optionally accepts a time stamp and returns an associative array
containing information about the date. If you omit the time stamp, it works with the current
time stamp as returned by time().
86. What is the purpose of date() function?
The date() function returns a formatted string representing a date. You can exercise an
enormous amount of control over the format that date() returns with a string argument that
you must pass to it.

87. How will you connect a MySql database using PHP?


PHP provides mysql_connect function to open a database connection.
connection mysql_connect(server,user,passwd,new_link,client_flag);
88. How will you create a MySql database using PHP?
PHP uses mysql_query function to create a MySQL database. This function takes two
parameters and returns TRUE on success or FALSE on failure.
bool mysql_query( sql, connection );
89. How will you close a MySql database using PHP?
Its simplest function mysql_close PHP provides to close a database connection. This function
takes connection resource returned by mysql_connect function. It returns TRUE on success
or FALSE on failure.
bool mysql_close ( resource $link_identifier );
If a resource is not specified then last opend database is closed.
90. How will you parse an XML document using PHP?
PHP 5's new SimpleXML module makes parsing an XML document, well, simple. It turns an
XML document into an object that provides structured access to the XML. To create a
SimpleXML object from an XML document stored in a string, pass the string to
simplexml_load_string( ). It returns a SimpleXML object.
91. Can you create a class in PHP?
Yes!
92. How will you add a constructor function to a PHP class?
PHP provides a special function called __construct() to define a constructor. You can pass as
many as arguments you like into the constructor function.
93. How will you add a destructor function to a PHP class?
Like a constructor function you can define a destructor function using function __destruct().
You can release all the resourceses with-in a destructor.

9|Valluvar College of Science and Management, Karur.


PROGRAMMING IN PHP (16SCCCA9,16SCCCS9) III BCA / B.Sc (CS)

94. How will you access the reference to same object within the object in PHP?
The variable $this is a special variable and it refers to the same object ie. itself.
95. How will you create objects in PHP?
Once you defined your class, then you can create as many objects as you like of that class
type. Following is an example of how to create object using new operator.
$physics = new Books;
$maths = new Books;
$chemistry = new Books;
96. How will you call member functions of a class in PHP?
After creating your objects, you will be able to call member functions related to that object.
One member function will be able to process member variable of related object only.
Following example shows how to set title and prices for the three books by calling member
functions.
$physics−>setTitle( "Physics for High School" );
$chemistry−>setTitle( "Advanced Chemistry" );
$maths−>setTitle( "Algebra" );
$physics−>setPrice( 10 );
$chemistry−>setPrice( 15 );
$maths−>setPrice( 7 );
97. What is function overriding?
Function definitions in child classes override definitions with the same name in parent
classes. In a child class, we can modify the definition of a function inherited from parent
class.
98. What are interfaces in PHP?
Interfaces are defined to provide a common function names to the implementors. Different
implementors can implement those interfaces according to their requirements. You can say,
interfaces are skeltons which are implemented by developers.
99. What is the use of final keyword?
PHP 5 introduces the final keyword, which prevents child classes from overriding a method
by prefixing the definition with final. If the class itself is being defined final then it cannot be
extended.

10 | V a l l u v a r C o l l e g e o f S c i e n c e a n d M a n a g e m e n t , K a r u r .
PROGRAMMING IN PHP (16SCCCA9,16SCCCS9) III BCA / B.Sc (CS)

11 | V a l l u v a r C o l l e g e o f S c i e n c e a n d M a n a g e m e n t , K a r u r .
PROGRAMMING IN PHP (16SCCCA9,16SCCCS9) III BCA / B.Sc (CS)

2 Mark Questions
Unit – I:
Essentials of PHP - Operators and Flow Control - Strings and Arrays.

1. What refers PHP?


2. What is PHP?
3. List the strength of PHP.
4. What are variables?
5. What is meant by constants?
6. What refers echo command?
7. What is PHP “Here” Documents?
8. What is execution operators? / What is the purpose of execution operator in PHP?
9. Write any two Operators in PHP.
10. What is Identical Operator? Give example.
11. How will you terminate a loop early?
12. What is string in Hypertext Preprocessor?
13. What PHP function to handle formatting of text string.
14. Write a note on Interpolating Strings.
15. What is array?
16. Write a note on Array-Slice function.
17. List the PHP’s Array Operators.

Unit – II:
Creating Functions - Reading Data in Web Pages - PHP Browser –
Handling Power.

1. What is function?
2. What refers get and post method?
3. What is the difference between get and post method?
4. What is usage of action attribute?
5. Write a note on forms.
6. What is the use of array() syntax in PHP?
7. What are global variables?
8. What is static variables?
9. What refers browser?
10. How to create the function in PHP?
11. What is mean by browser?
12. Differentiate PHP normal function and conditional function.
13. Write an usage of PHP’s server variable.
14. What is Data Validation? Give example.
15. Differentiate Client-side Data Validation and Server-side Data Validation.
16. What are hidden fields?

12 | V a l l u v a r C o l l e g e o f S c i e n c e a n d M a n a g e m e n t , K a r u r .
PROGRAMMING IN PHP (16SCCCA9,16SCCCS9) III BCA / B.Sc (CS)

Unit – III:
Object-Oriented Programming –Advanced Object-Oriented
Programming.

1. What is meant by Object?


2. Define OOPs.
3. How the Object differ from Function?
4. Write a note on class.
5. What is Constructors?
6. What is the purpose of destructors?
7. State three access modifiers with its meaning.
8. What is an Inheritance? List out it types.
9. Define the term overloading.
10. Write about Static Methods with example.
11. What is Interfaces?
12. What is Abstract Classes? Give example.
13. Write the difference between Abstract Classes and Interfaces.
14. Differentiate “==” operator and “===” operator.
15. Write about final keyword.
16. What is reflection?

Unit – IV:
File Handling –Working with Databases – Sessions, Cookies, and FTP
1. Write about writing to a file in PHP.
2. Write a note on fwrite functions.
3. What is stat function? / Write a note on stat functions.
4. Write an usage of stat function in PHP.
5. Write the syntax for copy and unlink functions.
6. Write a note on flock functions.
7. What is database?
8. What is the use of join operation?
9. What refers cookie? / Define Cookies.
10. What refers FTP? / Define FTP.
11. What is a session?
12. Write a program to find a session hit counter.
13. What is meant by object serialization?
Unit – V:
Ajax – Advanced Ajax – Drawing Images on the Server.
1. What refers Ajax? / What is AJAX? / Expand the term AJAX?
2. Why we need an AJAX?
3. List out the advantages of AJAX?
4. What are the applications of AJAX?
5. Write the ready state property of XMLHTTPRequest object and its purpose.
6. What is XML?
7. Write the difference between HTML and XML.
8. What is Java Script?
9. State any four image-creating function.
10. Write a syntax on Image string functions.
11. How to display images in HTML pages? / How to insert images in HTML pages.
12. What is the function used to draw filled-in-figures

13 | V a l l u v a r C o l l e g e o f S c i e n c e a n d M a n a g e m e n t , K a r u r .
Valluvar College of Science and Management,Karur.
Department of Computer Science
April-2020

Subject Name Programming in PHP Subject Code 16SCCCS9/16SCCCA9

Year III Class B.Sc(Computer Science) and BCA


Prepared By B.Gobinath,N.Arun,S.Boobalathandayuthapani

UNIT-1
5 Marks

1. Discuss about using PHP “Here” Statements.


2. How will you store data in Variables.
3. Explain PHP internal datatypes.
4. Illustrate about Operator Precedence in PHP.
5. Explain the Switch statement with examples.
6. Difference between while and do while loop with example.$
7. Explain for each loop with example.
8. Discuss (i) Terminatin loop early (ii) skipping iterations.
9. What is array? List its types with examples.
10. Discuss about sorting arrays.
11. Explain about print_r function with examples.
12. Discuss about sorting array.
13. Explain about sorting and merging arrays.

10 Marks

1. Expalin PHP operators with suitable examples.


2. Explain Control statements with examples.
3. Explain about Looping statements.

UNIT-2
5 Marks

1. Explain passing data to functions by reference.


2. Discuss variable scope in PHP.
3. How will you accessing Global data.
4. Explain the working with static variables.
5. Discuss about handling file uploads.
6. Discuss about any five PHP’s server variables.
7. Explain about the client side validation.
10 Marks

1. What is function? Explain various methods of functions.


2. How will you read data in webpages? Explain about any four HTML controls.
3. How to perform data validation for requiring data and numbers with suitable examples.

UNIT-3
5 Marks

1. What is class? Explain how to create the classes with suitable examples.
2. Explain about cloning objects.
3. Write difference between abstract class and interface.
4. Explain the concept of inheritence with suitable examples.
5. What are the role of constructor and destructor in PHP? Explain.
6. Explain the steps to creating interfaces.
7. How will you set access to properties and methods.
8. Explain about creating a static method.
9. Write short notes on “Final” keyword in PHP?
10. Explain about overloading in PHP.
11. Write short notes on FTP?

10 Marks

1. Explain about OOPS concepts in PHP with examples.


2. Explain about overloading method with suitable examples.
3. Discuss about abstract class and interface with neat examples.

UNIT-4
5 Marks

1. Write short notes on unlink.


2. How will you writing file with fwrite() or fputs()?
3. Explain the steps to creating mysql database.
4. Explain filesize(),file_exists() functions with neat examples.
5. How will you appending to files with fwrite() ?
6. Explain how to sorting your data.
7. Explain reading binary data with fread()?
8. Discuss flock() with examples.
9. How can set and read a cookie.
10. How will you create and remove directories with PHP.
11. Explain about adding attachments to E-mail.
12. Discuss about writing file counter using sessions.

10 Marks

1. How will you reading text from a file using fgets() and fgetc().
2. Explain about accessing the database in PHP.
3. Write the detail about any 5 file functions with suitable examples.
4. Explain the steps to creating and updating database in PHP.
5. Write short notes on Session and Cookies.
6. Explain downloading and uploading files in FTP.

UNIT-5
5 Marks

1. How to create and open the XMLHTTPRequest object.


2. Discuss the handling of XML with PHP
3. Explain the downloading the images using AJAX.
4. Explain the images handling in PHP?
5. How to draw the Rectangle,Eclipse and Polygons using images

10 Marks

1. Explain the detail about passing data to the server with GET and POST methods.
2. How to handle concurrent AJAX requests with the XMLHTTPRequest array and with javascript
inner functions.
PROGRAMMING IN PHP (16SCCCA9/16SCCCS9) III BCA / B.SC (CS)

VALLUVAR COLLEGE OF SCIENCE AND MANAGEMENT


DEPARTMENT OF COMPUTER SCIENCE

Important Questions
Unit – I:

Essentials of PHP - Operators and Flow Control - Strings and Arrays.

2 Marks Questions

1. What refers PHP?


2. What is PHP?
3. List the strength of PHP.
4. What are variables?
5. What is meant by constants?
6. What refers echo command?
7. What is PHP “Here” Documents?
8. What is execution operators? / What is the purpose of execution operator
in PHP?
9. Write any two Operators in PHP.
10.What is Identical Operator? Give example.
11.How will you terminate a loop early?
12.What is string in Hypertext Preprocessor?
13.What PHP function to handle formatting of text string.
14.Write a note on Interpolating Strings.
15.What is array?
16.Write a note on Array-Slice function.
17.List the PHP’s Array Operators.

5 Marks Questions

1. Discuss about using PHP “Here” Statements.


2. How will you store data in Variables.
3. Explain PHP internal datatypes.
4. Illustrate about Operator Precedence in PHP.
5. Explain the Switch statement with examples.
6. Difference between while and do while loop with example.$
7. Explain for each loop with example.
8. Discuss (i) Terminatin loop early (ii) skipping iterations.
9. What is array? List its types with examples.
10.Discuss about sorting arrays.
11.Explain about print_r function with examples.
12.Discuss about sorting array.
13.Explain about sorting and merging arrays.

10 Marks Questions

1. Explain PHP operators with suitable examples.


2. Explain Control statements with examples.
3. Explain about looping statements.

Prepared By - Arun Natarajan


PROGRAMMING IN PHP (16SCCCA9/16SCCCS9) III BCA / B.SC (CS)

Unit – II:

Creating Functions - Reading Data in Web Pages - PHP Browser – Handling


Power.

2 Marks Questions

1. What is function?
2. What refers get and post method?
3. What is the difference between get and post method?
4. What is usage of action attribute?
5. Write a note on forms.
6. What is the use of array() syntax in PHP?
7. What are global variables?
8. What is static variables?
9. What refers browser?
10.How to create the function in PHP?
11.What is mean by browser?
12.Differentiate PHP normal function and conditional function.
13.Write an usage of PHP’s server variable.
14.What is Data Validation? Give example.
15.Differentiate Client-side Data Validation and Server-side Data Validation.
16.What are hidden fields?

5 Marks Questions

1. Explain passing data to functions by reference.


2. Discuss variable scope in PHP.
3. How will you accessing Global data.
4. Explain the working with static variables.
5. Discuss about handling file uploads.
6. Discuss about any five PHP’s server variables.
7. Explain about the client side validation.

10 Marks Questions

1. What is function? Explain various methods of functions.


2. How will you read data in WebPages? Explain about any four HTML
controls.
3. How to perform data validation for requiring data and numbers with
suitable examples.

Prepared By - Arun Natarajan


PROGRAMMING IN PHP (16SCCCA9/16SCCCS9) III BCA / B.SC (CS)

Unit – III:

Object-Oriented Programming –Advanced Object-Oriented Programming.

2 Marks Questions

1. What is meant by Object?


2. Define OOPs.
3. How the Object differ from Function?
4. Write a note on class.
5. What is Constructors?
6. What is the purpose of destructors?
7. State three access modifiers with its meaning.
8. What is an Inheritance? List out it types.
9. Define the term overloading.
10.Write about Static Methods with example.
11.What is Interfaces?
12.What is Abstract Classes? Give example.
13.Write the difference between Abstract Classes and Interfaces.
14.Differentiate “==” operator and “===” operator.
15.Write about final keyword.
16.What is reflection?

5 Marks Questions

1. What is class? Explain how to create the classes with suitable examples.
2. Explain about cloning objects.
3. Write difference between abstract class and interface.
4. Explain the concept of inheritance with suitable examples.
5. What are the role of constructor and destructor in PHP? Explain.
6. Explain the steps to creating interfaces.
7. How will you set access to properties and methods?
8. Explain about creating a static method.
9. Write short notes on “Final” keyword in PHP?
10. Explain about overloading in PHP.
11. Write short notes on FTP?

10 Marks Questions

1. Explain about OOPS concepts in PHP with examples.


2. Explain about overloading method with suitable examples.
3. Discuss about abstract class and interface with neat examples.

Prepared By - Arun Natarajan


PROGRAMMING IN PHP (16SCCCA9/16SCCCS9) III BCA / B.SC (CS)

Unit – IV:

File Handling –Working with Databases – Sessions, Cookies, and FTP

2 Marks Questions

1. Write about writing to a file in PHP.


2. Write a note on fwrite functions.
3. What is stat function? / Write a note on stat functions.
4. Write an usage of stat function in PHP.
5. Write the syntax for copy and unlink functions.
6. Write a note on flock functions.
7. What is database?
8. What is the use of join operation?
9. What refers cookie? / Define Cookies.
10.What refers FTP? / Define FTP.
11.What is a session?
12.Write a program to find a session hit counter.
13.What is meant by object serialization?

5 Marks Questions

1. Write short notes on unlink.


2. How will you writing file with fwrite() or fputs()?
3. Explain the steps to creating mysql database.
4. Explain filesize(),file_exists() functions with neat examples.
5. How will you appending to files with fwrite() ?
6. Explain how to sorting your data.
7. Explain reading binary data with fread()?
8. Discuss flock() with examples.
9. How can set and read a cookie.
10.How will you create and remove directories with PHP.
11.Explain about adding attachments to E-mail.
12.Discuss about writing file counter using sessions.

10 Marks Questions

1. How will you reading text from a file using fgets() and fgetc().
2. Explain about accessing the database in PHP.
3. Write the detail about any 5 file functions with suitable examples.
4. Explain the steps to creating and updating database in PHP.
5. Write short notes on Session and Cookies.
6. Explain downloading and uploading files in FTP.

Prepared By - Arun Natarajan


PROGRAMMING IN PHP (16SCCCA9/16SCCCS9) III BCA / B.SC (CS)

Unit – V:

Ajax – Advanced Ajax – Drawing Images on the Server.

2 Marks Questions

1. What refers Ajax? / What is AJAX? / Expand the term AJAX?


2. Why we need an AJAX?
3. List out the advantages of AJAX?
4. What are the applications of AJAX?
5. Write the ready state property of XMLHTTPRequest object and its purpose.
6. What is XML?
7. Write the difference between HTML and XML.
8. What is Java Script?
9. State any four image-creating function.
10.Write a syntax on Image string functions.
11.How to display images in HTML pages? / How to insert images in HTML
pages.
12.What is the function used to draw filled-in-figures?

5 Mark Questions

1. How to create and open the XMLHTTPRequest object.


2. Discuss the handling of XML with PHP
3. Explain the downloading the images using AJAX.
4. Explain the images handling in PHP?
5. How to draw the Rectangle,Eclipse and Polygons using images

10 Marks Questions

Explain the detail about passing data to the server with GET and POST methods.

1. How to handle concurrent AJAX requests with the XMLHTTPRequest array


and with javascript inner functions.

All the Best

Prepared By - Arun Natarajan


PHP Basic Programs DEPARTMENT OF COMPUTER SCIENCE

PHP Simple Programs with Examples


PHP BASICS
1. PHP "Hello World!" application
<?php
// Simple greeting message
echo "Hello, world!";
?>

2. Embedding PHP within HTML


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>A Simple PHP File</title>
</head>
<body>
<h1><?php echo "Hello, world!"; ?></h1>
</body>
</html>
3. PHP single line comments

<?php
// This is a single line comment
# This is also a single line comment
echo 'Hello World!';
?>
4. PHP multi-line comments
<?php
/*
This is a multiple line comment block
that spans across more than
one line
*/
echo "Hello, world!";
?>
5. Creating variables in PHP

<?php
$txt = "Hello World!";
$number = 10;
// Display variables value
echo $txt;
echo "<br>";
echo $number;
?>

Valluvar College of Science and Management – Karur. 1


PHP Basic Programs DEPARTMENT OF COMPUTER SCIENCE

6. Case sensitivity of PHP variable names

<?php
// Assign values to variables
$color = "blue";
$Color = "red";
$COLOR = "green";
// Try to print variables values
echo "The color of the sky is " . $color . "<br>";
echo "The color of the sun is " . $Color . "<br>";
echo "The color of the tree is " . $COLOR . "<br>";
?>
PHP Data Types

7. PHP integers

<?php
$a = 123; // decimal number
var_dump($a);
echo "<br>";
$b = -123; // a negative number
var_dump($b);
echo "<br>";
$c = 0x1A; // hexadecimal number
var_dump($c);
echo "<br>";
$d = 0123; // octal number
var_dump($d);
?>

8. PHP strings

<?php
$a = 'Hello world!';
echo $a;
echo "<br>";
$b = "Hello world!";
echo $b;
echo "<br>";
$c = 'Stay here, I\'ll be back.';
echo $c;
?>

9. PHP floating point numbers or doubles

<?php
$a = 1.234;
var_dump($a);echo "<br>";
$b = 10.2e3;

Valluvar College of Science and Management – Karur. 2


PHP Basic Programs DEPARTMENT OF COMPUTER SCIENCE

var_dump($b);echo "<br>";
$c = 4E-10; var_dump($c);
?>

10. PHP Booleans

<?php
// Assign the value TRUE to a variable
$show_error = True;
var_dump($show_error);
?>

11. PHP arrays

<?php
$colors = array("Red", "Green", "Blue");
var_dump($colors);
echo "<br>";
$color_codes = array(
"Red" => "#ff0000",
"Green" => "#00ff00",
"Blue" => "#0000ff"
);
var_dump($color_codes);
?>

12. PHP objects

<?php
// Class definition
class greeting{
// properties
public $str = "Hello World!";
// methods
function show_greeting(){
return $this->str;
}
}
// Create object from class
$message = new greeting;
var_dump($message);
?>

13. PHP NULL

<?php
$a = NULL;
var_dump($a);
echo "<br>";
$b = "Hello World!";
$b = NULL;
var_dump($b); ?>

Valluvar College of Science and Management – Karur. 3


PHP Basic Programs DEPARTMENT OF COMPUTER SCIENCE

14. PHP resources

<?php // Open a file for reading


$handle = fopen("note.txt", "r"); var_dump($handle);
?>

PHP Echo and Print


15. Display strings of text with the echo statement
<?php
// Displaying string of text
echo "Hello World!";
?>
16. Display HTML code with the echo statement
<?php
// Displaying HTML code
echo "<h4>This is a simple heading.</h4>";
echo "<h4 style='color: red;'>This is heading with style.</h4>"
?>
17. Display variables with the echo statement
<?php
// Defining variables
$txt = "Hello World!";
$num = 123456789;
$colors = array("Red", "Green", "Blue");
// Displaying variables
echo $txt;
echo "<br>";
echo $num;
echo "<br>";
echo $colors[0];
?>
18. Display strings of text with the print statement
<?php
// Displaying string of text
print "Hello World!";
?>
19. Display HTML code with the print statement
<?php
// Displaying HTML code
print "<h4>This is a simple heading.</h4>";
print "<h4 style='color: red;'>This is heading with style.</h4>"
?>

Valluvar College of Science and Management – Karur. 4


PHP Basic Programs DEPARTMENT OF COMPUTER SCIENCE

20. Display variables with the print statement


<?php
// Defining variables
$txt = "Hello World!";
$num = 123456789;
$colors = array("Red", "Green", "Blue");
// Displaying variables
print $txt;
print "<br>";
print $num;
print "<br>";
print $colors[0];
?>

PHP Strings
21. Differences between single and double quoted strings
<?php
$my_str = 'World';
echo "Hello, $my_str!<br>";
echo 'Hello, $my_str!<br>';
echo '<pre>Hello\tWorld!</pre>';
echo "<pre>Hello\tWorld!</pre>";
echo 'I\'ll be back';
?>
22. Find the length of a string
<?php
$my_str = 'Welcome to Computer Science';
// Calculating and displaying string length
echo strlen($my_str);
?>
23. Replacing text within a string
<?php
$my_str = 'If the facts do not fit the theory, change the facts.';
// Display replaced string
echo str_replace("facts", "truth", $my_str);
?>
24. Reversing the direction of a string
<?php
$my_str = 'You can do anything, but not everything.';

// Display reversed string


echo strrev($my_str);
?>

Valluvar College of Science and Management – Karur. 5


PHP Basic Programs DEPARTMENT OF COMPUTER SCIENCE

PHP Operators
25. PHP arithmetic operators
<?php
$x = 10;
$y = 4;
echo($x + $y); echo "<br>";
echo($x - $y); echo "<br>";
echo($x * $y); echo "<br>";
echo($x / $y); echo "<br>";
echo($x % $y);
?>
26. PHP assignment operators
<?php
$x = 10;
echo $x; echo "<br>";
$x = 20;
$x += 30;
echo $x; echo "<br>";
$x = 50;
$x -= 20;
echo $x; echo "<br>";
$x = 5;
$x *= 25;
echo $x; echo "<br>";
$x = 50;
$x /= 10;
echo $x; echo "<br>";
$x = 100;
$x %= 15;
echo $x;
?>
27. PHP comparison operators
<?php
$x = 25;
$y = 35;
$z = "25";
var_dump($x == $z); echo "<br>";
var_dump($x === $z); echo "<br>";
var_dump($x != $y); echo "<br>";
var_dump($x !== $z); echo "<br>";
var_dump($x < $y); echo "<br>";
var_dump($x > $y); echo "<br>";
var_dump($x <= $y);echo "<br>";
var_dump($x >= $y);
?>
28. PHP incrementing and decrementing operators
<?php
$x = 10;
echo ++$x; echo "<br>";
echo $x; echo "<hr>";
$x = 10;
echo $x++; echo "<br>";
echo $x; echo "<hr>";

Valluvar College of Science and Management – Karur. 6


PHP Basic Programs DEPARTMENT OF COMPUTER SCIENCE

$x = 10;
echo --$x; echo "<br>";
echo $x; echo "<hr>";
$x = 10;
echo $x--; echo "<br>";
echo $x;
?>
29. PHP logical operators
<?php
$year = 2014;
// Leap years are divisible by 400 or by 4 but not 100
if(($year % 400 == 0) || (($year % 100 != 0) && ($year % 4 == 0))){
echo "$year is a leap year.";
} else{
echo "$year is not a leap year.";
}
?>
30. PHP string operators
<?php
$x = "Hello";
$y = " World!";
echo $x . $y; // Outputs: Hello World!
echo "<br>";
$x .= $y;
echo $x; // Outputs: Hello World!
?>
31. PHP array operators
<?php
$x = array("a" => "Red", "b" => "Green", "c" => "Blue");
$y = array("u" => "Yellow", "v" => "Orange", "w" => "Pink");
$z = $x + $y; // Union of $x and $y
var_dump($z); echo "<hr>";
var_dump($x == $y); echo "<br>";
var_dump($x === $y);echo "<br>";
var_dump($x != $y); echo "<br>";
var_dump($x <> $y);echo "<br>";
var_dump($x !== $y); ?>

PHP If...Else and Switch Statements


32. PHP if Statement
<?php
$d = date("D");
if($d == "Fri"){ echo "Have a nice weekend!"; }
?>
33. PHP if...else Statement
<?php
$d = date("D");
if($d == "Fri"){
echo "Have a nice weekend!";
} else{
echo "Have a nice day!"; } ?>

Valluvar College of Science and Management – Karur. 7


PHP Basic Programs DEPARTMENT OF COMPUTER SCIENCE

34. PHP if...elseif...else Statement


<?php
$d = date("D");
if($d == "Fri"){
echo "Have a nice weekend!";
} elseif($d == "Sun"){
echo "Have a nice Sunday!";
} else{
echo "Have a nice day!";
}
?>
35. PHP Switch...Case Statements
<?php
$today = date("D");
switch($today){
case "Mon":
echo "Today is Monday. Clean your house.";
break;
case "Tue":
echo "Today is Tuesday. Buy some food.";
break;
case "Wed":
echo "Today is Wednesday. Visit a doctor.";
break;
case "Thu":
echo "Today is Thursday. Repair your car.";
break;
case "Fri":
echo "Today is Friday. Party tonight.";
break;
case "Sat":
echo "Today is Saturday. Its movie time.";
break;
case "Sun":
echo "Today is Sunday. Do some rest.";
break;
default:
echo "No information available for that day.";
break;
}
?>

Valluvar College of Science and Management – Karur. 8


PHP Basic Programs DEPARTMENT OF COMPUTER SCIENCE

PHP Arrays
36. PHP indexed arrays
<?php
$colors = array("Red", "Green", "Blue");
// Printing array structure
print_r($colors);
?>
37. PHP associative arrays
<?php
$ages = array("Peter"=>22, "Clark"=>32, "John"=>28);
// Printing array structure
print_r($ages);
?>
38. PHP multidimensional array
<?php
// Define nested array
$contacts = array(
array(
"name" => "Peter Parker",
"email" => "peterparker@mail.com",
),
array(
"name" => "Clark Kent",
"email" => "clarkkent@mail.com",
),
array(
"name" => "Harry Potter",
"email" => "harrypotter@mail.com",
)
);
// Access nested value
echo "Peter Parker's Email-id is: " . $contacts[0]["email"];
?>
39. Viewing array structure and values
<?php
// Define array
$cities = array("London", "Paris", "New York");
// Display the cities array
Print_r($cities);
?>
40. Get complete array information
<?php
// Define array
$cities = array("London", "Paris", "New York");

// Display the cities array


var_dump($cities);
?>

Valluvar College of Science and Management – Karur. 9


PHP Basic Programs DEPARTMENT OF COMPUTER SCIENCE

PHP Sorting Arrays


41. Sorting indexed arrays in alphabetically ascending order
<?php
// Define array
$colors = array("Red", "Green", "Blue", "Yellow");
// Sorting and printing array
sort($colors);
print_r($colors);
?>
42. Sorting indexed arrays in numerically ascending order
<?php
// Define array
$numbers = array(1, 2, 2.5, 4, 7, 10);
// Sorting and printing array
sort($numbers);
print_r($numbers);
?>
43. Sorting indexed arrays in alphabetically descending order
<?php
// Define array
$colors = array("Red", "Green", "Blue", "Yellow");
// Sorting and printing array
rsort($colors);
print_r($colors);
?>
44. Sorting indexed arrays in numerically descending order
<?php
// Define array
$numbers = array(1, 2, 2.5, 4, 7, 10);
// Sorting and printing array
rsort($numbers);
print_r($numbers);
?>
45. Sorting associative arrays in ascending order by value
<?php // Define array
$age = array("Peter"=>20, "Harry"=>14, "John"=>45, "Clark"=>35);
// Sorting array by value and print
asort($age);
print_r($age);
?>
46. Sorting associative arrays in descending order by value
<?php
// Define array
$age = array("Peter"=>20, "Harry"=>14, "John"=>45, "Clark"=>35);
// Sorting array by value and print
arsort($age); print_r($age); ?>

Valluvar College of Science and Management – Karur. 10


PHP Basic Programs DEPARTMENT OF COMPUTER SCIENCE

47. Sorting associative arrays in ascending order by key


<?php
// Define array
$age = array("Peter"=>20, "Harry"=>14, "John"=>45, "Clark"=>35);
// Sorting array by value and print
ksort($age);
print_r($age);
?>
48. Sorting associative arrays in descending order by key
<?php
// Define array
$age = array("Peter"=>20, "Harry"=>14, "John"=>45, "Clark"=>35);
// Sorting array by value and print
krsort($age);
print_r($age);
?>

PHP Loops
49. PHP while loop
<?php
$i = 1;
while($i <= 3){
$i++;
echo "The number is " . $i . "<br>";
}
?>
50. PHP do...while loop
<?php
$i = 1;
do{
$i++;
echo "The number is " . $i . "<br>";
}
while($i <= 3);
?>
51. PHP for loop
<?php
for($i=1; $i<=3; $i++){
echo "The number is " . $i . "<br>";
}
?>
52. PHP foreach loop
<?php
$colors = array("Red", "Green", "Blue");
// Loop through count array
foreach($colors as $value){
echo $value . "<br>";
}
?>

Valluvar College of Science and Management – Karur. 11


PHP Basic Programs DEPARTMENT OF COMPUTER SCIENCE

53. PHP foreach loop extended


<?php
$superhero = array(
"name" => "Peter Parker",
"email" => "peterparker@mail.com",
"age" => 18
);

// Loop through superhero array


foreach($superhero as $key => $value){
echo $key . " : " . $value . "<br>";
}
?>

PHP Functions

54. Creating a function


<?php
// Defining function
function whatIsToday(){
echo "Today is " . date('l', mktime());
}
// Calling function
whatIsToday();
?>
55. PHP functions with parameters
<?php
// Defining function
function getSum($num1, $num2){
$sum = $num1 + $num2;
echo "Sum of the two numbers $num1 and $num2 is : $sum";
}
// Calling function
getSum(10, 20);
?>
56. PHP functions with optional parameters and default values
<?php
// Defining function
function customFont($font, $size=1.5){
echo "<p style=\"font-family: $font; font-size: {$size}em;\">Hello,
world!</p>";
}
// Calling function
customFont("Arial", 2);
customFont("Times", 3);
customFont("Courier");
?>

Valluvar College of Science and Management – Karur. 12


PHP Basic Programs DEPARTMENT OF COMPUTER SCIENCE

57. PHP functions returning values


<?php
// Defining function
function getSum($num1, $num2){
$total = $num1 + $num2;
return $total;
}
// Printing returned value
echo getSum(5, 10); // Outputs: 15
?>

PHP Date and Time

58. Get current date


<?php
// Return current date from the remote server
$today = date("d/m/Y");
echo $today;
?>
59. Formatting the dates
<?php
// Return current date from the remote server
echo date("d/m/Y") . "<br>";
echo date("d-m-Y") . "<br>";
echo date("d.m.Y");
?>
60. Formatting the times
<?php
// Return current date and time from the remote server
echo date("h:i:s") . "<br>";
echo date("F d, Y h:i:s A") . "<br>";
echo date("h:i a");
?>
61. Get current time as timestamp
<?php
/* Return current date and time
from the remote server as timestamp
*/
$timestamp = time();
echo($timestamp);
?>
62. Convert timestamp to human readable date and time
<?php
/* Return current date and time
from the remote server as timestamp
*/
$timestamp = time();
echo($timestamp);
echo "<br>";
// Converting timestamp to human readable format
echo(date("F d, Y h:i:s", $timestamp));
?>

Valluvar College of Science and Management – Karur. 13


PHP Basic Programs DEPARTMENT OF COMPUTER SCIENCE

63. Create timestamp from specific date and time


<?php
// Create the timestamp for a particular date
echo mktime(15, 20, 12, 5, 10, 2014);
?>
64. Get weekday name from timestamp
<?php
// Get weekday name from a particular date
echo date('l', mktime(0,0,0,1,4,2014));
?>
65. Get future date
<?php
// Return future date
$futureDate = mktime(0,0,0,date("m")+30,date("d"),date("Y"));
echo date("d/m/Y", $futureDate);
?>

Valluvar College of Science and Management – Karur. 14


PHP Basic Programs DEPARTMENT OF COMPUTER SCIENCE

MISCELLANEOUS PROGRAMS
1. Write a PHP script to get the PHP version and configuration information.
<?php
phpinfo();
?>

2. Write a PHP script to get the client IP address.


<?php
//whether ip is from share internet
if (!empty($_SERVER['HTTP_CLIENT_IP']))
{
$ip_address = $_SERVER['HTTP_CLIENT_IP'];
}
//whether ip is from proxy
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
{
$ip_address = $_SERVER['HTTP_X_FORWARDED_FOR'];
}
//whether ip is from remote address
else
{
$ip_address = $_SERVER['REMOTE_ADDR'];
}
echo $ip_address;
?>

3. Write a simple PHP browser detection script


<?php
echo "Your User Agent is :" . $_SERVER ['HTTP_USER_AGENT'];
?>
4. Write a PHP script to get the current file name
<?php
$current_file_name = basename($_SERVER['PHP_SELF']);
echo $current_file_name."\n";
?>
5. Write a PHP script, which will return the following components of the url
'https://www.google.com'.
<?php
$url = 'https://www.google.com';
$url=parse_url($url);
echo 'Scheme : '.$url['scheme']."\n";
echo 'Host : '.$url['host']."\n";
echo 'Path : '.$url['path']."\n";
?>

Valluvar College of Science and Management – Karur. 15


PHP Basic Programs DEPARTMENT OF COMPUTER SCIENCE

6. Write a PHP script, which changes the color of the first character of a word
<?php
$text = 'PHP Tutorial';
$text=preg_replace('/(\b[a-z])/i','<span style="color:red;">\1</span>',$text);
echo $text;
?>
7. Write a PHP script, to check whether the page is called from 'https' or
'http'.
<?php
if (!empty($_SERVER['HTTPS']))
{
echo 'https is enabled';
}
else
{
echo 'http is enabled'."\n";
}
?>
8. Write a PHP script to display source code of a webpage (e.g.
"http://www.example.com/").
<?php
$all_lines = file('https://www.w3resource.com/');
foreach ($all_lines as $line_num => $line)
{
echo "Line No.-{$line_num}: " . htmlspecialchars($line) . "\n";
}
?>
9. Write a simple PHP program to check that emails are valid.
<?php
// pass valid/invalid emails
$email = "mail@example.com";
if (filter_var($email, FILTER_VALIDATE_EMAIL))
{
echo '"' . $email . '" = Valid'."\n";
}
else
{
echo '"' . $email . '" = Invalid'."\n";
}
?>
10. Write a PHP script to get last modified information of a file.
<?php
$current_file_name = basename($_SERVER['PHP_SELF']);
$file_last_modified = filemtime($current_file_name);
echo "Last modified " . date("l, dS F, Y, h:ia", $file_last_modified)."\n";
?>

Valluvar College of Science and Management – Karur. 16


PHP Basic Programs DEPARTMENT OF COMPUTER SCIENCE

11. Write a PHP script to count number of lines in a file.

<?php
$file = basename($_SERVER['PHP_SELF']);
$no_of_lines = count(file($file));
echo "There are $no_of_lines lines in $file"."\n";
?>

12. Write a PHP script to print current PHP version.

<?php
echo 'Current PHP version : ' . phpversion();
// prints e.g. '2.0' or nothing if the extension isn't enabled
echo phpversion('tidy')."\n";
?>

13. Write a PHP script to delay the program execution for the given number of
seconds.

<?php
// current time
echo date('h:i:s') . "\n";
// sleep for 5 seconds
sleep(5);
// wake up
echo date('h:i:s')."\n";
?>

14. Write a PHP script to get the last occurred error.

<?php
echo $x;
print_r(error_get_last());
?>

15. Write a PHP script to get the full URL.

<?php
$full_url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
echo $full_url."\n";
?>

16. Write a PHP script to get the names of the functions of a module.

<?php
print_r(get_extension_funcs("JSON"));
echo "\n";
print_r(get_extension_funcs("XML"))."\n"; ?>

Valluvar College of Science and Management – Karur. 17


PHP Basic Programs DEPARTMENT OF COMPUTER SCIENCE

17. Write a PHP script to get the document root directory under which the current
script is executing, as defined in the server's configuration file.

<?php
// getenv() gets the value of an environment variable
$rd = getenv('DOCUMENT_ROOT');
echo $rd."\n";
?>

18. Write a PHP script to get the information about the operating system PHP is
running on.
<?php
echo php_uname()."\n";
echo PHP_OS."\n";
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
echo 'This is a server using Windows!';
} else {
echo 'This is a server not using Windows!'."\n";
}
?>

Valluvar College of Science and Management – Karur. 18


PROGRAMMING IN PHP
PHP basic programs
III-BCA ‘A’ 20.04.2020
1) Write a PHP program to reverse given string.
2) Write a PHP program to swap two numbers with and without using third variable.
3) Write a PHP program to find area of triangle and rectangle using functions.
4) Write a PHP program to find if the given year is leap year or not.
5) Write a program to print Factorial of any number
6) To check whether a number is Prime or not.
7) Write a program to find HCF of two numbers
8) Write a Program for finding the biggest number in an array without using any array
functions.
9) Write a program to find factor of any number
10) Write a Program for Bubble sorting in PHP
11) Write a Program for finding the smallest number in an array
12) Program to find the LCM of two numbers.
13) Write a program to find second highest number in an array.
14) Write a program to concatenate two strings character by character. e.g : AJAY + RAJ
= ARJAAJY
15) Write a program to find no of days between two dates in Php?
16) Write a program in PHP to find the occurrence of a word in a string?
17) Write a program to find a string is palindrome or not?
18) Write a program for this pattern ?
*
**
***
****
*****

19) Write a program for this pattern(number pyramid) ?


1
22
333
4444
55555
20) How to write a Floyd's Triangle?
1
23
456
78910
1112131415

Note:
While writing the programs first you have to write the logic for the program then you
have to write the code. For example,
Factorial Program:
In mathematics, the factorial of a positive integer n, denoted by n!, is the product of
all positive integers less than or equal to n:
n! = n * (n-1) * (n-2) * (n-3)*...*3*2*1.

For example,

5! = 5 * 4 * 3 * 2 * 1 = 120.

The value of 0! is always 1

Likewise you have to write the logic for each program and then you have to convert
the logic into code.
Refer your PHP lab manual for assistance.

All the Best

Вам также может понравиться