php basics 2 ics213, 1 / 2011 dr. seung hwan kang 1

48
PHP Basics 2 ICS213, 1 / 2011 Dr. Seung Hwan Kang 1

Upload: jocelin-hopkins

Post on 26-Dec-2015

217 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: PHP Basics 2 ICS213, 1 / 2011 Dr. Seung Hwan Kang 1

PHP Basics 2

ICS213, 1 / 2011

Dr. Seung Hwan Kang

1

Page 2: PHP Basics 2 ICS213, 1 / 2011 Dr. Seung Hwan Kang 1

2

•PhpDoc

•Functions•User-defined functions• Function arguments• Returning values• Built-in functions

•Dealing with HTML Forms

•Data Validation

•Filesystem Functions

•Uploading files

2

Outline

Page 3: PHP Basics 2 ICS213, 1 / 2011 Dr. Seung Hwan Kang 1

3

PhpDoc•G

ood documentation is essential to any software project.

•NetBeans 7 supports phpDocumentor that is designed to generate separate sets of documentation from the same source!

•http://manual.phpdoc.org/HTMLSmartyConverter/HandS/phpDocumentor/tutorial_phpDocumentor.howto.pkg.html

3

Page 4: PHP Basics 2 ICS213, 1 / 2011 Dr. Seung Hwan Kang 1

4

PhpDoc Installation on Windows 7p

hpDocumentor (known as PhpDoc) can be used to create professional documentation from PHP source code.

1. Install jdk-6u26-windows-i586.exe

2. Install netbeans-7.0-ml-php-windows.exe

3. Install xampp-win32-1.7.4-VC6-installer.exe

Page 5: PHP Basics 2 ICS213, 1 / 2011 Dr. Seung Hwan Kang 1

5

PhpDoc (cont’d)4.

Unzip PhpDocumentor-1.4.3.zip to C:\xampp5.

Edit C:\xampp\PhpDocumentor\phpdoc.bat on lines 17-18

SET phpCli=C:\xampp\php\php.exe

cd C:\xampp\PhpDocumentor

6. Edit C:\xampp\php\php.ini on line 1001

date.timezone = Asia/Bangkok

Page 6: PHP Basics 2 ICS213, 1 / 2011 Dr. Seung Hwan Kang 1

6

PhpDoc (cont’d)7

. Go to NetBeans > Tools > Options > PHP 8

. Set PHP 5 Interpreter to C:\xampp\php\php.exe

Page 7: PHP Basics 2 ICS213, 1 / 2011 Dr. Seung Hwan Kang 1

7

PhpDoc (cont’d)9

. Set PhpDoc script to C:\xampp\PhpDocumentor\phpdoc.bat -o HTML:frames:default

Page 8: PHP Basics 2 ICS213, 1 / 2011 Dr. Seung Hwan Kang 1

8

PhpDoc (cont’d)1

0. Important! You need to change the Path manually at least once when you create a PhpDoc target directory.

Go to Project Properties and look for PhpDoc. In Target Directory, the path to a directory should be a slash (/) rather than a backslash (\).

Use phpdoc as your PhpDoc target directory

Page 9: PHP Basics 2 ICS213, 1 / 2011 Dr. Seung Hwan Kang 1

9

PhpDoc (cont’d)1

1. Run Generate PhpDoc.

Page 10: PHP Basics 2 ICS213, 1 / 2011 Dr. Seung Hwan Kang 1

10

PhpDoc (cont’d)•1

2. PhpDoc is generated

Page 11: PHP Basics 2 ICS213, 1 / 2011 Dr. Seung Hwan Kang 1

11

PhpDoc (cont’d)/* Here are the tags: * @abstract * @access public or private * @author author name <author@email> * @copyright name date * @deprecated description * @deprec alias for deprecated * @example /path/to/example * @exception Javadoc-compatible, use as needed

11

Page 12: PHP Basics 2 ICS213, 1 / 2011 Dr. Seung Hwan Kang 1

12

PhpDoc (cont’d) * @global type $globalvarname or * @global type description of global variable usage in a function* @ignore * @internal private information for advanced developers only * @param type [$varname] description * @return type description * @link URL * @name procpagealias or * @name $globalvaralias

12

Page 13: PHP Basics 2 ICS213, 1 / 2011 Dr. Seung Hwan Kang 1

13

PhpDoc (cont’d)* @magic phpdoc.de compatibility * @package package name * @see name of another element that can be documented, produces a link to it in the documentation * @since a version or a date* @static * @staticvar type description of static variable usage in a function * @subpackage sub package name, groupings inside of a project * @throws Javadoc-compatible, use as needed

13

Page 14: PHP Basics 2 ICS213, 1 / 2011 Dr. Seung Hwan Kang 1

14

PhpDoc (cont’d)* @todo phpdoc.de compatibility * @var type a data type for a class variable * @version version */

14

Page 15: PHP Basics 2 ICS213, 1 / 2011 Dr. Seung Hwan Kang 1

15

PhpDoc (cont’d)<?php/* *

@author Ken *

@version 1.0 *

example of a user defined square function * * @param

int $num *

@returns int */function

square($num) {

return $num * $num;}

echo square(4);  

?>phpdoc_1.php

Page 16: PHP Basics 2 ICS213, 1 / 2011 Dr. Seung Hwan Kang 1

16

<?php

phpinfo();

?>

16

Function

Page 17: PHP Basics 2 ICS213, 1 / 2011 Dr. Seung Hwan Kang 1

17

User Defined Function<?php

/*

* example of a user defined square function

*

* @param int $num

* @returns int

*/

function square($num) {

return $num * $num;

}

echo square(4);  

?>

17

Page 18: PHP Basics 2 ICS213, 1 / 2011 Dr. Seung Hwan Kang 1

18

•Information may be passed to functions via the argument list, which is a comma-delimited (,) list of expressions.

18

Function Arguments

Page 19: PHP Basics 2 ICS213, 1 / 2011 Dr. Seung Hwan Kang 1

19

Function Arguments (cont’d)<?php

// Example Use of return()

function square($num){

return $num * $num;

}echo

square(4); // 16

?>

19

Page 20: PHP Basics 2 ICS213, 1 / 2011 Dr. Seung Hwan Kang 1

2020

<?php

/* Example Use of default parameters in functions */

function makecoffee($type = "cappuccino"){

return "Making a cup of $type.\n";

}

echo makecoffee();

echo makecoffee(null);

echo makecoffee("espresso");

?>

Function Arguments (cont’d)

Page 21: PHP Basics 2 ICS213, 1 / 2011 Dr. Seung Hwan Kang 1

2121

Function Arguments (cont’d)<?php

// Passing function parameters by reference

function add_some_extra(&$string){

$string .= "and something extra.";

}

$str = "This is a string, ";

add_some_extra($str);

echo $str;

?>

Page 22: PHP Basics 2 ICS213, 1 / 2011 Dr. Seung Hwan Kang 1

2222

<?php

/* Example Returning an array to get multiple values */

function small_numbers(){

return array (0, 1, 2);

}

print_r(list ($zero, $one, $two) = small_numbers());

?>

Returning Values – by an array

Page 23: PHP Basics 2 ICS213, 1 / 2011 Dr. Seung Hwan Kang 1

2323

Returning Value – by a reference<?

php//

Returning a reference from a functionfun

ction &square($number) {

return $number * $number;}

echo $val =& square(12);

?>

Page 24: PHP Basics 2 ICS213, 1 / 2011 Dr. Seung Hwan Kang 1

2424

•Date

•Time

•Mail

•Filesystem

•$_GET

•$_POST

•Header

•Exit

Built-in Functions

Page 25: PHP Basics 2 ICS213, 1 / 2011 Dr. Seung Hwan Kang 1

2525

<?php

$d = date('l jS \of F Y h:i:s A');

echo $d;

?>

Date Function

date.php

Page 26: PHP Basics 2 ICS213, 1 / 2011 Dr. Seung Hwan Kang 1

2626

<?php

$t = time();

echo $t;

?>

Time Function

date.php

Page 27: PHP Basics 2 ICS213, 1 / 2011 Dr. Seung Hwan Kang 1

2727

•crypt — One-way string hashing

•explode — Split a string by string

•strlen — Get string length

•strtolower — Make a string lowercase

•strtoupper — Make a string uppercase

•trim — Strip whitespace (or other characters) from the beginning and end of a string

•wordwrap — Wraps a string to a given number of characters

String Functions

Page 28: PHP Basics 2 ICS213, 1 / 2011 Dr. Seung Hwan Kang 1

2828

•One of the most powerful features of PHP is the way it handles HTML forms. The basic concept that is important to understand is that any form element will automatically be available to your PHP scripts.

•basic_form.html

•action.php

HTML Forms

Page 29: PHP Basics 2 ICS213, 1 / 2011 Dr. Seung Hwan Kang 1

2929

•Text Boxes

•Text Areas

•Checkboxes

•Radio Buttons

•Hidden Fields

•Select

•The submit button

HTML Forms (cont’d)

Page 30: PHP Basics 2 ICS213, 1 / 2011 Dr. Seung Hwan Kang 1

3030

<!DOCTYPE HTML>

<html> <head>

<title></title> <meta

http-equiv="Content-Type" content="text/html; charset=UTF-8"> </head> <body> <form

action="action.php" method="post">

<p>Your name: <input type="text" name="name" /></p>

<p>Your age: <input type="text" name="age" /></p>

<p><input type="submit" value=“OK”/></p>

</form> </body></html>When the user fills in this form and hits

the submit button, the action.php page is called.

basic_form.html

Page 31: PHP Basics 2 ICS213, 1 / 2011 Dr. Seung Hwan Kang 1

3131

Hi <?php echo $_POST['name']; ?>.

You are <?php echo (int) $_POST['age']; ?> years old.

Above we just introduced the $_POST superglobal which contains all POST data. That is, the $_POST['name'] and $_POST['age'] variables are automatically set for you by PHP.

Notice the method of our form is POST. If we used the method GET then our form information would live in the $_GET superglobal instead.

action.php

Page 32: PHP Basics 2 ICS213, 1 / 2011 Dr. Seung Hwan Kang 1

3232

•Information sent from a form with the POST method is invisible in the browser's address bar, and has no limits on the amount of information to send.

$_POST method

Page 33: PHP Basics 2 ICS213, 1 / 2011 Dr. Seung Hwan Kang 1

3333

•Information sent from a form with the GET method is visible in the browser's address bar, and has limits up to 100 characters.

•The $_GET should not be used when sending passwords or other sensitive information!

$_GET method

Page 34: PHP Basics 2 ICS213, 1 / 2011 Dr. Seung Hwan Kang 1

3434

<?php

// list.php

<a href="display.php?id=10">10</a>

?>

<?php

// display.php

echo $_GET['id']; // 10

?>

$_GET for passing information

Page 35: PHP Basics 2 ICS213, 1 / 2011 Dr. Seung Hwan Kang 1

3535

•Very Important!

•Without it, your site can be hacked!

•PHP makes it easier

•Do both client side and server side validations• Client side validation is not secure because some browser like Firefox and Opera can disable JavaScript • Server side validation cannot be disabled by a user

Data Validation

Page 36: PHP Basics 2 ICS213, 1 / 2011 Dr. Seung Hwan Kang 1

3636

•Age, should be less than 100, and numeric. Otherwise, you should reject anything else

if(strlen($_POST['age']) > 3) {

// error message }i

f(!is_int($_POST['age'])) { /

/ error message }i

f(($_POST['age'] > 100) || ($_POST['age'] < 18)) { /

/ error message }

Data Validation - Server-side

Page 37: PHP Basics 2 ICS213, 1 / 2011 Dr. Seung Hwan Kang 1

3737

header(string,replace,http_response_code)

<?php

// in action.php

if ($is_hacked > 250) {

/* returns a REDIRECT (302) status code to the browser */

header("location: error.php");

exit();

}?>

Header Function

Page 38: PHP Basics 2 ICS213, 1 / 2011 Dr. Seung Hwan Kang 1

3838

•Using other built-in functions, these files covers more examples of •HTML forms• data validation• Anti-Hacking tips

adv_form.html & action_2.php

Page 39: PHP Basics 2 ICS213, 1 / 2011 Dr. Seung Hwan Kang 1

3939

•One of the major uses of a server side scripting language is to provide a way of sending e-mail from the server and, in particular, to take form input and output it to an e-mail address. In this part, I will show you how to send e-mail messages using PHP.

•Syntax

bool mail ( string $to , string $subject , string $message [, string $additional_headers [, string $additional_parameters ]] )

Mail

Page 40: PHP Basics 2 ICS213, 1 / 2011 Dr. Seung Hwan Kang 1

4040

To send an email

<?php

$to = '[email protected]';

$subject = 'the subject';

$message = 'hello';

$headers = 'From:

[email protected]' . "\r\n" .

'Reply-To: [email protected]' . "\r\n" . 'X-

Mailer: PHP/' . phpversion();

mail($to, $subject, $message, $headers);

?>

Mail (cont’d)

Page 41: PHP Basics 2 ICS213, 1 / 2011 Dr. Seung Hwan Kang 1

4141

•file_get_contents - Reads entire file into a string

•file_put_contents - Write a string to a file

<?php

// simple page hit counter

$hits = file_get_contents('hits.txt');

echo $hits += 1;

file_put_contents('hits.txt', $hits);

?>

Filesystem Functions

Page 42: PHP Basics 2 ICS213, 1 / 2011 Dr. Seung Hwan Kang 1

42

•Allow users to upload files from a form

•Allow users to upload both text and binary files

•With PHP's file manipulation functions ($_FILES), you have full control over what is to be done with the file once it has been uploaded.

42

action_3.php

file_form.html

File Upload

Page 43: PHP Basics 2 ICS213, 1 / 2011 Dr. Seung Hwan Kang 1

43

File Upload (cont’d)<!DOCTYPE HTML><html> <head>

<title></title> <meta

http-equiv="Content-Type"

content="text/html; charset=UTF-8"> </head> <body> <!--

The data encoding type, enctype --> <form

enctype="multipart/form-data"

action="action_4.php" method="POST"> <!--

$_FILES array --> Send

this file: <input name="userfile" type="file" /> <input

type="submit" value="Send File" /> </form>

</body></html>

43file_form.html

Page 44: PHP Basics 2 ICS213, 1 / 2011 Dr. Seung Hwan Kang 1

44

File Upload (cont’d)•T

he contents of $_FILES from the example form is as follows. Note that this assumes the use of the file upload name userfile.

$_FILES['userfile']['name'] • The original name of the file on the client machine.

$_FILES['userfile']['type'] • The mime type of the file, if the browser provided this information. An

example would be "image/gif".$_F

ILES['userfile']['size'] • The size, in bytes, of the uploaded file.

•$_FILES['userfile']['tmp_name'] • The temporary filename of the file in which the uploaded file was stored on

the server. •$

_FILES['userfile']['error'] • The error code associated with this file upload.

44

Page 45: PHP Basics 2 ICS213, 1 / 2011 Dr. Seung Hwan Kang 1

45

File Upload (cont’d)<?php//

action_3.php

$uploaddir = './uploads/';

$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);

echo '<pre>';if

(move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) { echo "File

is valid, and was successfully uploaded.\n";} else { echo

"Possible file upload attack!\n";}

echo 'Here is some more debugging info:';

print_r($_FILES);

print "</pre>";

?>

45action_3.php

Page 46: PHP Basics 2 ICS213, 1 / 2011 Dr. Seung Hwan Kang 1

46

File Upload (cont’d)•R

estrictions on Upload<?phpif

((($_FILES["userfile"]["type"] == "image/gif") ||

($_FILES["userfile"]["type"] == "image/jpg") ||

($_FILES["userfile"]["type"] == "image/jpeg") ||

($_FILES["userfile"]["type"] == "image/png")) &&

($_FILES["userfile"]["size"] < 512000)){ // < 500 KB

// upload a file

upload_file();} else { echo "Invalid

file or too big file! <br />"; echo "Here is

some more debugging info: <br />";

print_r($_FILES);}

… // upload_file()?>

46

action_4.php

The user may only upload .gif or .jpeg or .png files.

The file size must be under 0.5 MB:

Page 47: PHP Basics 2 ICS213, 1 / 2011 Dr. Seung Hwan Kang 1

47

File Upload (cont’d)•W

hat If the file already exits?

<?php

if (file_exists("./uploads/" . $_FILES["userfile"]["name"])){  echo $_FILES["file"]["name"] . " already exists. ";

}

else {

// upload a file

upload_file();

}

?>

47

Page 48: PHP Basics 2 ICS213, 1 / 2011 Dr. Seung Hwan Kang 1

48

References•G

regory Beaver (2009) phpDocumentor Guide to Creating Fantastic Documentation http://manual.phpdoc.org/HTMLSmartyConverter/HandS/phpDocumentor/tutorial_phpDocumentor.pkg.html Accessed: 25/04/2011.