PHP The Notes
PHP The Notes
PEAR
PEAR is short for "PHP Extension and Application Repository". 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 organized OOP library. PEAR also provides a
command-line interface that can be used to automatically install "packages" . The purpose of PEAR is to provide:
• A structured library of open-sourced code for PHP users
• A system for code distribution and package maintenance
• A standard style for code written in PHP
• The PHP Foundation Classes (PFC),
• The PHP Extension Community Library (PECL)
• A web site, mailing lists and download mirrors to support the PHP/PEAR community
PHP features
• Performance: Scripts written in PHP executes faster than other Scripting languages. Optimized memory manager and third party
accelerators improves the performance and response time.
• Portability: PHP is portable to MS Windows, UNIX and Mac OS ,OS/2.
• Ease of use: PHP syntax is clear and consistent.
• Open Source: PHP has GPL license and so it is freely available without any cost.
• Community Support: PHP developing is done through more than 100 of developers among world.
• Third party application Support: PHP supports wide range of databases. It supports MySQL,postgre SQL ,ORACLE, and Ms
SQL Sever.
• Automatic Compilation: PHP is interpreted language that is a change made in source code will test automatically.
PHP3 vs PHP4
PHP4 cannot support oops concepts and Zend engine 1 is used.
Variables are temporary storage containers. In PHP, a variable can contain any type of data, such as, for example, strings, integers, floating-
point numbers, objects and arrays. PHP is loosely typed, meaning that it will implicitly change the type of a variable as needed, depending
on the operation being performed on its value. PHP variables are identified by a dollar sign $, followed by an identifier name. Variables
must be named using only letters (a-z, A-Z), numbers and the underscore character; their names must start with either a letter or an
underscore.
Example:
<?php
$x="John";
$$x="sam";
echo $x;
echo "<br>";
echo $$x;
echo "<br>";
echo $John;
?>
Output
John
sam
sam
Data Types
1. PHP's scalar data types
Scalar data is data that only contains a single value. PHP features 6 scalar data types:
Type Description Example values
integer A whole number 7, -23
float A floating point number 7.68, -23.45
string A sequence of characters "Hello", "abc123@#$"
unicode A sequence of Unicode characters "Hello", "abc123@#$"
binary A sequence of binary (non-Unicode) characters "Hello", "abc123@#$"
boolean Either true or false true, false
2. PHP's compound data types
Compound data can contain multiple values. PHP has 2 compound data types:
array
Can hold multiple values indexed by numbers or strings
object
Can hold multiple values (properties), and can also contain methods (functions) for working on properties
An array or object can contain multiple values, all accessed via one variable name. What's more, those values can themselves be other
arrays or objects. This allows you to create quite complex collections of data.
3. PHP's special data types
As well as scalar and compound types, PHP has 2 special data types that don't fall into the other categories:
resource
Used to access an external resource (for example, a file handle or database connection)
null
Can only contain the value null, which means "no value"
4. Loose typing in PHP
Some languages, such as Java, are strongly typed: once you've created a variable, you can't change the type of data stored in it. PHP, in
contrast, is loosely typed: you can change a variable's data type at any time.
In the following PHP example, $x starts off by holding integer data (3). The next line appends the string "hello" to the data using the
concatenation operator, which changes $x's value to "3hello" (a string data type). Finally, 5.67 is assigned to $x, changing its data type to a
float:
$x = 3;
$x .= "hello";
$x = 5.67;
5. Finding out the data type of a value
You can check a value's data type using one of the following PHP functions:
is_int( value )
Returns true if value is an integer, false otherwise
is_float( value )
Returns true if value is a float, false otherwise
is_string( value )
Returns true if value is a string, false otherwise
is_unicode( value )
Returns true if value is a Unicode string, false otherwise
is_binary( value )
Returns true if value is a binary string, false otherwise
is_bool( value )
Returns true if value is a Boolean, false otherwise
is_array( value )
Returns true if value is an array, false otherwise
is_object( value )
Returns true if value is an object, false otherwise
is_resource( value )
Returns true if value is a resource, false otherwise
is_null( value )
Returns true if value is null, false otherwise
is_unicode() and is_binary() are only available in PHP 6 and later.
For example, the following code displays 1 (true):
$x = 3.14;
echo is_float( $x );
6. Changing data types with settype()
As you've already seen, you can change a variable's data type simply by assigning a new value of a different type to the variable. However,
sometimes it's a good idea to explicitly set the type of the data held by a variable. For example, if you're handing data entered by a visitor,
or passing data to another program, then it's good to ensure that the data is of the correct type.
PHP has a function called settype() that converts a variable's value from one data type to another:
$x = 3.14;
settype( $x, "integer" );
In the above example, $x's data type is changed from float to integer (with the result that $x ends up containing the value 3).
Be careful when changing data types, since you may end up losing information — for example, when changing a float (3.14) to an integer
(3).
7. Changing data types with casting
If you just want to change a value's type at the time you use the value, then you can use casting. This merely changes the type of the value
that is to be used; the original variable remains untouched.
To cast a value, place the data type in parentheses before the value at the time you use it:
$x = 3.14;
echo (integer) $x;
The above code displays 3 (3.14 cast to an integer). However, note that $x still contains the value 3.14 after the cast operation.
You can, if you prefer, use (int) instead of (integer), and (bool) instead of (boolean).
Operators
An operator is any symbol used to perform an operation on a value. Operators can be classified into three based on the number of operands
it is processing.They are
Unary Operator (operates on only one operand)
Binary Operator (operates on two operands)
Ternary Operator (operates on three operands)
Unary Operator
Incrementing/Decrementing Operators
PHP supports specific operators for incrementing and decrementing numbers. These are a short hand way of expressing the increase or
decrease of a value by one:
Operand Name Sample Description
Samples:
$x = 1;
Binary Operator
The Assignment Operator(=)
The assignment operator allows you to assign a value to a variable. You can assign strings, integers, even the results of functions:
$var = "Hi there";
$var = 1;
$var = myfunction();
You can also use the Assignment Concatenation Operator to append a new value to the value an existing variable:
$var = "this is a test";
$var .=" of the emergency broadcast system";
print $var; -- This would output "This is a test of the emergency broadcast system"
Arithmetic Operators
Arithmetic Operators in PHP are used to work with numbers. Addition subtraction, division and multiplication are all supported:
Operand Name Sample Description
- Subtraction $var - $var2 Subtracts the second value from the first.
Comparison Operators
Comparison Operators allow you to test things like whether one number value is larger, smaller or equal to another. Unlike expressions with
Arithmetic Operators (which return a value), those with Comparison Operators evaluate to either TRUE or FALSE and are frequently used
in conditional statements:
Operand Name Sample Description
< Less than $var < $var2 Is true if the first value is less than the second.
The Equal and Not-Equal To operators are also used to evaluate whether non-numerical values are equal to each other.
This script how you can use a conditional statement to test whether or not the entered password is the same as the stored one:
<?php
$storedpassword = "mypassword";
$enteredpassword = "mypassword";
if ($storedpassword == $enteredpassword) {
print "The entered password was correct!";
}else {
print "The entered password was wrong!";
}
?>
In addition to the comparision operators listed above, PHP4 has added two new ones that not only allow you see if two values are equal, but
also check to see if they are of the same type.
Operand Name Sample Description
<?php
$storedusername = "user";
$enteredusername = "user";
$storedpassword = "mypassword";
$enteredpassword = "mypassword";
?>
The "AND" between the two separate conditions tells the script that both must be true for the entire statement to be considered true. If both
are true, then "The entered username and password were correct!" would be printed.
AND And $var AND $var2 Is true if both values are true.
XOR Xor $var XOR $var2 Is true if either value is true, but not both.
&& And $var && $var2 Is true if both values are true.
The same rules of precedence apply to Operators in PHP. Take a look at the below chart to get an idea of how various operators rank.
Operators listed in the same row have equal precedence.
Highest Precedence */%
+-.
< <= > >=
&&
||
And
Xor
Lowest precedence or
Since the first part of the above equation is surrounded, it would be calculated first, and $x would equal 100.
Ternary Operator
The ternary operator is a shorthand (albeit very hard to read) way of doing if statements.
<?php
$agestr = ($age < 16) ? 'child' : 'adult';
echo $agestr ;
?>
8.
Constants
Via define() directive, like define ("MYCONSTANT", 100);
parameters. It is also generally argued that echo is faster, but usually the speed advantage
is negligible, and might not be there for future versions of PHP. printf is a function, not a
construct, and allows such advantages as formatted output, but it’s the slowest way to
print out data out of echo, print and printf.
Operators
Control Structures and Control Loops
Control Structures allow a script to react differently depending on what has already occurred, or based on user input, and allow the graceful
handling of repetitive tasks.
In PHP, there are two primary types of Control Structures: Conditional Statements and Control Loops.
Conditional Statements
Conditional Statements allow you to branch the path of execution in a script based on whether a single, or multiple conditions, evaluate to
true or false.
If Statements
If Statements always begin with "if", followed by a condition surrounded in parentheses. If the condition evaluates to true, then the statement
or statements immediately following the condition will be executed.
<?php
$x=1;
This example illustrates the simplest kind of If Statement. In this case, had the condition been false, nothing would have occurred and you
would have seen a blank browser window when the script was run.
When you have more than one statement to be executed within a control structure, it's necessary to surround them with brackets:
<?php
$x=1;
if ($x == 1) {
print '$x is equal to 1';
$x++;
print 'now $x is equal to 2';
}
?>
Keep in mind that the positioning of the elements does not affect the execution of the script. All of the example arrangements below are
perfectly valid not only for If Statements, but for every form of control loop.
if ($x == 1)
print '$x is equal to 1';
if ($x == 1) {
print '$x is equal to 1';
}
You can also include multiple conditions within parentheses. For the nested statements to execute, all of the conditions must evaluate to true.
<?php
$x=1;
Else Statements
As the name implies, Else Statements allow you to do something else if the condition within an If Statement evaluated to false:
<?php
$x=1;
if ($x == 2) {
print '$x is equal to 2';
} else {
print '$x is equal to 1';
}
?>
Else If Statements
Thus far, we have been able to respond to one condition, and do something if that condition is not true. For evaluating multiple conditions
you could use Else If Statements .
A combination of If and Else Statements, Else If Statements are evaluated sequentially if the condition within the If Statement is false. When
a condition within an Else If Statement evaluates to true, the nested statements are parsed, the script stops executing the entire If/Else if/Else
Structure. The rest of the script proceeds to be parsed.
<?php
$x=1;
if ($x == 2) {
print '$x is equal to 2';
} else if ($x == 1) {
print '$x is equal to 1';
} else {
print '$x does not equal 2 or 1';
}
?>
The final else statement can be left off if you do not want anything to happen if none of the If or Else If Statements are true:
<?php
$x=0;
if ($x == 2) {
print '$x is equal to 2';
} else if ($x == 1) {
print '$x is equal to 1';
}
?>
In this case, since neither the condition within the If or Else if Conditions are true, and no Else Statement was provided, nothing would be
outputted to the browser.
Switches
Switches are a good alternative to If/Else if/Else Statements in situations where you want to check multiple values against a single variable
or condition. This is the basic syntax:
<?php
$var = "yes";
switch ($var) {
case "yes":
print '$var is equal to yes';
break;
case "no":
print '$var is equal to no';
break;
}
?>
After running this code snippet, much of what is here will probably make sense to you. In the first line of the switch statement, we have the
identifier "switch" followed by a variable surrounded by parenthesis. Each case includes a possible value for the variable.
Switches execute a little differently than If/Else if/Else statements. Once a case value matches the value of the switch expression, every
following statement is executed, including those following other cases.
To prevent this from happening, a break statement is used. "Break;" ends the execution of the switch statement, and lets the script continue
execution; it can also be used in while or for loops.
Optionally, you may also include a special case called "default". This case works much like and Else Statement, and will execute if all the
other cases are found to be false. This case should be the very last one you include.
<?php
$var = "yes";
switch ($var) {
case "maybe":
print '$var is equal to yes';
break;
case "no":
print '$var is equal to no';
break;
default:
print 'none of the other two cases were true, so this sentance will be printed out instead.';
}
?>
Similar to the Break Statement is the Exit Statement. Exit is particularly useful in situations where you run into what would be considered a
"fatal error" (for example, if the user had entered a password that was incorrect) or any other time you needed to end the execution of a script
before it naturally terminated.
<?php
$var = "yes";
switch ($var) {
case "yes":
print '$var is equal to yes';
exit;
case "no":
print '$var is equal to no';
break;
}
print "this will not be printed, because the script will have terminate before this line is reached";
?>
Unlike break, exit may be used anywhere in your scripts, inside or outside of control structures.
Control Loops
Frequently in PHP there are instances where you need to perform repetitive tasks, such as formatting data pulled from a database, sending
out emails to a mailing list, or cycling through the contents of an array. Control Loops allow you to perform these tasks almost effortlessly.
While Loops
The statements nested within the loop will execute as long as the condition within the parentheses evaluates to true. Since the validity of the
condition is checked before the loop is executed, if the condition is false, then the statements within the loop will not be executed at all.
<?php
$x=1;
When you run this snippet, you will see the numbers 1 through 10 printed on your screen.
Do...While Loops
Do...While Loops are similar to While Loops. The primary difference in how these work is that the validity of the condition in a Do...While
Loop is tested after the loop has itinerated once.
<?php
$x=11;
do {
print "$x<br>";
$x++;
} while ($x <=10);?>
In the example above, $x would be printed out one time, and then the execution of the loop would end, because $x is greater than 10.
For Loops
For Loops take three expressions separated by semi-colons. The first expression is only executed one time, when the loop initializes. The
next expression is a condition that is checked each time the loop itinerates. Once the condition is false, the loop will stop executing. The final
expression will be executed each time the loop iterates after the nested statements have been parsed.
<?php
for($x=1; $x<=10; $x++) {
print "$x<br>";
}
?>
Typically, it's best to use a For Loop in situations where you know how many elements you will be cycling through.
The Foreach Loop
This new loop was introduced in PHP version 4. Its used exclusively for looping through elements of an array, allowing you to easily print
out or perform operations on elements within an array.
<?php
$Array = array();
$Array[]="http://www.yahoo.com/";
$Array[]="http://www.internet.com";
$Array[]="http://www.google.com";
$Array[]="http://www.cnn.com/";
$Array[]="http://www.php.net/";
The loop advances an internal pointer through each row of the array, assigns the key and the value to variables, and then prints out one or
both of them until the end of the array is reached.
Array
Arrays
PHP arrays are extremely flexible.They allow numeric, auto-incremented keys, alphanumeric keys or a mix of both, and are capable of
storing practically any value, including other arrays,with over seventy functions for manipulating them.All arrays are ordered collections of
items, called elements. Each element has a value, and is identified by a key that is unique to the array it belongs to.Keys can be either
integer numbers or strings of arbitrary length.
Arrays are created one of two ways. The first is by explicitly calling the array() construct, which can be passed a series of values and,
optionally, keys.
eg:
<?php
$x[]=10;
$x[]=2;
echo $x[0]." ".$x[1]; //output will be 10 2
?>
PHP provides two functions that can be used to outputa variable’s value recursively: print_r() and var_dump(). They differ in a few key
points:
• While both functions recursively print out the contents of composite value,
only var_dump() outputs the data types of each value
• Only var_dump() is capable of outputting the value of more than one variable
at the same time
• Only print_r can return its output as a string, as opposed to writing it to the
script’s standard output
eg:
<?php
$x[]=10;
$x[]=2;
print_r($x); //output will be Array ( [0] => 10 [1] => 2 )
?
<?php
$x[]=10;
$x[]=2;
var_dump($x); //output will be array(2) { [0]=> int(10) [1]=> int(2) }
?>
<?php
$x[]=10;
$x[]=2;
$y=array('c','d');
var_dump($x,$y);
?>
output will be array(2) { [0]=> int(10) [1]=> int(2) } array(2) { [0]=> string(1) "c" [1]=> string(1) "d" }
Multi-dimensional Arrays
To create multi-dimensional arrays, we simply assign an array as the value for an array element.
Array Functions
Functions
Defining a function
To create a new function, we simply use the keyword function, followed by an identifier, a pair of parentheses and braces:
function name() { }
PHP function names are not case-sensitive. As with all identifiers in PHP, the name must consist only of letters (a-z), numbers and the
underscore character, and must not start with a number. To make your function do something, simply place the code to be execute between
the braces, then call it.
function display()
{
echo "Hello World!";
}
Returning Values
We can specify the return value of your function by using the return keyword:
function hello()
{
return "Hello World"; // No output is shown
}
return also allows you to interrupt the execution of a function and exit it even if you don’t want to return a value:
<?php
$x=0;
function notfive($x)
{
if ($x== 5) {
return; // Nothing else in the function will be processed
}
echo "$x";
}
eg:
function &query($sql)
{
$result = mysql_query($sql);
return $result;
}
Any variable defined within a function is no longer available after the function has finished executing. This allows the use of names which
may be in use elsewhere without having to worry about conflicts.
Passing Arguments
Arguments allow you to inject an arbitrary number of values into a function in order to influence its behaviour.
Eg:
<?php
function add($x,$y)
{
$z=$x+$y;
return $x;
}
echo add(2,3);
?>
Eg:
<?php
function hello()
{
if (func_num_args() > 0) {
$arg = func_get_arg(0); // The first argument is at position 0
echo "Hello $arg";
} else {
echo "Hello World";
}
}
hello("Reader"); // Displays "Hello Reader"
hello(); // Displays "Hello World"
?>
You can use variable-length argument lists even if you do specify arguments in the function header. However, this won’t affect the way the
variable-length argument list functions behave—for example, func_num_args() will still return the total number of arguments passed to
your function, both declared and anonymous.
<?php
function countAll($arg1)
{
if (func_num_args() == 0) {
die("You need to specify at least one argument");
} else {
$args = func_get_args(); // Returns an array of arguments
// Remove the defined argument from the beginning
array_shift($args);
$count = strlen ($arg1);
foreach ($args as $arg) {
$count += strlen($arg);
}
}
return $count;
}
echo countAll("foo", "bar", "baz"); // Displays ’9’
?>
Example
<?php
function pass_by_reference(&$param) {
array_push($param, 4, 5);
}
$ar = array(1,2,3);
pass_by_reference($ar);
Example
<?php
function pass_by_value($param) {
array_push($param, 4, 5);
}
$ar = array(1,2,3);
pass_by_value($ar);
asort()
arsort()
ksort()
krsort()
uksort()
sort()
natsort()
rsort()
Parameter Passing
pass by value vs pass by reference
FORMS
Form: is the area that containing form variables
<form name=”f1” method=” ” action=' '> </form>
Attributes of form tag:
method: contains the HTTP methods for form processing. HTTP includes two methods to achieve different goals. They are GET and
POST.
GET vs POST
GET POST
1. The GET is used when the result of a request does not make 1. POST is used when the result of a request has persistent side effect
any persistent changes. such as adding a row to database.
2. It uses the collected data to find the resource. 2. POST creates the resource needed.
3. Small amount of limited size data can pass through URL 3. Large amount of data can be passed through URL.
Maximum 1024 characters.
4. The name and value used in the form will display on the 4. The name and value used in form is passed through invisible STD
address bar proceeded by URL. So it is not secure. I/P. So user can't see the passed information. So it is secure.
5. Used to pass small amount of less sensitive data. 5. Used to pass large amount of sensitive data.
6. GET call moves within the page Eg: exp pagination, url 6. POST call moves from one page to another.
calling etc.
Action: when the form is submitted content is sent to another file. The name of that file is specified using action.
Different types of forms
Text Field: <input type=”text” name=”txtfld” size=25/>
Text area: <textarea name="textarea"></txtarea>
Password: <input type=”password” name=”psswdfld” size=25/>
Hidden Field: <input type="hidden" name="hiddenField" />
Check box: <input type="checkbox" name="chk" id="che" value="1" />
Radio Button: <input type="radio" name="radiobuttonname" value=”1”/>
Radio Button group: <input type="radio" name="male" value="1" /> <input type="radio" name="female" value="0" />
List: <select name="select"> <option>abc</option> <option>def</option> </select>
Submit Button: <input name="Submitbutt" type="submit" id="Submitbutt" value="Submit" />
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> or In the Java
Script code, we can call the document.form.submit() function to submit the form. For example: <input type=button value="Save"
onClick="document.form.submit()">
Reset button: <input name="resetbutt" type="reset" id="resetbutt" value="Reset" />
Button: <input name="backbutton" type="button" id="backbutton" value="Button" />
Field Set: <fieldset> <legend> Introuduction </legend> </fieldset>
File operations
uploading files
Once the Web server received the uploaded file, it will call the PHP script specified in the form action attribute to process them. This
receiving PHP script can get the uploaded file information through the predefined array called $_FILES. Uploaded file information is
organized in $_FILES as a two-dimensional array as:
$_FILES[$fieldName]['name'] - The Original file name on the browser system.
$_FILES[$fieldName]['type'] - The file type determined by the browser.
$_FILES[$fieldName]['size'] - The Number of bytes of the file content.
$_FILES[$fieldName]['tmp_name'] - The temporary filename of the file in which the uploaded file was stored on the server.
$_FILES[$fieldName]['error'] - The error code associated with this file upload.
The $fieldName is the name used in the <INPUT TYPE=FILE, NAME=fieldName>.
How to store the uploaded file to the final location?
DESCRIBE table_name;
The MySQL provides a LOAD DATA INFILE command. You can load data from a file.
What is maximum size of a database in mysql?If the operating system or filesystem places a limit on the number of files in a directory,
MySQL is bound by that constraint. The efficiency of the operating system in handling
large numbers of files in a directory can place a practical limit on the number of tables in
a database. If the time required to open a file in the directory increases significantly as the
number of files increases, database performance can be adversely affected.
normalization
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).
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).
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.
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
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.
Aggregate functions
GROUP BY vs ORDER BY
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).
JOIN
DROP vs TRUNCATE
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.
REPAIR
The syntex for repairing a mysql table is:
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.
PHPMyadmin
PHP interface to MYSQL
We can create MySQL database with the use of mysql_create_db($databaseName) to
create a database.
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";
. ")";
if (mysql_query($sql, $con)) {
} else {
}
mysql_close($con);
?>
mysql_fetch methods
MySQL fetch object will collect first single matching record where mysql_fetch_array
will collect all matching records from the table in an array
.
mysql_fetch_array() -> Fetch a result row as a combination of associative array and
regular array.
Answer 2:
etc.).
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
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.
unlink() is a function for file system handling. It will simply delete the file in context.
session_register($session_var);
$_SESSION['var'] = 'value';
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.
The session support can be turned on automatically at the site level, or manually in each
PHP page script:
Turning on session support automatically at the site level: Set session.auto_start =
1 in php.ini.
funtion.
COKKIES
Persistent Cookie
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 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
How to set cookies?
setcookie('variable','value','time')
Example: setcookie('Test',$i,time()+3600);
time()+3600 - denotes that the cookie will expire after an one hour
Example: setcookie('Test');
'; echo 'window.location.href="'.$filename.'";'; echo ''; echo ''; echo ''; echo ''; } }
redirect('http://maosjb.com'); ?>
2. Using php function: header("Location:http://maosjb.com ");
What type of headers have to be added in the mail function to attach a file?
string urlencode(str) - Returns the URL encoded version of the input string. String values to be used in URL query string need to be URL
encoded. In the URL encoded version: Alphanumeric characters are maintained as is.Space characters are converted to "+" characters.
Other non-alphanumeric characters are converted "%" followed by two hex digits representing the converted character.
string urldecode(str) - Returns the original string of the input URL encoded string.
For example:
$discount ="10.00%";
$url = "http://domain.com/submit.php?disc=".urlencode($discount);
echo $url;
Answer1
PASSWORD=PASSWORD("Password");
Answer2
You can use the MySQL PASSWORD() function to encrypt username and password. For
example,
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
<?php
print("<html>");
$comment = urlencode($comment);
print("<p>"
."<a href=\"processing_forms.php?name=Guest&comment=$comment\">"
$comment = urlencode($comment);
print("<p>"
.'<a href="processing_forms.php?'.$comment.'">'
print("</html>");
?>
CRYPT()
MD5()
Any class implementing the interface must define each method that is declared in the interface, and each method must have at least the
parameters identified in their interface definitions. It may have more parameters as long as they are optional, but it cannot have less
PolyMorphism
Definition: polymorphism describes multiple possible states for a single property .
<?php
class animal {
public $name;
protected function setName($name){
$this->name = $name;
}
public function speak(){
return "No Animal Selected!";
}
}
class dog extends animal {
public function __construct($name){
$this->setName($name);
}
public function speak(){
return "Woof Woof";
}
}
class cat extends animal {
public function __construct($name){
$this->setName($name);
}
public function speak(){
return "I'm In your class, overloading your methods"; // :)
}
}
class human extends animal {
public function __construct($name){
$this->setName($name);
}
public function speak(){
return "Hello, My Name is " . $this->name;
}
}
$animal = new animal(); // Animal
$dog = new dog('rover'); // Dog named Rover
$cat = new cat('garfield'); // Cat named Garfield
$human = new human('fred'); // Human named Fred
// Non-existent animal cannot speak
echo $animal->speak();
// Dog's bark
echo $dog->speak();
// Cat's do nefarious things
echo $cat->speak();
// Human's Introduce themselves
echo $human->speak();
Features and advantages of OBJECT ORIENTED PROGRAMMING?
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.
Abstract class vs interfaces
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.
polymorphism
Inheritance
What type of inheritance that php supports?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'.
access specifiers
scope resolution operator
include vs require vs include_once
Anwser 1:
require_once() and include_once() are both the functions to include and evaluate the
specified file only once. If the specified file is included previous to the present call
occurrence, it will not be done again.
But require() and include() will do it as many times they are asked to do.
Anwser 2:
The include_once() statement includes and evaluates the specified file during the
execution of the script. This is a behavior similar to the include() statement, with the only
difference being that if the code from a file has already been included, it will not be
included again. The major difference between include() and require() is that in failure
include() produces a warning message whereas require() produces a fatal errors.
Anwser 3:
All three are used to an include file into the current page.
If the file is not present, require(), calls a fatal error, while in include() does not.
The include_once() statement includes and evaluates the specified file during the
execution of the script. This is a behavior similar to the include() statement, with the only
difference being that if the code from a file has already been included, it will not be
included again. It des not call a fatal error if file not exists. require_once() does the same
Anwser 4:
File will not be included more than once. If we want to include a file once only and
further calling of the file will be ignored then we have to use the PHP function
include_once(). This will prevent problems with function redefinitions, variable value
reassignments, etc.
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.
MAIL
What is meant by MIME?
Answer 1:
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
aplication/x-shockwave-flash
Answer 2:
WWW's ability to recognize and handle files of different types is largely dependent on
the use of the MIME (Multipurpose Internet Mail Extensions) standard. The standard
provides for a system of registration of file types with information about the applications
needed to process them. This information is incorporated into Web server and browser
software, and enables the automatic recognition and display of registered file types.
What are the functions for IMAP?
AJAX
Javascript
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:[email protected]?subject=...";
return true;
CSS
What are the advantages and disadvantages of CASCADE 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
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
XML
JOOMLA
CuteFTP
CMS
Functions
nI2br(string)
Anwser1:
nl2br() inserts a HTML tag <br> before all new line characters \n in a string.
output:
god bless<br>
you
strstr(str,str);
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.
strstr() returns part of a given string from the first occurrence of a given substring to the
"@example.com".
split
explode
preg_match(pattern,str)
We can use the preg_match() function with "/.*@(.*)$/" as
preg_match("/.*@(.*)$/","http://[email protected]",$data);
echo $data[1];
$text = "mailto:[email protected]?subject=Feedback";
echo $output[1];
Note that the second index of $output, $output[1], gives the match, not the first one,
$output[0].
md5,crc32(),shat()
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.
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.
retrieves them.
On large strings that need to be formatted according to some length specifications, use
wordwrap() or chunk_split().
QUESTIONS");
print $formatted;
ucwords() makes every first letter of every word capital, but it does not lower-case
anything else. To avoid this, and get a properly formatted string, it’s worth using
strtolower() first.
htmlspecialchars only takes care of <, >, single quote ‘, double quote " and ampersand.
htmlentities translates all occurrences of character sequences that have different meaning
in HTML.
htmlspecialchars() - Convert some special characters to HTML entities (Only the most
widely used)
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.
Interestingly if you just pass a simple var instead of an array, count() will return 1.
a) ALL privilages
We can grant rights on all databse by usingh *.* or some specific database by database.*
or a specific table by database.table_name.
a) ALL privilages
We can grant rights on all databse by usingh *.* or some specific database by database.*
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.
RESTORE IT?
Answer 1:
db_name
The full backup file is just a set of SQL statements, so restoring it is very easy:
Utility to dump a database or a collection of database for backup or for transferring the
data to another SQL server (not necessarily a MySQL server). The dump will contain
-t, no-create-info
-d, no-data
Don't write any row information for the table. This is very useful if you just want to get a
Using imagetypes() function to find out what types of images are supported in your PHP
engine.
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 |
if(parseInt(myValue)== myValue)
alert('Integer');
else
alert('Not an integer');
Case Studio
Smart Draw
How can I know that a variable is a number or not using a JavaScript?
Answer 1:
Answer 2:
Syntax
isNaN(number)
Parameter Description
Friend functions
Sometimes a function is best shared among a number of different classes. Such functions can be declared either as member functions of one
class or as global functions. In either
case they can be set to be friends of other classes, by using a friend specifier in the class
that is admitting them. Such functions can use all attributes of the class which names
them as a friend, as if they were themselves members of that class.
A friend declaration is essentially a prototype for a member function, but instead of
requiring an implementation with the name of that class attached by the double colon
syntax, a global function or member function of another class provides the match.
class mylinkage
private:
mylinkage * prev;
mylinkage * next;
protected:
public:
mylinkage * succ();
mylinkage * pred();
mylinkage();
};
class C
};
class B
int f1();
};
It is also possible to specify all the functions in another class as friends, by specifying the
entire class as a friend.
class A
friend class B;
};
Friend functions allow binary operators to be defined which combine private data in a
pair of objects. This is particularly powerful when using the operator overloading features
of C++. We will return to it when we look at overloading.
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.
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.
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.
or,
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
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)?
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. For example:
What are the different ways to login to a remote server? Explain the means,
Please give a regular expression (preferably Perl/PREG style), which can be used to
identify the URL from within a HTML link tag.
The COM class provides a framework to integrate (D)COM components into your PHP scripts.
class constructor.
Parameters:
module_name: name or class-id of the requested component.
server_name: name of the DCOM server from which the component should be fetched. If
NULL, localhost is assumed. To allow DCOM com, allow_dcom has to be set to TRUE
in php.ini.
and vice versa. Possible values are CP_ACP, CP_MACCP, CP_OEMCP, CP_SYMBOL,
Usage:
$word->Selection->TypeText("This is a test…");
$word->Release();
$word = null;
file_uploads = On
; Temporary directory for HTTP uploaded files (will use system default if not
; specified).
upload_tmp_dir = C:\apache2triad\temp
upload_max_filesize = 2M
How can I set a cron and how can I execute it in Unix, Linux, and windows?
Cron is very simply a Linux module that allows you to run commands at predetermined
times or intervals. In Windows, it's called Scheduled Tasks. The name Cron is in fact
derived from the same word from which we get the word chronology, which means order
of time.
# crontab
This command 'edits' the crontab. Upon employing this command, you will be able to
enter the commands that you wish to run. My version of
Linux uses the text editor vi. You can find information on using vi here.
The syntax of this file is very important – if you get it wrong, your crontab will not
function properly. The syntax of the file should be as follows:
Minutes: 0-59
Hours: 0-23
Day_of_month: 1-31
Month: 1-12
Weekday: 0-6
We can also include multiple values for each entry, simply by separating each value with
a comma.
command can be any shell command and, as we will see momentarily, can also be used to
execute a Web document such as a PHP file.
So, if we want to run a script every Tuesday morning at 8:15 AM, our mycronjob file will
contain the following content on a single line:
15 8 * * 2 /path/to/scriptname
This all seems simple enough, right? Not so fast! If you try to run a PHP script in this
manner, nothing will happen (barring very special configurations that have PHP compiled
as an executable, as opposed to an Apache module). The reason is that, in order for PHP
to be parsed, it needs to be passed through Apache. In other words, the page needs to be
called via a browser or other means of retrieving
Web content. For our purposes, I'll assume that your server configuration includes wget,
as is the case with most default configurations. To test your configuration, log in to shell.
If you're using an RPM-based system (e.g. Redhat or Mandrake), type the following:
# wget help
If you are greeted with a wget package identification, it is installed in your system.
You could execute the PHP by invoking wget on the URL to the page, like so:
# wget http://www.example.com/file.php
Now, let's go back to the mailstock.php file we created in the first part of this article. We
saved it in our document root, so it should be accessible via the Internet. Remember that
we wanted it to run at 4PM Eastern time, and send you your precious closing bell report?
Since I'm located in the Eastern timezone, we can go ahead and set up our crontab to use
4:00, but if you live elsewhere, you might have to compensate for the time difference
when setting this value.
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
What is the difference between Reply-to and Return-path in the headers of a mail
function?
Return-path: Return path is when there is a mail delivery failure occurs then where to
PHP does not require (or support) explicit type definition in variable declaration; a
variable's type is determined by the context in which that variable is used. That is to say,
if you assign a string value to variable $var, $var becomes a string. If you then assign an
integer value to $var, it becomes an integer.
An example of PHP's automatic type conversion is the addition operator '+'. If any of the
operands is a float, then all operands are evaluated as floats, and the result will be a float.
Otherwise, the operands will be interpreted as integers, and the result will also be an
integer. Note that this does NOT change the types of the operands themselves; the only
change is in how the operands are evaluated.
If the last two examples above seem odd, see String conversion to numbers.
If you wish to change the type of a variable, see settype().
If you would like to test any of the examples in this section, you can use the var_dump()
function.
How can I embed a java programme in php file and what changes have to be done
in php.ini file?
There are two possible ways to bridge PHP and Java: you can either integrate PHP into a
Java Servlet environment, which is the more stable and efficient solution, or integrate
Java support into PHP. The former is provided by a SAPI module that interfaces with the
Servlet server, the latter by this Java extension.
The Java extension provides a simple and effective means for creating and invoking
methods on Java objects from PHP. The JVM is created using JNI, and everything runs
in-process.
Example Code:
Name
Default
Changeable
java.class.path
NULL
PHP_INI_ALL
java.home
NULL
PHP_INI_ALL
java.library.path
NULL
PHP_INI_ALL
java.library
JAVALIB
PHP_INI_ALL
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");
?>