Links

Book Marks


Misc

Hello World

The php, above, looks like <?php echo ' <p>Hello World</p>'; ?>

Comments

Comments are written like:


//This is a comment

for single lines and

/*
This is
a comment
block
*/

for multiple lines.

Space in source

this is a tab - which only shows in the source
<?php echo "this is a". "\t" . "tab - which only shows in the source"; ?>
This is a new line

Error Handling

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");
}
?>

Custom Error Handling

trigger_error function

Often used to trigger errors when viewers enter wrong input.

Filters

Testing filters has resulted in 100% fatal error Call to undefined function

Variables

Syntax

$var_name = value;

The Concatenation Operator

....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; ?>

More string variables

String Length

"strpos()" returns string length.

<?php
echo strlen("How many characters in the string.");
?>

The above code returns....

34

String Position

Returns the position of the first requested character.
The code, below, returns...


<?php echo strpos("What is the position of W?"); ?>

Samples

Hello Mars

"Hello Mars", above, is coded like...

<?php
$txt="Hello Mars";
echo $txt;
?>

Lots of string variable samples

More at http://www.w3schools.com

Add Slashes

This is how to add slashes before characters.
\This is how to add slashes before characters.
T\h\i\s \i\s \h\o\w \t\o \a\d\d \s\l\a\s\h\e\s \b\e\f\o\r\e \c\h\a\r\a\c\t\e\r\s.
Thi\s i\s h\ow t\o add \sla\she\s bef\o\re cha\racte\r\s.

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 & hex2bin

bin2hex converts binary to hexadecimal. pack() converts hexadecimal to binary.

42696e61727921
Binary!
<?php
$str = "Binary!";
echo bin2hex($str) . "<br />";
echo pack("H*",bin2hex($str)) . "<br />";
?>

Operators

+ 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
Should be 6: 6

<?php
$a = 5;
echo "Should be 5: " . $a++ . "<br />\n";
echo "Should be 6: " . $a . "<br />\n";
?>

Pre increment

Should be 6: 6
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
Should be 4: 4

<?php
$a = 5;
echo "Should be 5: " . $a-- . "<br />";
echo "Should be 4: " . $a . "<br />";
?>

Pre decrement

Should be 4: 4
Should be 4: 4

<?php
$a = 5;
echo "Should be 4: " . --$a . "<br />";
echo "Should be 4: " . $a-- . "<br />";
?>

Assignment Operators

= 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;
?>


9
4

Combined Assignment Operators

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
HelloThere!

Comparison Operators

Logical Operators

If Else Statements

<?php
$d=date("D");
if ($d=="Fri")
echo "Happy Friday!";
else
echo "It's not Friday.";
?>


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";
?>


It's Sunday!

Switch

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;
}
?>

i is an avacado
i is an avacado

The "break;" is required or it will then go on to the next lines (even when the first criteria has been satisfied.

Arrays

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";

Numeric Arrays

<?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];
?>


Washu is a Labrador Retriever and Kayto is a German Sheppard

Associative Arrays

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.

Multidimensional Array

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?";
?>


Is Washu a Labrador Retriever?

Loops

While

while (condition)
  {
  code to be executed;
  }

<?php
$n=1;
while($n<=5)
{
echo "The number is " . $n . "<br />";
$n++;
}
?>


The number is 1
The number is 2
The number is 3
The number is 4
The number is 5

Do while

do
  {
  code to be executed;
  }
while (condition);

<?php
$n=10;
do
{
$n++;
echo "The number is " . $n . "<br />";
}
while ($n<=15);
?>


The number is 11
The number is 12
The number is 13
The number is 14
The number is 15
The number is 16

It is one number off because it does the "do" BEFORE it checks the "while".

For

for (variable; condition; increment)
  {
  code to be executed;
  }

<?php
for ($a=1; $a<=5; $a++)
{
echo "The number is " . $a . "<br />";
}
?>


The number is 1
The number is 2
The number is 3
The number is 4
The number is 5

For Each

foreach ($array as $value)
  {
  code to be executed;
  }

<?php
$x=array("Washu", "Faye", "Rodney","Wednesday");
foreach ($x as $pet)
{
echo $pet . "<br />";
} ?>


Washu
Faye
Rodney
Wednesday

Functions

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!

Parameters

<?php
function k9name($dname)
{
echo $dname . " is a labrador retriever.<br />";
}
k9name("Washu");
k9name("Kate");
k9name("Flicka");
?>

Washu is a labrador retriever.
Kate is a labrador retriever.
Flicka 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 />";
?>

2
3

Common Functions

Date

Used to write the date

<?php
echo date("Y/m/d") . "<br />";
echo date("d-m-Y") . "<br />";
echo date("m.d.Y") . "<br />";
?>


2017/07/23
23-07-2017
07.23.2017

Include

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>

File handling

Open File

<?php
$file=fopen("welcome.txt","r") or exit("Unable to open file!");
?>

The "r", above is the mode inwhich to open the file.

Modes:

More file handling

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);
?>

Cookies

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>

Email

SAMPLE

<?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' />";
}
?>

Email 2

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>";
}
?>

Forms

Here is a form...

Name: Pet's name:

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.

Name: Pet's Name:

For the code, all that is done is to change the method from "post" to "get" in the form and in the second page.

Sessions

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'];
?>

Unset or destroy session

<?php
unset($_SESSION['views']);
?>


OR

<?php
session_destroy();
?>

Page Counter

Views=1

<?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.

Database

Connect to

Syntax:

mysql_connect(servername,username,password);

<?php
error_reporting(E_ALL);
$con = passwordam6t77I7gzdlLcMy");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
?>

End connection

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);
?>

Create Databse

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);
?>

Create Table in Database

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);

?>

Insert Data

<?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);

?>

Insert from an HTML form

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)
?>

Showing (SELECTing) Data

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);
?>

SAMPLE

Showing the Data in an HTML table

Could not connect: Can't connect to MySQL server on 'mysql2560int.domain.com' (111)