PHP

HelloWorld

<html>
<body>
/* comment */
<?php
echo "Hello World";
?>
 
</body>
</html>

Variables

  • PHP is a Loosely Typed Language
  • Variables always have the dollar $ sign
<html>
<body>
<?php
$txt="Reza!"; //variable starts with $
echo $txt;
?>
</body>
</html>

The Concatenation Operator

The concatenation operator (.) is used to put two string values together.

<?php
$txt1="Hello World!";
$txt2="What a nice day!";
echo $txt1 . " " . $txt2; //concat txt1 with space with txt2
?>

Conditions

if (condition)
code
elseif (condition)
code
else
code

switch (n)
{
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
default:
code to be executed if n is different from both label1 and label2;
}

$d=date("D");
if ($d=="Fri")
  echo "Have a nice weekend!";
elseif ($d=="Sun")
  echo "Have a nice Sunday!";
else
  echo "Have a nice day!";
 
switch ($x)
{
case 1:
  echo "Number 1";
  break;
case 2:
  echo "Number 2";
  break;
case 3:
  echo "Number 3";
  break;
default:
  echo "No number between 1 and 3";
}

Array

cars=array("Saab","Volvo","BMW","Toyota"); //numeric
cars[1]
 
$ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34); //Associative Array - like a map
ages['Peter'] = "32";
 
$families = array ("Griffin"=>array("Peter","Lois","Megan"),"Quagmire"=>array("Glenn"),"Brown"=>array("Cleveland","Loretta","Junior")); //multi-dimensional

Loops

<?php
while($i<=5)
  {
  echo "The number is " . $i . "<br />";
  $i++;
  }
 
$i=1;
do
  {
  $i++;
  echo "The number is " . $i . "<br />";
  }
while ($i<=5);
 
for ($i=1; $i<=5; $i++)
  {
  echo "The number is " . $i . "<br />";
  }
 
$x=array("one","two","three");
foreach ($x as $value)
  {
  echo $value . "<br />";
  }
?>

Functions

<?php
function writeName()
{
echo "Reza";
}
 
echo "My name is ";
writeName();
 
function writeName($fname)
{
echo $fname . " Reza <br />";
return $total. "something";
}
 
?>

Form

/*some html file:*/
<html>
<body>
    <form action="welcome.php" method="post">
       Name: <input type="text" name="fname" />
       Age: <input type="text" name="age" />
       <input type="submit" />
    </form>
</body>
</html>
 
//welcome.php file:
//we have access to all form elements:
Welcome <?php echo $_POST["fname"]; ?>!<br />
You are <?php echo $_POST["age"]; ?> years old.
 
<?php echo $_REQUEST["fname"]; //$_REQUEST function contains the contents of both $_GET, $_POST, and $_COOKIE.
  • A good way to validate a form on the server is to post the form to itself, instead of jumping to a different page. The user will then get the error messages on the same page as the form. This makes it easier to discover the error.

Server side include

  • include and require are similar except for handling errors:
    1. include() generates a warning, but the script will continue execution
    2. require() generates a fatal error, and the script will stop
<body>
    <?php include("header.php"); ?>
    <h1>Welcome to my home page!</h1>
    <p>Some text.</p>
</body>

Error Handling

<?php
 
//instead of this
 
$file=fopen("welcome.txt","r");
 
//we can do:
if(!file_exists("welcome.txt"))
  {
  die("File not found");//Equivalent to exit(). a better way is to create an error handler instead of exit.
  }
else
  {
  $file=fopen("welcome.txt","r");
  }
?>

custom error handling ??

Exceptions

try
  {
  somemethod();
  }
 
catch(Exception $e)
  {
  echo 'Message: ' .$e->getMessage();
  }
  • We can create custom exceptions

Built-in Functions

  • strlen(x): length of a string
  • strpos(x,y): search for character within a string
  • date(format,timestamp): date("Y/m/d"), date("D")
  • $email_address=filter_var($email_address, FILTER_SANITIZE_EMAIL): Filters a variable with a specified filter
  • phpinfo()
  • die(): Equivalent to exit()

AJAX

<html>
<head>
<script type="text/javascript">
function showHint(str)
{
if (str.length==0)
  { 
  document.getElementById("txtHint").innerHTML="";
  return;
  }
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest(); //Create an XMLHttpRequest object
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function() //Create the function to be executed when the server response is ready
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","gethint.php?q="+str,true); //Send the request off to a file on the server
xmlhttp.send();//send request to server
}
</script>
</head>
<body>
 
<p><b>Start typing a name in the input field below:</b></p>
<form> 
First name: <input type="text" onkeyup="showHint(this.value)" size="20" />
</form>
<p>Suggestions: <span id="txtHint"></span></p>
 
</body>
</html>

// gethint.php file

<?php
//get the q parameter from URL
$q=$_GET["q"];
//output the response
echo "response: " . $q; //notice that this is not return statement
?>

Reference

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License