Question 1. What's Php?
Answer :
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.
Question 2. What Is A
Session?
Answer :
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.
Question 3. What Is
Meant By Pear In Php?
Answer :
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".
Question 4. How Can We
Know The Number Of Days Between Two Given Dates Using Php?
Answer :
Simple arithmetic:
$date1 = date('Y-m-d');
$date2 = '2006-07-01';
$days = (strtotime() - strtotime()) / (60 * 60 * 24);
echo "Number of days since '2006-07-01': $days";
Question 5. How Can We
Repair A Mysql Table?
Answer :
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.
Question 6. What Is The
Difference Between $message And $$message?
Answer :
$message is a simple
variable whereas $$message is a variable's variable,which
means
value of the variable. Example:
$user = 'bob'
is equivalent to
$message = 'user';
$$message = 'bob';
Question 7. What Is A
Persistent Cookie?
Answer :
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.
Question 8. How Do You
Define A Constant?
Answer :
Via define() directive,
like define ("MYCONSTANT", 100);
Question 9. What Are The
Differences Between Require And Include, Include_once?
Answer :
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.
Question 10. What Is
Meant By Urlencode And Urldecode?
Answer :
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.
Question 11. How To Get
The Uploaded File Information In The Receiving Script?
Answer :
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 .
Question 12. What Is The
Difference Between Mysql_fetch_object And Mysql_fetch_array?
Answer :
MySQL fetch object will
collect first single matching record where mysql_fetch_array will collect all
matching records from the table in an array.
Question 13. How Can I
Execute A Php Script Using Command Line?
Answer :
Just run the PHP CLI
(Command Line Interface) program and provide the PHP script file name as the
command line argument. For example, "php myScript.php", assuming
"php" is the command to invoke the CLI program.
Be aware that if your PHP script was written for the Web CGI interface, it may
not execute properly in command line environment.
Question 14. I Am Trying
To Assign A Variable The Value Of 0123, But It Keeps Coming Up With A Different
Number, What's The Problem?
Answer :
PHP Interpreter treats
numbers beginning with 0 as octal.
Question 15. Would I Use
Print "$a Dollars" Or "{$a} Dollars" To Print Out The
Amount Of Dollars In This Example?
Answer :
In this example it
wouldn’t matter, since the variable is all by itself, but if you were to print
something like "{$a},000,000 mln dollars", then you definitely need
to use the braces.
Question 16. What Are
The Different Tables Present In Mysql? Which Type Of Table Is Generated When We
Are Creating A Table In The Following Syntax: Create Table Employee(eno
Int(2),ename Varchar(10))?
Answer :
Total 5 types of tables
we can create
1. MyISAM
2. Heap
3. Merge
4. INNO DB
5. ISAM
MyISAM is the default storage engine as of MySQL 3.23. When you fire the above
create query MySQL will create a MyISAM table.
Question 17. How To
Create A Table?
Answer :
If you want to create a
table, you can run the CREATE TABLE statement as shown in the following sample
script:
<?php
include "mysql_connection.php";
$sql = "CREATE TABLE fyi_links ("
. " id INTEGER NOT NULL"
. ", url VARCHAR(80) NOT NULL"
. ", notes VARCHAR(1024)"
. ", counts INTEGER"
. ", time TIMESTAMP DEFAULT
sysdate()"
. ")";
if (mysql_query($sql, $con)) {
print("Table fyi_links created.n");
} else {
print("Table creation failed.n");
}
mysql_close($con);
?>
Remember that
mysql_query() returns TRUE/FALSE on CREATE statements. If you run this script,
you will get something like this:
Table fyi_links created.
Question 18. How Can We
Encrypt The Username And Password Using Php?
Answer :
You can encrypt a
password with the following Mysql>SET
PASSWORD=PASSWORD("Password");
Question 19. How Do You
Pass A Variable By Value?
Answer :
Just like in C++, put an
ampersand in front of it, like $a = &$b.
Question 20. What Is The
Functionality Of The Functions Strstr() And Stristr()?
Answer :
string strstr ( string
haystack, string needle ) returns part of haystack string from the first
occurrence of needle to the end of haystack. This function is case-sensitive.
stristr() is idential to strstr() except that it is case insensitive.
Question 21. When Are
You Supposed To Use Endif To End The Conditional Statement?
Answer :
When the original if was
followed by : and then the code block without braces.
Question 22. How Can We
Send Mail Using Javascript?
Answer :
No. There is no way to
send emails directly using JavaScript.
But you can use JavaScript to execute a client side email program send the
email using the "mailto" code. Here is an example:
function myfunction(form)
{
tdata=document.myform.tbox1.value;
location="mailto:mailid@domain.com?subject=...";
return true;
}
Question 23. What Is The
Functionality Of The Function Strstr And Stristr?
Answer :
strstr() returns part of
a given string from the first occurrence of a given substring to the end of the
string. For example: strstr("user@example.com","@") will
return "@example.com".
stristr() is idential to strstr() except that it is case insensitive.
Question 24. What Is The
Difference Between Ereg_replace() And Eregi_replace()?
Answer :
eregi_replace() function
is identical to ereg_replace() except that it ignores case distinction when
matching alphabetic characters.
Question 25. How Do I
Find Out The Number Of Parameters Passed Into Function9?
Answer :
func_num_args() function
returns the number of parameters passed in.
Question 26. What Is The
Purpose Of The Following Files Having Extensions: Frm, Myd, And Myi? What These
Files Contain?
Answer :
In MySQL, the default
table type is MyISAM.
Each MyISAM table is stored on disk in three files. The files have names that
begin with
the table name and have an extension to indicate the file type.
The '.frm' file stores
the table definition.
The data file has a '.MYD' (MYData) extension.
The index file has a '.MYI' (MYIndex) extension.
Question 27. If The
Variable $a Is Equal To 5 And Variable $b Is Equal To Character A, What's The
Value Of $$b?
Answer :
5, it’s a reference to
existing variable.
Question 28. How To
Protect Special Characters In Query String?
Answer :
If you want to include
special characters like spaces in the query string, you need to protect them by
applying the urlencode() translation function. The script below shows how to
use urlencode():
<?php
print("<html>");
print("<p>Please click the links below"
." to submit comments about FYICenter.com:</p>");
$comment = 'I want to say: "It\'s a good site! :->"';
$comment = urlencode($comment);
print("<p>"
."<a
href=\"processing_forms.php?name=Guest&comment=$comment\">"
."It's an excellent site!</a></p>");
$comment = 'This visitor said: "It\'s an average site! :-("';
$comment = urlencode($comment);
print("<p>"
.'<a href="processing_forms.php?'.$comment.'">'
."It's an average site.</a></p>");
print("</html>");
?>
Question 29. Are Objects
Passed By Value Or By Reference?
Answer :
Everything is passed by
value.
Question 30. What Are
The Differences Between Drop A Table And Truncate A Table?
Answer :
DROP TABLE table_name - This will delete
the table and its data.
TRUNCATE TABLE
table_name - This will delete the data of the table, but not the table
definition.
Question 31. What Are
The Differences Between Get And Post Methods In Form Submitting, Give The Case
Where We Can Use Get And We Can Use Post Methods?
Answer :
When you want to send
short or small data, not containing ASCII characters, then you can use GET”
Method. But for long data sending, say more then 100 character you can use POST
method.
Once most important
difference is when you are sending the form with GET method. You can see the
output which you are sending in the address bar. Whereas if you send the form
with POST” method then user can not see that information.
Question 32. How Do You
Call A Constructor For A Parent Class?
Answer :
parent::constructor($value).
Question 33. What Are
The Different Types Of Errors In Php?
Answer :
Here are three basic
types of runtime errors in PHP:
Notices: These are trivial,
non-critical errors that PHP encounters while executing a script - for example,
accessing a variable that has not yet been defined. By default, such errors are
not displayed to the user at all - although you can change this default behavior.
Warnings: These are more
serious errors - for example, attempting to include() a file which does not
exist. By default, these errors are displayed to the user, but they do not
result in script termination.
Fatal errors: These are critical
errors - for example, instantiating an object of a nonexistent class, or
calling a non-existent function. These errors cause the immediate termination
of the script, and PHP's default behavior is to display them to the user when
they take place.
Internally, these variations
are represented by twelve different error types.
Question 34. What's The
Special Meaning Of __sleep And __wakeup?
Answer :
__sleep returns the
array of all the variables than need to be saved, while __wakeup retrieves
them.
Question 35. How Can We
Submit A Form Without A Submit Button?
Answer :
If you don't want to use
the Submit button to submit a form, you can use normal hyper links to submit a
form. But you need to use some JavaScript code in the URL of the link. For
example:
<a href="javascript: document.myform.submit();">Submit
Me</a>.
Question 36. Would You
Initialize Your Strings With Single Quotes Or Double Quotes?
Answer :
Since the data inside
the single-quoted string is not parsed for variable substitution, it’s always a
better idea speed-wise to initialize a string with single quotes, unless you
specifically need variable substitution.
Question 37. What Is The
Difference Between The Functions Unlink And Unset?
Answer :
unlink() is a function
for file system handling. It will simply delete the file in context.
unset() is a function
for variable management. It will make a variable undefined.
Question 38. How Come
The Code Works, But Doesn't For Two-dimensional Array Of Mine?
Answer :
Any time you have an
array with more than one dimension, complex parsing syntax is required. print
"Contents: {$arr[1][2]}" would’ve worked.
Question 39. How Can We
Register The Variables Into A Session?
Answer :
session_register($session_var);
$_SESSION['var'] = 'value';
Question 40. What Is The
Difference Between Characters \023 And \x23?
Answer :
The first one is octal
23, the second is hex 23.
Question 41. How Can We
Submit Form Without A Submit Button?
Answer :
We can use a simple
JavaScript code linked to an event trigger of any form field. In the JavaScript
code, we can call the document.form.submit() function to submit the form. For
example: <input type=button value="Save"
onClick="document.form.submit()">.
Question 42. How Can We
Create A Database Using Php And Mysql?
Answer :
We can create MySQL
database with the use of mysql_create_db($databaseName) to create a database.
Question 43. How Many
Ways We Can Retrieve The Date In Result Set Of Mysql Using Php?
Answer :
As individual objects so
single record or as a set or arrays.
Question 44. How Many
Ways Can We Get The Value Of Current Session Id?
Answer :
session_id() returns the
session id for the current session.
Question 45. Can We Use
Include ("abc.php") Two Times In A Php Page "makeit.php"?
Answer :
Yes.
Question 46. What's The
Difference Between Include And Require?
Answer :
It’s how they handle
failures. If the file is not found by require(), it will cause a fatal error
and halt the execution of the script. If the file is not found by include(), a
warning will be issued, but execution will continue.
Question 47. Explain The
Ternary Conditional Operator In Php?
Answer :
Expression preceding the
? is evaluated, if it’s true, then the expression preceding the : is executed,
otherwise, the expression following : is executed.
Question 48. What's The
Difference Between Htmlentities() And Htmlspecialchars()?
Answer :
htmlspecialchars only
takes care of <, >, single quote ‘, double quote " and ampersand.
htmlentities translates all occurrences of character sequences that have
different meaning in HTML.
Question 49. How To
Store The Uploaded File To The Final Location?
Answer :
move_uploaded_file (
string filename, string destination)
This function checks to
ensure that the file designated by filename is a valid upload file (meaning
that it was uploaded via PHP's HTTP POST upload mechanism). If the file is
valid, it will be moved to the filename given by destination.
If filename is not a
valid upload file, then no action will occur, and move_uploaded_file() will
return FALSE.
If filename is a valid
upload file, but cannot be moved for some reason, no action will occur, and
move_uploaded_file() will return FALSE. Additionally, a warning will be issued.
Question 50. What Is The
Difference Between Reply-to And Return-path In The Headers Of A Mail Function?
Answer :
Reply-to : Reply-to is where
to delivery the reply of the mail.
Return-path : Return path is
when there is a mail delivery failure occurs then where to delivery the failure
notification.
Question 51. So If Md5()
Generates The Most Secure Hash, Why Would You Ever Use The Less Secure Crc32()
And Sha1()?
Answer :
Crypto usage in PHP is
simple, but that doesn’t mean it’s free. First off, depending on the data that
you’re encrypting, you might have reasons to store a 32-bit value in the
database instead of the 160-bit value to save on space. Second, the more secure
the crypto is, the longer is the computation time to deliver the hash value. A
high volume site might be significantly slowed down, if frequent md5()
generation is required.
Question 52. How Can We
Destroy The Session, How Can We Unset The Variable Of A Session?
Answer :
session_unregister() - Unregister a
global variable from the current session.
session_unset() - Free all session
variables.
Question 53. What Type
Of Headers Have To Be Added In The Mail Function To Attach A File?
Answer :
$boundary = '--' . md5(
uniqid ( rand() ) );
$headers = "From: \"Me\"\n";
$headers .= "MIME-Version: 1.0\n";
$headers .= "Content-Type: multipart/mixed;
boundary=\"$boundary\"";
Question 54. List Out
Different Arguments In Php Header Function?
Answer :
void header ( string
string [, bool replace [, int http_response_code]]).
Question 55. What Are
The Different Functions In Sorting An Array?
Answer :
Sorting functions in
PHP:
asort()
arsort()
ksort()
krsort()
uksort()
sort()
natsort()
rsort()
Question 56. How Can We
Know The Count / Number Of Elements Of An Array?
Answer :
2 ways:
sizeof($array) - This function is
an alias of count().
count($urarray) - This function returns the number of
elements in an array. Interestingly if you just pass a simple var instead of an
array, count() will return 1.
Question 57. How Many
Ways I Can Redirect A Php Page?
Answer :
Here are the possible
ways of php page redirection.
Using Java script:
'; echo 'window.location.href="'.$filename.'";'; echo ''; echo '';
echo ''; echo ''; } }
redirect
Using php function: header
Question 58. How Many
Ways We Can Pass The Variable Through The Navigation Between The Pages?
Answer :
At least 3 ways:
1. Put the variable into session in the first page, and get it back from
session in the next page.
2. Put the variable into cookie in the first page, and get it back from the
cookie in the next page.
3. Put the variable into a hidden form field, and get it back from the form in
the next page.
Question 59. What Is The
Maximum Length Of A Table Name, A Database Name, Or A Field Name In Mysql?
Answer :
Database name: 64
characters
Table name: 64 characters
Column name: 64 characters
Question 60. How Many
Values Can The Set Function Of Mysql Take?
Answer :
MySQL SET function can
take zero or more values, but at the maximum it can take 64 values.
Question 61. What Are
The Other Commands To Know The Structure Of A Table Using Mysql Commands Except
Explain Command?
Answer :
DESCRIBE table_name;
Question 62. How Can We
Find The Number Of Rows In A Table Using Mysql?
Answer :
Use this for MySQL
SELECT COUNT(*) FROM table_name;
Question 63. What
Changes I Have To Do In Php.ini File For File Uploading?
Answer :
Make the following line
uncomment like:
; Whether to allow HTTP file uploads.
file_uploads = On
; Temporary directory for HTTP uploaded files (will use system default if not
; specified).
upload_tmp_dir = C:\apache2triad\temp
; Maximum allowed size for uploaded files.
upload_max_filesize = 2M
Question 64. What's The
Difference Between Md5(), Crc32() And Sha1() Crypto On Php?
Answer :
The major difference is
the length of the hash generated. CRC32 is, evidently, 32 bits, while sha1()
returns a 128 bit value, and md5() returns a 160 bit value. This is important
when avoiding collisions.
Question 65. How Can We
Find The Number Of Rows In A Result Set Using Php?
Answer :
Here is how can you find
the number of rows in a result set in PHP:
$result =
mysql_query($any_valid_sql, $database_link);
$num_rows = mysql_num_rows($result);
echo "$num_rows rows found";
Question 66. What Is The
Default Session Time In Php And How Can I Change It?
Answer :
The default session time
in php is until closing of browser.
Question 67. How Many
Ways We Can We Find The Current Date Using Mysql?
Answer :
SELECT CURDATE();
SELECT CURRENT_DATE();
SELECT CURTIME();
SELECT CURRENT_TIME();
Question 68. How Many
Ways We Can Give The Output To A Browser?
Answer :
HTML output
PHP, ASP, JSP, Servlet Function
Script Language output Function
Different Type of embedded Package to output to a browser.
Question 69. Please Give
A Regular Expression (preferably Perl/preg Style), Which Can Be Used To
Identify The Url From Within A Html Link Tag?
Answer :
Try this:
/href="([^"]*)"/i.
Question 70. Give The
Syntax Of Grant Commands?
Answer :
The generic syntax for
GRANT is as following
GRANT [rights] on [database] TO [username@hostname] IDENTIFIED BY [password]
Now rights can be:
a) ALL privilages
b) Combination of CREATE, DROP, SELECT, INSERT, UPDATE and DELETE etc.
We can grant rights on
all databse by usingh *.* or some specific database by database.* or a specific
table by database.table_name.
Question 71. What Are
The Different Ways To Login To A Remote Server? Explain The Means, Advantages
And Disadvantages?
Answer :
There is at least 3 ways
to logon to a remote server:
Use ssh or telnet if you concern with security
You can also use rlogin to logon to a remote server.
Question 72. Give The
Syntax Of Revoke Commands?
Answer :
The generic syntax for
revoke is as following
REVOKE [rights] on [database] FROM [username@hostname]
Now rights can be:
a) ALL privilages
b) Combination of CREATE, DROP, SELECT, INSERT, UPDATE and DELETE etc.
We can grant rights on
all databse by usingh *.* or some specific database by database.* or a specific
table by database.table_name.
Question 73. When
Viewing An Html Page In A Browser, The Browser Often Keeps This Page In Its
Cache. What Can Be Possible Advantages/disadvantages Of Page Caching? How Can
You Prevent Caching Of A Certain Page (please Give Several Alternate
Solutions)?
Answer :
When you use the metatag
in the header section at the beginning of an HTML Web page, the Web page may
still be cached in the Temporary Internet Files folder.
A page that Internet
Explorer is browsing is not cached until half of the 64 KB buffer is filled.
Usually, metatags are inserted in the header section of an HTML document, which
appears at the beginning of the document. When the HTML code is parsed, it is read
from top to bottom. When the metatag is read, Internet Explorer looks for the
existence of the page in cache at that exact moment. If it is there, it is
removed. To properly prevent the Web page from appearing in the cache, place
another header section at the end of the HTML document.
Question 74. When You
Want To Show Some Part Of A Text Displayed On An Html Page In Red Font Color?
What Different Possibilities Are There To Do This? What Are The
Advantages/disadvantages Of These Methods?
Answer :
There are 2 ways to show
some part of a text in red:
Using HTML tag <font
color="red">
2. Using HTML tag </font>
Question 75. What Is The
Difference Between Char And Varchar Data Types?
Answer :
CHAR is a fixed length
data type. CHAR(n) will take n characters of storage even if you enter less
than n characters to that column. For example, "Hello!" will be
stored as "Hello! " in CHAR(10) column.
VARCHAR is a variable
length data type. VARCHAR(n) will take only the required storage for the actual
number of characters entered to that column. For example, "Hello!"
will be stored as "Hello!" in VARCHAR(10) column.
Question 76. How Can We
Encrypt And Decrypt A Data Present In A Mysql Table Using Mysql?
Answer :
AES_ENCRYPT() and
AES_DECRYPT().
Question 77. How Can We
Change The Name Of A Column Of A Table?
Answer :
MySQL query to rename
table: RENAME TABLE tbl_name TO new_tbl_name
or,
ALTER TABLE tableName CHANGE OldName newName.
Question 78. How Can
Increase The Performance Of Mysql Select Query?
Answer :
We can use LIMIT to stop
MySql for further search in table after we have received our required no. of
records, also we can use LEFT JOIN or RIGHT JOIN instead of full join in cases
we have related data in two or more tables.
Question 79. Will
Comparison Of String "10" And Integer 11 Work In Php?
Answer :
Yes, internally PHP will
cast everything to the integer type, so numbers 10 and 11 will be compared.
Question 80. What Type
Of Inheritance That Php Supports?
Answer :
In PHP an extended class
is always dependent on a single base class, that is, multiple inheritance is
not supported. Classes are extended using the keyword 'extends'.
Question 81. What Is The
Functionality Of Md5 Function In Php?
Answer :
string md5(string)
It calculates the MD5 hash of a string. The hash is a 32-character hexadecimal
number.
Question 82. How Can I
Load Data From A Text File Into A Table?
Answer :
The MySQL provides a
LOAD DATA INFILE command. You can load data from a file.
Great tool but you need to make sure that:
Data must be delimited.
b) Data fields must match table columns correctly.
Question 83. How Can We
Know The Number Of Days Between Two Given Dates Using Mysql?
Answer :
Use DATEDIFF()
SELECT DATEDIFF(NOW(),'2006-07-01');
Question 84. How Can We
Change The Data Type Of A Column Of A Table?
Answer :
This will change the
data type of a column:
ALTER TABLE table_name CHANGE colm_name same_colm_name [new data type].
Question 85. How Can We
Know That A Session Is Started Or Not?
Answer :
A session starts by
session_start() function.
This session_start() is always declared in header portion. it always declares
first. then we write session_ register().
Question 86. What Are
The Advantages And Disadvantages Of Cascade Style Sheets?
Answer :
External Style Sheets
Advantages
Can control styles for multiple documents at once Classes can be created for
use on multiple HTML element types in many documents Selector and grouping
methods can be used to apply styles under complex contexts
Disadvantages
An extra download is
required to import style information for each document The rendering of the
document may be delayed until the external style sheet is loaded Becomes
slightly unwieldy for small quantities of style definitions
Embedded Style Sheets
Advantages
Classes can be created for use on multiple tag types in the document Selector
and grouping methods can be used to apply styles under complex contexts No
additional downloads necessary to receive style information
Disadvantage
This method can not
control styles for multiple documents at once
Inline Styles
Advantages
Useful for small quantities of style definitions Can override other style
specification methods at the local level so only exceptions need to be listed
in conjunction with other style methods
Disadvantages
Does not distance style
information from content (a main goal of SGML/HTML) Can not control styles for
multiple documents at once Author can not create or control classes of elements
to control multiple element types within the document Selector grouping methods
can not be used to create complex element addressing scenarios
Question 87. If We Login
More Than One Browser Windows At The Same Time With Same User And After That We
Close One Window, Then Is The Session Is Exist To Other Windows Or Not? And If
Yes Then Why? If No Then Why?
Answer :
Session depends on
browser. If browser is closed then session is lost. The session data will be
deleted after session time out. If connection is lost and you recreate
connection, then session will continue in the browser.
Question 88. What's The
Difference Between Accessing A Class Method Via -> And Via ::?
Answer :
:: is allowed to access
methods that can perform static operations, i.e. those, which do not require
object initialization.
Question 89. What Are
The Mysql Database Files Stored In System ?
Answer :
Data is stored in
name.myd
Table structure is stored in name.frm
Index is stored in name.myi
Question 90. Explain
Normalization Concept?
Answer :
The normalization
process involves getting our data to conform to three progressive normal forms,
and a higher level of normalization cannot be achieved until the previous
levels have been achieved (there are actually five normal forms, but the last
two are mainly academic and will not be discussed).
First Normal Form
The First Normal Form (or 1NF) involves removal of redundant data from
horizontal rows. We want to ensure that there is no duplication of data in a
given row, and that every column stores the least amount of information
possible (making the field atomic).
Second Normal Form
Where the First Normal Form deals with redundancy of data across a horizontal
row, Second Normal Form (or 2NF) deals with redundancy of data in vertical
columns. As stated earlier, the normal forms are progressive, so to achieve
Second Normal Form, your tables must already be in First Normal Form.
Third Normal Form
I have a confession to make; I do not often use Third Normal Form. In Third
Normal Form we are looking for data in our tables that is not fully dependant
on the primary key, but dependant on another value in the table
Question 91. What Is The
Difference Between Php4 And Php5?
Answer :
PHP4 cannot support oops
concepts and Zend engine 1 is used.
PHP5 supports oops concepts and Zend engine 2 is used.
Error supporting is increased in PHP5.
XML and SQLLite will is increased in PHP5.
Question 92. What Are
The Advantages Of Stored Procedures, Triggers, Indexes?
Answer :
A stored procedure is a
set of SQL commands that can be compiled and stored in the server. Once this
has been done, clients don't need to keep re-issuing the entire query but can
refer to the stored procedure. This provides better overall performance because
the query has to be parsed only once, and less information needs to be sent
between the server and the client. You can also raise the conceptual level by
having libraries of functions in the server. However, stored procedures of
course do increase the load on the database server system, as more of the work
is done on the server side and less on the client (application) side. Triggers
will also be implemented. A trigger is effectively a type of stored procedure,
one that is invoked when a particular event occurs. For example, you can
install a stored procedure that is triggered each time a record is deleted from
a transaction table and that stored procedure automatically deletes the
corresponding customer from a customer table when all his transactions are
deleted.
Indexes are used to find
rows with specific column values quickly. Without an index, MySQL must begin
with the first row and then read through the entire table to find the relevant
rows. The larger the table, the more this costs. If the table has an index for
the columns in question, MySQL can quickly determine the position to seek to in
the middle of the data file without having to look at all the data. If a table
has 1,000 rows, this is at least 100 times faster than reading sequentially. If
you need to access most of the rows, it is faster to read sequentially, because
this minimizes disk seeks.
Question 93. What Are
The Difference Between Abstract Class And Interface?
Answer :
Abstract class: abstract classes are
the class where one or more methods are abstract but not necessarily all method
has to be abstract. Abstract methods are the methods, which are declare in its
class but not define. The definition of those methods must be in its extending
class.
Interface: Interfaces are one
type of class where all the methods are abstract. That means all the methods
only declared but not defined. All the methods must be define by its
implemented class
Question 94. Can We Use
Include(abc.php) Two Times In A Php Page Makeit.php?
Answer :
Yes we can include that
many times we want, but here are some things to make sure of: (including
abc.PHP, the file names are case-sensitive) there shouldn't be any duplicate
function names, means there should not be functions or classes or variables
with the same name in abc.PHP and makeit.php.
Question 95. How Can I
Make A Script That Can Be Bilingual (supports English, German)?
Answer :
You can change char set
variable in above line in the script to support bi language.
Question 96. What Is The
Maximum Size Of A File That Can Be Uploaded Using Php And How Can We Change
This?
Answer :
You can change maximum
size of a file set upload_max_filesize variable in php.ini file.
Question 97. How Can We
Get Second Of The Current Time Using Date Function?
Answer :
$second =
date("s");
Question 98. What Are
The Differences Between Mysql_fetch_array(), Mysql_fetch_object(),
Mysql_fetch_row()?
Answer :
mysql_fetch_array
- Fetch
a result row as an associative array and a numeric array.
mysql_fetch_object - Returns an object
with properties that correspond to the fetched row and moves the internal data
pointer ahead. Returns an object with properties that correspond to the fetched
row, or FALSE if there are no more rows.
mysql_fetch_row()
- Fetches
one row of data from the result associated with the specified result
identifier. The row is returned as an array. Each result column is stored in an
array offset, starting at offset 0.
Question 99. What Are
The Features And Advantages Of Object Oriented Programming?
Answer :
One of the main
advantages of OO programming is its ease of modification; objects can easily be
modified and added to a system there by reducing maintenance costs. OO
programming is also considered to be better at modeling the real world than is
procedural programming. It allows for more complicated and flexible
interactions. OO systems are also easier for non-technical personnel to
understand and easier for them to participate in the maintenance and
enhancement of a system because it appeals to natural human cognition patterns.
For some systems, an OO approach can speed development time since many objects
are standard across systems and can be reused. Components that manage dates,
shipping, shopping carts, etc. can be purchased and easily modified for a
specific system.
Question 100. What Are
The Reasons For Selecting Lamp (linux, Apache, Mysql, Php) Instead Of
Combination Of Other Software Programs, Servers And Operating Systems?
Answer :
All of those are open
source resource. Security of Linux is very more than windows. Apache is a
better server that IIS both in functionality and security. Mysql is world most
popular open source database. Php is more faster that asp or any other scripting
language.
Question 101. What Is
Meant By Nl2br()?
Answer :
nl2br() inserts a HTML
tag
before all new line characters n in a string.
echo nl2br("god
bless n you");
output:
god bless
you
Question 102. What Are
The Current Versions Of Apache, Php, And Mysql?
Answer :
PHP: PHP 5.1.2
MySQL: MySQL 5.1
Apache: Apache 2.1
Question 103. How Can We
Encrypt And Decrypt A Data Presented In A Table Using Mysql?
Answer :
You can use functions:
AES_ENCRYPT() and AES_DECRYPT() like:
AES_ENCRYPT(str,
key_str)
AES_DECRYPT(crypt_str, key_str)
Question 104. How Can We
Destroy The Cookie?
Answer :
Set the cookie with a
past expiration time.
Question 105. How Can I
Retrieve Values From One Database Server And Store Them In Other Database
Server Using Php?
Answer :
For this purpose, you
can first read the data from one server into session variables. Then connect to
other server and simply insert the data into the database.
Question 106. How Can We
Submit From Without A Submit Button?
Answer :
Trigger the JavaScript
code on any event ( like onSelect of drop down list box, onfocus, etc )
document. myform.submit(); This will submit the form.
Question 107. Who Is The
Father Of Php And What Is The Current Version Of Php And Mysql?
Answer :
Rasmus Lerdorf.
PHP 5.1. Beta
MySQL 5.0
Question 108. Tools Used
For Drawing Er Diagrams?
Answer :
Case Studio.
Smart Draw.
Question 109. In How
Many Ways We Can Retrieve Data In The Result Set Of Mysql Using Php?
Answer :
mysql_fetch_array - Fetch a result row
as an associative array, a numeric array, or both
mysql_fetch_assoc - Fetch a result row as an associative array
mysql_fetch_object - Fetch a result row as an object
mysql_fetch_row - Get a result row as an enumerated array
Question 110. What Are
The Functions For Imap?
Answer :
imap_body - Read the message body
imap_check - Check current mailbox
imap_delete - Mark a message for deletion from current mailbox
imap_mail - Send an email message
Question 111. Check If A
Variable Is An Integer In Javascript ?
Answer :
var myValue =9.8;
if(parseInt(myValue)== myValue)
alert('Integer');
else
alert('Not an integer');
Question 112. What Are
Encryption Functions In Php?
Answer :
CRYPT()
MD5()
Question 113. What Types
Of Images That Php Supports ?
Answer :
Using imagetypes()
function to find out what types of images are supported in your PHP engine.
imagetypes() - Returns
the image types supported.
This function returns a
bit-field corresponding to the image formats supported by the version of GD
linked into PHP. The following bits are returned, IMG_GIF | IMG_JPG | IMG_PNG |
IMG_WBMP | IMG_XPM.
Question 114. What Is
The Difference Between Htmlentities() And Htmlspecialchars()?
Answer :
htmlspecialchars() - Convert some
special characters to HTML entities (Only the most widely used)
htmlentities() - Convert ALL
special characters to HTML entities.
Question 115. How To
Reset/destroy A Cookie ?
Answer :
Reset a cookie by
specifying expire time in the past:
Example: setcookie('Test',$i,time()-3600); // already expired time
Reset a cookie by specifying its name only
Example: setcookie('Test');
Question 116. What Is
The Functionality Of The Function Htmlentities?
Answer :
htmlentities() - Convert
all applicable characters to HTML entities
This function is identical to htmlspecialchars() in all ways, except with
htmlentities(), all characters which have HTML character entity equivalents are
translated into these entities.
Question 117. How Can We
Get The Properties (size, Type, Width, Height) Of An Image Using Php Image
Functions?
Answer :
To know the image size
use getimagesize() function
To know the image width use imagesx() function
To know the image height use imagesy() function
Question 118. How To Set
Cookies?
Answer :
setcookie('variable','value','time')
;
variable - name of the cookie variable
value - value of the cookie variable
time - expiry time
Example:
setcookie('Test',$i,time()+3600);
Test - cookie variable name
$i - value of the variable 'Test'
time()+3600 - denotes that the cookie will expire after an one hour.
Question 119. How Can We
Increase The Execution Time Of A Php Script?
Answer :
By the use of void
set_time_limit(int seconds) Set the number of seconds a script is allowed to
run. If this is reached, the script returns a fatal error. The default limit is
30 seconds or, if it exists, the max_execution_time value defined in the
php.ini. If seconds is set to zero, no time limit is imposed.
When called,
set_time_limit() restarts the timeout counter from zero. In other words, if the
timeout is the default 30 seconds, and 25 seconds into script execution a call
such as set_time_limit(20) is made, the script will run for a total of 45
seconds before timing out.
Question 120. In How
Many Ways We Can Retrieve Data In The Result Set Of Mysql Using Php?
Answer :
mysql_fetch_array - Fetch a result
row as an associative array, a numeric array, or both.
mysql_fetch_assoc - Fetch a result
row as an associative array.
mysql_fetch_object - Fetch a result
row as an object.
mysql_fetch_row —- Get a result
row as an enumerated array.
Question 121. Who Is The
Father Of Php And What Is The Current Version Of Php And Mysql?
Answer :
Rasmus Lerdorf.
PHP 5.1. Beta
MySQL 5.0
Question 122. What's The
Difference Between Include And Require?
Answer :
It’s how they handle
failures. If the file is not found by require(), it will cause a fatal error
and halt the execution of the script. If the file is not found by include(), a
warning will be issued, but execution will continue.
Question 123. Steps For
The Payment Gateway Processing?
Answer :
An online payment
gateway is the interface between your merchant account and your Web site. The
online payment gateway allows you to immediately verify credit card transactions
and authorize funds on a customer’s credit card directly from your Web site. It
then passes the transaction off to your merchant bank for processing, commonly
referred to as transaction batching.
Question 124. Can We Use
Include(abc.php) Two Times In A Php Page Makeit.php?
Answer :
Yes we can include that
many times we want, but here are some things to make sure of: (including
abc.PHP, the file names are case-sensitive).
there shouldn't be any duplicate function names, means there should not be functions
or classes or variables with the same name in abc.PHP and makeit.php.
Question 125. How Many
Ways We Can Give The Output To A Browser?
Answer :
HTML output
PHP, ASP, JSP, Servlet Function
Script Language output Function
Different Type of embedded Package to output to a browser.
Question 126. What Are
The Different Ways To Login To A Remote Server? Explain The Means, Advantages
And Disadvantages?
Answer :
There is at least 3 ways
to logon to a remote server:
Use ssh or telnet if you concern with security
You can also use rlogin to logon to a remote server.
Question 127. What Is
Meant By Mime?
Answer :
MIME is Multipurpose
Internet Mail Extensions is an Internet standard for the format of e-mail.
However browsers also uses MIME standard to transmit files. MIME has a header
which is added to a beginning of the data. When browser sees such header it
shows the data as it would be a file (for example image) Some examples of MIME
types:
audio/x-ms-wmp
image/png
application/x-shockwave-flash
Question 128. What Is
The Difference Between Group By And Order By In Sql?
Answer :
To sort a result, use an
ORDER BY clause.
The most general way to satisfy a GROUP BY clause is to scan the whole table
and create a new temporary table where all rows from each group are
consecutive, and then use this temporary table to discover groups and apply
aggregate functions (if any). ORDER BY [col1],[col2],...[coln]; Tells DBMS
according to what columns it should sort the result. If two rows will have the
same value in col1 it will try to sort them according to col2 and so on.
GROUP BY
[col1],[col2],...[coln]; Tells DBMS to group (aggregate) results with same
value of column col1. You can use COUNT(col1), SUM(col1), AVG(col1) with it, if
you want to count all items in group, sum all values or view average.
Question 129. Who Is The
Father Of Php And Explain The Changes In Php Versions?
Answer :
Rasmus Lerdorf is known
as the father of PHP.PHP/F1 2.0 is an early and no longer supported version of
PHP. PHP 3 is the successor to PHP/FI 2.0 and is a lot nicer. PHP 4 is the
current generation of PHP, which uses the Zend engine under the hood. PHP 5
uses Zend engine 2 which, among other things, offers many additionalOOP
features .
Question 130. Which Method
Do You Follow To Get A Record From A Million Records? (searching Not From
Database, From An Array In Php)?
Answer :
use array_searchfl,
array_keys, arrayyalues, array_key_exists, and in_array.
Question 131. Are
Namespaces Are There In Javascript?
Answer :
A namespace is a
container and allows you to bundle up all your functionality using a unique
name. In JavaScript, a namespace is really just an object that you’ve attached
all further methods, properties and objects. But it is not always necessary to
use namespace.
Question 132. What Is
'float' Property In Css?
Answer :
The float property sets
where an image or a text will appear in another element.
Question 133. What Are
The Advantages/disadvantages Of Mysql And Php?
Answer :
Both of them are open
source software (so free of cost), support cross platform. php is faster then
ASP and iSP.
Question 134. What Are
The File Upload Settings In Configuration File?
Answer :
There are several
settings in the PHP configuration file related to file uploading:
• file_uploads = On/Off - Whether or not to allow HTTP file uploads.
• upload_tmp_dir = directory - The temporary directory used for storing files
when doing file upload.
• upload_max_filesize = size - The maximum size of an uploaded file.
Question 135. How To
Uploaded Files To A Table?
Answer :
To store uploaded files
to MySQL database, you can use the normal SELECT statement as shown in the
modified processing_uploaded_files.php listed below:
<?php
$con = mysql_connect("localhost", "", "");
mysql_select_db("pickzy");
$error = $_FILES['pickzycenter_logo']['error'];
$tmp_name = $_FILES['pickzycenter_logo']['tmp_name'];
$size = $_FILES['pickzycenter_logo']['size'];
$name = $_FILES['pickzycenter_logo']['name'];
$type = $_FILES['pickzycenter_logo']['type'];
print("
\n");
if ($error == UPLOAD_ERR_OK && $size > 0) {
$fp = fopen($tmp_name, 'r');
$content = fread($fp, $size);
fclose($fp);
$content = addslashes($content);
$sql = "INSERT INTO pickzy_files (name, type, size, content)"
. " VALUES ('$name', '$type', $size, '$content')";
mysql_query($sql, $con);
print("File stored.\n");
} else {
print("Upload faield.\n");
}
print("
\n");
mysql_close($con);
?>
Note that addslashes() is used to add backslashes to special characters that
need to be protected in SQL statements.
Question 136. How To
Create A Table To Store Files?
Answer :
If you using MySQL
database and want to store files in database, you need to create BLOB columns,
which can holds up to 65,535 characters. Here is a sample script that creates a
table with a BLOB column to be used to store uploaded files:
<?php
$con = mysql_connect("localhost", "", "");
mysql_select_db("pickzy");
$sql = "CREATE TABLE pickzy_files ("
. " id INTEGER NOT NULL AUTO_INCREMENT"
. ", name VARCHAR(80) NOT NULL"
. ", type VARCHAR(80) NOT NULL"
. ", size INTEGER NOT NULL"
. ", content BLOB"
. ", PRIMARY KEY (id)"
. ")";
mysql_query($sql, $con);
mysql_close($con);
?>
Question 137. Why Do You
Need To Filter Out Empty Files?
Answer :
When you are processing
uploaded files, you need to check for empty files, because they could be
resulted from a bad upload process but the PHP engine could still give no
error.
For example, if a user
typed a bad file name in the upload field and submitted the form, the PHP
engine will take it as an empty file without raising any error. The script
below shows you an improved logic to process uploaded files:
<?php
$file = '\pickzycenter\images\pickzycenter.logo';
$error = $_FILES['pickzycenter_logo']['error'];
$tmp_name = $_FILES['pickzycenter_logo']['tmp_name'];
print("
\n");
if ($error==UPLOAD_ERR_OK) {
if ($_FILES['pickzycenter_logo']['size'] > 0) {
move_uploaded_file($tmp_name, $file);
print("File uploaded.\n");
} else {
print("Loaded file is empty.\n");
}
} else if ($error==UPLOAD_ERR_NO_FILE) {
print("No files specified.\n");
} else {
print("Upload faield.\n");
}
print("
\n");
?>
Question 138. How To
Move Uploaded Files To Permanent Directory?
Answer :
PHP stores uploaded
files in a temporary directory with temporary file names. You must move
uploaded files to a permanent directory, if you want to keep them permanently.
PHP offers the
move_uploaded_file() to help you moving uploaded files. The example script,
processing_ uploaded_files.php, below shows a good example:
<?php
$file = '\pickzycenter\images\pickzycenter.logo';
print("<pre>\n");
move_uploaded_file($_FILES['pickzycenter_logo']['tmp_name'], $file);
print("File uploaded: ".$file."\n");
print("</pre>\n");
?>
Note that you need to
change the permanent directory, "\pickzycenter\images\", used in this
script to something else on your Web server. If your Web server is provided by
a Web hosting company, you may need to ask them which directories you can use
to store files.
If you copy both
scripts, logo_upload.php and processing_uploaded_files.php, to your Web server,
you can try them to upload an image file to your Web server.
Question 139. How To
Process The Uploaded Files?
Answer :
How to process the uploaded
files? The answer is really depending on your application. For example:
You can attached the
outgoing emails, if the uploaded files are email attachments.
You can move them to
user's Web page directory, if the uploaded files are user's Web pages.
You can move them to a
permanent directory and save the files names in the database, if the uploaded
files are articles to be published on the Web site.
You can store them to
database tables, if you don't want store them as files.
Question 140. How Many
Escape Sequences Are Recognized In Single-quoted Strings?
Answer :
There are 2 escape
sequences you can use in single-quoted strings:
• \\ - Represents the back slash character.
• \' - Represents the single quote character.
Question 141. What Are
The Special Characters You Need To Escape In Double-quoted Stings?
Answer :
There are two special
characters you need to escape in a double-quote string: the double quote
(") and the back slash (\). Here is a PHP script example of double-quoted
strings:
<?php
echo "Hello world!";
echo "Tom said: \"Who's there?\"";
echo "\\ represents an operator.";
?>
This script will print:
Hello world!Tom said: "Who's there?"\ represents an operator.
Question 142. How Many
Escape Sequences Are Recognized In Double-quoted Strings?
Answer :
There are 12 escape
sequences you can use in double-quoted strings:
• \\ - Represents the back slash character.
• \" - Represents the double quote character.
• \$ - Represents the dollar sign.
• \n - Represents the new line character (ASCII code 10).
• \r - Represents the carriage return character (ASCII code 13).
• \t - Represents the tab character (ASCII code 9).
• \{ - Represents the open brace character.
• \} - Represents the close brace character.
• \[ - Represents the open bracket character.
• \] - Represents the close bracket character.
• \nnn - Represents a character as an octal value.
• \xnn - Represents a character as a hex value.
Question 143. How To
Include Variables In Double-quoted Strings?
Answer :
Variables included in
double-quoted strings will be interpolated. Their values will be concatenated
into the enclosing strings. For example, two statements in the following PHP
script will print out the same string:
<?php
$variable = "and";
echo "part 1 $variable part 2\n";
echo "part 1 ".$variable." part 2\n";
?>
This script will print:
part 1 and part 2
part 1 and part 2
Question 144. How To
Access A Specific Character In A String?
Answer :
Any character in a
string can be accessed by a special string element expression:
• $string{index} - The index is the position of the character counted from left
and starting from 0.
Here is a PHP script example:
<?php
$string = 'It\'s Friday!';
echo "The first character is $string{0}\n";
echo "The first character is {$string{0}}\n";
?>
This script will print:
The first character is It's Friday!{0}
The first character is I
Question 145. How To
Assigning A New Character In A String?
Answer :
The string element
expression, $string{index}, can also be used at the left side of an assignment
statement. This allows you to assign a new character to any position in a
string. Here is a PHP script example:
<?php
$string = 'It\'s Friday?';
echo "$string\n";
$string{11} = '!';
echo "$string\n";
?>
This script will print:
It's Friday?
It's Friday!
Question 146. How To Get
The Number Of Characters In A String?
Answer :
You can use the
"strlen()" function to get the number of characters in a string. Here
is a PHP script example of strlen():
<?php
print(strlen('It\'s Friday!'));
?>
This script will print:
12
Question 147. How To
Remove The New Line Character From The End Of A Text Line?
Answer :
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);
?>
Question 148. How To
Remove Leading And Trailing Spaces From User Input Values?
Answer :
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...
?>
Question 149. How To
Take A Substring From A Given String?
Answer :
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)."\n");
print("Position counted form right:
".substr($string,-7,3)."\n");
?>
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.
Question 150. How To
Replace A Substring In A Given String?
Answer :
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)."\n");
sleep(10*60);
print(substr_replace($string, "5", $pos, 2)."\n");
?>
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.
Question 151. How To
Convert Strings To Upper Or Lower Cases?
Answer :
Converting strings to
upper or lower cases are easy. Just use strtoupper() or strtolower() functions.
Here is a PHP script on how to use them:
<?php
$string = "PHP string functions are easy to use.";
$lower = strtolower($string);
$upper = strtoupper($string);
print("$lower\n");
print("$upper\n");
print("\n");
?>
This script will print:
php string functions are easy to use.
PHP STRING FUNCTIONS ARE EASY TO USE.
Question 152. How To
Convert The First Character To Upper Case?
Answer :
If you are processing an
article, you may want to capitalize the first character of a sentence by using
the ucfirst() function. You may also want to capitalize the first character of
every words for the article title by using the ucwords() function. Here is a
PHP script on how to use ucfirst() and ucwords():
<?php
$string = "php string functions are easy to use.";
$sentence = ucfirst($string);
$title = ucwords($string);
print("$sentence\n");
print("$title\n");
print("\n");
?>
This script will print:
Php string functions are easy to use.
Php String Functions Are Easy To Use.
Question 153. How To
Convert Strings In Hex Format?
Answer :
If you want convert a
string into hex format, you can use the bin2hex() function. Here is a PHP
script on how to use bin2hex():
<?php
$string = "Hello\tworld!\n";
print($string."\n");
print(bin2hex($string)."\n");
?>
This script will print:
Hello world!
48656c6c6f09776f726c64210a
Question 154. How To
Generate A Character From An Ascii Value?
Answer :
If you want to generate
characters from ASCII values, you can use the chr() function.
chr() takes the ASCII value in decimal format and returns the character
represented by the ASCII value. chr() complements ord(). Here is a PHP script
on how to use chr():
<?php
print(chr(72).chr(101).chr(108).chr(108).chr(111)."\n");
print(ord("H")."\n");
?>
This script will print:
Hello
72
Question 155. How To
Convert A Character To An Ascii Value?
Answer :
If you want to convert
characters to ASCII values, you can use the ord() function, which takes the
first charcter of the specified string, and returns its ASCII value in decimal
format. ord() complements chr(). Here is a PHP script on how to use ord():
<?php
print(ord("Hello")."\n");
print(chr(72)."\n");
?>
This script will print:
72
H
Question 156. How To
Join Multiple Strings Into A Single String?
Answer :
If you multiple strings
stored in an array, you can join them together into a single string with a
given delimiter by using the implode() function. Here is a PHP script on how to
use implode():
<?php
$date = array('01', '01', '2006');
$keys = array('php', 'string', 'function');
print("A formated date:
".implode("/",$date)."\n");
print("A keyword list: ".implode(",
",$keys)."\n");
?>
This script will print:
A formated date: 01/01/2006
A keyword list: php, string, function
Question 157. What Is An
Array In Php?
Answer :
An array in PHP is
really an ordered map of pairs of keys and values.
Comparing with Perl, an array in PHP is not like a normal array in Perl. An
array in PHP is like an associate array in Perl. But an array in PHP can work
like a normal array in Perl.
Comparing with Java, an array in PHP is not like an array in Java. An array in
PHP is like a TreeMap class in Java. But an array in PHP can work like an array
in Java.
Question 158. How To
Test If A Variable Is An Array?
Answer :
Testing if a variable is
an array is easy. Just use the is_array() function. Here is a PHP script on how
to use is_array():
<?php
$var = array(0,0,7);
print("Test 1: ". is_array($var)."\n");
$var = array();
print("Test 2: ". is_array($var)."\n");
$var = 1800;
print("Test 3: ". is_array($var)."\n");
$var = true;
print("Test 4: ". is_array($var)."\n");
$var = null;
print("Test 5: ". is_array($var)."\n");
$var = "PHP";
print("Test 6: ". is_array($var)."\n");
print("\n");
?>
This script will print:
Test 1: 1
Test 2: 1
Test 3:
Test 4:
Test 5:
Test 6:
Question 159. How To
Retrieve Values Out Of An Array?
Answer :
You can retrieve values
out of arrays using the array element expression $array[$key].
Here is a PHP example script:
<?php $languages = array(); $languages["Zero"] = "PHP";
$languages["One"] = "Perl";
$languages["Two"] = "Java"; print("Array with inserted
values:\n");
print_r($languages); ?>
This script will print:
Array with default keys:
The second value: Perl
Array with specified keys:
The third value: Java
Question 160. How Values
In Arrays Are Indexed?
Answer :
Values in an array are
all indexed their corresponding keys. Because we can use either an integer or a
string as a key in an array, we can divide arrays into 3 categories:
Numerical Array - All
keys are sequential integers.
Associative Array - All
keys are strings.
Mixed Array - Some keys
are integers, some keys are strings.
Question 161. How The
Values Are Ordered In An Array?
Answer :
PHP says that an array
is an ordered map. But how the values are ordered in an array?
The answer is simple. Values are stored in the same order as they are inserted
like a queue. If you want to reorder them differently, you need to use a sort
function. Here is a PHP script show you the order of array values:
<?php
$mixed = array();
$mixed["Two"] = "Java";
$mixed["3"] = "C+";
$mixed["Zero"] = "PHP";
$mixed[1] = "Perl";
$mixed[""] = "Basic";
$mixed[] = "Pascal";
$mixed[] = "FORTRAN";
$mixed["Two"] = "";
unset($mixed[4]);
print("Order of array values:\n");
print_r($mixed);
?>
This script will print:
Order of array values:
Array
(
[Two] =>
[3] => C+
[Zero] => PHP
[1] => Perl
[] => Basic
[5] => FORTRAN
)
Question 162. How To Get
The Total Number Of Values In An Array?
Answer :
You can get the total
number of values in an array by using the count() function. Here is a PHP
example script:
<?php
$array = array("PHP", "Perl", "Java");
print_r("Size 1: ".count($array)."\n");
$array = array();
print_r("Size 2: ".count($array)."\n");
?>
This script will print:
Size 1: 3
Size 2: 0
Note that count() has an alias called sizeof().
Question 163. How To
Find A Specific Value In An Array?
Answer :
There are two functions
can be used to test if a value is defined in an array or not:
array_search($value,
$array) - Returns the first key of the matching value in the array, if found.
Otherwise, it returns false.
in_array($value, $array)
- Returns true if the $value is defined in $array.
Here is a PHP script on
how to use arrary_search():
<?php
$array = array("Perl",
"PHP", "Java", "PHP");
print("Search 1:
".array_search("PHP",$array)."n");
print("Search 2:
".array_search("Perl",$array)."n");
print("Search 3:
".array_search("C#",$array)."n");
print("n");
?>
This script will print:
Search 1: 1
Search 2: 0
Search 3:
Question 164. How To
Merge Values Of Two Arrays Into A Single Array?
Answer :
You can use the
array_merge() function to merge two arrays into a single array.
array_merge() appends all pairs of keys and values of the second array to the
end of the first array. Here is a PHP script on how to use array_merge():
<?php
$lang = array("Perl", "PHP", "Java",);
$os = array("i"=>"Windows",
"ii"=>"Unix", "iii"=>"Mac");
$mixed = array_merge($lang, $os);
print("Merged:\n");
print_r($mixed);
?>
This script will print:
Merged:
Array
(
[0] => Perl
[1] => PHP
[2] => Java
[i] => Windows
[ii] => Unix
[iii] => Mac
)
Question 165. How To
Randomly Retrieve A Value From An Array?
Answer :
If you have a list of
favorite greeting messages, and want to randomly select one of them to be used
in an email, you can use the array_rand() function. Here is a PHP example
script:
<?php
$array = array("Hello!", "Hi!", "Allo!",
"Hallo!", "Coucou!");
$key = array_rand($array);
print("Random greeting: ".$array[$key]."\n");
?>
This script will print:
Random greeting: Coucou!
Question 166. How To Pad
An Array With The Same Value Multiple Times?
Answer :
If you want to add the
same value multiple times to the end or beginning of an array, you can use the
array_pad($array, $new_size, $value) function. If the second argument,
$new_size, is positive, it will pad to the end of the array. If negative, it
will pad to the beginning of the array. If the absolute value of $new_size if
not greater than the current size of the array, no padding takes place. Here is
a PHP script on how to use array_pad():
<?php
$array = array("Zero"=>"PHP",
"One"=>"Perl", "Two"=>"Java");
$array = array_pad($array, 6, ">>");
$array = array_pad($array, -8, "---");
print("Padded:\n");
print(join(",", array_values($array)));
print("\n");
?>
This script will print:
Padded:
---,---,PHP,Perl,Java,>>,>>,>>
Question 167. How To
Join Multiple Strings Stored In An Array Into A Single String?
Answer :
If you multiple strings
stored in an array, you can join them together into a single string with a
given delimiter by using the implode() function. Here is a PHP script on how to
use implode():
<?php
$date = array('01', '01', '2006');
$keys = array('php', 'string', 'function');
print("A formated date:
".implode("/",$date)."\n");
print("A keyword list: ".implode(",
",$keys)."\n");
?>
This script will print:
A formated date: 01/01/2006
A keyword list: php, string, function
Question 168. How To
Define A User Function?
Answer :
You can define a user
function anywhere in a PHP script using the function statement like this:
"function name() {...}". Here is a PHP script example on how to
define a user function:
<?php
function msg() {
print("Hello world!\n");
}
msg();
?>
This script will print:
Hello world!
Question 169. How To
Invoke A User Function?
Answer :
You can invoke a
function by entering the function name followed by a pair of parentheses. If
needed, function arguments can be specified as a list of expressions enclosed
in parentheses. Here is a PHP script example on how to invoke a user function:
<?php
function hello($f) {
print("Hello $f!\n");
}
hello("Bob");
?>
This script will print:
Hello Bob!
Question 170. How To
Return A Value Back To The Function Caller?
Answer :
You can return a value
to the function caller by using the "return $value" statement.
Execution control will be transferred to the caller immediately after the
return statement. If there are other statements in the function after the
return statement, they will not be executed. Here is a PHP script example on
how to return values:
<?php
function getYear() {
$year = date("Y");
return $year;
}
print("This year is: ".getYear()."\n");
?>
This script will print:
This year is: 2006
Question 171. How To
Pass An Argument To A Function?
Answer :
To pass an argument to a
function, you need to:
•Add an argument definition in the function definition.
•Add a value as an argument when invoking the function.
Here is a PHP script on how to use arguments in a function():
<?php
function f2c($f) {
return ($f - 32.0)/1.8;
}
print("Celsius: ".f2c(100.0)."\n");
print("Celsius: ".f2c(-40.0)."\n");
?>
This script will print:
Celsius: 37.777777777778
Celsius: -40
Question 172. How
Variables Are Passed Through Arguments?
Answer :
Like more of other
programming languages, variables are passed through arguments by values, not by
references. That means when a variable is passed as an argument, a copy of the
value will be passed into the function. Modipickzyng that copy inside the
function will not impact the original copy. Here is a PHP script on passing
variables by values:
<?php
function swap($a, $b) {
$t = $a;
$a = $b;
$b = $t;
}
$x = "PHP";
$y = "JSP";
print("Before swapping: $x, $y\n");
swap($x, $y);
print("After swapping: $x, $y\n");
?>
This script will print:
Before swapping: PHP, JSP
After swapping: PHP, JSP
As you can see, original variables were not affected.
Question 173. How To
Pass Variables By References?
Answer :
You can pass a variable
by reference to a function by taking the reference of the original variable,
and passing that reference as the calling argument. Here is a PHP script on how
to use pass variables by references:
<?php
function swap($a, $b) {
$t = $a;
$a = $b;
$b = $t;
}
$x = "PHP";
$y = "JSP";
print("Before swapping: $x, $y\n");
swap(&$x, &$y);
print("After swapping: $x, $y\n");
?>
This script will print:
Before swapping: PHP, JSP
After swapping: JSP, PHP
As you can see, the function modified the original variable.
Note that call-time pass-by-reference has been deprecated. You need to define
arguments as references.
Question 174. Can You
Define An Argument As A Reference Type?
Answer :
You can define an
argument as a reference type in the function definition. This will
automatically convert the calling arguments into references. Here is a PHP
script on how to define an argument as a reference type:
<?php
function ref_swap(&$a, &$b) {
$t = $a;
$a = $b;
$b = $t;
}
$x = "PHP";
$y = "JSP";
print("Before swapping: $x, $y\n");
ref_swap($x, $y);
print("After swapping: $x, $y\n");
?>
This script will print:
Before swapping: PHP, JSP
After swapping: JSP, PHP
Question 175. Can You
Pass An Array Into A Function?
Answer :
You can pass an array
into a function in the same as a normal variable. No special syntax needed.
Here is a PHP script on how to pass an array to a function:
<?php
function average($array) {
$sum = array_sum($array);
$count = count($array);
return $sum/$count;
}
$numbers = array(5, 7, 6, 2, 1, 3, 4, 2);
print("Average: ".average($numbers)."\n");
?>
This script will print:
Average: 3.75
Question 176. How Arrays
Are Passed Through Arguments?
Answer :
Like a normal variable,
an array is passed through an argument by value, not by reference. That means
when an array is passed as an argument, a copy of the array will be passed into
the function. Modipickzyng that copy inside the function will not impact the
original copy. Here is a PHP script on passing arrays by values:
<?php
function shrink($array) {
array_splice($array,1);
}
$numbers = array(5, 7, 6, 2, 1, 3, 4, 2);
print("Before shrinking:
".join(",",$numbers)."\n");
shrink($numbers);
print("After shrinking:
".join(",",$numbers)."\n");
?>
This script will print:
Before shrinking: 5,7,6,2,1,3,4,2
After shrinking: 5,7,6,2,1,3,4,2
As you can see, original variables were not affected.
Question 177. Can You
Define An Array Argument As A Reference Type?
Answer :
You can define an array
argument as a reference type in the function definition. This will
automatically convert the calling arguments into references. Here is a PHP
script on how to define an array argument as a reference type:
<?php
function ref_shrink(&$array) {
array_splice($array,1);
}
$numbers = array(5, 7, 6, 2, 1, 3, 4, 2);
print("Before shrinking:
".join(",",$numbers)."\n");
ref_shrink($numbers);
print("After shrinking:
".join(",",$numbers)."\n");
?>
This script will print:
BBefore shrinking: 5,7,6,2,1,3,4,2
After shrinking: 5
Question 178. What Is
The Scope Of A Variable Defined In A Function?
Answer :
The scope of a local
variable defined in a function is limited with that function. Once the function
is ended, its local variables are also removed. So you can not access any local
variable outside its defining function. Here is a PHP script on the scope of
local variables in a function:
<?php
?>
function myPassword() {
$password = "U8FIE8W0";
print("Defined inside the function? ".
isset($password)."\n");
}
myPassword();
print("Defined outside the function? ".
isset($password)."\n");
?>
This script will print:
Defined inside the function? 1
Defined outside the function?
Question 179. What Is
The Scope Of A Variable Defined Outside A Function?
Answer :
A variable defined
outside any functions in main script body is called global variable. However, a
global variable is not really accessible globally any in the script. The scope
of global variable is limited to all statements outside any functions. So you
can not access any global variables inside a function. Here is a PHP script on
the scope of global variables:
<?php
?>
$login = "pickzycenter";
function myLogin() {
print("Defined inside the function? ". isset($login)."\n");
}
myLogin();
print("Defined outside the function? ". isset($login)."\n");
?>
This script will print:
Defined inside the function?
Defined outside the function? 1
Question 180. How To
Access A Global Variable Inside A Function?
Answer :
By default, global
variables are not accessible inside a function. However, you can make them
accessible by declare them as "global" inside a function. Here is a
PHP script on declaring "global" variables:
<?php
?>
$intRate = 5.5;
function myAccount() {
global $intRate;
print("Defined inside the function? ".
isset($intRate)."\n");
}
myAccount();
print("Defined outside the function? ".
isset($intRate)."\n");
?>
This script will print:
Defined inside the function? 1
Defined outside the function? 1
Question 181. How To
Specify Argument Default Values?
Answer :
If you want to allow the
caller to skip an argument when calling a function, you can define the argument
with a default value when defining the function. Adding a default value to an
argument can be done like this "function name($arg=expression){}. Here is
a PHP script on how to specify default values to arguments:
<?php
function printKey($key="download") {
print("PHP $key\n");
}
printKey();
printKey("hosting");
print("\n");
?>
This script will print:
PHP download
PHP hosting
Question 182. How To
Define A Function With Any Number Of Arguments?
Answer :
If you want to define a
function with any number of arguments, you need to:
•Declare the function with no argument.
•Call func_num_args() in the function to get the number of the arguments.
•Call func_get_args() in the function to get all the arguments in an array.
Here is a PHP script on how to handle any number of arguments:
<?php
function myAverage() {
$count = func_num_args();
$args = func_get_args();
$sum = array_sum($args);
return $sum/$count;
}
$average = myAverage(102, 121, 105);
print("Average 1: $average\n");
$average = myAverage(102, 121, 105, 99, 101, 110, 116, 101, 114);
print("Average 2: $average\n");
?>
This script will print:
Average 1: 109.33333333333
Average 2: 107.66666666667
Question 183. How To
Read The Entire File Into A Single String?
Answer :
If you have a file, and
you want to read the entire file into a single string, you can use the
file_get_contents() function. It opens the specified file, reads all characters
in the file, and returns them in a single string. Here is a PHP script example
on how to file_get_contents():
<?php
$file = file_get_contents("/windows/system32/drivers/etc/services");
print("Size of the file: ".strlen($file)."\n");
?>
This script will print:
Size of the file: 7116
Question 184. How To
Open A File For Reading?
Answer :
If you want to open a
file and read its contents piece by piece, you can use the fopen($fileName,
"r") function. It opens the specified file, and returns a file
handle. The second argument "r" tells PHP to open the file for
reading. Once the file is open, you can use other functions to read data from
the file through this file handle. Here is a PHP script example on how to use
fopen() for reading:
<?php
$file = fopen("/windows/system32/drivers/etc/hosts", "r");
print("Type of file handle: " . gettype($file) . "\n");
print("The first line from the file handle: " . fgets($file));
fclose($file);
?>
This script will print:
Type of file handle: resource
The first line from the file handle: # Copyright (c) 1993-1999
Note that you should always call fclose() to close the opened file when you are
done with the file.
Question 185. How To
Open A File For Writing?
Answer :
If you want to open a
new file and write date to the file, you can use the fopen($fileName, "w")
function. It creates the specified file, and returns a file handle. The second
argument "w" tells PHP to open the file for writing. Once the file is
open, you can use other functions to write data to the file through this file
handle. Here is a PHP script example on how to use fopen() for writing:
<?php
$file = fopen("/temp/todo.txt", "w");
fwrite($file,"Download PHP scripts at dev.pickzycenter.com.\r\n");
fclose($file);
?>
This script will write the following to the file:
Download PHP scripts at dev.pickzycenter.com.
Note that you should use "\r\n" to terminate lines on Windows. On a
Unix system, you should use "\n".
Question 186. How To
Read One Character From A File?
Answer :
If you have a text file,
and you want to read the file one character at a time, you can use the fgetc()
function. It reads the current character, moves the file pointer to the next
character, and returns the character as a string. If end of the file is
reached, fgetc() returns Boolean false. Here is a PHP script example on how to
use fgetc():
<?php
$file = fopen("/windows/system32/drivers/etc/services",
"r");
$count = 0;
while ( ($char=fgetc($file)) !== false ) {
if ($char=="/") $count++;
}
fclose($file);
print("Number of /: $count\n");
?>
This script will print:
Number of /: 113
Note that rtrim() is used to remove "\n" from the returning string of
fgets().
Question 187. How To
Read A File In Binary Mode?
Answer :
If you have a file that
stores binary data, like an executable program or picture file, you need to
read the file in binary mode to ensure that none of the data gets modified
during the reading process. You need to:
•Open the file with fopen($fileName, "rb").
•Read data with fread($fileHandle,$length).
Here is a PHP script example on reading binary file:
<?php
$in = fopen("/windows/system32/ping.exe", "rb");
$out = fopen("/temp/myPing.exe", "w");
$count = 0;
while (!feof($in)) {
$count++;
$buffer = fread($in,64);
fwrite($out,$buffer);
}
fclose($out);
fclose($in);
print("About ".($count*64)." bytes read.\n");
?>
This script will print:
About 16448 bytes read.
This script actually copied an executable program file ping.exe in binary mode
to new file. The new file should still be executable.
Question 188. How To
Open Standard Output As A File Handle?
Answer :
If you want to open the
standard output as a file handle yourself, you can use the
fopen("php://stdout") function. It creates a special file handle
linking to the standard output, and returns the file handle. Once the standard
output is opened to a file handle, you can use fwrite() to write data to the
starndard output like a regular file. Here is a PHP script example on how to
write to standard output:
<?php
$stdout = fopen("php://stdout", "w");
fwrite($stdout,"To do:\n");
fwrite($stdout,"Looking for PHP hosting provider!\n");
fclose($stdout);
?>
This script will print:
What's your name?
To do:
Looking for PHP hosting provider!
If you don't want to open the standard output as a file handle yourself, you
can use the constant STDOUT predefined by PHP as the file handle for standard
output.
If you are using your script in a Web page, standard output is merged into the
Web page HTML document.
print() and echo() also writes to standard output.
Question 189. How To
Create A Directory?
Answer :
You can use the mkdir()
function to create a directory. Here is a PHP script example on how to use
mkdir():
<?php
if (file_exists("/temp/download")) {
print("Directory already exists.\n");
} else {
mkdir("/temp/download");
print("Directory created.\n");
}
?>
This script will print:
Directory created.
If you run this script again, it will print:
Directory already exists.
Question 190. How To
Remove An Empty Directory?
Answer :
If you have an empty
existing directory and you want to remove it, you can use the rmdir(). Here is
a PHP script example on how to use rmdir():
<?php
if (file_exists("/temp/download")) {
rmdir("/temp/download");
print("Directory removed.\n");
} else {
print("Directory does not exist.\n");
}
?>
This script will print:
Directory removed.
If you run this script again, it will print:
Directory does not exist.
Question 191. How To
Remove A File?
Answer :
If you want to remove an
existing file, you can use the unlink() function. Here is a PHP script example
on how to use unlink():
<?php
if (file_exists("/temp/todo.txt")) {
unlink("/temp/todo.txt");
print("File removed.\n");
} else {
print("File does not exist.\n");
}
?>
This script will print:
File removed.
If you run this script again, it will print:
File does not exist.
Question 192. How To
Copy A File?
Answer :
If you have a file and
want to make a copy to create a new file, you can use the copy() function. Here
is a PHP script example on how to use copy():
<?php
unlink("/temp/myPing.exe");
copy("/windows/system32/ping.exe", "/temp/myPing.exe");
if (file_exists("/temp/myPing.exe")) {
print("A copy of ping.exe is created.\n");
}
?>
This script will print:
A copy of ping.exe is created.
Question 193. How To Get
The Directory Name Out Of A File Path Name?
Answer :
If you have the full
path name of a file, and want to get the directory name portion of the path
name, you can use the dirname() function. It breaks the full path name at the
last directory path delimiter (/) or (\), and returns the first portion as the
directory name. Here is a PHP script example on how to use dirname():
<?php
$pathName = "/temp/download/todo.txt";
$dirName = dirname($pathName);
print("File full path name: $pathName\n");
print("File directory name: $dirName\n");
print("\n");
?>
This script will print:
File full path name: /temp/download/todo.txt
File directory name: /temp/download
Question 194. How To
Break A File Path Name Into Parts?
Answer :
If you have a file name,
and want to get different parts of the file name, you can use the pathinfo()
function. It breaks the file name into 3 parts: directory name, file base name
and file extension; and returns them in an array. Here is a PHP script example
on how to use pathinfo():
<?php
$pathName = "/temp/download/todo.txt";
$parts = pathinfo($pathName);
print_r($parts);
print("\n");
?>
This script will print:
Array
(
[dirname] => /temp/download
[basename] => todo.txt
[extension] => txt
)
Question 195. How To
Create A Web Form?
Answer :
If you take input data
from visitors on your Web site, you can create a Web form with input fields to
allow visitors to fill in data and submit the data to your server for
processing. A Web form can be created with the <FORM> tag with some input
tags. The &FORM tag should be written in the following format:
<form action=processing.php method=get/post>
......
</form>
Where "processing.php" specifies the PHP page that processes the
submitted data in the form.
Question 196. What Are
Form Input Html Tags?
Answer :
HTML tags that can be
used in a form to collect input data are:
•<SUBMIT ...> - Displayed as a button allow users to submit the form.
•<INPUT TYPE=TEXT ...> - Displayed as an input field to take an input
string.
•<INPUT TYPE=RADIO ...> - Displayed as a radio button to take an input
flag.
•<INPUT TYPE=CHECKBOX ...> - Displayed as a checkbox button to take an
input flag.
•<SELECT ...> - Displayed as a dropdown list to take input selection.
•<TEXTAREA ...> - Displayed as an input area to take a large amount of
input text.
Question 197. How To
Generate A Form?
Answer :
Generating a form seems
to be easy. You can use PHP output statements to generate the required
<FORM> tag and other input tags. But you should consider to organized
your input fields in a table to make your form looks good on the screen. The
PHP script below shows you a good example of HTML forms:
<?php
print("<html><form action=processing_forms.php
method=post>");
print("<table><tr><td colspan=2>Please enter and submit
your"
." comments about PICKZYCenter.com:</td></tr>");
print("<tr><td>Your Name:</td>"
."<td><input type=text
name=name></td></tr>\n");
print("<tr><td>Comments:</td>"
."<td><input type=text
name=comment></td></tr>\n");
print("<tr><td colspan=2><input
type=submit><td></tr></table>\n");
print("</form></html>\n");
?>
If you save this script as a PHP page, submit_comments.php, on your Web site,
and view this page, you will see a simple Web form.
Question 198. Where Is
The Submitted Form Data Stored?
Answer :
When a user submit a form
on your Web server, user entered data will be transferred to the PHP engine,
which will make the submitted data available to your PHP script for processing
in pre-defined arrays:
• $_GET - An associate array that store form data submitted with the GET
method.
• $_POST - An associate array that store form data submitted with the POST
method.
• $_REQUEST - An associate array that store form data submitted with either GET
or POST method. $_REQUEST also contains the cookie values received back from
the browser.
Question 199. What
Happens If An Expected Input Field Was Not Submitted?
Answer :
Obviously, if an
expected input field was not submitted, there will no entry in the $_REQUEST
array for that field. You may get an execution error, if you are not checking
the existence of the expected entries in $_REQUEST. For example, if you copy
processing_forms.php to your local Web server, and run your browser with
http://localhost/processing_forms.php?name=Joe, you will an error page like
this:
You have submitted the following information:
Name = Joe
Comments =
Thank you!
PHP Notice: Undefined index:
comment in ...\processing_forms.php on line 3
Question 200. How To
Avoid The Undefined Index Error?
Answer :
If you don't want your
PHP page to give out errors as shown in the previous exercise, you should
consider checking all expected input fields in $_REQUEST with the isset()
function as shown in the example script below:
<?php
if (isset($_REQUEST['name'])) {
$name = $_REQUEST['name'];
} else {
$name = "";
}
if (isset($_REQUEST['comment'])) {
$comment = $_REQUEST['comment'];
} else {
$comment = "";
}
print("<html><pre>");
print("You have submitted the following information:\n");
print(" Name = $name\n");
print(" Comments = $comment\n");
print("Thank you!\n");
print("</pre></html>\n");
?>
Question 201. How To
List All Values Of Submitted Fields?
Answer :
If you want list all
values of submitted fields, you can write a simple loop to retrieve all entries
in the $_REQUEST array. Below is an improved version of processing_forms.php to
list all submited input values:
<?php
print("<html><pre>");
$count = count($_REQUEST);
print("Number of values: $count\n");
foreach ($_REQUEST as $key=>$value) {
print(" $key = $value\n");
}
print("</pre></html>\n");
?>
Question 202. How To Retrieve
The Original Query String?
Answer :
If you have coded some
values in the URL without using the standard form GET format, you need to
retrieve those values in the original query string in $_SERVER['QUERY_STRING'].
The script below is an enhanced version of processing_forms.php which print the
original query string:
<?php
print("<html><pre>");
print(" query_string = {$_SERVER['QUERY_STRING']}\n");
$count = count($_REQUEST);
print("Number of values: $count\n");
foreach ($_REQUEST as $key=>$value) {
if (is_array($value)) {
print(" $key is an array\n");
for ($i = 0; $i < count($value); $i++) {
$sub_value = $value[$i];
if (get_magic_quotes_gpc()) {
$sub_value = stripslashes($sub_value);
}
print(" ".$key."[".$i."] =
".$sub_value."\n");
}
} else {
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
print(" $key = $value\n");
}
}
print("</pre></html>\n");
?>
Question 203. How To
Support Multiple-page Forms?
Answer :
If you have a long form
with a lots of fields, you may want to divide the fields into multiple groups
and present multiple pages with one group of fields on one page. This makes the
a long form more user-friendly. However, this requires you to write good
scripts that:
• When processing the first page and other middle pages, you must keep those
input values collected so far in the session or as hidden values in the next
page form.
• When processing the last page, you should collect all input values from all
pages for final process, like saving everything to the database.
Question 204. What Is A
Cookie?
Answer :
A cookie is a small
amount of information sent by a Web server to a web browser and then sent back
unchanged by the browser each time it accesses that server. HTTP cookies are
used for authenticating, tracking, and maintaining specific information about
users, such as site preferences and the contents of their electronic shopping
carts. The term "cookie" is derived from "magic cookie", a
well-known concept in computing which inspired both the idea and the name of
HTTP cookies.
A cookie consists of a cookie name and cookie value.
Question 205. How To
Send A Cookie To The Browser?
Answer :
If you want to sent a
cookie to the browser when it comes to request your PHP page, you can use the
setcookie( ) function. Note that you should call setcookie() function before
any output statements. The following script shows you how to set cookies:
<?php
setcookie("LoginName","XYZ");
setcookie("PreferredColor","Blue");
print("2 cookies were delivered.\n");
?>
Question 206. How To Receive
A Cookie From The Browser?
Answer :
If you know that a
cookie has been sent to the browser when it was visiting the server previously,
you can check the built-in $_COOKIE array, which contains all cookies that were
sent by the server previously. The script below shows you how to pickup one
cookie from the $_COOKIE and loop through all cookies in $_COOKIE:
<?php
if (isset($_COOKIE["LoginName"])) {
$loginName = $_COOKIE["LoginName"];
print("Received a cookie named as LoginName:
".$loginName."\n");
} else {
print("Did not received any cookie named as LoginName.\n");
}
print("All cookies received:\n");
foreach ($_COOKIE as $name => $value) {
print " $name = $value\n";
}
?>
Question 207. How
Cookies Are Transported From Servers To Browsers?
Answer :
Cookies are transported
from a Web server to a Web browser in the header area of the HTTP response
message. Each cookie will be included in a separate "Set-Cookie:"
header line in the following format:
Set-Cookie: name=value; expires=time; path=pathVal; domain=domainVal.
Question 208. How
Cookies Are Transported From Browsers To Servers?
Answer :
Cookies are transported
from a Web browser to a Web server in the header area of the HTTP request
message. Each cookie will be included in a separate "Cookie:" header
line in the following format:
GET / HTTP/1.1
Cookie: name1=value1
Cookie: name2=value2
Cookie: name3=value3
......
Accept: */*
Question 209. Where Are
The Persistent Cookies Stored On Your Computer?
Answer :
The location and file
names where persistent cookies are stored on your computer depend on which
browser you are using. If you using Microsoft Internet Explorer, persistent
cookies are stored in the \Documents and Settings\$user\Cookies directory.
Cookies are stored in multiple cookie files with one file per Web server. Check
your cookie directory on your local system, you will be surprised to see how
many Web servers are setting persistent cookies to your computer.
Question 210. How To
Delete Cookie Files On Your Computer?
Answer :
A simple way to delete
cookie files on your computer is to use the function offered by the IE browser.
The following tutorial exercise shows you how to delete cookie files created by
IE:
• Open IE (Internet Explorer)
• Go to Options/Internet Options
• Click the Delete Cookies button on the options dialog window.
Check the cookie directory again. All cookie files should be deleted.
Question 211. How Does
Firefox Manage Cookies?
Answer :
FireFox browser allows
you to delete old cookies, and gives you options to keep persistent cookies in
cookie files until they reach their expiration time. The following tutorial
shows you how to manage cookies in FireFox:
• Run FireFox
• Go to Tools/Options
• Click Privacy and then Cookies
• Click the Clear button to delete all old cookies
• Change the Keep Cookies option to "until they expire" to allow
persistent cookies to be store a cookie file.
Question 212. What Are
The Options To Transfer Session Ids?
Answer :
Once a new session is
created, its session ID must be transferred to the client browser and included
in the next client request, so that the PHP engine can find the same session
created by the same visitor. The PHP engine has two options to transfer the
session ID to the client browser:
As URL parameter - The Session ID will be
embedded in all URLs in the HTML document delivered to the client browser. When
the visitor clicks any of those URLs, the session ID will be returned back to
the Web server as part of the requesting URL.
As a cookie - The session ID will be
delivered as a cookie to the client browser. When visitor requests any other
pages on the Web server, the session ID will be returned back to the Web server
also as a cookie.
The PHP engine is
configured to use URL parameters for transferring session IDs by default.
Question 213. Is It More
Secure To Use Cookies To Transfer Session Ids?
Answer :
yes, because attacking
your Web site using URL parameters is much easier than using cookies.
So if you are the system administrator of your Web server, you should set
session.use_only_cookies=1.
If your Web server is provided by a hosting service provider, ask them to set
session.use_only_cookies=1.
Question 214. What Is
The Timeout Period On Session Values?
Answer :
The PHP engine has no
direct settings on session timeout period. But it has a session garbage
collection mechanism that you can set to remove those special files containing
session values. There are 3 settings you can use to define the session garbage
collection mechanism:
session.gc_probability = 1
session.gc_divisor = 1000
session.gc_maxlifetime = 1440
The first two settings tell the PHP engine to run the garbage collection
process once every 1000 requests received by the Web server. The last setting
tells the PHP engine to treat session values as garbage 1440 seconds after they
have not been used.
Putting all settings together, your session values probably be removed 1440
seconds after the visitor stopping using your Web site. The probability of this
removal is one over 1000 requests received after the 1440-second period.
In another word, if visitor John stopped using your site, and there is no other
visitors coming to your site, session values created for John will never be
removed. However, if you have a busy site, like 1000 requests per minute,
John's session values will be removed about one minute plus 1440 seconds after
John stopped using the site.
Question 215. How To Set
Session.gc_maxlifetime Properly?
Answer :
As you know that
session.gc_maxlifetime is the session value timeout period. You should set this
value based on the usage pattern of your visitors. Here are some suggestions:
# Set it to 20 minutes for a normal Web site:
session.gc_maxlifetime = 1200
# Set it to 24 hours if visitors comes to the site many time a day:
# Example: Yahoo email site expires your session in 24 hours.
session.gc_maxlifetime = 86400
Question 216. How To Set
Session.gc_divisor Properly?
Answer :
As you know that
session.gc_divisor is the frequency of when the session garbage collection
process will be executed. You should set this value based on the income request
traffic. Here are some suggestions:
# Set it to 10, if traffic is less than 10,000 per day:
session.gc_divisor = 10
# Set it to 100, if traffic is between 10,000 and 100,000 per day:
session.gc_divisor = 100
# Set it to 1000, if traffic is greater than 100,000 per day:
session.gc_divisor = 1000
Question 217. How To
Remove Values Saved In The Current Session?
Answer :
If you want to remove
values saved in the current session, you should use the unset() function on
those saved values in $_SESSION, or use array() to empty $_SESSION:
unset($_SESSION['MyColor'])
- Removes one value named MyColor in the current session.
$_SESSION = array() -
Removes all values in the current session.
unset($_SESSION) - Bad
statement. It may affect the session mechanism.
Question 218. How To
Close A Session Properly?
Answer :
Let's say you site
requires users to login. When a logged in user clicks the logout button, you
need to close the session associated with this user properly in 3 steps:
1. Remove all session values with $_SESSION = array().
2. Remove the session ID cookie with the setcookie() function.
3. Destroy the session object with the session_destroy() function.
Below is a good sample script:
<?php
session_start();
$_SESSION = array();
if (isset($_COOKIE[session_name()])) {
setcookie(session_name(), '', time()-42000, '/');
}
session_destroy();
print("<html><pre>");
print("Thank you for visiting PICKZYCenter.com.\n");
print(" <a href=login.php>Login Again.</a>\n");
print("</pre></html>\n");
?>
Question 219. What Is
Session_register()?
Answer :
session_register() is
old function that registers global variables into the current session. You should
stop using session_register() and use array $_SESSION to save values into the
current session now.
Question 220. What Do
You Need To Connect Php To Mysql?
Answer :
If you want to access
MySQL database server in your PHP script, you need to make sure that MySQL
module is installed and turned on in your PHP engine. Check the PHP
configuration file, php.ini, to make sure the extension=php_mysql.dll is not
commented out.
The MySQL module offers a number of functions to allow you to work with MySQL
server. Some commonly used MySQL functions are:
• mysql_connect -- Open a connection to a MySQL Server
• mysql_close -- Close MySQL connection
• mysql_db_query -- Send a MySQL query
• mysql_fetch_array -- Fetch a result row as an associative array, a numeric
array, or both
• mysql_free_result -- Free result memory
• mysql_list_tables -- List tables in a MySQL database
• mysql_list_fields -- List MySQL table fields
Question 221. How To
Connect To Mysql From A Php Script?
Answer :
If you want access the
MySQL server, you must create a connection object first by calling the
mysql_connect() function in the following format:
$con = mysql_connect($server, $username, $password);
If you are connecting to a local MySQL server, you don't need to specify
username and password. If you are connecting to a MySQL server offered by your
Web hosting company, they will provide you the server name, username, and
password.
The following script shows you how to connect to a local MySQL server, obtained
server information, and closed the connection:
<?php
$con = mysql_connect('localhost');
print(mysql_get_server_info($con)."\n");
print(mysql_get_host_info($con)."\n");
mysql_close($con);
?>
Question 222. How To Run
A Sql Statement?
Answer :
You can run any types of
SQL statements through the mysql_query() function. It takes the SQL statement
as a string and returns different types of data depending on the SQL statement
type and execution status:
• Returning FALSE, if the execution failed.
• Returning a result set object, if the execution is successful on a SELECT
statement or other statement returning multiple rows of data.
• Returning TRUE, if the execution is successful on other statements.
Here is a good example of running a SQL statement with the mysql_query()
function:
<?php
include "mysql_connection.php";
$sql = 'SELECT sysdate() FROM dual';
$rs = mysql_query($sql, $con);
$row = mysql_fetch_array($rs);
print("Database current time: ". $row[0] ."\n");
mysql_close($con);
?>
Question 223. How To Get
The Number Of Rows Selected Or Affected By A Sql Statement?
Answer :
There are two functions
you can use the get the number of rows selected or affected by a SQL statement:
mysql_num_rows($rs) - Returns the number
of rows selected in a result set object returned from SELECT statement.
mysql_affected_rows() - Returns the
number of rows affected by the last INSERT, UPDATE or DELETE statement.
Question 224. What Is A
Result Set Object?
Answer :
A result set object is a
logical representation of data rows returned by mysql_query() function on
SELECT statements. Every result set object has an internal pointer used to
identify the current row in the result set. Once you get a result set object,
you can use the following functions to retrieve detail information:
• mysql_free_result($rs) - Closes this result set object.
• mysql_num_rows($rs) - Returns the number rows in the result set.
• mysql_num_fields($rs) - Returns the number fields in the result set.
• mysql_fetch_row($rs) - Returns an array contains the current row indexed by
field position numbers.
• mysql_fetch_assoc($rs) - Returns an array contains the current row indexed by
field names.
• mysql_fetch_array($rs) - Returns an array contains the current row with double
indexes: field position numbers and filed names.
• mysql_fetch_lengths($rs) - Returns an array contains lengths of all fields in
the last row returned.
• mysql_field_name($rs, $i) - Returns the name of the field of the specified
index.
Question 225. What Is
File Upload?
Answer :
File upload is Web page
function which allows visitor to specify a file on the browser's system and
submit it to the Web server. This is a very useful function for many
interactive Web sites. Some examples are:
Web base email systems
for users to send attachments.
Forums that allows
user to submit pictures.
Web sites file
managers for users to build their own Web pages.
Which HTML Tag Allows
Users to Specify a File for Uploading?
To present an input field on your Web page to allow users to specify a local
file to upload, you need to use the <INPUT TYPE="FILE" ...> tag
inside a <FORM ...> tag. The <INPUT TYPE="FILE" ...> will
be displayed as a text input field followed by a button called
"Browse...". Users can either enter the full path name of a local
file, or click Browse button to go through a dialog box to select a file
interactively. The following PHP code shows you a good example of the file
upload tag:
<?php
print("<html><form>n");
print("<input type=file>n");
print("<input type=submit>n");
print("</form></html>n");
?>