PHP

  Home  Computer Programming  PHP


“Learn PHP programming with Interview Questions and Answers and examples.”



139 PHP Questions And Answers

21⟩ How To Remove the New Line Character from the End of a Text Line in PHP?

If you are using fgets() to read a line from a text file, you may want to use the chop() function to remove the new line character from the end of the line as shown in this PHP script:

<?php

$handle = fopen("/tmp/inputfile.txt", "r");

while ($line=fgets()) {

$line = chop($line);

# process $line here...

}

fclose($handle);

?>

 173 views

22⟩ How To Remove Leading and Trailing Spaces from User Input Values in PHP?

If you are taking input values from users with a Web form, users may enter extra spaces at the beginning and/or the end of the input values. You should always use the trim() function to remove those extra spaces as shown in this PHP script:

<?php

$name = $_REQUEST("name");

$name = trim($name);

# $name is ready to be used...

?>

 140 views

23⟩ How to Find a Substring from a Given String in PHP?

To find a substring in a given string, you can use the strpos() function. If you call strpos($haystack, $needle), it will try to find the position of the first occurrence of the $needle string in the $haystack string. If found, it will return a non-negative integer represents the position of $needle. Othewise, it will return a Boolean false. Here is a PHP script example of strpos():

<?php

$haystack1 = "2349534134345globalguideline16504381640386488129";

$haystack2 = "globalguideline234953413434516504381640386488129";

$haystack3 = "guideline234953413434516504381640386488129ggl";

$pos1 = strpos($haystack1, "globalguideline");

$pos2 = strpos($haystack2, "globalguideline");

$pos3 = strpos($haystack3, "globalguideline");

print("pos1 = ($pos1); type is " . gettype($pos1) . " ");

print("pos2 = ($pos2); type is " . gettype($pos2) . " ");

print("pos3 = ($pos3); type is " . gettype($pos3) . " ");

?>

This script will print:

pos1 = (13); type is integer

pos2 = (0); type is integer

pos3 = (); type is boolean

"pos3" shows strpos() can return a Boolean value

 160 views

24⟩ What Is the Best Way to Test the strpos() Return Value in PHP?

Because strpos() could two types of values, Integer and Boolean, you need to be careful about testing the return value. The best way is to use the "Identical(===)" operator. Do not use the "Equal(==)" operator, because it does not differentiate "0" and "false". Check out this PHP script on how to use strpos():

<?php

$haystack = "needle234953413434516504381640386488129";

$pos = strpos($haystack, "needle");

if ($pos==false) {

print("Not found based (==) test ");

} else {

print("Found based (==) test ");

}

if ($pos===false) {

print("Not found based (===) test ");

} else {

print("Found based (===) test ");

}

?>

This script will print:

Not found based (==) test

Found based (===) test

Of course, (===) test is correct.

 148 views

25⟩ How To Replace a Substring in a Given String in PHP?

If you know the position of a substring in a given string, you can replace that substring by another string by using the substr_replace() function. Here is a PHP script on how to use substr_replace():

<?php

$string = "Warning: System will shutdown in NN minutes!";

$pos = strpos($string, "NN");

print(substr_replace($string, "15", $pos, 2)." ");

sleep(10*60);

print(substr_replace($string, "5", $pos, 2)." ");

?>

This script will print:

Warning: System will shutdown in 15 minutes!

(10 minutes later)

Warning: System will shutdown in 5 minutes!

Like substr(), substr_replace() can take negative starting position counted from the end of the string.

 193 views

26⟩ How To Take a Substring from a Given String in PHP?

If you know the position of a substring in a given string, you can take the substring out by the substr() function. Here is a PHP script on how to use substr():

<?php

$string = "beginning";

print("Position counted from left: ".substr($string,0,5)." ");

print("Position counted form right: ".substr($string,-7,3)." ");

?>

This script will print:

Position counted from left: begin

Position counted form right: gin

substr() can take negative starting position counted from the end of the string.

 186 views

27⟩ What is PHP?

The PHP Hypertext Preprocessor is a programming language that allows web developers to create dynamic content that interacts with databases. PHP is basically used for developing web based software applications.

 141 views

28⟩ What Is a Session in PHP?

A session is a logical object created by the PHP engine to allow you to preserve data across subsequent HTTP requests.

There is only one session object available to your PHP scripts at any time. Data saved to the session by a script can be retrieved by the same script or another script when requested from the same visitor.

Sessions are commonly used to store temporary data to allow multiple PHP pages to offer a complete functional transaction for the same visitor.

 159 views

29⟩ What is meant by PEAR in php?

Answer1:

PEAR is the next revolution in PHP. This repository is bringing higher level programming to PHP. PEAR is a framework and distribution system for reusable PHP components. It eases installation by bringing an automated wizard, and packing the strength and experience of PHP users into a nicely organised OOP library. PEAR also provides a command-line interface that can be used to automatically install "packages"

Answer2:

PEAR is short for "PHP Extension and Application Repository" and is pronounced just like the fruit. The purpose of PEAR is to provide:

A structured library of open-sourced code for PHP users

A system for code distribution and package maintenance

A standard style for code written in PHP

The PHP Foundation Classes (PFC),

The PHP Extension Community Library (PECL),

A web site, mailing lists and download mirrors to support the PHP/PEAR community

PEAR is a community-driven project with the PEAR Group as the governing body. The project has been founded by Stig S. Bakken in 1999 and quite a lot of people have joined the project since then.

 158 views

30⟩ How can we repair a MySQL table?

The syntex for repairing a mysql table is:

REPAIR TABLE tablename

REPAIR TABLE tablename QUICK

REPAIR TABLE tablename EXTENDED

This command will repair the table specified.

If QUICK is given, MySQL will do a repair of only the index tree.

If EXTENDED is given, it will create index row by row.

 166 views

32⟩ What is the difference between $message and $$message?

Anwser 1:

$message is a simple variable whereas $$message is a reference variable. Example:

$user = 'bob'

is equivalent to

$holder = 'user';

$$holder = 'bob';

Anwser 2:

They are both variables. But $message is a variable with a fixed name. $$message is a variable who's name is stored in $message. For example, if $message contains "var", $$message is the same as $var.

 142 views

35⟩ What Is a Persistent Cookie in PHP?

A persistent cookie is a cookie which is stored in a cookie file permanently on the browser's computer. By default, cookies are created as temporary cookies which stored only in the browser's memory. When the browser is closed, temporary cookies will be erased. You should decide when to use temporary cookies and when to use persistent cookies based on their differences:

* Temporary cookies can not be used for tracking long-term information.

* Persistent cookies can be used for tracking long-term information.

* Temporary cookies are safer because no programs other than the browser can access them.

* Persistent cookies are less secure because users can open cookie files see the cookie values.

 150 views

36⟩ How To Write the FORM Tag Correctly for Uploading Files?

When users clicks the submit button, files specified in the <INPUT TYPE=FILE...> will be transferred from the browser to the Web server. This transferring (uploading) process is controlled by a properly written <FORM...> tag as:

<FORM ACTION=receiving.php METHOD=post ENCTYPE=multipart/form-data>

Note that you must specify METHOD as "post" and ENCTYPE as "multipart/form-data" in order for the uploading process to work. The following PHP code, called logo_upload.php, shows you a complete FORM tag for file uploading:

<?php

print("<html><form action=processing_uploaded_files.php"

." method=post enctype=multipart/form-data>n");

print("Please submit an image file a Web site logo for"

." rendc.org:<br>n");

print("<input type=file name=globalguideline_logo><br>n");

print("<input type=submit>n");

print("</form></html>n");

?>

 139 views

37⟩ What are the differences between require and include, include_once?

Anwser 1:

require_once() and include_once() are both the functions to include and evaluate the specified file only once. If the specified file is included previous to the present call occurrence, it will not be done again.

But require() and include() will do it as many times they are asked to do.

Anwser 2:

The include_once() statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the include() statement, with the only difference being that if the code from a file has already been included, it will not be included again. The major difference between include() and require() is that in failure include() produces a warning message whereas require() produces a fatal errors.

Anwser 3:

All three are used to an include file into the current page.

If the file is not present, require(), calls a fatal error, while in include() does not.

The include_once() statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the include() statement, with the only difference being that if the code from a file has already been included, it will not be included again. It des not call a fatal error if file not exists. require_once() does the same as include_once(), but it calls a fatal error if file not exists.

Anwser 4:

File will not be included more than once. If we want to include a file once only and further calling of the file will be ignored.

 151 views

38⟩ What is meant by urlencode and urldecode?

Anwser 1:

urlencode() returns the URL encoded version of the given string. URL coding converts special characters into % signs followed by two hex digits. For example: urlencode("10.00%") will return "10%2E00%25". URL encoded strings are safe to be used as part of URLs.

urldecode() returns the URL decoded version of the given string.

Anwser 2:

string urlencode(str) - Returns the URL encoded version of the input string. String values to be used in URL query string need to be URL encoded. In the URL encoded version:

Alphanumeric characters are maintained as is.

Space characters are converted to "+" characters.

Other non-alphanumeric characters are converted "%" followed by two hex digits representing the converted character.

string urldecode(str) - Returns the original string of the input URL encoded string.

For example:

$discount ="10.00%";

$url = "http://domain.com/submit.php?disc=".urlencode($discount);

echo $url;

You will get "http://domain.com/submit.php?disc=10%2E00%25".

 166 views

39⟩ How To Get the Uploaded File Information in the Receiving Script?

Once the Web server received the uploaded file, it will call the PHP script specified in the form action attribute to process them. This receiving PHP script can get the uploaded file information through the predefined array called $_FILES. Uploaded file information is organized in $_FILES as a two-dimensional array as:

* $_FILES[$fieldName]['name'] - The Original file name on the browser system.

* $_FILES[$fieldName]['type'] - The file type determined by the browser.

* $_FILES[$fieldName]['size'] - The Number of bytes of the file content.

* $_FILES[$fieldName]['tmp_name'] - The temporary filename of the file in which the uploaded file was stored on the server.

* $_FILES[$fieldName]['error'] - The error code associated with this file upload.

The $fieldName is the name used in the <INPUT TYPE=FILE, NAME=fieldName>.

 134 views