PHP Coding:
- PHP will fall in between the HTML body tags
- PHP scripts always start with <?php and end with ?>
- Each line of code of PHP ends with a ;
- To print, you can use "echo" or "print".
Sample:
<?php echo "hello"; ?>
- Variables in PHP start with a $
- <?php
- $txt = "hello";
- echo $txt;
- ?>
- You can connect multiple variables with a .
- $txt1 = "hello";
- $txt2 = "class";
- echo $txt1 . $txt2;
- This will create: "helloclass". If you want to add a space, you need to do the following:
- echo $txt1 . " " . $txt2;
- This gives you "hello class"
- You can make comments in your coding to help you or others understand what you've done. You do this with //
- //this is a comment
- /*
- Now the next
- few lines of text
- are a comment block
- */
- PHP functions:
- phpinfo () - this allows you to see different types of information about a computer system as well as the way PHP is set up.
- Try the following between the ()
- INFO_GENERAL
- INFO_CREDITS
- INFO_CONFIGURATION
- INFO_MODULES
- INFO_ENVIRONMENT
- INFO_VARIABLES
- INFO_LICENSE
- INFO_ALL
- This is by no means a full list of functions in PHP
- PHP Server Variables
- The servers hold a variety of information that could be of use. The variable $_SERVER is a reserved variable that contains all server information.
- "Referer: " . $_SERVER["HTTP_REFERER"] . "<br />";
- "Browser: " . $_SERVER["HTTP_USER_AGENT"] . "br />";
- "User's IP address: " . $_SERVER["REMOTE_ADDR"];
- Each of the above will, if used with the "echo" statement give you the user's URL from which they came, their Browser and their IP address.
- Header()
- sends raw HTTP headers through HTTP protocol ... for example you can redirect someone to another page.
- header ("Location: http://www.apple.com/");
- fopen()
- Allows php to open a specifiet file.
- $f=fopen("welcome.txt", "r");
- we're opening the file "welcome.txt" as a read only file and assigning it to the variable $f.
- you can also check to see if it can or can't open the file and return a comment.
- if (!($f=fopen("welcome.txt", r)))
- exit (unable to open file!);
- Conditional Statements:
- There are two conditional statements:
- if (...else) which allows you to have code executed if a given condition is true and something else executed if it is not true
- $d=date("D");
- if ($d=="Fri")
- echo "Have a nice weekend!";
- else
- echo "Have a nice day!";
- If more then one condition is to be executed, those lines should be in {}
- if ($x-=10)
- {
- echo "Hello<br />";
- echo "Good morning<br />";
- }
- switch statement which allows you to select multiple lines of code to execute.
- //first we have a variable that is evaluated once.
- switch ($x)
- //the value is then compared with each case, if it matches, the code is executed.
- {
- case 1:
- case 2:
- case 3:
- default:
- eco "No number between 1 and 3";
- }