Ok, so how do you load a .php file into your web browser, and what does it do when you type (for example) http://www.edrackham.com/index.php then hit enter?
PHP can be used within a file with the extension '.php'. There are other valid extensions such as '.php3' and '.phps' but I'm using '.php' as it’s widely and more commonly used. ALL PHP code MUST be entered within PHP "start and end" tags. N.B. The '…' represents php code. There are three main PHP "start and end" tags and one 'bonus' tag as I like to call it, shown below:
Option 1 (<?php … ?>) is the most common, and will be used throughout the remainder of this tutorial. A simple PHP script may look like either of the following:
Or
'echo' is a built-in function within PHP (as are MANY MANY others). echo simply prints whatever follows into the document… in this case, <p> This is my first PHP script. w00t</p>. This would obviously display the text 'This is my first PHP script. w00t' in a web browser, using the <p></p> HTML tags.
Nearly every line in PHP is ended with a ';' (semi-colon). Only 'instructors' (a piece of code telling PHP what to do) needs a terminator (';'). This is much the same for languages such as C, and JavaScript. A piece of code like the following shows an example of how not EVERY line needs a terminator:
As you can see only the 'echo' function line uses a terminator, not the 'for' loop, nor the closing curly bracket. Out of curiosity, the above function would produce:
I am line number 0
I am line number 1
I am line number 2
I am line number 3
I am line number 4
I am line number 5
I am line number 6
I am line number 7
I am line number 8
I am line number 9
You can use 3 types of comments:
A variable in PHP begins with the ‘$’ sign, and can be named ANYTHING you like as long as you stick to these golden rules:
To declare a variable, think of a decent name:
Bang a $ dollar sign infront of it:
Use the equal sign (=) after it, and assign a literal value:
Asigning a variable is an instruction, and as such, should have a terminator at the end of it:
oops… I mean:
There. w00t is now assigned the value "edrackham". One last thing to consider is that if you had a string, which included 'special characters' like the (") speechmark, you have to 'escape' the character. Observe:
Would result in an error because the PHP parser will begin to read along the line, it'd print "My mate said" then it meets another speechmark, this closes the echo session, and then mis-interperts the next word "Hey" as an invalid command or terminator. So how do we overcome this? We can "escape" special chars using the \ (backslash).
See… simple, we escaped the internal speechmarks using '\'. This function would now work no problemo. Search google for PHP special chars that need escaping.
Discussion
No comments for “Basic PHP Tutorial”
Post a comment