During work with any language we make use of variables. Variables are used to store values and reuse them in our code. We use different types of variables in our code such as strings (text), integers (numbers), floats (decimal numbers), Boolean (true or false) and objects. In PHP we can make use of variable while writing scripts. In this lesson we’re going to cover PHP variables.
PHP Variable Syntax
$var_name = value;
Important Variable in PHP?
Some key points to notice:
(1) Remember to put the $ sign in front of variables when declaring variables in PHP.
(2)Variable names must start with letters or underscore.
(3) Variables can’t include characters except letters, numbers or underscore.
What is a variable?
A variable is a indicate to store values such as strings, integers or decimals so we can easily reuse those values in our code. For example, we can store a string value such as “Hello world” or an integer value of 100 into a variable.
PHP variable types?
Different Java or C++, PHP doesn’t care about primitive types. Any variable, a string, an integer or a float is declared the same way. PHP converts the types in the code by itself. Here’s what I mean.
//an integer variable $var_name = 300;
//an float variable $var_name = 300.00 ?>
PHP Variable type manage
Like talk about above, PHP doesn’t require variables to declared using primitive types. Therefore, manage between two types doesn’t require use of any special function. We can simply do things like…
//string var $var = “0″;
//var is now float $var += 8.5;
//var is now integer $var += 3;
//var is now string $var .= ” is the sum”; echo $var;
?>
Concatenating variables in PHP?
In PHP we can join two variables by using the dot ‘.’ operator.
$var1 = “Hello world”; $var2 = “and Java”;
//prints “Hello world and Java” echo $var1 . $var2;
$var1 = “1″; $var2 = “2″;
//prints “12″; echo $var1 . $var2;
?>
So there you have it, a quick and easy variable lesson in PHP.
Javascript can be used with PHP without problems, as long as you keep in mind that they operate in different environments (see Frames, JavaScript, and PHP Overview):
PHP, is server side. Therefore, if you want to pass data from a form to PHP, you have to submit it and load the page again. There is no getting about it.
Javascript is client side (run in the browser), and can help you with dynamic functionality. You can easily use JavaScript and PHP jointly. However, just like PHP knows nothing about Javascript. PHP will just echo the Javascript code to the HTML page, just as it would echo the value of a string variable.
EXAMPLE
<?php
echo ‘Welcome to PHP’;
?>
and
<?php
echo ‘<script type=”text/javascript”>
<!–
if ( 1 ) {
window.open(\’any.php?name=News\’, \’hello world\’,
\’HEIGHT=500, resizable=yes, WIDTH=500\’);
}
//–>
</script>’;
?>
They both echo strings, of which the first one is simply displayed in the client’s browser as a welcome message, while the second one is take by the client’s browser and leads to the browser sending a request for the News module, which in turn sends the usual home page of a PHP site to be displayed on the client.
With this in brain, Javascript does not demand any special treatment when used in PHP blocks. Just append the Javascript code to the $content variable of the block and you are done. Of course, you have to escape double quotes – and it is a good idea to add a newline (\n) to the end of each Javascript line (see Javascript and BLOCKs).
If you use sed, the following sequence of set commands, applied to a Javascript file, will produce the right PHP code to include in the PHP block:
(A) 1,$s/”/\\”/g
(B) 1,$s/^/\$content \.= “/
(C) 1,$s/$/”;/
(D) 1,$s/”;$/\\n”;/
A Escape all double quotes.
B. Add a newline \n at the end of each JS line
C Add the string ‘”;’ at the end of every line.
D. Add the string ‘$content .= “‘ at the start of every line
Server Side Includes
You can insert the content of a file into a PHP file before the server carry out it, with the include() or require() function. The two functions are identical in every way, except how they handle errors.
The include() function generates a warning (but the script will continue execution)
The require() function generates a fatal error (and the script execution will stop after the error).
This can save the developer a substantial amount of time. This means that you can develop a standard header or menu file that you want all your web pages to include. When the header needs to be updated, you can only update this one include file, or when you add a new page to your site, you can simply change the menu file
The include() Function
The include() function get all the text in a particular file and copies it into the file that uses the include function.
Example
suppose that you have a standard header file, called “welcome.php”. To include the header file in a page, use the include() function, like this:
<html>
<body>
<?php include(“welcome.php”); ?>
<h1>Welcome</h1>
<p>any text</p>
</body>
</html>
Example
Now, let’s suppose we have a standard menu file that should be used on all pages (include files usually have a “.php” extension). Look at the “any.php” file below:
<html>
<body>
<a href=”http://www.any.com/xxx.php”>hi</a> |
<a href=”http://www.any.com/zzz.php”>your Us</a> |
<a href=”http://www.any.com/yyy.php”>name Us</a>
The three files, “xxx.php”, “zzz.php”, and “yyy.php” should all include the “any.php” file. Here is the code in “xxx.php”:
<?php include(“any.php”); ?>
<h1>Welcome</h1>
<p>any text</p>
</body>
</html>
If you look at the source code of the “xxx.php” in a browser, it will look something like this:
<html>
<body>
<a href=”xxx.php”>hi</a> |
<a href=”zzz.php”>your Us</a> |
<a href=”yyy.php”>name</a>
<h1>Welcome</h1>
<p>any text</p>
</body>
</html>
And, of course, we would have to do the same thing for “zzz.php” and “yyy.php”. By using include files, you simply have to update the text in the “any.php” file if you decide to rename or change the order of the links or add another web page to the site.
The require() Function
The require() function is indistinguishable to include(), except for that it handles errors differently.
The include() function produce a warning (but the script will continue execution) while the require() function generates a fatal error (and the script execution will stop after the error).
If you include a file with the include() function and an error occurs, you might get an error message like the one below.
PHP code
<html>
<body>
<?php
include(“phpguru.php.php”);
echo “Welcome!”;
?>
</body>
</html>
Error message:
Warning: include(phpguru.php) [function.include]:
failed to open stream:
No such file or directory in on line 5
Warning: include() [function.include]:
Failed opening ‘phpguru.php’ for inclusion
(include_path=’.;C:\php\ar’)
on line 5
Welcome!
Now, let’s run the same example with the require() function.
PHP code:
<html>
<body>
<?php
require(“phpguru.php “);
echo “Welcome!”;
?>
</body>
</html>
It is recommended to use the require() function instead of include(), because scripts should not continue executing if files are missing or misnamed.
The $_POST variable is used to collect values from a form with method=”post”. Information sent from a form with the POST method is invisible to others and has no limits on the amount of information to send.
The $_POST variable is used to collect values from a form with method=”post”.
The $_POST variable is an array of variable names and values sent by the HTTP POST method.
Example
<form action=”chi1.php” method=”post”>
Enter your name: <input type=”text” name=”name” />
Enter your Dob: <input type=”text” name=”Dob” />
<input type=”OK” />
</form>
The “chi1.php” file can now use the $_POST variable to catch the form data (notice that the names of the form fields will automatically be the ID keys in the $_POST array):
hi <?php echo $_POST["name"]; ?>.<br />
your <?php echo $_POST["Dob"]; ?> how old!
Why make use of $_POST?
A Variables have no length limit
B Variables sent with HTTP POST are not shown in the URL
yet, because the variables are not displayed in the URL, it is not possible to bookmark the page.
The $_REQUEST Variable
The PHP $_REQUEST variable contains the contents of both $_GET, $_POST, and $_COOKIE.
The PHP $_REQUEST variable can be used to get the result from form data sent with both the GET and POST methods.
Example
hi <?php echo $_REQUEST["name"]; ?>.<br />
your <?php echo $_REQUEST["Dob"]; ?> how old!
Setting and reading cookies in PHP is a part of–dare we say it?–cake. We don’t want to get into all the misinformation about cookies, but they’re important and useful. Sometimes they’re the right tool for the work.
create and modify a cookie In PHP
To create and modify a cookie, use the PHP function setcookie(). setcookie() takes up to six arguments, depending upon how much control you want over the cookie and who can read its value.
The best way of setting a cookie is like this:
setcookie(‘name’, ‘xxx’);
Then, for every further page on your site viewed by this browser (without the user quitting) you’ll have the value of ‘xxx’ stored in the variable $name for easy right to use in PHP. This type of cookie is known as a session cookie, since it lasts for the length of a user’s session.
If you want the cookie to persevere after the person exits his or her browser, you must pass setcookie() through a third parameter, the date you want the cookie to expire. Since PHP’s background springs fully formed from the head of Unix, you correspond to this time as the number of seconds since March 23, 1985. If you’re a Unix programmer, this makes total sense. But, if you’re from a Windows or a Macintosh background, you’re just trembling your head wondering if you’ll ever understand those wacky Unix folk.
PHP has a very nice function, mktime(). You pass mktime() (in this order) the hour, minute, second, month, day, and year that you want to represent, and mktime() returns to you the number of seconds since March 1, 1985. So, if you want to simulate a ZZZ meltdown:
<?php
$ZZZ = mktime(0,0,0,1,1,2000);
setcookie(‘name’, ‘xxx’, $ZZZ);
?>
your cookie will end with the millennium.
If you want to update a cookie to store a newer value, you can simply overwrite its value. So, even if you’ve previously sent the cookie above on an earlier page, it’s perfectly legal to go ahead and change your name to “akki.”
<?php
$ZZZ = mktime(0,0,0,1,1,2000);
setcookie(‘name’, ‘akki’, $ZZZ);
?>
Note that doing this doesn’t alter the value of the variable $name. It’s set when the page is loaded. If you want to make sure these two are always in sync, you can code like this:
<?php
$name = ‘Akki’;
$ZZZ = mktime(0,0,0,1,1,2000);
setcookie(‘name’, $name, $ZZZ);
?>
The next two parameters for setcookie() let you control the path and the domain of who can read your cookie. By default, only pages equivalent to or lower down in the ladder on the same server that sends the cookie can read its value. That’s for security’s sake. However, if you had an account that’s sometimes “www.any.com” but also “other.any.com,” and your account lets you serve pages from ~/myhome, you should modify setcookie() as such:
<?php
setcookie(‘name’, ‘akki’, $ZZZ, ‘~/myhome’, ‘.any.com’);
?>
The last parameter to setcookie(), which we’ve never used, teach that the cookie be sent only to a Web server that’s running a secure connection such as SSL. For this to occur, set the sixth value to 1.
Delete Cookie
Deleting a cookie is simple, simply pass setcookie() the name of your cookie and PHP will arrange for it to be deleted.
<?php setcookie(‘name’); ?>
There’s one last important item to cite about using cookies. Because of the way cookies work within HTTP, it’s important that you send all cookies before you print any text. If you don’t, PHP will give you a warning and your cookies will not be sent. So, this is OK:
<?php
setcookie(‘name’, ‘akki’);
echo “Good Morning!”;
?>
But this is not:
<?php
echo “Good Morning!”;
setcookie(‘name’, ‘akki’);
?>