php notes

some of these notes may have been created from other online sources.

they are just my home schooling notes.

 

<?php  //opening tag
?>     //closing tag
//     //comment
#      //comment
/* */  //comment multi line
.      //conctentation operator the2 dot between strings and variables joins the two. “$hello”.” World” = hello World

display information about the php environment:
<?php phpinfo(); ?>

to send data to the browser use the echo function.
echo “stuff to echo”;

In PHP, you define a variable with the following form:

$variable_name = value;

The first character after the dollar sign must be a letter or underscore
PHP variables may only be composed of alphanumeric characters and underscores; for example, a-z, A-Z, 0-9, and _.

you crate global variables (variables that retain their value throught the life of the program)
by using the keyword global before the variable:
global myvariable;

Static variables provide a variable that isn’t destroyed when a function ends.
You can use the static variable value again the next time you call the function
static myvariable = 4;

A constant, like its name implies, cannot change its value during the execution of your program
Constants do not have a dollar sign ($) before them
Constants are defined and accessed globally
Constants cannot be redefined or undefined once they have been set
Constants can only be defined using the define function, not by simple assignment

define(“HELLO”, “Hello world!”);  //the constant will be accessed like so: “echo HELLO” echos the value of the constant

Predefines Constants:
__FILE__, which returns the name of the PHP file that’s being executed
__LINE__, which returns the line number in that file.

$num+=y        Addition    $num=$num+y

$num -=y    Subtraction    $num=$num-y

$num *=y    Multiplication    $num=$num*y

$num /=y    Division    $num=$num/y

$num.= “y”    Concatenation    $string=$string.”y”
——————————————————————————–
COMMON USEFUL FUNCTIONS:
strtolower(string_to_convert); = converts strings to lowecase.
strtoupper(string_to_convert); = converts strings to uppercase.
md5(file or string to hash);   = creates an md5 checksum
function_exists(“nameOfFunction”); = checks to see if a function already exists
var_dump();                      = dumps an array  var_dump($myarray);

array_push();             = accepts two arguments— an array to add to and the value to push onto it. if the second value is an array it will create a multidimensional array

isset();             = returns true if the variable passed to it has been set and false otherwise
asort();             = sorts an associative array by value not keys
ksort();             = sorts an associative array by key
rsort();              = sorts data in an array in reverse
sort();                 = sorts data in an array //sort($myarray) will sort alphabetically or numerically
count();                         = counts the number of elements in an array
$numElements = count($shapes);   = this would count the number elements in $shapes, and assign the value to $numElements
sort();                = sorts an array alphabetically, and numerically
extract();                      = extracts the keys from an array and creates variables with their names, the value being whatever the value was for that key
extract($myarray);
extract($shapes,EXTR_PREFIX_ALL,”shapes”); // $shapes_SodaCan, $shapes_NotePad, $shapes_Apple, $shapes_Orange, and
//$shapes_PhoneBook are now set
date(‘d-m-Y’)  // output the date day month, and year with – between them
date(‘d/m/Y’)  // output the date day month, and year with / between them
isset($variableName)   // checks if a varible is set / returns true if the variable is initialized
empty($variableName)   // checks for an empty variable / returns true if the variable is not initialized
is_numeric($variableName)  // returns true if the variable is a number or string that can be converted to a number
range($lo, $hi, $step)    // returns an array filled with values from low to high with the increment as $step.
range(1, 10, 1)           //return an array with values one threw ten with the increment as 1

the extr prefix tells it to prefix all the variables with the data provided

compact();                         = creates an array from a list of variables.

example:
<?php
$SodaCan=’Cylinder’;
$NotePad=’Rectangle’;
$Apple = ‘Sphere’;
$Orange = ‘Sphere’;
$PhoneBook = ‘Rectangle’;

$shapes=compact(‘SodaCan’, ‘Note Pad’, ‘Apple’, ‘Orange’, ‘PhoneBook’);
echo var_dump($shapes);
?>

gettype($myvariable);         //get the variables type
settype( $undecided, string );    //set the type of variable named undecided to string
——————————————————————————–
REGEXP REGULAR EXPRESSIONS:

[:lower:]  //a-z
[:alnum:]  //a-z A-Z 0-9

regexp are contained in forwardslash characters
/abc/

a regexp defines a pattern that can be searched for in a string.
the pattern is case sensitive and enclosed in forward slashes in a text string
to create a case-insensitive regexp add an “i” modifier to the end of the regexp
‘/hello/i’  //matches hello HELLO Hello etc.

the backslash is the escape character in regular expressions
it gives special meaning to some characters and removes it from others.

the carat “^” is a character that when placed infront of other characters it negates them.

when a character has special meaning in a pattern it is called a metacharacter

the “-” when used will match characters between it, a-z will match a through z.

preg_match($pattern_to_search_for, $string_to_search);

—————————————————————————————————
SANITIZING USER INPUT:

to prevent escape characters being submitted to mysql:
$variable = mysql_real_escape_string($variable);      //where $variable is the variable needing cleaning

to remove slashes:
$variable = stripslashes($variable);

to remove html:
$variable = htmlentities($variable);  //changes the tags to &
$variable = strip_tags($variable);    //removes the tags entirely

<?php
function sanitizeString($var)
{
if (get_magic_quotes_gpc()) $var = stripslashes($var);
$var = htmlentities($var);
$var = strip_tags($var);
return $var;
}

function sanitizeMySQL($var)
{
$var = mysql_real_escape_string($var);
$var = sanitizeString($var);
return $var;
}
?>

Add this code to the end of your PHP programs and you can then call it for each user
input to sanitize, like this:
$variable = sanitizeString($_POST[‘user_input’]);
Or, when you have an open MySQL connection:
$variable = sanitizeMySQL($_POST[‘user_input’]);

—————————————————————————————————
SETTING COOKIES:

setcookie(name, value, expire, path, domain, secure, httponly);

a cookie with the name username and the value “Hannah” that is accessible
across the entire web server on the current domain, and will be removed from the
browser’s cache in seven days
setcookie(‘username’, ‘Hannah’, time() + 60 * 60 * 24 * 7, ‘/’);

if (isset($_COOKIE[‘username’]))
$username = $_COOKIE[‘username’];

to destroy a cookie set the date to expire in the past:
setcookie(‘username’, ‘Hannah’, time() – 2592000, ‘/’);

—————————————————————————————————
AUTHENTICATION:

$token = md5(‘mypassword’);  //run md5sum on password before storing it

$token = sha1(‘mypassword’);  //run sha1 on password before storing it

—————————————————————————————————
CLASSES:
classes are similar to c++ classes.
the difference is when you use the closing braces there is no “;”
you also use the keyword “new” to get memory allocated for the class object when creating objects.
the reference returned by new is assigned to a variable.
you then use that variable to access vatriables and method of that class.
in a class when you define a variable you must define it with the keyword var. (var $myvariable = 1;)
YOU MUST USE VAR TO DECLARE A VARIABLE IN A CLASS.

When referring to methods and variables from within the class, you must use the syntax:

$this->variable or method name;  //remember the item is heap stored, and all heap stored objects use -> for access.
The special variable $this always points to the currently executing object. For use inside the class.

example: $this->age = $new_age;

notice that age does not contain a $

For use outside the class itself use the name of the variable that was assigned when using new:
myobject = new myclass;
myobject->myfunction();
myobject->myvariable = 5;

class myclass
{
function myclass() { } //constructor for class
Class code here;
}

creating a new instance of myclass:
$myvariable = new myclass;

When a class inherits from another class, the class that it inherits from is called the superclass.
The class that inherits the other class is called the sub class.
to inherit from a class use the “extends” keyword.
example which “new_class” inherits from “myclass”

To call the parent class method of a class which inherits from a superclass:

parent::method_from_parent
parentclassname::methodname()

class myclass
{

function sayhi()
{ echo “Hello”;}

}

class new_class extends myclass
{
function newfunction()
{
parent::sayhi();
}
}

when inheriting from a superclass alsways make sure to call the constructor
of the superclass.

do this using the constructor in your new class:

class myclass extends aclass
{
function myclass()
{
parent::aclass();
}
}

you can detect if you are in an object by using :
if ($this == null)  //code to execute if there is no “this” pointer and the function
//was called using the scope resolution operator (::)

you can call a method in a class which does not have any objects created yet by using the scope
resolution operator ::

myclass::function_in_myclass();

class constructors with default values:
class first_class
{
var $name;
function first_class( $n=”anon” )  //constructor with deafault values

——————————————————————————–
FUNCTIONS:
Function names aren’t case sensitive
when you pass a function a variable it makes a copy of the variable.
you can use a reference (&variable_name) like in c to pass the memory location
unlike c you do not have to assign a pointer to hold the reference.
the reference is addressable by the name chosen by the function you pass it to
(name in arguments)

function some_function(arguments)
{ code to execute }

function myfunction()
{
echo (“Hello from function-land!”);
}

functions with defualt values:
function capitalize( $str, $each=TRUE )
{
code here;
inside here variable names are $str and $each.
}

FUNCTION ALIASES:
function myfunction()
{
print (“test”);
}

$avariable = “myfunction”;

$avariable();      //avariable is an alias for myfunction

——————————————————————————–
Including and Requiring PHP Files:
All the include and require functions can take a local file or URL as input, but they cannot import a remote file.
You should always use include_once, as there really isn’t any drawback to using it instead of include

include        includes a file and warns if it can not import the file (file unavailable)

require        stops processing of the particular page if they can’t retrieve the resource.

include_once    includes a file and warns if it can not import the file (file unavailable)

require_once    stops processing of the particular page if they can’t retrieve the resource.

example include:

include(‘add.php’);
——————————————————————————–
CASTING VARIABLES:
You can create reference variables like below:
$myvariable = 5;
mynewvariable = &$myvariable;

myvariable now = mynewvariable (they both point to the same memory location)

++$x; // $x is incremented
– – $x; // $x is decremented
If these operators are used as part of a test expression, the incrementation occurs
before the test is carried out

TYPES:

(int), (integer)
Cast to integer

(bool), (boolean)
Cast to Boolean

(float), (double), (real)
Cast to float

(string)
Cast to string

(array)
Cast to array

(object)
Cast to object

example casting to string:

$test=1234;
$test_string=(string)$test;

GLOBAL VARIABLES:

when you declare a variable outside of a function, but want to access that variable inside the function
you use the keyword global infront of the variable name inside the function to access the variable that is outside the function.

$myvariable                //variable declared outside function

function myfunction()
{
global $myvariable;       //variable declared global, so function can access the original myvariable

}

——————————————————————————–
OPERATOR PRECEDENCE:
section 4.2 in Learning PHP and MYSQL
division and multiplication are before addition and subtraction.
You can change the order of precedence with the ( ) operators

NOT then AND then OR

Operators
++ – – (cast)          11
/ *%            10
+ –            9
< <= => >        8
== === !=        7
&&            6
||            5
= += – = /= *=%= .=    4
and            3
xor            2
or               1

——————————————————————————–
ARRAYS: page 122
arrays have a key / value pair combo going on.
the key can be a string or a number.
when the key is a number it is called a numeric array.
when the key is a string it is called an associative array.

if you create an array, and use the brackets to assign a number to the value
and you jump ahead some numbers it will start counting from the last number you used

$myarray[0] = 0;
$myarray[1] = 1;
$myarray[3] = 2;
$myarray[5] = 3;
$myarray[] = 4;   //bucket number is 6, value is 4

$users = array (“Bert”, “Sharon”, “Betty”, “Harry” );  //creation of array using the array function

print “$users[2]”;  //access the thrid bucket of the array

For example, to assign the first two days of the week to a numeric indexed array, you would use:

<?php
$weekdays[]=’Monday’;
$weekdays[]=’Tuesday’;
?>

You could also specify the index values, which has the same end result as:

<?php
$weekdays[0]=’Monday’;
$weekdays[1]=’Tuesday’;
?>

If you do specify the index yourself, be careful not to skip over numbers

The other way to assign values to an array is to use the array function.
The array function allows you to create your array and assign multiple elements all at once.
The array takes pairs of index keys and values as parameters. It returns an array assigned to a variable.
The elements to be assigned are separated by commas.

numeric arrays:

<?php
$weekdays=array(‘Monday’,
‘Tuesday’,
‘Wednesday’,
‘Thursday’,
‘Friday’,
‘Saturday’,
‘Sunday’);
?>

associative arrays:
<?php
$shapes=array(‘Soda Can’ => ‘Cylinder’,
‘Note Pad’ => ‘Rectangle’,
‘Apple’ => ‘Sphere’,
‘Orange’ => ‘Sphere’,
‘Phonebook’ => ‘Rectangle’);
?>

To add values to the end of an existing array, you can use the array identifier.
For example, to add Thursday to the $weekdays array:

<?php
$weekdays[] = “Thursday”;
?>

To add another shape to your associative array, use a similar syntax:

<?php
$shapes[“Megaphone”]= “Cone”;
?>

MULTI DIMENSIONAL ARRAYS:
<?php
$objects=array(‘Soda Can’ =>    array(‘Shape’    => ‘Cylinder’,
‘Color’    => ‘Red’,
‘Material’ => ‘Metal’),
‘Note Pad’ =>    array(‘Shape’    => ‘Rectangle’,
‘Color’    => ‘White’,
‘Material’ => ‘Paper’),
‘Apple’ =>       array(‘Shape’    => ‘Sphere’,
‘Color’    => ‘Red’,
‘Material’ => ‘Fruit’),
‘Orange’ =>      array(‘Shape’    => ‘Sphere’,
‘Color’    => ‘Orange’,
‘Material’ => ‘Fruit’),
‘Phonebook’ =>  array(‘Shape’    => ‘Rectangle’,
‘Color’    => ‘Yellow’,
‘Material’ => ‘Paper’));
echo $objects[‘Soda Can’][‘Shape’];  //access second part of array using []. soda can is one level, shape is the second
?>

———————————————————————————————————-
THE FOREACH STATEMENT:
<?php
$shapes=array(‘Soda Can’ => ‘Cylinder’,     //array is defined
‘Note Pad’ => ‘Rectangle’,
‘Apple’ => ‘Sphere’,
‘Orange’ => ‘Sphere’,
‘Phonebook’ => ‘Rectangle’);  //end of array definition
foreach ($shapes as $key => $value) {      //for each loops through the elements in the array
print”The $key is a $value.<br>n”;    //prints out the key and value pairs
}
?>

$users = array (“Bert”, “Sharon”, “Betty”, “Harry” );
foreach ( $users as $val )                            //$users loops through all the array contents $val being current item
{
print “$val<br>”;
}

foreach with associative arrays:

foreach( $array as $key=>$value )
{
//…
}
——————————————————————————————————-

——————————————————————————–
TRUTH TABLE:

AND (&&)
TRUE if both operands must be TRUE

OR  (||)
TRUE if at least one operand is trUE

XOR (xor)
TRUE if only one operand is trUE

NOT (!)
TRUE if FALSE, FALSE if trUE

——————————————————————————–
THE IF STATEMENT:

if (conditional expression)
{
block of code;
}

if (x == 0)
{
do code;
}

IF ELSE:
if ($username == “Admin”){
echo (‘Welcome to the admin page.’);
}
else {
echo (‘Welcome to the user page.’);
}

THE ELSEIF STATEMENT:
if ($username == “Admin”){
echo (‘Welcome to the admin page.’);
}
elseif ($username == “Guest”){
echo (‘Please take a look around.’);
}
else {
echo (“Welcome back, $username.”);
}

——————————————————————————–
THE TENARY OPERATOR

{expression} ? return_when_expression_true : return_when_expression_false;

<?php
$logged_in = TRUE;
$user = “Admin”;
$banner = ($logged_in==TRUE)?”Welcome back $user!”:”Please login.”;
echo “$banner”;
?>

——————————————————————————–

THE SWITCH STATEMENT:
The switch statement works by taking the value after the switch keyword and comparing it to the cases in the order they appear
If no case matches, no code is executed. Once a case matches, the code is executed
The expression the switch statement uses must evaluate to a simple type like a number, integer, or string. An array can be used only if a specific member of the array is referenced as a simple type.
If you want only the code in the matching block to execute, you can place a break keyword at the end of that block.

switch ($action) {
case “ADD”:
echo “Perform actions for adding.”;
echo “As many statements as you like can be in each block.”;
break;
case “MODIFY”:
echo “Perform actions for modifying.”;
break;
case “DELETE”:
echo “Perform actions for deleting.”;
break;

default:                             //defualt case
echo “Error: Action must be either ADD, MODIFY, or DELETE.”;

}
——————————————————————————–
LOOPS:
break out of any loop by using the “break;” statement
continue statement stops processing the current block of code in a loop and jumps to the next iteration of the loop

THE WHILE LOOP:

while (expression)
{
code to
execute;
}

THE DO WHILE LOOP:

do {
code to execute;
}while (expression);

THE FOR LOOP:
for (initialization expression; test expression; modification expression)
{
code that is executed;
}

<?php
for ($num = 1; $num <= 10; $num++) {
print “Number is $num<br />n”;
}
?>

——————————————————————————–

$GLOBALS
Contains any global variables that are accessible for the local script.
The variable names are used to select which part of the array to access.

$_SERVER
Contains information about the web server environment.

$_GET
Contains information from GET requests (a form submission).

$_POST
Contains information from POST requests (another type of form submission).

$_COOKIE
Contains inform from HTTP cookies.

$_FILES
Contains information from POST file uploads.

$_ENV
Contains information about the environment (Windows or Mac).

$_REQUEST
Contains information from user inputs. These values should not be trusted.

$_SESSION
Contains information from any variables registered in a session.

$PHP_SELF
contains the name of the script running and is part of the $_SERVER array.

The echo function uses quotes to define the start and end of a string
to include quotes in a string use excape characters

————————————————————————
strings:

Use strcmp (string1, string2) to compare two strings including the case / The return value is 0 if the two strings have the same text.
Use strcasecmp (string1, string2) to compare two strings without comparing the case / The return value is 0 if the two strings have the same text.

Variables and text strings are joined together with a period (.). This can be done multiple times
echo “Hi, I’m Max. Who are you? ” . $my_string . “Paula”;
$str = “This is an example of “. 3 .” in the middle of a string.”; //This is an example of 3 in the middle of a string.

————————————————————————
MYSQL:

create table

CONNECT TO MYSQL:
below is db_login.php

<?php
$db_host=’hostname of database server’;
$db_database=’database name’;  //currently mydatabase
$db_username=’username’;
$db_password=’password’;
?>

—————————————————-
MYSQL CONNECT AND CHECK CONNECTION:

<?php
include(‘db_login.php’); //above in text
$connection = mysql_connect($db_host, $db_username, $db_password);
if (!$connection){
die (“Could not connect to the database: <br />”. mysql_error());
}
if ($connection)
{
echo “it works”;
}
?>

—————————————————-
MYSQL SELECT DATABASE:

$db_select = mysql_select_db($db_database); //currently mydatabase
if (!$db_select){
die (“Could not select the database: <br />”. mysql_error());
}

————————————————————————

Leave a Reply