05 February 2008

PHP Programing | PHP Basic | chapter 3 Variable and Constanta

Basic
Variables in PHP are represented by a dollar sign followed by the name of the variable. The variable name is case-sensitive. Variable names follow the same rules as other labels in PHP. A valid variable 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]*'
Note: For our purposes here, a letter is a-z, A-Z, and the ASCII characters from 127 through 255 (0x7f-0xff).


$var = "Bob";
$Var = "Joe";
echo "$var, $Var"; // outputs "Bob, Joe"

$4site = 'not yet'; // invalid; starts with a number
$_4site = 'not yet'; // valid; starts with an underscore
$täyte = 'mansikka'; // valid; 'ä' is ASCII 228.

In PHP 3, variables are always assigned by value. That is to say, when you assign an expression to a variable, the entire value of the original expression is copied into the destination variable. This means, for instance, that after assigning one variable's value to another, changing one of those variables will have no effect on the other. For more information on this kind of assignment, see Expressions.
PHP 4 offers another way to assign values to variables: assign by reference. This means that the new variable simply references (in other words, "becomes an alias for" or "points to") the original variable. Changes to the new variable affect the original, and vice versa. This also means that no copying is performed; thus, the assignment happens more quickly. However, any speedup will likely be noticed only in tight loops or when assigning large arrays or objects. To assign by reference, simply prepend an ampersand (&) to the beginning of the variable which is being assigned (the source variable). For instance, the following code snippet outputs 'My name is Bob' twice:

$foo = 'Bob'; // Assign the value 'Bob' to $foo
$bar = &$foo; // Reference $foo via $bar.
$bar = "My name is $bar"; // Alter $bar...
echo $foo; // $foo is altered too.
echo $bar;
?>

One important thing to note is that only named variables may be assigned by reference.

$foo = 25;
$bar = &$foo; // This is a valid assignment.
$bar = &(24 * 7); // Invalid; references an unnamed expression.

function test() {
return 25;
}

$bar = &test(); // Invalid.
?>

Predefined variables
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.
Despite these factors, here is a list of predefined variables available under a stock installation of PHP 3 running as a module under a stock installation of Apache 1.3.6.
For a list of all predefined variables (and lots of other useful information), please see (and use) phpinfo().
Note: This list is neither exhaustive nor intended to be. It is simply a guideline as to what sorts of predefined variables you can expect to have access to in your script.
Apache variables
These variables are created by the Apache webserver. If you are running another webserver, there is no guarantee that it will provide the same variables; it may omit some, or provide others not listed here. That said, a large number of these variables are accounted for in the CGI 1.1 specification, so you should be able to expect those.
Note that few, if any, of these will be available (or indeed have any meaning) if running PHP on the command line.
GATEWAY_INTERFACE
What revision of the CGI specification the server is using; i.e. 'CGI/1.1'.
SERVER_NAME
The name of the server host under which the current script is executing. If the script is running on a virtual host, this will be the value defined for that virtual host.
SERVER_SOFTWARE
Server identification string, given in the headers when responding to requests.
SERVER_PROTOCOL
Name and revision of the information protocol via which the page was requested; i.e. 'HTTP/1.0';
REQUEST_METHOD
Which request method was used to access the page; i.e. 'GET', 'HEAD', 'POST', 'PUT'.
QUERY_STRING
The query string, if any, via which the page was accessed.
DOCUMENT_ROOT
The document root directory under which the current script is executing, as defined in the server's configuration file.
HTTP_ACCEPT
Contents of the Accept: header from the current request, if there is one.
HTTP_ACCEPT_CHARSET
Contents of the Accept-Charset: header from the current request, if there is one. Example: 'iso-8859-1,*,utf-8'.
HTTP_ACCEPT_ENCODING
Contents of the Accept-Encoding: header from the current request, if there is one. Example: 'gzip'.
HTTP_ACCEPT_LANGUAGE
Contents of the Accept-Language: header from the current request, if there is one. Example: 'en'.
HTTP_CONNECTION
Contents of the Connection: header from the current request, if there is one. Example: 'Keep-Alive'.
HTTP_HOST
Contents of the Host: header from the current request, if there is one.
HTTP_REFERER
The address of the page (if any) which referred the browser to the current page. This is set by the user's browser; not all browsers will set this.
HTTP_USER_AGENT
Contents of the User_Agent: header from the current request, if there is one. This is a string denoting the browser software being used to view the current page; i.e. Mozilla/4.5 [en] (X11; U; Linux 2.2.9 i586). Among other things, you can use this value with get_browser() to tailor your page's functionality to the capabilities of the user's browser.
REMOTE_ADDR
The IP address from which the user is viewing the current page.
REMOTE_PORT
The port being used on the user's machine to communicate with the web server.

SCRIPT_FILENAME
The absolute pathname of the currently executing script.
SERVER_ADMIN
The value given to the SERVER_ADMIN (for Apache) directive in the web server configuration file. If the script is running on a virtual host, this will be the value defined for that virtual host.
SERVER_PORT
The port on the server machine being used by the web server for communication. For default setups, this will be '80'; using SSL, for instance, will change this to whatever your defined secure HTTP port is.
SERVER_SIGNATURE
String containing the server version and virtual host name which are added to server-generated pages, if enabled.
PATH_TRANSLATED
Filesystem- (not document root-) based path to the current script, after the server has done any virtual-to-real mapping.
SCRIPT_NAME
Contains the current script's path. This is useful for pages which need to point to themselves.
REQUEST_URI
The URI which was given in order to access this page; for instance, '/index.html'.
Environment variables
These variables are imported into PHP's global namespace from the environment under which the PHP parser is running. Many are provided by the shell under which PHP is running and different systems are likely running different kinds of shells, a definitive list is impossible. Please see your shell's documentation for a list of defined environment variables. Other environment variables include the CGI variables, placed there regardless of whether PHP is running as a server module or CGI processor.
PHP variables
These variables are created by PHP itself. The $HTTP_*_VARS variables are available only if the track_vars configuration is turned on. When enabled, the variables are always set, even if they are empty arrays. This prevents a malicious user from spoofing these variables.
Note: As of PHP 4.0.3, track_vars is always turned on, regardless of the configuration file setting.
If the register_globals directive is set, then these variables will also be made available in the global scope of the script; i.e., separate from the $HTTP_*_VARS arrays. This feature should be used with care, and turned off if possible; while the $HTTP_*_VARS variables are safe, the bare global equivalents can be overwritten by user input, with possibly malicious intent. If you cannot turn off register_globals, you must take whatever steps are necessary to ensure that the data you are using is safe.
argv
Array of arguments passed to the script. When the script is run on the command line, this gives C-style access to the command line parameters. When called via the GET method, this will contain the query string.
argc
Contains the number of command line parameters passed to the script (if run on the command line).
PHP_SELF
The filename of the currently executing script, relative to the document root. If PHP is running as a command-line processor, this variable is not available.
HTTP_COOKIE_VARS
An associative array of variables passed to the current script via HTTP cookies.
HTTP_GET_VARS
An associative array of variables passed to the current script via the HTTP GET method.
HTTP_POST_VARS
An associative array of variables passed to the current script via the HTTP POST method.
HTTP_POST_FILES
An associative array of variables containing information about files uploaded via the HTTP POST method. See POST method uploads for information on the contents of $HTTP_POST_FILES.
$HTTP_POST_FILES is available only in PHP 4.0.0 and later.
HTTP_ENV_VARS
An associative array of variables passed to the current script via the parent environment.
HTTP_SERVER_VARS
An associative array of variables passed to the current script from the HTTP server. These variables are analogous to the Apache variables described above.
Variable scope
The scope of a variable is the context within which it is defined. For the most part all PHP variables only have a single scope. This single scope spans included and required files as well. For example:

$a = 1;
include "b.inc";

Here the $a variable will be available within the included b.inc script. However, within user-defined functions a local function scope is introduced. Any variable used inside a function is by default limited to the local function scope. For example:


$a = 1; /* global scope */

Function Test () {
echo $a; /* reference to local scope variable */
}

Test ();

This script will not produce any output because the echo statement refers to a local version of the $a variable, and it has not been assigned a value within this scope. You may notice that this is a little bit different from the C language in that global variables in C are automatically available to functions unless specifically overridden by a local definition. This can cause some problems in that people may inadvertently change a global variable. In PHP global variables must be declared global inside a function if they are going to be used in that function. An example:

$a = 1;
$b = 2;

Function Sum () {
global $a, $b;

$b = $a + $b;
}

Sum ();
echo $b;

The above script will output "3". By declaring $a and $b global within the function, all references to either variable will refer to the global version. There is no limit to the number of global variables that can be manipulated by a function.
A second way to access variables from the global scope is to use the special PHP-defined $GLOBALS array. The previous example can be rewritten as:

$a = 1;
$b = 2;

Function Sum () {
$GLOBALS["b"] = $GLOBALS["a"] + $GLOBALS["b"];
}

Sum ();
echo $b;

The $GLOBALS array is an associative array with the name of the global variable being the key and the contents of that variable being the value of the array element.
Another important feature of variable scoping is the static variable. A static variable exists only in a local function scope, but it does not lose its value when program execution leaves this scope. Consider the following example:

Function Test () {
$a = 0;
echo $a;
$a++;
}

This function is quite useless since every time it is called it sets $a to 0 and prints "0". The $a++ which increments the variable serves no purpose since as soon as the function exits the $a variable disappears. To make a useful counting function which will not lose track of the current count, the $a variable is declared static:

Function Test () {
static $a = 0;
echo $a;
$a++;
}

Now, every time the Test() function is called it will print the value of $a and increment it.
Static variables also provide one way to deal with recursive functions. A recursive function is one which calls itself. Care must be taken when writing a recursive function because it is possible to make it recurse indefinitely. You must make sure you have an adequate way of terminating the recursion. The following simple function recursively counts to 10, using the static variable $count to know when to stop:

Function Test () {
static $count = 0;

$count++;
echo $count;
if ($count < 10) {
Test ();
}
$count--;
}

Variable variables
Sometimes it is convenient to be able to have variable variable names. That is, a variable name which can be set and used dynamically. A normal variable is set with a statement such as:

$a = "hello";

A variable variable takes the value of a variable and treats that as the name of a variable. In the above example, hello, can be used as the name of a variable by using two dollar signs. i.e.

$$a = "world";

At this point two variables have been defined and stored in the PHP symbol tree: $a with contents "hello" and $hello with contents "world". Therefore, this statement:

echo "$a ${$a}";

produces the exact same output as:

echo "$a $hello";

i.e. they both produce: hello world.
In order to use variable variables with arrays, you have to resolve an ambiguity problem. That is, if you write $$a[1] then the parser needs to know if you meant to use $a[1] as a variable, or if you wanted $$a as the variable and then the [1] index from that variable. The syntax for resolving this ambiguity is: ${$a[1]} for the first case and ${$a}[1] for the second.
Variables from outside PHP
HTML Forms (GET and POST)
When a form is submitted to a PHP script, any variables from that form will be automatically made available to the script by PHP. If the track_vars configuration option is turned on, then these variables will be located in the associative arrays $HTTP_POST_VARS, $HTTP_GET_VARS, and/or $HTTP_POST_FILES, according to the source of the variable in question.
For more information on these variables, please read Predefined variables.

Simple form variable

Name:






When the above form is submitted, the value from the text input will be available in $HTTP_POST_VARS['username']. If the register_globals configuration directive is turned on, then the variable will also be available as $username in the global scope.
PHP also understands arrays in the context of form variables. You may, for example, group related variables together, or use this feature to retrieve values from a multiple select input:


More complex form variables

Name:

Email:

Beer:







In PHP 3, the array form variable usage is limited to single-dimensional arrays. In PHP 4, no such restriction applies.
IMAGE SUBMIT variable names
When submitting a form, it is possible to use an image instead of the standard submit button with a tag like:



When the user clicks somewhere on the image, the accompanying form will be transmitted to the server with two additional variables, sub_x and sub_y. These contain the coordinates of the user click within the image. The experienced may note that the actual variable names sent by the browser contains a period rather than an underscore, but PHP converts the period to an underscore automatically.
HTTP Cookies
PHP transparently supports HTTP cookies as defined by Netscape's Spec. Cookies are a mechanism for storing data in the remote browser and thus tracking or identifying return users. You can set cookies using the SetCookie() function. Cookies are part of the HTTP header, so the SetCookie function must be called before any output is sent to the browser. This is the same restriction as for the Header() function. Any cookies sent to you from the client will automatically be turned into a PHP variable just like GET and POST method data.
If you wish to assign multiple values to a single cookie, just add [] to the cookie name. For example:

SetCookie ("MyCookie[]", "Testing", time()+3600);

Note that a cookie will replace a previous cookie by the same name in your browser unless the path or domain is different. So, for a shopping cart application you may want to keep a counter and pass this along. i.e.

SetCookie Example
$Count++;
SetCookie ("Count", $Count, time()+3600);
SetCookie ("Cart[$Count]", $item, time()+3600);



Environment variables
PHP automatically makes environment variables available as normal PHP variables.

echo $HOME; /* Shows the HOME environment variable, if set. */

Since information coming in via GET, POST and Cookie mechanisms also automatically create PHP variables, it is sometimes best to explicitly read a variable from the environment in order to make sure that you are getting the right version. The getenv() function can be used for this. You can also set an environment variable with the putenv() function.
Dots in incoming variable names
Typically, PHP does not alter the names of variables when they are passed into a script. However, it should be noted that the dot (period, full stop) is not a valid character in a PHP variable name. For the reason, look at it:

$varname.ext; /* invalid variable name */

Now, what the parser sees is a variable named $varname, followed by the string concatenation operator, followed by the barestring (i.e. unquoted string which doesn't match any known key or reserved words) 'ext'. Obviously, this doesn't have the intended result.
For this reason, it is important to note that PHP will automatically replace any dots in incoming variable names with underscores.
Determining variable types
Because PHP determines the types of variables and converts them (generally) as needed, it is not always obvious what type a given variable is at any one time. PHP includes several functions which find out what type a variable is. They are gettype(), is_long(), is_double(), is_string(), is_array(), and is_object().
Declaration and input mechanism PHP 4.2.0
Aplication that created by PHP until version 4.1.0 have a weak security system. The application is easy to penetrated even it can cause the webserver crash because of the user action that not responsible who know about the blind spot of the PHP. This Weak security level is a expensive price that had to be payed by the easy of PHP. The Easy of that PHP bring to user is we didn’t have to declare the variable that we want to use in the script.every input that come from input form or URL string will be done same.
Every variable that will be use in PHP script after PHP version 4.1.0 and newer must be declarated. Variable declaration show the source and the data it keeped. The declaraion can be done with easy way we can use the expresion assignment for the variable that keep data and come from its script
For example
$a=1;
$b=$a*1;
Initialization of a variable can be in form of a result from an expression proses,not always in form of a value filling or constanta.
Read a data from a Form or URL using PHP 4.2.0
In the form definitions used to receive an input from user, we must declare a method with ‘POST’ or ‘GET’.if not definited,default method for the proses is get. Data inputed by user from form or url string will be saved in the variable associatif array, $_GET and $_POST we can access the variable using the expression like a $_GET [var_name] and $_POST [var_name].
Examlple:
$guestname=$_GET[‘guestname’];
$guestname=$_POST[‘guestname’];
Constants
PHP defines several constants and provides a mechanism for defining more at run-time. Constants are much like variables, save for the two facts that constants must be defined using the define() function, and that they cannot later be redefined to another value.
The predefined constants (always available) are:
__FILE__
The name of the script file presently being parsed. If used within a file which has been included or required, then the name of the included file is given, and not the name of the parent file.
__LINE__
The number of the line within the current script file which is being parsed. If used within a file which has been included or required, then the position within the included file is given.
PHP_VERSION
The string representation of the version of the PHP parser presently in use; e.g. '3.0.8-dev'.
PHP_OS
The name of the operating system on which the PHP parser is executing; e.g. 'Linux'.
TRUE
A true value.
FALSE
A false value.
E_ERROR
Denotes an error other than a parsing error from which recovery is not possible.
E_WARNING
Denotes a condition where PHP knows something is wrong, but will continue anyway; these can be caught by the script itself. An example would be an invalid regexp in ereg().
E_PARSE
The parser choked on invalid syntax in the script file. Recovery is not possible.
E_NOTICE
Something happened which may or may not be an error. Execution continues. Examples include using an unquoted string as a hash index, or accessing a variable which has not been set.
E_ALL
All of the E_* constants rolled into one. If used with error_reporting(), will cause any and all problems noticed by PHP to be reported.
The E_* constants are typically used with the error_reporting() function for setting the error reporting level. See all these constants at Error handling.
You can define additional constants using the define() function.
Note that these are constants, not C-style macros; only valid scalar data may be represented by a constant.

Defining Constants
define("CONSTANT", "Hello world.");
echo CONSTANT; // outputs "Hello world."
?>




Using __FILE__ and __LINE__
function report_error($file, $line, $message) {
echo "An error occured in $file on line $line: $message.";
}

report_error(__FILE__,__LINE__, "Something went wrong!");
?>



Expressions
Expressions are the most important building stones of PHP. In PHP, almost anything you write is an expression. The simplest yet most accurate way to define an expression is "anything that has a value".
The most basic forms of expressions are constants and variables. When you type "$a = 5", you're assigning '5' into $a. '5', obviously, has the value 5, or in other words '5' is an expression with the value of 5 (in this case, '5' is an integer constant).
After this assignment, you'd expect $a's value to be 5 as well, so if you wrote $b = $a, you'd expect it to behave just as if you wrote $b = 5. In other words, $a is an expression with the value of 5 as well. If everything works right, this is exactly what will happen.
Slightly more complex examples for expressions are functions. For instance, consider the following function:

function foo () {
return 5;
}

Assuming you're familiar with the concept of functions (if you're not, take a look at the chapter about functions), you'd assume that typing $c = foo() is essentially just like writing $c = 5, and you're right. Functions are expressions with the value of their return value. Since foo() returns 5, the value of the expression 'foo()' is 5. Usually functions don't just return a static value but compute something.
Of course, values in PHP don't have to be integers, and very often they aren't. PHP supports three scalar value types: integer values, floating point values and string values (scalar values are values that you can't 'break' into smaller pieces, unlike arrays, for instance). PHP also supports two composite (non-scalar) types: arrays and objects. Each of these value types can be assigned into variables or returned from functions.
So far, users of PHP/FI 2 shouldn't feel any change. However, PHP takes expressions much further, in the same way many other languages do. PHP is an expression-oriented language, in the sense that almost everything is an expression. Consider the example we've already dealt with, '$a = 5'. It's easy to see that there are two values involved here, the value of the integer constant '5', and the value of $a which is being updated to 5 as well. But the truth is that there's one additional value involved here, and that's the value of the assignment itself. The assignment itself evaluates to the assigned value, in this case 5. In practice, it means that '$a = 5', regardless of what it does, is an expression with the value 5. Thus, writing something like '$b = ($a = 5)' is like writing '$a = 5; $b = 5;' (a semicolon marks the end of a statement). Since assignments are parsed in a right to left order, you can also write '$b = $a = 5'.
Another good example of expression orientation is pre- and post-increment and decrement. Users of PHP/FI 2 and many other languages may be familiar with the notation of variable++ and variable--. These are increment and decrement operators. In PHP/FI 2, the statement '$a++' has no value (is not an expression), and thus you can't assign it or use it in any way. PHP enhances the increment/decrement capabilities by making these expressions as well, like in C. In PHP, like in C, there are two types of increment - pre-increment and post-increment. Both pre-increment and post-increment essentially increment the variable, and the effect on the variable is idential. The difference is with the value of the increment expression. Pre-increment, which is written '++$variable', evaluates to the incremented value (PHP increments the variable before reading its value, thus the name 'pre-increment'). Post-increment, which is written '$variable++' evaluates to the original value of $variable, before it was incremented (PHP increments the variable after reading its value, thus the name 'post-increment').
A very common type of expressions are comparison expressions. These expressions evaluate to either 0 or 1, meaning FALSE or TRUE (respectively). PHP supports > (bigger than), >= (bigger than or equal to), == (equal), != (not equal), < (smaller than) and <= (smaller than or equal to). These expressions are most commonly used inside conditional execution, such as if statements.
The last example of expressions we'll deal with here is combined operator-assignment expressions. You already know that if you want to increment $a by 1, you can simply write '$a++' or '++$a'. But what if you want to add more than one to it, for instance 3? You could write '$a++' multiple times, but this is obviously not a very efficient or comfortable way. A much more common practice is to write '$a = $a + 3'. '$a + 3' evaluates to the value of $a plus 3, and is assigned back into $a, which results in incrementing $a by 3. In PHP, as in several other languages like C, you can write this in a shorter way, which with time would become clearer and quicker to understand as well. Adding 3 to the current value of $a can be written '$a += 3'. This means exactly "take the value of $a, add 3 to it, and assign it back into $a". In addition to being shorter and clearer, this also results in faster execution. The value of '$a += 3', like the value of a regular assignment, is the assigned value. Notice that it is NOT 3, but the combined value of $a plus 3 (this is the value that's assigned into $a). Any two-place operator can be used in this operator-assignment mode, for example '$a -= 5' (subtract 5 from the value of $a), '$b *= 7' (multiply the value of $b by 7), etc.
There is one more expression that may seem odd if you haven't seen it in other languages, the ternary conditional operator:

$first ? $second : $third
If the value of the first subexpression is true (non-zero), then it the second subexpression is evaluated, and that is the result of the conditional expression. Otherwise, the third subexpression is evaluated, and that is the value.
The following example should help you understand pre- and post-increment and expressions in general a bit better:

function double($i) {
return $i*2;
}
$b = $a = 5; /* assign the value five into the variable $a and $b */
$c = $a++; /* post-increment, assign original value of $a
(5) to $c */
$e = $d = ++$b; /* pre-increment, assign the incremented value of
$b (6) to $d and $e */

/* at this point, both $d and $e are equal to 6 */

$f = double($d++); /* assign twice the value of $d before
the increment, 2*6 = 12 to $f */
$g = double(++$e); /* assign twice the value of $e after
the increment, 2*7 = 14 to $g */
$h = $g += 10; /* first, $g is incremented by 10 and ends with the
value of 24. the value of the assignment (24) is
then assigned into $h, and $h ends with the value
of 24 as well. */
In the beginning of the chapter we said that we'll be describing the various statement types, and as promised, expressions can be statements. However, not every expression is a statement. In this case, a statement has the form of 'expr' ';' that is, an expression followed by a semicolon. In '$b=$a=5;', $a=5 is a valid expression, but it's not a statement by itself. '$b=$a=5;' however is a valid statement.
One last thing worth mentioning is the truth value of expressions. In many events, mainly in conditional execution and loops, you're not interested in the specific value of the expression, but only care about whether it means TRUE or FALSE (PHP doesn't have a dedicated boolean type). The truth value of expressions in PHP is calculated in a similar way to perl. Any numeric non-zero numeric value is TRUE, zero is FALSE. Be sure to note that negative values are non-zero and are thus considered TRUE! The empty string and the string "0" are FALSE; all other strings are TRUE. With non-scalar values (arrays and objects) - if the value contains no elements it's considered FALSE, otherwise it's considered TRUE.
PHP provides a full and powerful implementation of expressions, and documenting it entirely goes beyond the scope of this manual. The above examples should give you a good idea about what expressions are and how you can construct useful expressions. Throughout the rest of this manual we'll write expr to indicate any valid PHP expression.
Maybe just enough for the chapter 3 and I will continue the chapter 4 that will discussed Operators

Comments :

0 komentar to “PHP Programing | PHP Basic | chapter 3 Variable and Constanta”


Post a Comment

Please Report me if there's a dead link or invalid link in this post