ads

affiliate_link Free Website Hosting

Wednesday, July 27, 2011

Integers

Integers

An integer is a number of the set Z = {..., -2, -1, 0, 1, 2, ...}.
See also:

Syntax

Integers can be specified in decimal (base 10), hexadecimal (base 16), or octal (base 8) notation, optionally preceded by a sign (- or +).
To use octal notation, precede the number with a 0 (zero). To use hexadecimal notation precede the number with 0x.
Example #1 Integer literals
<?php
$a 
1234// decimal number$a = -123// a negative number$a 0123// octal number (equivalent to 83 decimal)$a 0x1A// hexadecimal number (equivalent to 26 decimal)?>
Formally, the structure for integer literals is:
decimal     : [1-9][0-9]*
            | 0

hexadecimal : 0[xX][0-9a-fA-F]+

octal       : 0[0-7]+

integer     : [+-]?decimal
            | [+-]?hexadecimal
            | [+-]?octal
The size of an integer is platform-dependent, although a maximum value of about two billion is the usual value (that's 32 bits signed). PHP does not support unsigned integers. Integer size can be determined using the constant PHP_INT_SIZE, and maximum value using the constant PHP_INT_MAX since PHP 4.4.0 and PHP 5.0.5.
Warning
If an invalid digit is given in an octal integer (i.e. 8 or 9), the rest of the number is ignored.
Example #2 Octal weirdness
<?php
var_dump
(01090); // 010 octal = 8 decimal?>

Integer overflow

If PHP encounters a number beyond the bounds of the integer type, it will be interpreted as a float instead. Also, an operation which results in a number beyond the bounds of the integer type will return a float instead.
<?php
$large_number 
=  2147483647;var_dump($large_number);// output: int(2147483647)
$large_number =  2147483648;var_dump($large_number);// output: float(2147483648)

// it's true also for hexadecimal specified integers between 2^31 and 2^32-1:
var_dump0xffffffff );// output: float(4294967295)

// this doesn't go for hexadecimal specified integers above 2^32-1:
var_dump0x100000000 );// output: int(2147483647)
$million 1000000;$large_number =  50000 $million;var_dump($large_number);// output: float(50000000000)?>
Warning
Unfortunately, there was a bug in PHP which caused this to not always work correctly when negative numbers were involved. For example, the result of -50000 * $million is -429496728. However, when both operands were positive, there was no problem.
This was fixed in PHP 4.1.0.
There is no integer division operator in PHP. 1/2 yields the float 0.5. The value can be casted to an integer to round it downwards, or the round() function provides finer control over rounding.
<?php
var_dump
(25/7);         // float(3.5714285714286) var_dump((int) (25/7)); // int(3)var_dump(round(25/7));  // float(4) ?>

Converting to integer

To explicitly convert a value to integer, use either the (int) or (integer) casts. However, in most cases the cast is not needed, since a value will be automatically converted if an operator, function or control structure requires an integer argument. A value can also be converted to integer with the intval() function.
See also: type-juggling.

From booleans

FALSE will yield 0 (zero), and TRUE will yield 1 (one).

From floating point numbers

When converting from float to integer, the number will be rounded towards zero.
If the float is beyond the boundaries of integer (usually +/- 2.15e+9 = 2^31), the result is undefined, since the float doesn't have enough precision to give an exact integer result. No warning, not even a notice will be issued when this happens!
Warning
Never cast an unknown fraction to integer, as this can sometimes lead to unexpected results.
<?phpecho (int) ( (0.1+0.7) * 10 ); // echoes 7!?>

Booleans

Booleans

This is the simplest type. A boolean expresses a truth value. It can be either TRUE or FALSE.
Note: The boolean type was introduced in PHP 4.

Syntax

To specify a boolean literal, use the keywords TRUE or FALSE. Both are case-insensitive.
<?php
$foo 
True// assign the value TRUE to $foo?>
Typically, some kind of operator which returns a boolean value, and the value is passed on to a control structure.
<?php// == is an operator which test
// equality and returns a boolean
if ($action == "show_version") {
    echo 
"The version is 1.23";
}
// this is not necessary...if ($show_separators == TRUE) {
    echo 
"<hr>\n";
}
// ...because instead, this can be used:if ($show_separators) {
    echo 
"<hr>\n";
}
?>

Converting to boolean

To explicitly convert a value to boolean, use the (bool) or (boolean) casts. However, in most cases the cast is unncecessary, since a value will be automatically converted if an operator, function or control structure requires a boolean argument.
See also Type Juggling.
When converting to boolean, the following values are considered FALSE:
Every other value is considered TRUE (including any resource).
Warning
-1 is considered TRUE, like any other non-zero (whether negative or positive) number!
<?php
var_dump
((bool) "");        // bool(false)var_dump((bool) 1);         // bool(true)var_dump((bool) -2);        // bool(true)var_dump((bool) "foo");     // bool(true)var_dump((bool) 2.3e5);     // bool(true)var_dump((bool) array(12)); // bool(true)var_dump((bool) array());   // bool(false)var_dump((bool) "false");   // bool(true)?>

Instruction separation

Instruction separation

As in C or Perl, PHP requires instructions to be terminated with a semicolon at the end of each statement. The closing tag of a block of PHP code automatically implies a semicolon; you do not need to have a semicolon terminating the last line of a PHP block. The closing tag for the block will include the immediately trailing newline if one is present.
<?php
    
echo 'This is a test';?>
<?php echo 'This is a test' ?>
<?php echo 'We omitted the last closing tag';
Note: The closing tag of a PHP block at the end of a file is optional, and in some cases omitting it is helpful when using include() or require(), so unwanted whitespace will not occur at the end of files, and you will still be able to add headers to the response later. It is also handy if you use output buffering, and would not like to see added unwanted whitespace at the end of the parts generated by the included files.

Comment

Comments

PHP supports 'C', 'C++' and Unix shell-style (Perl style) comments. For example:
<?php
    
echo 'This is a test'// This is a one-line c++ style comment
    /* This is a multi line comment
       yet another line of comment */
    
echo 'This is yet another test';
    echo 
'One Final Test'# This is a one-line shell-style comment?>
The "one-line" comment styles only comment to the end of the line or the current block of PHP code, whichever comes first. This means that HTML code after // ... ?> or # ... ?> WILL be printed: ?> breaks out of PHP mode and returns to HTML mode, and // or # cannot influence that. If the asp_tags configuration directive is enabled, it behaves the same with // %> and # %>. However, the </script> tag doesn't break out of PHP mode in a one-line comment.
<h1>This is an <?php # echo 'simple';?> example.</h1>
<p>The header above will say 'This is an  example'.</p>
'C' style comments end at the first */ encountered. Make sure you don't nest 'C' style comments. It is easy to make this mistake if you are trying to comment out a large block of code.
<?php
 
/*
    echo 'This is a test'; /* This comment will cause a problem */
 
*/?>

Wednesday, July 20, 2011

Escaping from HTML

Escaping from HTML

When PHP parses a file, it looks for opening and closing tags, which tell PHP to start and stop interpreting the code between them. Parsing in this manner allows php to be embedded in all sorts of different documents, as everything outside of a pair of opening and closing tags is ignored by the PHP parser. Most of the time you will see php embedded in HTML documents, as in this example.
<p>This is going to be ignored.</p>
<?php echo 'While this is going to be parsed.'?><p>This will also be ignored.</p>
You can also use more advanced structures:
Example #1 Advanced escaping
<?phpif ($expression) {
    
?>    <strong>This is true.</strong>
    <?php } else {
    
?>    <strong>This is false.</strong>
    <?php }?>
This works as expected, because when PHP hits the ?> closing tags, it simply starts outputting whatever it finds (except for an immediately following newline - see instruction separation ) until it hits another opening tag. The example given here is contrived, of course, but for outputting large blocks of text, dropping out of PHP parsing mode is generally more efficient than sending all of the text through echo() or print().
There are four different pairs of opening and closing tags which can be used in php. Two of those, <?php ?> and <script language="php"> </script>, are always available. The other two are short tags and ASP style tags, and can be turned on and off from the php.ini configuration file. As such, while some people find short tags and ASP style tags convenient, they are less portable, and generally not recommended.
Note: Also note that if you are embedding PHP within XML or XHTML you will need to use the <?php ?> tags to remain compliant with standards.
Example #2 PHP Opening and Closing Tags
1.  <?php echo 'if you want to serve XHTML or XML documents, do like this'?>
2.  <script language="php">
        
echo 'some editors (like FrontPage) don\'t
              like processing instructions'
;
    
</script>
3.  <? echo 'this is the simplest, an SGML processing instruction'; ?>
    <?= expression ?> This is a shortcut for "<? echo expression ?>"

4.  <% echo 'You may optionally use ASP-style tags'; %>
    <%= $variable; # This is a shortcut for "<% echo . . ." %>
While the tags seen in examples one and two are both always available, example one is the most commonly used, and recommended, of the two.
Short tags (example three) are only available when they are enabled via the short_open_tag php.ini configuration file directive, or if php was configured with the --enable-short-tags option.
ASP style tags (example four) are only available when they are enabled via the asp_tags php.ini configuration file directive.

Dealing with Forms

Dealing with Forms

One of the most powerful features of PHP is the way it handles HTML forms. The basic concept that is important to understand is that any form element will automatically be available to your PHP scripts. Please read the manual section on Variables from external sources for more information and examples on using forms with PHP. Here is an example HTML form:
Example #1 A simple HTML form
<form action="action.php" method="post">
 <p>Your name: <input type="text" name="name" /></p>
 <p>Your age: <input type="text" name="age" /></p>
 <p><input type="submit" /></p>
</form>
There is nothing special about this form. It is a straight HTML form with no special tags of any kind. When the user fills in this form and hits the submit button, the action.php page is called. In this file you would write something like this:
Example #2 Printing data from our form
Hi <?php echo htmlspecialchars($_POST['name']); ?>.
You are <?php echo (int)$_POST['age']; ?> years old.
A sample output of this script may be:
Hi Joe. You are 22 years old.
Apart from the htmlspecialchars() and (int) parts, it should be obvious what this does. htmlspecialchars() makes sure any characters that are special in html are properly encoded so people can't inject HTML tags or Javascript into your page. For the age field, since we know it is a number, we can just convert it to an integer which will automatically get rid of any stray characters. You can also have PHP do this for you automatically by using the filter extension. The $_POST['name'] and $_POST['age'] variables are automatically set for you by PHP. Earlier we used the $_SERVER superglobal; above we just introduced the $_POST superglobal which contains all POST data. Notice how the method of our form is POST. If we used the method GET then our form information would live in the $_GET superglobal instead. You may also use the $_REQUEST superglobal, if you do not care about the source of your request data. It contains the merged information of GET, POST and COOKIE data. Also see the import_request_variables() function.
You can also deal with XForms input in PHP, although you will find yourself comfortable with the well supported HTML forms for quite some time. While working with XForms is not for beginners, you might be interested in them. We also have a short introduction to handling data received from XForms in our features section.

Something Useful

Something Useful

Let us do something more useful now. We are going to check what sort of browser the visitor is using. For that, we check the user agent string the browser sends as part of the HTTP request. This information is stored in a variable. Variables always start with a dollar-sign in PHP. The variable we are interested in right now is $_SERVER['HTTP_USER_AGENT'].
Note: $_SERVER is a special reserved PHP variable that contains all web server information. It is known as a superglobal. See the related manual page on superglobals for more information. These special variables were introduced in PHP » 4.1.0. Before this time, we used the older $HTTP_*_VARS arrays instead, such as $HTTP_SERVER_VARS. Although deprecated, these older variables still exist. (See also the note on old code.)
To display this variable, you can simply do:
Example #1 Printing a variable (Array element)
<?phpecho $_SERVER['HTTP_USER_AGENT'];?>
A sample output of this script may be:

Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)
There are many types of variables available in PHP. In the above example we printed an Array element. Arrays can be very useful.
$_SERVER is just one variable that PHP automatically makes available to you. A list can be seen in the Reserved Variables section of the manual or you can get a complete list of them by looking at the output of the phpinfo() function used in the example in the previous section.
You can put multiple PHP statements inside a PHP tag and create little blocks of code that do more than just a single echo. For example, if you want to check for Internet Explorer you can do this:
Example #2 Example using control structures and functions
<?phpif (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== FALSE) {
    echo 
'You are using Internet Explorer.<br />';
}
?>
A sample output of this script may be:
You are using Internet Explorer.<br />
Here we introduce a couple of new concepts. We have an if statement. If you are familiar with the basic syntax used by the C language, this should look logical to you. Otherwise, you should probably pick up an introductory PHP book and read the first couple of chapters, or read the Language Reference part of the manual.
The second concept we introduced was the strpos() function call. strpos() is a function built into PHP which searches a string for another string. In this case we are looking for 'MSIE' (so-called needle) inside $_SERVER['HTTP_USER_AGENT'] (so-called haystack). If the needle is found inside the haystack, the function returns the position of the needle relative to the start of the haystack. Otherwise, it returns FALSE. If it does not return FALSE, the if expression evaluates to TRUE and the code within its {braces} is executed. Otherwise, the code is not run. Feel free to create similar examples, with if, else, and other functions such as strtoupper() and strlen(). Each related manual page contains examples too. If you are unsure how to use functions, you will want to read both the manual page on how to read a function definition and the section about PHP functions.
We can take this a step further and show how you can jump in and out of PHP mode even in the middle of a PHP block:
Example #3 Mixing both HTML and PHP modes
<?phpif (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== FALSE) {?><h3>strpos() must have returned non-false</h3>
<p>You are using Internet Explorer</p>
<?php} else {?><h3>strpos() must have returned false</h3>
<p>You are not using Internet Explorer</p>
<?php}?>
A sample output of this script may be:
<h3>strpos() must have returned non-false</h3>
<p>You are using Internet Explorer</p>
Instead of using a PHP echo statement to output something, we jumped out of PHP mode and just sent straight HTML. The important and powerful point to note here is that the logical flow of the script remains intact. Only one of the HTML blocks will end up getting sent to the viewer depending on the result of strpos(). In other words, it depends on whether the string MSIE was found or not

Your first PHP-enabled page

Your first PHP-enabled page

Create a file named hello.php and put it in your web server's root directory (DOCUMENT_ROOT) with the following content:
Example #1 Our first PHP script: hello.php
<html>
 <head>
  <title>PHP Test</title>
 </head>
 <body>
 <?php echo '<p>Hello World</p>'?>
 </body>
</html>
Use your browser to access the file with your web server's URL, ending with the "/hello.php" file reference. When developing locally this URL will be something like http://localhost/hello.php or http://127.0.0.1/hello.php but this depends on the web server's configuration. If everything is configured correctly, this file will be parsed by PHP and the following output will be sent to your browser:
<html>
 <head>
  <title>PHP Test</title>
 </head>
 <body>
 <p>Hello World</p>
 </body>
</html>
This program is extremely simple and you really did not need to use PHP to create a page like this. All it does is display: Hello World using the PHP echo() statement. Note that the file does not need to be executable or special in any way. The server finds out that this file needs to be interpreted by PHP because you used the ".php" extension, which the server is configured to pass on to PHP. Think of this as a normal HTML file which happens to have a set of special tags available to you that do a lot of interesting things.
If you tried this example and it did not output anything, it prompted for download, or you see the whole file as text, chances are that the server you are on does not have PHP enabled, or is not configured properly. Ask your administrator to enable it for you using the Installation chapter of the manual. If you are developing locally, also read the installation chapter to make sure everything is configured properly. Make sure that you access the file via http with the server providing you the output. If you just call up the file from your file system, then it will not be parsed by PHP. If the problems persist anyway, do not hesitate to use one of the many » PHP support options.
The point of the example is to show the special PHP tag format. In this example we used <?php to indicate the start of a PHP tag. Then we put the PHP statement and left PHP mode by adding the closing tag, ?>. You may jump in and out of PHP mode in an HTML file like this anywhere you want. For more details, read the manual section on the basic PHP syntax.

What is PHP?

What is PHP?

PHP (recursive acronym for "PHP: Hypertext Preprocessor") is a widely-used open source general-purpose scripting language that is especially suited for web development and can be embedded into HTML.
Nice, but what does that mean? An example:
Example #1 An introductory example
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <title>Example</title>
    </head>
    <body>

        <?php
            
echo "Hi, I'm a PHP script!";
        
?>
    </body>
</html>
Instead of lots of commands to output HTML (as seen in C or Perl), PHP pages contain HTML with embedded code that does "something" (in this case, output "Hi, I'm a PHP script!"). The PHP code is enclosed in special start and end processing instructions <?php and ?> that allow you to jump into and out of "PHP mode."
What distinguishes PHP from something like client-side JavaScript is that the code is executed on the server, generating HTML which is then sent to the client. The client would receive the results of running that script, but would not know what the underlying code was. You can even configure your web server to process all your HTML files with PHP, and then there's really no way that users can tell what you have up your sleeve.
The best things in using PHP are that it is extremely simple for a newcomer, but offers many advanced features for a professional programmer. Don't be afraid reading the long list of PHP's features. You can jump in, in a short time, and start writing simple scripts in a few hours.