[ PHP >> PHP Language Construct ]
PHP Syntax [1]
<?php //PHP Code Start - This is a comment
/*
This is
a block comment */
$txt="Hello World"; //Variable - end with [;]
echo $txt; //Print out
//PHP Code End
?>
if...else
if{
}
else{
}
Switch...Case
switch ($x)
{
case 1:
break;
default:
}
While Loop
while($i<=10)
{
echo "The number is " . $i . " "; //{brown}[.] concatenate{/brown}
$i++;
}
Do While
do
{
$i++;
echo "The number \" is " . $i . " "; //{brown}[\] escape character{/brown}
}
while ($i<10);
?>
For Loop
for ($i=1; $i<=10; $i++)
{
echo "Hello World! ";
}
For Each
$arr=array("one", "two", "three");
foreach ($arr as $value)
{
echo "Value: " . $value . " ";
}
Define
bool define ( string name, mixed value [, bool case_insensitive] )
define("GREETING", "Hello you.", true);
echo GREETING; // outputs "Hello you."
echo Greeting; // outputs "Hello you." If bool false this will issue a notice
$_SERVER
$_SERVER is a global reserved variable that contains all server information. Try
$_SERVER["HTTP_REFERER"]
$_SERVER["HTTP_USER_AGENT"]
$_SERVER["REMOTE_ADDR"]
Redirect
http://www.w3schools.com/");
?>
POST
$_POST["txtName"] //Passed by Post method
Cookie
//setcookie(name, value, expire, path, domain);
setcookie("txtName", $name, time()+36000);
if (isset($_COOKIE["txtName"])) //Check for the cookie
echo "Welcome " . $_COOKIE["txtName"]; //Retrieve the cookie
Session Variable
session_start(); //Put at the top of the page before header gets sent
//Set it
$_SESSION['MySession']['Name'] = 'Jyotirmaya';
//Get it
if(isset($_SESSION['MySession'])) {
$varSession = $_SESSION['MySession']['Name'];
}
//Remove it
unset($_SESSION['MySession']);
//or
session_unregister('MySession');
SSI - Server Side Include
Files can be icluded multiple times using require(). require() results in a Fatal Error if file not present.
Files can only be included once using require_once().
Files can be icluded multiple times using include(). include() produces a Warning if file not present.
Files can only be included once using include_once().
Function
function my_Function_message($msg) {
echo $msg;
}
Call it by doing this inside Php tags
my_Function("Hello World");
Classes
MyBaseClass
{
var $myNumber; // Class variable definition
// Add $num articles of $artnr to the cart
function print_myNumber ()
{
echo $this->myNumber; //Use $this-> for local variables
}
}
?>
Uses
$myInstance = new MyBaseClass;
$myInstance->myNumber = 10; //Only one [$] sign
$myInstance->print_myNumber();
Miscellaneous
Stop Error/Warning Messages
ini_set("display_errors",0); //Replace with 1 to see errors/warnings
@Method_Name(); //Stops warning and error fro this method
See Also
References [1] W3schools PHP Tutorial [2] PHP Manual
Contributors
Jyotirmaya Nanda
I block the IP address(es) of users trying to vandalize my wiki. A simple mail to me can remove your IP from the blocked list. If you are new to wiki and want to try something out please do so at the Wiki Sand Box. Thank you !!.
|