Hello World
The php, above, looks like <?php
echo ' <p>Hello World</p>';
?>
Comments are written like:
//This is a comment
for single lines and
/*
This is
a comment
block
*/
for multiple lines.
<?php
echo "this is a". "\t" . "tab - which only shows in the source";
?>
Example 1: If the welcome file does not exist, the browser prints "File not found."
<?php
if(!file_exists("welcome.txt"))
{
die("File not found");
}
else
{
$file=fopen("welcome.txt","r");
}
?>
error_function(error_level,error_message,
error_file,error_line,error_context)
Often used to trigger errors when viewers enter wrong input.
Testing filters has resulted in 100% fatal error Call to undefined function
Syntax
$var_name = value;
....puts strings together. It is a ".". The {" "} in the code adds a space.
Hello Venus! What a muggy day!
<?php
$txt1="Hello Venus!";
$txt2="What a muggy day!";
echo $txt1 . " " . $txt2;
?>
"strpos()" returns string length.
<?php
echo strlen("How many characters in the string.");
?>
The above code returns....
34Returns the position of the first requested character.
The code, below, returns...
<?php
echo strpos("What is the position of W?");
?>
"Hello Mars", above, is coded like...
<?php
$txt="Hello Mars";
echo $txt;
?>
More at http://www.w3schools.com
In the above sample,echo $str."<br />";
just prints the string.
echo addcslashes($str,'A..Z')."<br />";
adds slashes before the capital letters.
echo addcslashes($str,'a..z')."<br />";
adds slashes in front of the lower case letters.
echo addcslashes($str,'o..s');
adds slashes in front of the letters that are in the alpha-numeric range of o-s.
The entire code...
<?php
$str = "This is how to add slashes before characters.";
echo $str."<br />";
echo addcslashes($str,'A..Z')."<br />";
echo addcslashes($str,'a..z')."<br />";
echo addcslashes($str,'o..s');
?>
Be careful using addcslashes() on 0, r, n and t. In PHP, \0, \r, \n and \t are predefined escape sequences.
addslashes() adds slashes to predefined characters: ('), ("), (\), NULL.
This function can be used to prepare a string for storage in a database and database queries.
PHP runs addslashes() on all GET, POST, and COOKIE data by default. Therefore you should not use addslashes() on strings that have already been escaped, this will cause double escaping. The function get_magic_quotes_gpc() can be used to check this.
bin2hex converts binary to hexadecimal. pack() converts hexadecimal to binary.
42696e61727921
<?php
$str = "Binary!";
echo bin2hex($str) . "<br />";
echo pack("H*",bin2hex($str)) . "<br />";
?>
+ Addition when x=2, x+2 returns 4
4
<?php
$x = "2";
echo $x+2;
?>
- Subtraction when x=2, 5-x returns 3
3
<?php
$x=2;
echo 5-$x;
?>
* Multiplication when x=4, x*5 returns 20
20
<?php $x=4; echo $x*5; ?>
/ Division when x=15, x/5 returns 3
0<?php $x=15; echo x/3; ?>
% returns the remainder of division
0<?php echo 10%2; ?>
++ will return increment and -- will return decrement
Post increment
Should be 5: 5<?php
$a = 5;
echo "Should be 5: " . $a++ . "<br />\n";
echo "Should be 6: " . $a . "<br />\n";
?>
Pre increment
Should be 6: 6<?php
$a = 5;
echo "Should be 6: " . ++$a . "<br />n";
echo "Should be 6: " . $a . "<>br />\n";
?>
Post decrement
Should be 5: 5
<?php
$a = 5;
echo "Should be 5: " . $a-- . "<br />";
echo "Should be 4: " . $a . "<br />";
?>
Pre decrement
Should be 4: 4
<?php
$a = 5;
echo "Should be 4: " . --$a . "<br />";
echo "Should be 4: " . $a-- . "<br />";
?>
= means "gets set to". So $a = 5 means $a "gets set to" 5
In the code, below, $b gets set to 4 & $a gets set to $b + 5 (or 9)
<?php
$a = ($b = 4) +5;
echo $a; . "<br />"
echo $b;
?>
Combined Assignment operators are:
Combined Assignment Operators do two things. Examples are below.
<?php
$a = 3;
$a += 5;
$b = "Hello";
$b .= "There!";
echo $a;
echo $b;
?>
8
<?php
$d=date("D");
if ($d=="Fri")
echo "Happy Friday!";
else
echo "It's not Friday.";
?>
If more than one line is to be executed in a single "if", use curly brackets.
<?php
$d=date("D");
if ($d=="Fri")
ÊÊ{
ÊÊecho "Hello!<br />";
ÊÊecho "Have a nice weekend!";
ÊÊecho "See you on Monday!";
ÊÊ}
?>
If...elseif...else:
<?php
$d=date("D");
if ($d=="Fri")
echo "Happy Friday!":
elseif ($d=="Sun")
echo "It's Sunday!";
else
echo "It is not Friday nor is it Sunday";
?>
The following is two different ways to write the same thing.
<?php
$i = "avacado"
if ($i == "apple")
{
echo "i is an apple";
}
elseif ($i == "pear")
{
echo "i is a pear";
}
elseif ($i == "avacado")
{
echo "i is an avacado";
}
?>
<?php
$i = "avacado";
switch ($i) {
case "apple":
echo "i is an apple";
break;
case "pear":
echo "i is a pear";
break;
case "avacado":
echo "i is an avacado";
break;
}
?>
The "break;" is required or it will then go on to the next lines (even when the first criteria has been satisfied.
Arrays can be written in two ways
$dog=array("Labrador Retriever","German Sheppard","Malanios","Border Collie");
$dog[0]="Labrador Retriever";
$dog[1]="German Sheppard";
$dog[2]="Malanios";
$dog[3]="Border Collie";
<?php
$dog[0]="Labrador Retriever";
$dog[1]="German Sheppard";
$dog[2]="Malanios";
$dog[3]="Border Collie";
echo "Washu is a " . $dog[0] . " and Kayto is a " . $dog[1];
?>
ID keys are assigined values.
<?php
$breed['Washu'] = "Labrador Retriever";
$breed['Kate'] = "Labrador Retriever";
$breed['Kayto'] = "German Sheppard";
$breed['Miles'] = "Border Collie";
echo "Washu is a " . $breed['Washu'] . ".";
?>
Washu is a Labrador Retriever.
Arrays can consist of arrays.
<?php
$breed = array
(
"Labrador Retriever"=>array
(
"Washu",
"Kate",
"Flicka"
),
"German Sheppard"=>array
(
"Kayto",
"Denim"
),
"Mixed-Breed"=>array
(
"Faye"
)
);
echo "Is " . $breed['Labrador Retriever'][0] . " a Labrador Retriever?";
?>
while (condition)
Ê {
Ê code to be executed;
Ê }
<?php
$n=1;
while($n<=5)
{
echo "The number is " . $n . "<br />";
$n++;
}
?>
do
Ê {
Ê code to be executed;
Ê }
while (condition);
<?php
$n=10;
do
{
$n++;
echo "The number is " . $n . "<br />";
}
while ($n<=15);
?>
It is one number off because it does the "do" BEFORE it checks the "while".
for (variable; condition; increment)
Ê {
ÊÊcode to be executed;
Ê }
<?php
for ($a=1; $a<=5; $a++)
{
echo "The number is " . $a . "<br />";
}
?>
foreach ($array as $value)
Ê {
ÊÊcode to be executed;
Ê }
<?php
$x=array("Washu", "Faye", "Rodney","Wednesday");
foreach ($x as $pet)
{
echo $pet . "<br />";
}
?>
For info on 700 built-in functions, see: http://www.w3schools.com/php/php_functions.asp
function functionName()
{
code to be executed;
}
<?php
function dogname()
{
echo "Washu!";
}
echo "The dog's name is ";
dogname();
?>
The dog's name is Washu!
<?php
function k9name($dname)
{
echo $dname . " is a labrador retriever.<br />";
}
k9name("Washu");
k9name("Kate");
k9name("Flicka");
?>
Washu is a labrador retriever.A sample with a return.
<?php
function add($x,$y)
{
$total=$x=$y;
return $total;
}
echo add(2,2) . "<br />";
echo add(2,3) . "<br />";
?>
2Used to write the date
<?php
echo date("Y/m/d") . "<br />";
echo date("d-m-Y") . "<br />";
echo date("m.d.Y") . "<br />";
?>
Loads .php into .php
The "require" is the same except that the script will stop running if there is an error.
The header and the links menu of this page were made with "include".
<div style="width:100%; height:133;" >
<?php include("php_2/header.php"); ?>
</div>
<?php
$file=fopen("welcome.txt","r") or exit("Unable to open file!");
?>
The "r", above is the mode inwhich to open the file.
Modes:
In the code, below, if there is not a sample it has NOT been tested.
CLOSE FILE
<?php
$file=fopen("test.txt","r");
//some code to be exectuted
fclose($file);
?>
CHECK END OF FILE
if (feof($file)) echo "End of file";
READ FILE LINE BY LINE
SAMPLE
<?php
$file = fopen("welcome.txt", "r") or exit("Unable to open file!");
//Output a line of the file until the end is reached
while(!feof($file))
{
echo fgets($file). "<br />";
}
fclose($file);
?>
READ CHARACTER BY CHARACTER
<?php
$file=fopen("welcome.txt","r") or exit("Unable to open file!");
while (!feof($file))
{
echo fgetc($file));
}
fclose($file);
?>
SET COOKIE
setcookie(name, value, expire, path, domain);
<?php
/* set cookie that expires in an hour */
setcookie("user", "Washu", time()+3600);
echo "retrieve cookie<br />";
echo $_COOKIE["user"] . "<br />";
print_r($_COOKIE);
echo "<br />";
echo "verify cookie<br />";
/* verify cookie */
if (isset($_COOKIE["user"]))
echo "Welcome " . $_COOKIE["user"] . "!<br />";
else
echo "Welcome guest!<br />";
?>
To delete a cookie, set time to negative.
For browsers that do not support cookies, use forms
<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="name" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
</body>
</html>
<html>
<body>
Welcome <?php echo $_POST["name"]; ?>.<br />
You are <?php echo $_POST["age"]; ?> years old.
</body>
</html>
<?php
error_reporting(E_ALL);
if (isset($_REQUEST['email']))
{
$email = $_REQUEST['email'];
$subject = $_REQUEST['subject'];
$message = $_REQUEST['message'];
mail("mcaldwell@brophy.com", "Subject: $subject", $message, "From: $email");
echo "Thank you for the email";
}
else
{
echo "<form method='post' action='mail.php'> Email: <input name='email' type='text' />&'t;br /> Subject: <input name='subject' type='text' /><br /> Message:<br /><textarea name='message' rows='15' cols='40'></textarea><input type='submit' />";
}
?>
This is a more secure form of email. "The FILTER_SANITIZE_EMAIL" removes all illegal e-mail characters. The "FILTER_VALIDATE_EMAIL" filter validates value as an e-mail address.
<?php
error_reporting(E_ALL);
function spamcheck($field)
{
$field=filter_var($field, FILTER_SANITIZE_EMAIL);
if(filter_var($field, FILTER_VALIDATE_EMAIL))
{
return TRUE;
}
else
{
return FALSE;
}
}
if (isset($_REQUEST['email']))
{
$mailcheck = spamcheck($$_REQUEST['email']);
if ($mailcheck==FALSE)
{
echo "Invalid input";
}
else
{
$email = $_REQUEST['email'];
$subject = $_REQUEST['subject'];
$message = $_REQUEST['message'];
mail("mcaldwell@brophy.com", "Subject: $subject", $message, "From: $email");
echo "Thank you for the email";
}
}
else
{
echo "<form method='post' action='mail.php'> Email: <input name='email' type='text' />$lt;br /> Subject: $lt;input name='subject' type='text' />$lt;br /> Message:$lt;br />$lt;textarea name='message' rows='15' cols='40'></textarea>$lt;input type='submit' />$lt;/form>";
}
?>
Here is a form...
Here is the code for the form:
<form action="question.php" method="post">
Name: <input type="text" name="fname" />
Pet's name: <input type="text" name="pname" />
<input type="submit" />
</form>
Here is the code for the other (question.php) page:
<body>
<:p>
Hello <?php echo $_POST["fname"]; ?>!<br />
<?php echo $_POST["pname"]; ?> misses you!</p>
</body>
You can use $_GET to show the stuff in the address box of the browser which will allow the viewer to bookmark.
For the code, all that is done is to change the method from "post" to "get" in the form and in the second page.
Start Sessions
The code come BEFORE the HTML
<?php session_start(); ?>
Store and Retrieve Sessions
SAMPLE
In the head tag:
<?php
session_start();
// store session data
$_SESSION['views']=1;
?>
In the body:
<?php
//retrieve session data
echo "Pageviews=". $_SESSION['views'];
?>
<?php
unset($_SESSION['views']);
?>
OR
<?php
session_destroy();
?>
<?php
session_start();
if(isset($_SESSION['views']))
$_SESSION['views']=$_SESSION['views']+1;
else
$_SESSION['views']=1;
echo "Views=". $_SESSION['views'];
?>
If the "views" varaible is set, it adds 1. If the variable is not set, it creates it.
Syntax:
mysql_connect(servername,username,password);
<?php
error_reporting(E_ALL);
$con = passwordam6t77I7gzdlLcMy");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
?>
Connection will be ended when script is done running.
To end before that, see the untested code below
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
ÊÊ{
ÊÊdie('Could not connect: ' . mysql_error());
ÊÊ}
// some code
mysql_close($con);
?>
SPECIAL NOTE: Can not seem to create a database on my server externally. Need to use content management system at host website
Create code:
<?php
$con = mysql_connect("localhost","UI",PW");
if (!$con)
ÊÊ{
ÊÊdie('Could not connect: ' . mysql_error());
ÊÊ}
if (mysql_query("CREATE DATABASE my_db",$con))
ÊÊ{
ÊÊecho "Database created";
ÊÊ}
else
ÊÊ{
ÊÊecho "Error creating database: " . mysql_error();
ÊÊ}
mysql_close($con);
?>
The dogID int NOT NULL AUTO_INCREMENT, PRIMARY KEY(dogID),
part, shown below, has to do with indetifying rows in the table.
<?php
error_reporting(E_ALL);
$con = mysql_connect("localhost","UI","PW");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("name of db" , $con);
$sql = "CREATE TABLE Dogs
(
dogID int NOT NULL AUTO_INCREMENT,
PRIMARY KEY(dogID),
DogName varchar(15),
DogBreed varchar (40),
Age int
)";
mysql_query($sql,$con);
mysql_close($con);
?>
<?php
error_reporting(E_ALL);
$con = mysql_connect("localhost","UI","PW");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("name of db" , $con);
$sql = "CREATE TABLE Dogs
(
dogID int NOT NULL AUTO_INCREMENT,
PRIMARY KEY(dogID),
DogName varchar(15),
DogBreed varchar (40),
Age int
)";
mysql_query($sql,$con);
mysql_query("INSERT INTO Dogs (DogName, DogBreed, Age)
VALUES ('Washu', 'Labrador Retriever' , '4')");
mysql_query("INSERT INTO Dogs (DogName, DogBreed, Age)
VALUES ('Kate', 'Labrador Retriever' , '1')");
mysql_close($con);
?>
The HTML part: (not tested)
<html>
<body>
<form action="insert.php" method="post">
Firstname: <input type="text" name="firstname" />
Lastname: <input type="text" name="lastname" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
</body>
</html>
The php part (not tested):
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
ÊÊ{
ÊÊdie('Could not connect: ' . mysql_error());
ÊÊ}
mysql_select_db("my_db", $con);
$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
if (!mysql_query($sql,$con))
ÊÊ{
ÊÊdie('Error: ' . mysql_error());
ÊÊ}
echo "1 record added";
mysql_close($con)
?>
The following code assumes database and table have already been created (see above for that creation) it also inserts a new entry.
<?php
error_reporting(E_ALL);
$con = mysql_connect("localhost","UI","PW");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("db1073543_sa7763_main" , $con);
mysql_query("INSERT INTO Dogs (DogName, DogBreed, Age)
VALUES ('Faye', 'Rottie-GSD-Lab' , '6')");
$result = mysql_query("SELECT * FROM Dogs");
while($row = mysql_fetch_array($result))
{
echo $row['DogName'] . " " . $row['DogBreed'];
echo "<:br />";
}
mysql_close($con);
?>