PHP

cornawakeSoftware and s/w Development

Nov 4, 2013 (3 years and 5 months ago)

79 views



PHP



Rescursive acronym for "PHP: Hypertext Preprocessor".


It is an open source scripting language that can be
embedded into HTML. Php Code is embedded inside
HTML code, unlike other scripting languages like Perl
which produce WHOLE html codes, PHP code is embeded
anywhere inside an HTML code.



JavaScript is client
-
side processed while PHP is processed
on the server side.



When an HTML code with embedded PHP is shown to a
client, all the client can see is the final HTML version.
They have no way of knowing that some of that code came
from PHP.

PHP START AND OPEN TAGS

<?


?>

<%

echo 'ASP
-
style tags';

%>

<?= expression ?> Short cut for <? echo expression ?>

<%= $variable %> Short cut for <% echo $variable %>

<script language='php'>


echo "php code";

</script>

The preferred method that is enabled by default in PHP 4 is

<?php


?>

Others may need further PHP configuration after installing PHP.




PHP is case sensitive just like Java.


PHP Autoglobals:



$_SERVER

is a special reserved PHP
variable that contains all web server
information. It's known as an Autoglobal.



To display some of the values, do the
following:





Printing a variable (Array element)

<?php echo
$_SERVER["HTTP_USER_AGENT"];

?>

A sample output of this script may be:
Mozilla/4.0 (compatible; MSIE 5.01; Windows NT)



$_SERVER is one of many variables
automatically made available to you by
PHP. You can get a complete list of the auto
variables by using: <?php phpinfo(); ?>




PHP interface to the DB


<html>


<body bgColor="#33AACC" Text="#000000">


<center>


<?php



echo "<h1>$header</h1>";



$db = mysql_connect("localhost", "db_username",

"db_password");



mysql_select_db("dbname",$db);



$result = mysql_query("SELECT * FROM


$tablename",$db);



if ($result == "") {



echo "SORRY, THIS INFORMATION IS


CURRENTLY UNAVAILABLE.<br>";



}




else if ($myrow = mysql_fetch_array($result)) {



echo "<table width=600 cellspacing=0 cellpadding=0



border=1>
\
n <tr align=center>";




/* make header with column names */



$description = mysql_query("DESCRIBE



$tablename",$db);



echo "<th> Num. </th>";



$ncols = 0;



while ($colnames = mysql_fetch_array($description)) {



echo "<th> $colnames[0] </th>";



$ncols = $ncols + 1;



}






echo "</tr>
\
n";



$count = 0;



do {



$count = $count + 1;



print "<tr><td>$count</td>";



for ($i=0; $i < $ncols; $i++) {



print "<td>$myrow[$i]</td>";



}



print "</tr>
\
n";



} while ($myrow = mysql_fetch_array($result));


}


// mysql_fetch_array may also be indexed as an associative array


// e.g. $myrow[‘id’] works if id is one of the selected attributes.


</table>


</center>


</body>


</html>




FUNCTIONS IN PHP



Examples:



<?php

function

foo($arg)

{


if

($arg

<

10)

{


echo

"$arg

is

less

than

10";


}

else

{


echo

"$arg

is

not less

than

0";


}

}


foo(15);

/*

Echoes

15

is not less

than

10"

*/

?>





Use the return statement to have the
function return a value e.g.

function adder($first, $second) {



return $first+$second;

}

$a = 5;

$sum = adder($a,10); /* Call adder */




Reference/value Parameters: An & before the
parameter at the function header indicates a
reference parameter, otherwise it is a value
parameter e.g.



$a=1; $c=2;


function test(&$bb) {



global $c; // imports (brings in) the externally defined c



$bb = $c;



$c++;


}


test($b);


echo “$a $b $c”;

// displays 1 2 3


why?





Default Values for Paramaters:


Example:

function divide ($num, $den=2) {


return $num/$den;

}

/* $den defaults to 2 if not specified at call time
*/

echo divide(2); /* echoes 1 */



Some useful pre
-
defined functions:


gettype($var)


-

Get the type of a variable

settype($var, type)

-

Set a variable to a certain type e.g.




settype($myvar, "integer");

isset($var)


-

Determine whether a variable is set






i.e. has a value

unset($var)


-

Unset a given variable, destroys the



specified variable and returns true


isset example:

<?php

if

(isset($var)) {


echo

"Your

variable

is

set";

}


else

{


echo

"Your

variable

was

not

set";

}

?>






Scope of variables:

Variables declared or used in a function are local to that function.

For a function to access a variable outside of the function block,

it must use the global keyword to import the variable. Example:

<?php

$tax

=

1.06;

$state

=

'MI';

$weight

=

5;

function

total(&$total,

$shipping

=

1.33)

{




global

$tax, $state, $weight;

//import global variables


if

($state

==

'MI') {



$total

=

$tax

*

$total

+

($shipping

*

$weight);




}


else {

$total

=

$shipping

*

$weight;



}



}

$total = 1000;



total($total);

printf( “Total

with

shipping and

tax

(if

applicable)

is:

<b>$%.2f</b>",

$total);


?>

static $var=0; within a function forces $var to remain static over calls to the function.



Functions may be placed in a file and included in the scripts that may need
them. In PHP4, if you have a return statement at the end of the include
file, the returned value may be assigned to a variable at the include
statement


Example:

<?php

/*

foo.inc file.

*/

function f1() {


echo “hello world”;


}


$x = 20;


return

time();

?>


Then you could write the following in script.php:

<?php

$y =

include('foo.inc'); // include ‘foo.inc’ works too


// more PHP code my be added before or after the include.

?>



setcookie

--

Send a cookie


boolean
setcookie

( string name [, string value [, int expire
[, string path [, string domain [, int secure]]]]])


setcookie()

defines a cookie to be sent along with the rest of
the header information. Cookies must be sent
before

any
other headers are sent (this is a restriction of cookies, not
PHP). This requires you to place calls to this function
before any <html> or <head> tags. If headers exist prior to
calling this function,
setcookie()

will fail and return
FALSE
. If
setcookie()

successfully runs, it will return
TRUE

This does not mean the user accepted the cookie or
not.


All the arguments except the
name

argument are optional.
If only the name argument is present, the cookie by that
name will be deleted from the remote client. You may also
replace any argument with an empty string (
""
) in order to
skip that argument. The
expire

and
secure

arguments are
integers and cannot be skipped with an empty string. Use a
zero (
0
) instead.




Expire=date value



The
expire

argument is a regular Unix
time integer as returned by the time() or
mktime() functions.


The date string is formatted as: Wdy, DD
-
Mon
-
YYYY HH:MM:SS GMT. For example,


Sunday, 03
-
Nov
-
2002 00:00:00 GMT





domain
=
DOMAIN_NAME



When searching the cookie list for valid cookies, a
comparison of the
domain

attributes of the setcookie
function is made with the Internet domain name of the
host (server) setting the cookie. If there is a tail match,
then the cookie will go through
path

matching to see if
it should be sent. "Tail matching" means that
domain

attribute is matched against the tail of the fully qualified
domain name of the host. A
domain

attribute of
“emich.edu" would match host names “my.emich.edu”.



The default value of
domain

is the host name of the
server which generated the cookie response.




path
=
PATH



The
path

attribute is used to specify the subset of URLs
in a domain for which the cookie is valid. If a cookie
has already passed
domain

matching, then the
pathname component of the URL is compared with the
path attribute, and if there is a match, the cookie is
considered valid and is sent along with the URL
request. The path "/foo" would match "/foo/bar" and
"/foo/bar.html". The path "/" is the most general path.


If the
path

is not specified, it as assumed to be the same
path as the document being described by the header
which contains the cookie.


The
secure

indicates that the cookie should only
be transmitted over a secure HTTPS connection.





Once the cookies have been set, they can be accessed on
the next page load with the $_COOKIE or
$HTTP_COOKIE_VARS arrays.


Common Pitfalls:


Cookies will not become visible until the next loading of
any page that the cookie is intended for. To test if a cookie
was successfully set, check for the cookie on a next
loading page before the cookie expires. Expire time is set
via the
expire

parameter.


Cookies must be deleted with the same parameters as they
were set with.


Cookies names can be set as array names and will be
available to your PHP scripts as arrays but seperate cookies
are stored on the users system..




Example 1.


setcookie

("TestCookie", $value);


setcookie ("TestCookie",
$value,time()+3600); /* expire in 1 hour */
setcookie ("TestCookie",
$value,time()+3600, "/~ikeji/",
“db1.acad.emich.edu", 0);






DELETING COOKIE

When deleting a cookie you should assure that the expiration
date is in the past, to trigger the removal mechanism in
your browser. Examples follow how to delete cookies sent
in previous example:


setcookie ("TestCookie", "", time()
-

3600);

setcookie ("TestCookie", "", time()
-

3600, "/~ikeji/",
“db1.acad.emich.edu", 1);

Note that the value portion of the cookie will automatically be
urlencoded when you send the cookie, and when it is
received, it is automatically decoded and assigned to a
variable by the same name as the cookie name. To see the
contents of our test cookie in a script, use


echo $_COOKIE["TestCookie"];




You may also set array cookies by using array notation in the
cookie name. This has the effect of setting as many cookies
as you have array elements, but when the cookie is
received by your script, the values are all placed in an
array with the cookie's name:

setcookie ("cookie[three]", "cookiethree");

setcookie ("cookie[two]", "cookietwo");

setcookie ("cookie[one]", "cookieone");



if (isset ($_COOKIE[‘cookie’])) {


$arr = $_COOKIE[‘cookie’];


while (list ($name, $value) = each ($arr)) {




echo "$name == $value<br>
\
n";


}


}



PHP/RADIO BOX EXAMPLE

<html><body>

<form action=“ans.php" method="post">



What is your name?:


<input type=‘text’ name=‘nm’ size=30><br>


What is 1+1?


<input type="radio" name="choice" value=“1"
checked>1


<input type="radio" name="choice" value=“2">2

<input type="radio" name="choice" value=“3">3

<input type="submit" value="Submit">

</form>

</body></html>




On the ans.php, you may access the ans by using

<?php


echo $_POST[‘nm’];


if ($_POST[‘choice’] == “2”) {


echo “correct”;


}


else {


echo “sorry, wrong answer”;


}

?>



PHP/CHECK BOXES EXAMPLE

<form action=“ans.php"> // default is get method

<input name=“choices[]" type="checkbox" value=“A">A

<input name=“choices[]" type="checkbox" value=“B">B

<input name=“choices[]" type="checkbox" value="C">C

<input name=“choices[]" type="checkbox" value="D">D

<input type="submit" name="submit" value="Submit">

</form>


PHP Code to process it

<?php

$items = $_GET[‘choices’];

for ($i=0; $i<count($items); $i++)

{


echo "$items[$i]”;

}

?>



PHP/SELECT BOXES EXAMPLE


To pass multiple values, as in a "Multiple Select
Box", put [] after the variable name, like
choices[]
.


<SELECT NAME=“choices[]" MULTIPLE
SIZE=“3">


<OPTION VALUE="1">One</OPTION>


<OPTION VALUE="2">Two</OPTION>


<OPTION VALUE=“3">Three</OPTION>


<OPTION VALUE=“4">Four</OPTION>


<OPTION VALUE=“5">Five</OPTION>

</SELECT>



On the receiving page, you simply do a
count() on choices, and iterate through the
list of values that was selected just like in
the checkbox example.

<?php


$items=$_GET[‘choices’];


for

($i=0;

$i<count($items);

$i++)

{


echo

$items[$i];

}

?>




PHP/FILE UPLOAD EXAMPLE

<form action="file
-
upload.php"
method="post" enctype="multipart/form
-
data">


Send these files:<br>


<input name="userfile[]" type="file"><br>


<input name="userfile[]" type="file"><br>


<input type="submit" value="Send files">

</form>



When the above form is submitted, the arrays
$_FILES['userfile'], $_FILES['userfile']['name'], and
$_FILES['userfile']['size'] will be initialized.


For instance, assume that the filenames /home/test/one.html
and /home/test/two.out are submitted. In this case,
$_FILES['userfile']['name'][0] would contain the value
one.html, and $_FILES['userfile']['name'][1] would contain
the value two.out.


$_FILES['userfile'][‘tmp_name'][0],
$_FILES[‘userfile’][‘tmp_name’][1] will contain the
temporary local names of the files on the server. Use these
names to access the files on the local server.



Similarly, $_FILES['userfile']['size'][0] and
$_FILES['userfile']['type'][0] are also set.




fgets


(PHP 3, PHP 4 )


fgets

--

Gets line from file pointer


Description


string
fgets

( int fp [, int length])


Returns a string of up to length
-

1 bytes read from
the file pointed to by fp. Reading ends when
length
-

1 bytes have been read, on a newline
(which is included in the return value), or on EOF
(whichever comes first). If no length is specified,
the length defaults to 1k, or 1024 bytes.


If an error occurs, returns
FALSE
.



FILE I/O EXAMPLE

<?php


$FILE = fopen(“in.dat","r");

// for reading only


$NEWFILE = open(“out.dat","w");// open for
writing only



// continously read in from data.txt

while ($BUFFER = fgets($FILE,4096)) {


fputs($NEWFILE,$BUFFER); //write to out.dat

}


fclose($FILE); // close in.dat

fclose($NEWFILE); // close out.dat

?>



RELATED FILE UPLOAD FUNCTIONS


bool
move_uploaded_file

( string filename, string
destination)


This function checks to ensure that the file
designated by
filename

is a valid upload file
(meaning that it was uploaded via PHP's HTTP
POST upload mechanism). If the file is valid, it
will be moved to the filename given by
destination
.


If
filename

is not a valid upload file, then no
action will occur, and
move_uploaded_file()

will
return
FALSE
.