SlideShare a Scribd company logo
Creating HTML Forms




 Pengaturcaraan PHP
Managing HTML forms with PHP is a two-step process. First, you create
the HTML form itself, using any text or WYSIWYG editor you choose. Then,
you create the corresponding PHP script that will receive and process the
form data. An HTML form is created using the form tags and various input
types. The form tags look as follows:




 The most important attribute of your form tag is action, which dictates to
 which page the form data will be sent. The second attribute — method —
 has its own issues, but post is the value you'll use most frequently.




                                                                              1
Pengaturcaraan PHP
Choosing a Method

The method attribute of a form dictates how the data is sent to the
handling page. The two options — get and post — refer to the HTTP
(Hypertext Transfer Protocol) method to be used. In short, the get
method sends the submitted data to the receiving page as a series of
name-value pairs appended to the URL.

Consider the example shown below:




Pengaturcaraan PHP
The benefit of using the get method
is that the resulting page can be
bookmarked in the user's Web
browser (since it's a URL). For that
matter, you can also click Back in
your Web browser to return to a get
page, or reload it without problem
(neither of which is true for post).

Unfortunately, you are limited to how
much data can be transmitted via get
and it's less secure (since the data is
visible).




                                                                       2
Pengaturcaraan PHP




Pengaturcaraan PHP




                     3
Pengaturcaraan PHP




Pengaturcaraan PHP




                     4
Pengaturcaraan PHP




Pengaturcaraan PHP




                     5
Pengaturcaraan PHP




    Handling an HTML
    Form




                       6
Pengaturcaraan PHP
 Once you have an HTML form, the next step is to write a bare-
 bones PHP script to handle it. When we say that this script will be
 handling the form, we mean that it will do something with the
 data it receives; that is it will reiterate the data back to the Web
 browser.




  The PHP page that receives the form data will assign what the user
  entered into this form element to a special variable called
  $_REQUEST['weight']. It is very important that the spelling and
  capitalization match exactly, as PHP is case-sensitive when it comes to
  variable names. $_REQUEST['weight'] can then be used like any other
  variable: printed, used in mathematical computations, concatenated, and
  so on.




  Pengaturcaraan PHP
Registering Globals

In earlier versions of PHP, the
register_globals setting was turned on by
default. This feature gave PHP an ease of
use by automatically turning form inputs
into similarly named variables, like $name
or $email (as opposed to having to refer
to $_REQUEST['name'] and
$_REQUEST['email'] first).

As of version 4.2 of PHP, the
developers behind PHP opted to turn this
setting off by default because not relying
on this feature improves the security
of your scripts. Unfortunately, this also    To work around this, there are two
had the side effect that a lot of existing   options. First, you could turn
scripts no longer worked and many
beginning programmers were stymied
                                             register_globals back on, assuming
when they saw blank values in their          that you have administrative control
form results, error messages, or just        over your PHP installation. Second,
blank pages.                                 you could start using the
                                             superglobal variables, such as
                                             $_REQUEST, $_GET, and $_POST.




                                                                                    7
Pengaturcaraan PHP




Pengaturcaraan PHP
Following the rules outlined before, the data entered into the name form
input, which has a name value of name, will be accessible through the
variable $_REQUEST['name']. The data entered into the email form input,
which has a name value of email, will be accessible through
$_REQUEST['email']. The same applies to the entered comments data.
Again, the spelling and capitalization of your variables here must exactly
match the corresponding name values in the HTML form.




                                                                             8
Pengaturcaraan PHP




Pengaturcaraan PHP




                     9
Pengaturcaraan PHP




Pengaturcaraan PHP
$_REQUEST

$_REQUEST is a special variable type in PHP, available since version
4.1. It stores all of the data sent to a PHP page through either the GET
or POST methods, as well as data accessible in cookies.

Blank pages
If you see a blank page after submitting the form, first check the
HTML source to look for HTML errors, and then confirm that
display_errors is on in your PHP configuration.




                                                                           10
Pengaturcaraan PHP
Others way to avoid _$_REQUEST[‘variable’]

extract($_GET);
extract($_POST);
extract($_COOKIE);

User can call directly the name of variable like $name without using
the method $_POST[“name”].




         Managing Magic Quotes




                                                                       11
Pengaturcaraan PHP




Pengaturcaraan PHP




                     12
Pengaturcaraan PHP
In PHP there are two main types of Magic Quotes: magic_quotes_gpc,
which applies to form, URL, and cookie data (gpc stands for get, post,
cookie); and magic_quotes_runtime, which applies to data retrieved
from external files and databases. If Magic Quotes is enabled on your
server, you can undo its effect using the stripslashes() function.




      This function will remove any backslashes found in $var.




Pengaturcaraan PHP




                                                                         13
Pengaturcaraan PHP




 Pengaturcaraan PHP
addslashes() function

You can emulate what Magic Quotes does if it's disabled by using the
opposite of the stripslashes() function, addslashes().

trim() function

When working with strings stemming from forms, it's also a good idea to
use the trim() function, which removes excess white spaces from
both ends of the value.

$name = trim($name);




                                                                          14
Conditionals




  Pengaturcaraan PHP
Conditionals, like variables, are integral to programming, and most people are
familiar with them in some form or another. Dynamic Web pages, as you might
imagine, frequently require the use of conditionals to alter a script's behavior
according to set criteria.

PHP's three primary terms for creating conditionals are if, else, and elseif
(which can also be written as two words, else if).

Every conditional includes an if clause, as shown here.




                                                                                   15
Pengaturcaraan PHP
The if clause in turn can specify an
alternate course of action by using else.




 It can also be written to include
 another condition and a couple of
 alternatives by using elseif and else,
 as in this example.




 Pengaturcaraan PHP
If a condition is true, the code in the
following curly braces ({}) will be
executed. If not, PHP will continue on.
If there is a second condition (after an
elseif), that will be checked for truth.

The process will continue — you can
use as many elseif clauses as you
want — until PHP hits an else, which
will be automatically executed at that
point, or until the conditional
terminates without an else.

For this reason, it's important that the
else always come last and be treated
as the default action unless specific
criteria (the conditions)




                                            16
In the second example, a new function, isset(), is introduced. This function
checks if a variable is set, meaning that it has a value other than NULL.
You can also use the comparative and logical operators, listed in the table
below, in conjunction with parentheses to make more complicated expressions.


  SYMBOL       MEANING                       TYPE            EXAMPLE
                                                             $x == $y
  ==           is equal to                   comparison
  !=                                                         $x ! = $y
               is not equal to               comparison
                                                             $x < $y
  <            less than                     comparison
                                                             $x > $y
  >            greater than                  comparison
                                                             $x <= $y
  <=           less than or equal to         comparison
                                                             $x >= $y
  >=           greater than or equal to      comparison
  !                                                          !$x
               not                           logical
                                                             $x && $y
  &&           and                           logical

  ||           or                            logical         $x || $y


  XOR          and not                       logical         $x XOR $y




  Pengaturcaraan PHP




                                                                               17
Pengaturcaraan PHP
This is a simple and effective way to validate a form input

(particularly a radio button, check box, or select). If the user checks either
gender radio button, then $_REQUEST['gender'] will have a value, meaning
that the condition isset($_REQUEST['gender']) is true. In such a case, the
shorthand version of this variable — $gender — is assigned the value of
$_REQUEST['gender'], repeating the technique used with $name, $email,
and $comments.

If the condition is not true, then $gender is assigned the value of NULL,
indicating that it has no value. Notice that NULL is not in quotes.




 Pengaturcaraan PHP




                                                                                 18
Pengaturcaraan PHP
This if-elseif-else conditional looks at the value of the $gender variable and
prints a different message for each possibility. It's very important to
remember that the double equals sign (==) means equals, whereas a single
equals sign (=) assigns a value.

The distinction is important because the condition $gender == 'M' may or
may not be true, but $gender = 'M' will always be true.




Pengaturcaraan PHP




                                                                                 19
Pengaturcaraan PHP
Switch

PHP has another type of conditional, called the
switch, best used in place of a long if-elseif-else
conditional. The syntax of switch is shown here.

The switch conditional compares the value of
$variable to the different cases. When it finds a
match, the following code is executed, up until
the break. If no match is found, the default is
executed, assuming it exists (it's optional).

The switch conditional is limited in its usage in that
it can only check a variable's value for equality
against certain cases; more complex conditions
cannot be easily checked.




 Pengaturcaraan PHP




                                                         20
Validating Form Data




Pengaturcaraan PHP
Validating form data requires
the use of conditionals and
any number of functions,
operators, and expressions.
One common function to be
used is isset(), which tests if
a variable has a value
(including 0, FALSE, or an
empty string, but not NULL).

To check that a user typed something into textual elements like name,
email, and comments, you can use the empty() function. It checks if a
variable has an empty value — an empty string, 0, NULL, or FALSE.




                                                                        21
Pengaturcaraan PHP
The first aim of form validation is ensuring that something was entered or
selected in form elements. The second goal is to ensure that submitted data is
of the right type (numeric, string, etc.), of the right format (like an email
address), or a specific acceptable value (like $gender being equal to either M
or F).

Next, let's write a new handle_form.php script that makes sure variables have
values before they're referenced.




 Pengaturcaraan PHP




                                                                                 22
Pengaturcaraan PHP




Pengaturcaraan PHP




                     23
Pengaturcaraan PHP




Pengaturcaraan PHP




                     24
Pengaturcaraan PHP
strlen() function

Another way of validating text inputs is to use the strlen() function to see if
more than zero characters were typed.

if (strlen($var) > 0) {
// $var has a value.
} else {
// $var does not have a value.
}




             Arrays




                                                                                  25
Pengaturcaraan PHP
Unlike strings and numbers (which are scalar variables, meaning they can
store only a single value at a time), an array can hold multiple, separate
pieces of information. An array is therefore like a list of values, each value
being a string or a number or even another array.

Arrays are structured as a series of key-value pairs, where one pair is an
item or element of that array. For each item in the list, there is a key (or
index) associated with it. The resulting structure is not unlike a spreadsheet
or database table.




PHP supports two kinds of arrays. The first type, called indexed arrays, uses
numbers as the keys, as in the first example, the $artists array. As in most
programming languages, with indexed arrays, your arrays will begin with the
first index at 0, unless you specify the keys explicitly.


             Key                  Value
             0                    Low
             1                    Aimee Mann
             2                    Ani DiFranco
             3                    Spiritualized

The second type of array, associative, uses strings as keys as in the
following example. The $states array uses the state abbreviation for its
keys.
            Key                   Value
            MD                    Maryland
            PA                    Pennsylvania
            IL                    Illinois
            MO                    Missouri




                                                                                 26
Pengaturcaraan PHP
An array follows the same naming rules as any other variable. So offhand,
you might not be able to tell that $var is an array as opposed to a string or
number. The important syntactical difference has to do with accessing
individual array elements.

To retrieve a specific value from an array, you refer to the array name first,
followed by the key, in square brackets:




Pengaturcaraan PHP
Because arrays use a different syntax than other variables, printing them can be
trickier. First, since an array can contain multiple values, you cannot use a
simple print statement.

Second, the keys in associative arrays complicate printing them and cause a
parse error.




                                                                                   27
Pengaturcaraan PHP
 To work around this, wrap your array name and key in curly braces when your
 array uses strings for its keys.

 Numerically indexed arrays don't have this problem.




Superglobal Arrays

PHP includes several predefined arrays by default. These are the superglobal
variables — $_GET, $_POST, $_SESSION, $_REQUEST, $_SERVER,
$_COOKIE, and so forth, added to PHP as of version 4.1.

The $_GET variable is where PHP stores all of the variables and values sent to a
PHP script via the get method (presumably but not necessarily from an HTML
form). $_POST stores all of the data sent to a PHP script from an HTML form
that uses the post method. Both of these — along with $_COOKIE — are
subsets of $_REQUEST.

The superglobals have two benefits over registered global variables. First,
they are more secure because they are more precise (they indicate where the
variable came from). Second, they are global in scope (hence the name). If you
find the syntax of these variables to be confusing, you can use the shorthand
technique at the top of your scripts as follows:




                                                                                   28
Pengaturcaraan PHP




Pengaturcaraan PHP




                     29
Pengaturcaraan PHP




 Pengaturcaraan PHP
Earlier versions of PHP

The superglobals are new to PHP as of version 4.1. If you are using an
earlier version of the language, use $HTTP_POST_VARS instead of
$_POST, and $HTTP_GET_VARS instead of $_GET.




                                                                         30
Creating and Accessing
            Arrays




 Pengaturcaraan PHP
Creating Arrays

Although you can use PHP-generated
arrays, there will frequently be times
when you want to create your own.
There are two primary ways to define
your own array. First, you could add
one element at a time to build one,
as in this example.

It's important to understand that if
you specify a key and a value already
exists indexed with that same key, the
new value will overwrite the existing
one. In this example, based on the
latest assignment, the value of
$array['son'] is Michael and that of
array[2] is orange.




                                         31
Pengaturcaraan PHP
Instead of adding one element at a time, you can use the array() function to
build an entire array in one step.

This function can be used whether or not you explicitly set the key.




Pengaturcaraan PHP
On the other hand, if you set the first numeric key value, the added
values will be keyed incrementally thereafter, as in this example.

Finally, if you want to create an array of sequential numbers you can use the
range() function.




                                                                                32
Accessing Arrays

Individual array elements can be accessed by key (e.g., $_POST['email']). This
works when you know exactly what the keys are or if you want to refer to only a
single element. To access every array element, use the foreach loop.

The foreach loop will iterate through every element in $array, assigning each
element's value to the $value variable. In this example, you can access both
the keys and values.




 Pengaturcaraan PHP




                                                                                  33
Pengaturcaraan PHP




Pengaturcaraan PHP




                     34
Pengaturcaraan PHP




Pengaturcaraan PHP




                     35
Pengaturcaraan PHP
count() or sizeof() function
To determine the number of elements in an array, use the count() or
sizeof() function (the two are synonymous):

$num=count($array);

range() function
The range() function can also create an array of sequential letters as
of PHP 4.1:

$alphabet=range('a','z');

Error message in foreach loop
If you see an 'Invalid argument supplied for foreach()' error
message, that means you are trying to use a foreach loop on a variable
that is not an array.




            Multidimensional
            Arrays




                                                                         36
Pengaturcaraan PHP
An array's values could be any combination of numbers, strings, and even
other arrays. This last option — an array consisting of other arrays — creates
a multidimensional array.

Multidimensional arrays are much more common than you might expect
(especially if you use the superglobals) but remarkably easy to work with. As
an example, let's say you have an array called $states and another one called
$provinces for Canada, both created by the following definitions.




 Pengaturcaraan PHP
These two arrays could be combined into one multidimensional array as
follows:




                                                                                 37
Pengaturcaraan PHP



 To access the $states array, you refer to $abbr['US']

 To access Maryland, use $abbr['US']['MD']


 Of course, you can still access multidimensional arrays
 using the foreach loop, nesting one inside another if
 necessary.




Pengaturcaraan PHP
To print out one of these values, surround the whole construct in curly
braces:




                                                                          38
Pengaturcaraan PHP




Pengaturcaraan PHP




                     39
Pengaturcaraan PHP




Pengaturcaraan PHP




                     40
Pengaturcaraan PHP




Pengaturcaraan PHP




                     41
Pengaturcaraan PHP




Pengaturcaraan PHP




                     42
Pengaturcaraan PHP




Pengaturcaraan PHP




                     43
Pengaturcaraan PHP




Pengaturcaraan PHP




                     44
Pengaturcaraan PHP
$_POST['interests']

Even if the user selects only one interest, $_POST['interests'] will still be
an array because the HTML name for the corresponding input is interests[]
(the square brackets make it an array).

select menu
You can also end up with a multidimensional array by having an HTML
form's select menu allow for multiple selections:

‹select name="interests[]" multiple="multiple"›
  ‹option value="Music"›Music‹/option›
  ‹option value="Movies"›Movies‹/option›
  ‹option value="Books"›Books‹/option›
  ‹option value="Skiing"›Skiing‹/option›
  ‹option value="Napping"›Napping‹/option›
‹/select›




             Arrays and Strings




                                                                                45
Pengaturcaraan PHP
Because strings and arrays are so commonly used, PHP has two functions
for converting between these two variable types.




The key to using and understanding these two functions is the separator and
glue relationships. When turning an array into a string, you set the glue —
the characters or code that will be inserted between the array values in the
generated string. Conversely, when turning a string into an array, you specify
the separator, which is the code that delineates between the different elements
in the generated array.

Let's examine some examples.




 Pengaturcaraan PHP

The $days_array variable is
now a five-element array,
with Mon indexed at 0, Tue
indexed at 1, etc.



The $string2 variable is now
a comma-separated list of
days — Mon, Tue, Wed,
Thurs, Fri.




                                                                                  46
Pengaturcaraan PHP




Pengaturcaraan PHP




                     47
Pengaturcaraan PHP




Pengaturcaraan PHP




                     48
Sorting Arrays




Pengaturcaraan PHP

One of the many advantages arrays have over the other variable types is
the ability to sort them. PHP includes several functions you can use for
sorting arrays, all simple in syntax.




                                                                           49
Pengaturcaraan PHP
Array (sort/rsort)

Sorting Array :
sort($pantry_food); - Sort with ascending 0 - 9
rsort($pantry_food); - Sort with Descending 9 – 0

Sort with alphabet alphabet
asort($pantry_food); - Sort with ascending A - Z
arsort($pantry_food); - Sort with Descending Z – A




Pengaturcaraan PHP




                                                     50
Pengaturcaraan PHP




Pengaturcaraan PHP




                     51
Pengaturcaraan PHP




Pengaturcaraan PHP
Array (Adding/Replace)
In array, we can add or change content of array
example 1 :
$fruit = array('banana','papaya');

Cara menambah :
<? $fruit[2] = “apple”;
print “$fruit[2] ?>
The Output
apple




                                                  52
Pengaturcaraan PHP
Array (merging)

You also can merge 2 or more array.
Example 1 :
$pantry = array(
  1 => "apples",
  2 => "oranges",
  3 => "bananas"
  );
$pantry2 = array(
  1 => "potatoes",
  2 => "bread",
  3 => "tomatoes"
  );




Pengaturcaraan PHP
Array (Merging)

Way to combine :
<?
$pantry_food = array_merge ($pantry, $pantry2);
?>
The Output
$pantry_food[0] = "apples";
$pantry_food[1] = "oranges";
$pantry_food[2] = "bananas";
$pantry_food[3] = "potatoes";
$pantry_food[4] = "bread";
$pantry_food[5] = "tomatoes";




                                                  53
Pengaturcaraan PHP
Array (push)

The way to add content at the last of array elemt :

example
$pantry = array(
1 => "tomatoes",
0 => "oranges",
4 => "bananas",
3 => "potatoes",
2 => "bread"
);
array_push($pantry, "apples");




          For and While Loops




                                                      54
Two types of loops you'll use when managing arrays are for and while.
Consider the example of while loop.

As long as the condition part of the loop is true, the loop will be executed.
Once it becomes false, the loop is stopped. If the condition is never true, the
loop will never be executed. The while loop will most frequently be used
when retrieving results from a database.




 Pengaturcaraan PHP
The for loop has a more complicated syntax.

Upon first executing the loop, the initial expression is run. Then the condition
is checked and, if true, the contents of the loop are executed. After execution,
the closing expression is run and the condition is checked again. This
process continues until the condition is false. Again, the loop will never be
executed if the condition is never true.




                                                                                   55
Pengaturcaraan PHP
Consider this example.




The first time this loop is run, the $i variable is set to the value of 1. Then
the condition is checked (is 1 less than or equal to 10?). Since this is
true, 1 is printed out (echo $i). Then, $i is incremented to 2 ($i++), the
condition is checked, and so forth. The result of this script will be the
numbers 1 through 10 printed out.




Pengaturcaraan PHP




                                                                                  56
Pengaturcaraan PHP




Pengaturcaraan PHP




                     57
Pengaturcaraan PHP




    String Manipulation




                          58
Pengaturcaraan PHP
String – “strtok”

To take a certain char in the one sentence. The way to take the char can
use “,” “.” or anything else


Sntax “strtok(“variable",“condition");”
Example :
<?php
$bigstring = "BigBad Wolf";
$firstpart = strtok($bigstring," ");
echo "$firstpart";
?>
The output
BigBad




Pengaturcaraan PHP
 String – “substr”

 To take the char based on position. It start from left and counting start by 0

 Syntax “substr(“variable",position,length);”

 Example :
 <?php
 $bigstring = "BigBad Wolf";
 $example = substr($bigstring,7,4);
 echo "$example";
 ?>
 The output
 Wolf




                                                                                  59
Pengaturcaraan PHP
String – “eregi/ereg”

To search char in variable. Ereg only can search based on case sensitive
saja.

eregi can search without concern about case-sensitive

Syntax “ereg(“condition",“variable");”
Syntax “eregi(“condition",“variable");”




Pengaturcaraan PHP
Example ereg

$pattern = "z";
$search_area = "My car goes ZOOM.";
$search_result = ereg($pattern,$search_area);

if ($search_result){
// print this if there is a true result.
echo "Success, the pattern was found!";
} else {
// print this if there is a false result.
echo "Failure, the pattern was not found!";
}
Output
Failure, the pattern was not found!




                                                                           60
Pengaturcaraan PHP
Example eregi

$pattern = "z";
$search_area = "My car goes ZOOM.";
$search_result = eregi($pattern,$search_area);

if ($search_result){
// print this if there is a true result.
echo "Success, the pattern was found!";
} else {
// print this if there is a false result.
echo "Failure, the pattern was not found!";
}
Output
Success, the pattern was found!




Pengaturcaraan PHP
String – “str_replace”

Syntax “str_replace(",","", “variable");”

To change anything (like coma) to the anything (like $ dollar sign)

Contoh :
$cfcost1 = “2,300.00”;
$cfcost1 = str_replace(",","","$cfcost1");

Output :
2300.00




                                                                      61
Pengaturcaraan PHP
String – “eregi_replace”

To replace char in variable based on search

Syntax: eregi_replace(pattern,replacement,search_area);

Example
$entry = “user@yahoo.com
$pattern = “@";
$replacement = “(a)";
$entry = ereg_replace($pattern,$replacement,$entry);
echo "$entry";

output
user(a)yahoo.com




Pengaturcaraan PHP
 String - “strlen”

 To count total of char in the variable value

 Syntax “strlen(“variable")”
 Example :
 if(strlen($password) < 6)
 {
         print “Jumlah password anda kurang dari 6 aksara”;
 }
 else
 {
         print “Tahniah”;
 }




                                                              62
Pengaturcaraan PHP
String - “strstr”

To search certain value in variable

Syntax “strstr(“variable“,”word to search”)”
Example :
$member = “pAB7”;
if(strstr($member,”AB”))
{
        print “Membership anda akan luput tidak lama lagi”;
}
else
{
        print “Tahniah”;
}




Pengaturcaraan PHP
String - “trim”

To clear any blank space in variable at the beginning and end

Syntax “trim(“variable“)”

Example :
$member = “      pAB7 ”;
$member = trim($member)
print “$member”;

Output
// print “pAB7”;




                                                                63
Pengaturcaraan PHP
String - “rtrim”

To clear any blank space at the end of variable

Syntax “trim(“variable“)”

Example :
$member = “      pAB7         ”;
$member = trim($member)
print “$member”;

Output
// print “       pAB7”;




Pengaturcaraan PHP
String - “ltrim”

To clear any blank space and the begging of variable

Syntax “ltrim(“variable“)”

Example :
$member = “      pAB7         ”;
$member = trim($member)
print “$member”;

Output
// print “pAB7        ”;




                                                       64
Pengaturcaraan PHP
String - “substr_replace”

The function same with substr() but it can change the content of variable

syntax “substr_replace(“variable“,”Word To Replace”, position, length)”

Contoh :
$member = “mz02xyz”;
$member = substr_replace($member, “03”, 2, 2)
print “$member”;

Output
// print “mz03xyz”;




Pengaturcaraan PHP
String - “str_repeat”

To repeat the sentence follow by total of number required

Syntax “str_repeat($string, $n)” : repeat $string $n times
Example :
echo str_repeat('*', 10);

Output
// print “***********”;




                                                                            65
Pengaturcaraan PHP
String - “strtoupper”

To convert variable to UPPER CASE

Syntax “strtoupper(“variable”)”

Example :
$member = “mzxyz”;
$member =strtoupper($member)
print “$member”;

Output
// print “MZXYZ”;




Pengaturcaraan PHP
String - “strtolower”

To convert variable to lowercase

Syntax “strtolower(“variable”)”

Example :
$member = “MZXYZ”;
$member =strtoupper($member)
print “$member”;

Output
// print “mzxyz”;




                                    66
Pengaturcaraan PHP
String - “strrchr”

To get the value of the end of variable with condition

Syntax “strrchr(“variable”, “aksara”) ”

Example :
$file = “file.php”;
$ext = $ext = substr(strrchr($file, '.'), 1);
print “$ext”;

Output
// print “php”;




Pengaturcaraan PHP
 String - “wordwrap()”

 To display variable with the smart appearance which the default can set

 Syntax “wordwrap(“variable”,”panjang sesuatu ayat”)”

 Example :
 $string = “Malaysia negara maju, aman, makmur dan sentoasa”;
 $string .= “Terdiri daripada 14 buah negeri dan sebuah kerajaan
 persekutuann”;
 echo wordwrap($string,75,”<br>”);

 Output

  Malaysia negara maju, aman, makmur dan sentoasa Terdiri daripada
 14 buah negeri dan sebuah kerajaan persekutuan




                                                                           67
Random




Pengaturcaraan PHP
Number (Random)

To get random number

Example :
<?php
$random_number = rand( );
echo "$random_number";
?>
The output
221381276




                            68
Pengaturcaraan PHP
Number (Random)

To get spcific number in random, we must put a value in the ().

Example :
<?php
$random_number = rand(0,10);
echo "$random_number";
?>
The output
0




Pengaturcaraan PHP
Password Encrypt – md5

To encrypt the password

Example :
<?php
    $passwd = md5($password);
      echo "$passwd";
 ?>

The output
ddf3rf5765g434dfg676




                                                                  69
End




      70

More Related Content

What's hot

Php variables (english)
Php variables (english)Php variables (english)
Php variables (english)
Mahmoud Masih Tehrani
 
Php
PhpPhp
Sperimentazioni di Tecnologie e Comunicazioni Multimediali: Lezione 5
Sperimentazioni di Tecnologie e Comunicazioni Multimediali: Lezione 5Sperimentazioni di Tecnologie e Comunicazioni Multimediali: Lezione 5
Sperimentazioni di Tecnologie e Comunicazioni Multimediali: Lezione 5
Salvatore Iaconesi
 
Open Source Package PHP & MySQL
Open Source Package PHP & MySQLOpen Source Package PHP & MySQL
Open Source Package PHP & MySQL
kalaisai
 
Php-mysql by Jogeswar Sir
Php-mysql by Jogeswar SirPhp-mysql by Jogeswar Sir
Lecture7 form processing by okello erick
Lecture7 form processing by okello erickLecture7 form processing by okello erick
Lecture7 form processing by okello erick
okelloerick
 
PHP - DataType,Variable,Constant,Operators,Array,Include and require
PHP - DataType,Variable,Constant,Operators,Array,Include and requirePHP - DataType,Variable,Constant,Operators,Array,Include and require
PHP - DataType,Variable,Constant,Operators,Array,Include and require
TheCreativedev Blog
 
Lecture3 php by okello erick
Lecture3 php by okello erickLecture3 php by okello erick
Lecture3 php by okello erick
okelloerick
 
Data Types In PHP
Data Types In PHPData Types In PHP
Data Types In PHP
Mark Niebergall
 
PHP Workshop Notes
PHP Workshop NotesPHP Workshop Notes
PHP Workshop Notes
Pamela Fox
 
Web 11 | AJAX + JSON + PHP
Web 11 | AJAX + JSON + PHPWeb 11 | AJAX + JSON + PHP
Web 11 | AJAX + JSON + PHP
Mohammad Imam Hossain
 
Php Tutorials for Beginners
Php Tutorials for BeginnersPhp Tutorials for Beginners
Php Tutorials for Beginners
Vineet Kumar Saini
 
PHP Variables and scopes
PHP Variables and scopesPHP Variables and scopes
PHP Variables and scopes
sana mateen
 
Web 8 | Introduction to PHP
Web 8 | Introduction to PHPWeb 8 | Introduction to PHP
Web 8 | Introduction to PHP
Mohammad Imam Hossain
 
Basic PHP
Basic PHPBasic PHP
Basic PHP
Todd Barber
 

What's hot (20)

Php variables (english)
Php variables (english)Php variables (english)
Php variables (english)
 
Php
PhpPhp
Php
 
Sperimentazioni di Tecnologie e Comunicazioni Multimediali: Lezione 5
Sperimentazioni di Tecnologie e Comunicazioni Multimediali: Lezione 5Sperimentazioni di Tecnologie e Comunicazioni Multimediali: Lezione 5
Sperimentazioni di Tecnologie e Comunicazioni Multimediali: Lezione 5
 
Open Source Package PHP & MySQL
Open Source Package PHP & MySQLOpen Source Package PHP & MySQL
Open Source Package PHP & MySQL
 
Php-mysql by Jogeswar Sir
Php-mysql by Jogeswar SirPhp-mysql by Jogeswar Sir
Php-mysql by Jogeswar Sir
 
Lecture7 form processing by okello erick
Lecture7 form processing by okello erickLecture7 form processing by okello erick
Lecture7 form processing by okello erick
 
PHP - DataType,Variable,Constant,Operators,Array,Include and require
PHP - DataType,Variable,Constant,Operators,Array,Include and requirePHP - DataType,Variable,Constant,Operators,Array,Include and require
PHP - DataType,Variable,Constant,Operators,Array,Include and require
 
Operators in PHP
Operators in PHPOperators in PHP
Operators in PHP
 
Lecture3 php by okello erick
Lecture3 php by okello erickLecture3 php by okello erick
Lecture3 php by okello erick
 
Data Types In PHP
Data Types In PHPData Types In PHP
Data Types In PHP
 
Php i basic chapter 3
Php i basic chapter 3Php i basic chapter 3
Php i basic chapter 3
 
PHP Workshop Notes
PHP Workshop NotesPHP Workshop Notes
PHP Workshop Notes
 
Variables in PHP
Variables in PHPVariables in PHP
Variables in PHP
 
Web 11 | AJAX + JSON + PHP
Web 11 | AJAX + JSON + PHPWeb 11 | AJAX + JSON + PHP
Web 11 | AJAX + JSON + PHP
 
Php Tutorials for Beginners
Php Tutorials for BeginnersPhp Tutorials for Beginners
Php Tutorials for Beginners
 
PHP Variables and scopes
PHP Variables and scopesPHP Variables and scopes
PHP Variables and scopes
 
Web 8 | Introduction to PHP
Web 8 | Introduction to PHPWeb 8 | Introduction to PHP
Web 8 | Introduction to PHP
 
Basic PHP
Basic PHPBasic PHP
Basic PHP
 
PHP
PHP PHP
PHP
 
Php & my sql
Php & my sqlPhp & my sql
Php & my sql
 

Viewers also liked

Opinator. the new customer engagement
Opinator. the new customer engagementOpinator. the new customer engagement
Opinator. the new customer engagement
OPINATOR
 
安全な(共用)DNSサービスの提供
安全な(共用)DNSサービスの提供安全な(共用)DNSサービスの提供
安全な(共用)DNSサービスの提供
causeless
 
Experiencing products in the virtual world r8
Experiencing products in the virtual world r8Experiencing products in the virtual world r8
Experiencing products in the virtual world r8radygogo
 
Opinator. The New Customer Engagement
Opinator. The New Customer EngagementOpinator. The New Customer Engagement
Opinator. The New Customer Engagement
OPINATOR
 
Pineapple named mohammed causes row at university freshers’ fair
Pineapple named mohammed causes row at university freshers’ fairPineapple named mohammed causes row at university freshers’ fair
Pineapple named mohammed causes row at university freshers’ fair
Jerry Tasman
 
BALI (11-15 Oct 2012)
BALI (11-15 Oct 2012)BALI (11-15 Oct 2012)
BALI (11-15 Oct 2012)Chiew Yuen
 
CVI Business system
CVI Business systemCVI Business system
CVI Business system
耀辉 刘
 
Pentration Testing Zentyal Networks
Pentration Testing Zentyal NetworksPentration Testing Zentyal Networks
Pentration Testing Zentyal Networks
mussa khonje
 
Konsument ok
Konsument okKonsument ok
Konsument okankowy
 
Cookies and sessions
Cookies and sessionsCookies and sessions
Cookies and sessionssalissal
 
Impact of service quality on satisfaction and loyalty case of two public sect...
Impact of service quality on satisfaction and loyalty case of two public sect...Impact of service quality on satisfaction and loyalty case of two public sect...
Impact of service quality on satisfaction and loyalty case of two public sect...radygogo
 

Viewers also liked (13)

Air digital
Air digitalAir digital
Air digital
 
Opinator. the new customer engagement
Opinator. the new customer engagementOpinator. the new customer engagement
Opinator. the new customer engagement
 
安全な(共用)DNSサービスの提供
安全な(共用)DNSサービスの提供安全な(共用)DNSサービスの提供
安全な(共用)DNSサービスの提供
 
Experiencing products in the virtual world r8
Experiencing products in the virtual world r8Experiencing products in the virtual world r8
Experiencing products in the virtual world r8
 
Opinator. The New Customer Engagement
Opinator. The New Customer EngagementOpinator. The New Customer Engagement
Opinator. The New Customer Engagement
 
Pineapple named mohammed causes row at university freshers’ fair
Pineapple named mohammed causes row at university freshers’ fairPineapple named mohammed causes row at university freshers’ fair
Pineapple named mohammed causes row at university freshers’ fair
 
BALI (11-15 Oct 2012)
BALI (11-15 Oct 2012)BALI (11-15 Oct 2012)
BALI (11-15 Oct 2012)
 
CVI Business system
CVI Business systemCVI Business system
CVI Business system
 
Tgr
TgrTgr
Tgr
 
Pentration Testing Zentyal Networks
Pentration Testing Zentyal NetworksPentration Testing Zentyal Networks
Pentration Testing Zentyal Networks
 
Konsument ok
Konsument okKonsument ok
Konsument ok
 
Cookies and sessions
Cookies and sessionsCookies and sessions
Cookies and sessions
 
Impact of service quality on satisfaction and loyalty case of two public sect...
Impact of service quality on satisfaction and loyalty case of two public sect...Impact of service quality on satisfaction and loyalty case of two public sect...
Impact of service quality on satisfaction and loyalty case of two public sect...
 

Similar to Programming with php

PHP Basic
PHP BasicPHP Basic
PHP Basic
Yoeung Vibol
 
FYBSC IT Web Programming Unit IV PHP and MySQL
FYBSC IT Web Programming Unit IV  PHP and MySQLFYBSC IT Web Programming Unit IV  PHP and MySQL
FYBSC IT Web Programming Unit IV PHP and MySQL
Arti Parab Academics
 
forms.pptx
forms.pptxforms.pptx
forms.pptx
asmabagersh
 
OpenGurukul : Language : PHP
OpenGurukul : Language : PHPOpenGurukul : Language : PHP
OpenGurukul : Language : PHP
Open Gurukul
 
PHP Basics
PHP BasicsPHP Basics
PHP Basics
Muthuganesh S
 
PHP Basics
PHP BasicsPHP Basics
PHP Basics
Saraswathi Murugan
 
Web application security
Web application securityWeb application security
Web application securitysalissal
 
Dynamic website
Dynamic websiteDynamic website
Dynamic websitesalissal
 
Php using variables-operators
Php using variables-operatorsPhp using variables-operators
Php using variables-operators
Khem Puthea
 
Developing web applications
Developing web applicationsDeveloping web applications
Developing web applicationssalissal
 
Introduction To Php For Wit2009
Introduction To Php For Wit2009Introduction To Php For Wit2009
Introduction To Php For Wit2009
cwarren
 
Operators php
Operators phpOperators php
Operators php
Chandni Pm
 
Intoroduction to Adnvanced Internet Programming Chapter two.pptx
Intoroduction to Adnvanced Internet Programming Chapter two.pptxIntoroduction to Adnvanced Internet Programming Chapter two.pptx
Intoroduction to Adnvanced Internet Programming Chapter two.pptx
JerusalemFetene
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
Taha Malampatti
 
php.pdf
php.pdfphp.pdf
Php ch-2_html_forms_and_server_side_scripting
Php ch-2_html_forms_and_server_side_scriptingPhp ch-2_html_forms_and_server_side_scripting
Php ch-2_html_forms_and_server_side_scripting
bantamlak dejene
 
html forms and server side scripting
html forms and server side scriptinghtml forms and server side scripting
html forms and server side scripting
bantamlak dejene
 
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)Muhamad Al Imran
 
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)Muhamad Al Imran
 

Similar to Programming with php (20)

PHP Basic
PHP BasicPHP Basic
PHP Basic
 
FYBSC IT Web Programming Unit IV PHP and MySQL
FYBSC IT Web Programming Unit IV  PHP and MySQLFYBSC IT Web Programming Unit IV  PHP and MySQL
FYBSC IT Web Programming Unit IV PHP and MySQL
 
forms.pptx
forms.pptxforms.pptx
forms.pptx
 
OpenGurukul : Language : PHP
OpenGurukul : Language : PHPOpenGurukul : Language : PHP
OpenGurukul : Language : PHP
 
PHP Basics
PHP BasicsPHP Basics
PHP Basics
 
PHP Basics
PHP BasicsPHP Basics
PHP Basics
 
Web application security
Web application securityWeb application security
Web application security
 
Dynamic website
Dynamic websiteDynamic website
Dynamic website
 
Php using variables-operators
Php using variables-operatorsPhp using variables-operators
Php using variables-operators
 
Developing web applications
Developing web applicationsDeveloping web applications
Developing web applications
 
Php essentials
Php essentialsPhp essentials
Php essentials
 
Introduction To Php For Wit2009
Introduction To Php For Wit2009Introduction To Php For Wit2009
Introduction To Php For Wit2009
 
Operators php
Operators phpOperators php
Operators php
 
Intoroduction to Adnvanced Internet Programming Chapter two.pptx
Intoroduction to Adnvanced Internet Programming Chapter two.pptxIntoroduction to Adnvanced Internet Programming Chapter two.pptx
Intoroduction to Adnvanced Internet Programming Chapter two.pptx
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
 
php.pdf
php.pdfphp.pdf
php.pdf
 
Php ch-2_html_forms_and_server_side_scripting
Php ch-2_html_forms_and_server_side_scriptingPhp ch-2_html_forms_and_server_side_scripting
Php ch-2_html_forms_and_server_side_scripting
 
html forms and server side scripting
html forms and server side scriptinghtml forms and server side scripting
html forms and server side scripting
 
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
 
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
 

Recently uploaded

The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
DhatriParmar
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
DeeptiGupta154
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
Celine George
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
Atul Kumar Singh
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Atul Kumar Singh
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
Peter Windle
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
TechSoup
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
GeoBlogs
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Po-Chuan Chen
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
heathfieldcps1
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
Anna Sz.
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
EugeneSaldivar
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
Vikramjit Singh
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
RaedMohamed3
 

Recently uploaded (20)

The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
 

Programming with php

  • 1. Creating HTML Forms Pengaturcaraan PHP Managing HTML forms with PHP is a two-step process. First, you create the HTML form itself, using any text or WYSIWYG editor you choose. Then, you create the corresponding PHP script that will receive and process the form data. An HTML form is created using the form tags and various input types. The form tags look as follows: The most important attribute of your form tag is action, which dictates to which page the form data will be sent. The second attribute — method — has its own issues, but post is the value you'll use most frequently. 1
  • 2. Pengaturcaraan PHP Choosing a Method The method attribute of a form dictates how the data is sent to the handling page. The two options — get and post — refer to the HTTP (Hypertext Transfer Protocol) method to be used. In short, the get method sends the submitted data to the receiving page as a series of name-value pairs appended to the URL. Consider the example shown below: Pengaturcaraan PHP The benefit of using the get method is that the resulting page can be bookmarked in the user's Web browser (since it's a URL). For that matter, you can also click Back in your Web browser to return to a get page, or reload it without problem (neither of which is true for post). Unfortunately, you are limited to how much data can be transmitted via get and it's less secure (since the data is visible). 2
  • 6. Pengaturcaraan PHP Handling an HTML Form 6
  • 7. Pengaturcaraan PHP Once you have an HTML form, the next step is to write a bare- bones PHP script to handle it. When we say that this script will be handling the form, we mean that it will do something with the data it receives; that is it will reiterate the data back to the Web browser. The PHP page that receives the form data will assign what the user entered into this form element to a special variable called $_REQUEST['weight']. It is very important that the spelling and capitalization match exactly, as PHP is case-sensitive when it comes to variable names. $_REQUEST['weight'] can then be used like any other variable: printed, used in mathematical computations, concatenated, and so on. Pengaturcaraan PHP Registering Globals In earlier versions of PHP, the register_globals setting was turned on by default. This feature gave PHP an ease of use by automatically turning form inputs into similarly named variables, like $name or $email (as opposed to having to refer to $_REQUEST['name'] and $_REQUEST['email'] first). As of version 4.2 of PHP, the developers behind PHP opted to turn this setting off by default because not relying on this feature improves the security of your scripts. Unfortunately, this also To work around this, there are two had the side effect that a lot of existing options. First, you could turn scripts no longer worked and many beginning programmers were stymied register_globals back on, assuming when they saw blank values in their that you have administrative control form results, error messages, or just over your PHP installation. Second, blank pages. you could start using the superglobal variables, such as $_REQUEST, $_GET, and $_POST. 7
  • 8. Pengaturcaraan PHP Pengaturcaraan PHP Following the rules outlined before, the data entered into the name form input, which has a name value of name, will be accessible through the variable $_REQUEST['name']. The data entered into the email form input, which has a name value of email, will be accessible through $_REQUEST['email']. The same applies to the entered comments data. Again, the spelling and capitalization of your variables here must exactly match the corresponding name values in the HTML form. 8
  • 10. Pengaturcaraan PHP Pengaturcaraan PHP $_REQUEST $_REQUEST is a special variable type in PHP, available since version 4.1. It stores all of the data sent to a PHP page through either the GET or POST methods, as well as data accessible in cookies. Blank pages If you see a blank page after submitting the form, first check the HTML source to look for HTML errors, and then confirm that display_errors is on in your PHP configuration. 10
  • 11. Pengaturcaraan PHP Others way to avoid _$_REQUEST[‘variable’] extract($_GET); extract($_POST); extract($_COOKIE); User can call directly the name of variable like $name without using the method $_POST[“name”]. Managing Magic Quotes 11
  • 13. Pengaturcaraan PHP In PHP there are two main types of Magic Quotes: magic_quotes_gpc, which applies to form, URL, and cookie data (gpc stands for get, post, cookie); and magic_quotes_runtime, which applies to data retrieved from external files and databases. If Magic Quotes is enabled on your server, you can undo its effect using the stripslashes() function. This function will remove any backslashes found in $var. Pengaturcaraan PHP 13
  • 14. Pengaturcaraan PHP Pengaturcaraan PHP addslashes() function You can emulate what Magic Quotes does if it's disabled by using the opposite of the stripslashes() function, addslashes(). trim() function When working with strings stemming from forms, it's also a good idea to use the trim() function, which removes excess white spaces from both ends of the value. $name = trim($name); 14
  • 15. Conditionals Pengaturcaraan PHP Conditionals, like variables, are integral to programming, and most people are familiar with them in some form or another. Dynamic Web pages, as you might imagine, frequently require the use of conditionals to alter a script's behavior according to set criteria. PHP's three primary terms for creating conditionals are if, else, and elseif (which can also be written as two words, else if). Every conditional includes an if clause, as shown here. 15
  • 16. Pengaturcaraan PHP The if clause in turn can specify an alternate course of action by using else. It can also be written to include another condition and a couple of alternatives by using elseif and else, as in this example. Pengaturcaraan PHP If a condition is true, the code in the following curly braces ({}) will be executed. If not, PHP will continue on. If there is a second condition (after an elseif), that will be checked for truth. The process will continue — you can use as many elseif clauses as you want — until PHP hits an else, which will be automatically executed at that point, or until the conditional terminates without an else. For this reason, it's important that the else always come last and be treated as the default action unless specific criteria (the conditions) 16
  • 17. In the second example, a new function, isset(), is introduced. This function checks if a variable is set, meaning that it has a value other than NULL. You can also use the comparative and logical operators, listed in the table below, in conjunction with parentheses to make more complicated expressions. SYMBOL MEANING TYPE EXAMPLE $x == $y == is equal to comparison != $x ! = $y is not equal to comparison $x < $y < less than comparison $x > $y > greater than comparison $x <= $y <= less than or equal to comparison $x >= $y >= greater than or equal to comparison ! !$x not logical $x && $y && and logical || or logical $x || $y XOR and not logical $x XOR $y Pengaturcaraan PHP 17
  • 18. Pengaturcaraan PHP This is a simple and effective way to validate a form input (particularly a radio button, check box, or select). If the user checks either gender radio button, then $_REQUEST['gender'] will have a value, meaning that the condition isset($_REQUEST['gender']) is true. In such a case, the shorthand version of this variable — $gender — is assigned the value of $_REQUEST['gender'], repeating the technique used with $name, $email, and $comments. If the condition is not true, then $gender is assigned the value of NULL, indicating that it has no value. Notice that NULL is not in quotes. Pengaturcaraan PHP 18
  • 19. Pengaturcaraan PHP This if-elseif-else conditional looks at the value of the $gender variable and prints a different message for each possibility. It's very important to remember that the double equals sign (==) means equals, whereas a single equals sign (=) assigns a value. The distinction is important because the condition $gender == 'M' may or may not be true, but $gender = 'M' will always be true. Pengaturcaraan PHP 19
  • 20. Pengaturcaraan PHP Switch PHP has another type of conditional, called the switch, best used in place of a long if-elseif-else conditional. The syntax of switch is shown here. The switch conditional compares the value of $variable to the different cases. When it finds a match, the following code is executed, up until the break. If no match is found, the default is executed, assuming it exists (it's optional). The switch conditional is limited in its usage in that it can only check a variable's value for equality against certain cases; more complex conditions cannot be easily checked. Pengaturcaraan PHP 20
  • 21. Validating Form Data Pengaturcaraan PHP Validating form data requires the use of conditionals and any number of functions, operators, and expressions. One common function to be used is isset(), which tests if a variable has a value (including 0, FALSE, or an empty string, but not NULL). To check that a user typed something into textual elements like name, email, and comments, you can use the empty() function. It checks if a variable has an empty value — an empty string, 0, NULL, or FALSE. 21
  • 22. Pengaturcaraan PHP The first aim of form validation is ensuring that something was entered or selected in form elements. The second goal is to ensure that submitted data is of the right type (numeric, string, etc.), of the right format (like an email address), or a specific acceptable value (like $gender being equal to either M or F). Next, let's write a new handle_form.php script that makes sure variables have values before they're referenced. Pengaturcaraan PHP 22
  • 25. Pengaturcaraan PHP strlen() function Another way of validating text inputs is to use the strlen() function to see if more than zero characters were typed. if (strlen($var) > 0) { // $var has a value. } else { // $var does not have a value. } Arrays 25
  • 26. Pengaturcaraan PHP Unlike strings and numbers (which are scalar variables, meaning they can store only a single value at a time), an array can hold multiple, separate pieces of information. An array is therefore like a list of values, each value being a string or a number or even another array. Arrays are structured as a series of key-value pairs, where one pair is an item or element of that array. For each item in the list, there is a key (or index) associated with it. The resulting structure is not unlike a spreadsheet or database table. PHP supports two kinds of arrays. The first type, called indexed arrays, uses numbers as the keys, as in the first example, the $artists array. As in most programming languages, with indexed arrays, your arrays will begin with the first index at 0, unless you specify the keys explicitly. Key Value 0 Low 1 Aimee Mann 2 Ani DiFranco 3 Spiritualized The second type of array, associative, uses strings as keys as in the following example. The $states array uses the state abbreviation for its keys. Key Value MD Maryland PA Pennsylvania IL Illinois MO Missouri 26
  • 27. Pengaturcaraan PHP An array follows the same naming rules as any other variable. So offhand, you might not be able to tell that $var is an array as opposed to a string or number. The important syntactical difference has to do with accessing individual array elements. To retrieve a specific value from an array, you refer to the array name first, followed by the key, in square brackets: Pengaturcaraan PHP Because arrays use a different syntax than other variables, printing them can be trickier. First, since an array can contain multiple values, you cannot use a simple print statement. Second, the keys in associative arrays complicate printing them and cause a parse error. 27
  • 28. Pengaturcaraan PHP To work around this, wrap your array name and key in curly braces when your array uses strings for its keys. Numerically indexed arrays don't have this problem. Superglobal Arrays PHP includes several predefined arrays by default. These are the superglobal variables — $_GET, $_POST, $_SESSION, $_REQUEST, $_SERVER, $_COOKIE, and so forth, added to PHP as of version 4.1. The $_GET variable is where PHP stores all of the variables and values sent to a PHP script via the get method (presumably but not necessarily from an HTML form). $_POST stores all of the data sent to a PHP script from an HTML form that uses the post method. Both of these — along with $_COOKIE — are subsets of $_REQUEST. The superglobals have two benefits over registered global variables. First, they are more secure because they are more precise (they indicate where the variable came from). Second, they are global in scope (hence the name). If you find the syntax of these variables to be confusing, you can use the shorthand technique at the top of your scripts as follows: 28
  • 30. Pengaturcaraan PHP Pengaturcaraan PHP Earlier versions of PHP The superglobals are new to PHP as of version 4.1. If you are using an earlier version of the language, use $HTTP_POST_VARS instead of $_POST, and $HTTP_GET_VARS instead of $_GET. 30
  • 31. Creating and Accessing Arrays Pengaturcaraan PHP Creating Arrays Although you can use PHP-generated arrays, there will frequently be times when you want to create your own. There are two primary ways to define your own array. First, you could add one element at a time to build one, as in this example. It's important to understand that if you specify a key and a value already exists indexed with that same key, the new value will overwrite the existing one. In this example, based on the latest assignment, the value of $array['son'] is Michael and that of array[2] is orange. 31
  • 32. Pengaturcaraan PHP Instead of adding one element at a time, you can use the array() function to build an entire array in one step. This function can be used whether or not you explicitly set the key. Pengaturcaraan PHP On the other hand, if you set the first numeric key value, the added values will be keyed incrementally thereafter, as in this example. Finally, if you want to create an array of sequential numbers you can use the range() function. 32
  • 33. Accessing Arrays Individual array elements can be accessed by key (e.g., $_POST['email']). This works when you know exactly what the keys are or if you want to refer to only a single element. To access every array element, use the foreach loop. The foreach loop will iterate through every element in $array, assigning each element's value to the $value variable. In this example, you can access both the keys and values. Pengaturcaraan PHP 33
  • 36. Pengaturcaraan PHP count() or sizeof() function To determine the number of elements in an array, use the count() or sizeof() function (the two are synonymous): $num=count($array); range() function The range() function can also create an array of sequential letters as of PHP 4.1: $alphabet=range('a','z'); Error message in foreach loop If you see an 'Invalid argument supplied for foreach()' error message, that means you are trying to use a foreach loop on a variable that is not an array. Multidimensional Arrays 36
  • 37. Pengaturcaraan PHP An array's values could be any combination of numbers, strings, and even other arrays. This last option — an array consisting of other arrays — creates a multidimensional array. Multidimensional arrays are much more common than you might expect (especially if you use the superglobals) but remarkably easy to work with. As an example, let's say you have an array called $states and another one called $provinces for Canada, both created by the following definitions. Pengaturcaraan PHP These two arrays could be combined into one multidimensional array as follows: 37
  • 38. Pengaturcaraan PHP To access the $states array, you refer to $abbr['US'] To access Maryland, use $abbr['US']['MD'] Of course, you can still access multidimensional arrays using the foreach loop, nesting one inside another if necessary. Pengaturcaraan PHP To print out one of these values, surround the whole construct in curly braces: 38
  • 45. Pengaturcaraan PHP $_POST['interests'] Even if the user selects only one interest, $_POST['interests'] will still be an array because the HTML name for the corresponding input is interests[] (the square brackets make it an array). select menu You can also end up with a multidimensional array by having an HTML form's select menu allow for multiple selections: ‹select name="interests[]" multiple="multiple"› ‹option value="Music"›Music‹/option› ‹option value="Movies"›Movies‹/option› ‹option value="Books"›Books‹/option› ‹option value="Skiing"›Skiing‹/option› ‹option value="Napping"›Napping‹/option› ‹/select› Arrays and Strings 45
  • 46. Pengaturcaraan PHP Because strings and arrays are so commonly used, PHP has two functions for converting between these two variable types. The key to using and understanding these two functions is the separator and glue relationships. When turning an array into a string, you set the glue — the characters or code that will be inserted between the array values in the generated string. Conversely, when turning a string into an array, you specify the separator, which is the code that delineates between the different elements in the generated array. Let's examine some examples. Pengaturcaraan PHP The $days_array variable is now a five-element array, with Mon indexed at 0, Tue indexed at 1, etc. The $string2 variable is now a comma-separated list of days — Mon, Tue, Wed, Thurs, Fri. 46
  • 49. Sorting Arrays Pengaturcaraan PHP One of the many advantages arrays have over the other variable types is the ability to sort them. PHP includes several functions you can use for sorting arrays, all simple in syntax. 49
  • 50. Pengaturcaraan PHP Array (sort/rsort) Sorting Array : sort($pantry_food); - Sort with ascending 0 - 9 rsort($pantry_food); - Sort with Descending 9 – 0 Sort with alphabet alphabet asort($pantry_food); - Sort with ascending A - Z arsort($pantry_food); - Sort with Descending Z – A Pengaturcaraan PHP 50
  • 52. Pengaturcaraan PHP Pengaturcaraan PHP Array (Adding/Replace) In array, we can add or change content of array example 1 : $fruit = array('banana','papaya'); Cara menambah : <? $fruit[2] = “apple”; print “$fruit[2] ?> The Output apple 52
  • 53. Pengaturcaraan PHP Array (merging) You also can merge 2 or more array. Example 1 : $pantry = array( 1 => "apples", 2 => "oranges", 3 => "bananas" ); $pantry2 = array( 1 => "potatoes", 2 => "bread", 3 => "tomatoes" ); Pengaturcaraan PHP Array (Merging) Way to combine : <? $pantry_food = array_merge ($pantry, $pantry2); ?> The Output $pantry_food[0] = "apples"; $pantry_food[1] = "oranges"; $pantry_food[2] = "bananas"; $pantry_food[3] = "potatoes"; $pantry_food[4] = "bread"; $pantry_food[5] = "tomatoes"; 53
  • 54. Pengaturcaraan PHP Array (push) The way to add content at the last of array elemt : example $pantry = array( 1 => "tomatoes", 0 => "oranges", 4 => "bananas", 3 => "potatoes", 2 => "bread" ); array_push($pantry, "apples"); For and While Loops 54
  • 55. Two types of loops you'll use when managing arrays are for and while. Consider the example of while loop. As long as the condition part of the loop is true, the loop will be executed. Once it becomes false, the loop is stopped. If the condition is never true, the loop will never be executed. The while loop will most frequently be used when retrieving results from a database. Pengaturcaraan PHP The for loop has a more complicated syntax. Upon first executing the loop, the initial expression is run. Then the condition is checked and, if true, the contents of the loop are executed. After execution, the closing expression is run and the condition is checked again. This process continues until the condition is false. Again, the loop will never be executed if the condition is never true. 55
  • 56. Pengaturcaraan PHP Consider this example. The first time this loop is run, the $i variable is set to the value of 1. Then the condition is checked (is 1 less than or equal to 10?). Since this is true, 1 is printed out (echo $i). Then, $i is incremented to 2 ($i++), the condition is checked, and so forth. The result of this script will be the numbers 1 through 10 printed out. Pengaturcaraan PHP 56
  • 58. Pengaturcaraan PHP String Manipulation 58
  • 59. Pengaturcaraan PHP String – “strtok” To take a certain char in the one sentence. The way to take the char can use “,” “.” or anything else Sntax “strtok(“variable",“condition");” Example : <?php $bigstring = "BigBad Wolf"; $firstpart = strtok($bigstring," "); echo "$firstpart"; ?> The output BigBad Pengaturcaraan PHP String – “substr” To take the char based on position. It start from left and counting start by 0 Syntax “substr(“variable",position,length);” Example : <?php $bigstring = "BigBad Wolf"; $example = substr($bigstring,7,4); echo "$example"; ?> The output Wolf 59
  • 60. Pengaturcaraan PHP String – “eregi/ereg” To search char in variable. Ereg only can search based on case sensitive saja. eregi can search without concern about case-sensitive Syntax “ereg(“condition",“variable");” Syntax “eregi(“condition",“variable");” Pengaturcaraan PHP Example ereg $pattern = "z"; $search_area = "My car goes ZOOM."; $search_result = ereg($pattern,$search_area); if ($search_result){ // print this if there is a true result. echo "Success, the pattern was found!"; } else { // print this if there is a false result. echo "Failure, the pattern was not found!"; } Output Failure, the pattern was not found! 60
  • 61. Pengaturcaraan PHP Example eregi $pattern = "z"; $search_area = "My car goes ZOOM."; $search_result = eregi($pattern,$search_area); if ($search_result){ // print this if there is a true result. echo "Success, the pattern was found!"; } else { // print this if there is a false result. echo "Failure, the pattern was not found!"; } Output Success, the pattern was found! Pengaturcaraan PHP String – “str_replace” Syntax “str_replace(",","", “variable");” To change anything (like coma) to the anything (like $ dollar sign) Contoh : $cfcost1 = “2,300.00”; $cfcost1 = str_replace(",","","$cfcost1"); Output : 2300.00 61
  • 62. Pengaturcaraan PHP String – “eregi_replace” To replace char in variable based on search Syntax: eregi_replace(pattern,replacement,search_area); Example $entry = “user@yahoo.com $pattern = “@"; $replacement = “(a)"; $entry = ereg_replace($pattern,$replacement,$entry); echo "$entry"; output user(a)yahoo.com Pengaturcaraan PHP String - “strlen” To count total of char in the variable value Syntax “strlen(“variable")” Example : if(strlen($password) < 6) { print “Jumlah password anda kurang dari 6 aksara”; } else { print “Tahniah”; } 62
  • 63. Pengaturcaraan PHP String - “strstr” To search certain value in variable Syntax “strstr(“variable“,”word to search”)” Example : $member = “pAB7”; if(strstr($member,”AB”)) { print “Membership anda akan luput tidak lama lagi”; } else { print “Tahniah”; } Pengaturcaraan PHP String - “trim” To clear any blank space in variable at the beginning and end Syntax “trim(“variable“)” Example : $member = “ pAB7 ”; $member = trim($member) print “$member”; Output // print “pAB7”; 63
  • 64. Pengaturcaraan PHP String - “rtrim” To clear any blank space at the end of variable Syntax “trim(“variable“)” Example : $member = “ pAB7 ”; $member = trim($member) print “$member”; Output // print “ pAB7”; Pengaturcaraan PHP String - “ltrim” To clear any blank space and the begging of variable Syntax “ltrim(“variable“)” Example : $member = “ pAB7 ”; $member = trim($member) print “$member”; Output // print “pAB7 ”; 64
  • 65. Pengaturcaraan PHP String - “substr_replace” The function same with substr() but it can change the content of variable syntax “substr_replace(“variable“,”Word To Replace”, position, length)” Contoh : $member = “mz02xyz”; $member = substr_replace($member, “03”, 2, 2) print “$member”; Output // print “mz03xyz”; Pengaturcaraan PHP String - “str_repeat” To repeat the sentence follow by total of number required Syntax “str_repeat($string, $n)” : repeat $string $n times Example : echo str_repeat('*', 10); Output // print “***********”; 65
  • 66. Pengaturcaraan PHP String - “strtoupper” To convert variable to UPPER CASE Syntax “strtoupper(“variable”)” Example : $member = “mzxyz”; $member =strtoupper($member) print “$member”; Output // print “MZXYZ”; Pengaturcaraan PHP String - “strtolower” To convert variable to lowercase Syntax “strtolower(“variable”)” Example : $member = “MZXYZ”; $member =strtoupper($member) print “$member”; Output // print “mzxyz”; 66
  • 67. Pengaturcaraan PHP String - “strrchr” To get the value of the end of variable with condition Syntax “strrchr(“variable”, “aksara”) ” Example : $file = “file.php”; $ext = $ext = substr(strrchr($file, '.'), 1); print “$ext”; Output // print “php”; Pengaturcaraan PHP String - “wordwrap()” To display variable with the smart appearance which the default can set Syntax “wordwrap(“variable”,”panjang sesuatu ayat”)” Example : $string = “Malaysia negara maju, aman, makmur dan sentoasa”; $string .= “Terdiri daripada 14 buah negeri dan sebuah kerajaan persekutuann”; echo wordwrap($string,75,”<br>”); Output Malaysia negara maju, aman, makmur dan sentoasa Terdiri daripada 14 buah negeri dan sebuah kerajaan persekutuan 67
  • 68. Random Pengaturcaraan PHP Number (Random) To get random number Example : <?php $random_number = rand( ); echo "$random_number"; ?> The output 221381276 68
  • 69. Pengaturcaraan PHP Number (Random) To get spcific number in random, we must put a value in the (). Example : <?php $random_number = rand(0,10); echo "$random_number"; ?> The output 0 Pengaturcaraan PHP Password Encrypt – md5 To encrypt the password Example : <?php $passwd = md5($password); echo "$passwd"; ?> The output ddf3rf5765g434dfg676 69
  • 70. End 70