Beruflich Dokumente
Kultur Dokumente
TUTOR
[A Quick Guide for Beginners]
by
S A Shakil
[1]
1. Introduction to PHP
Welcome! Let's start by answering some of the basic questions on PHP and OPEN SOURCE...
2. PHP Syntax
Welcome! In this section we're going to learn how PHP and HTML works together. We are also going to build
our first PHP web page. Exciting! Are you ready?
3. PHP Variables
Welcome! A variable is a mean to store values such as strings or integers so we can easily reuse those values
in our code. For example, we can store a string value such as "I Love PHP" or an integer value such as 100 into a
variable. When ever we need to use these values, we simply call that variable instead writing out those values over
and over again in our code. Here is an example.
<?php
$str="I love PHP"; //here is one variable with a string value
echo $str; // here we print the $str value onto the browser
echo $str; //here we reuse the $str variable to print its value again in our
code
echo $num; //here we reuse the $num variable to print its value again in our
code
?>
The following code should print "I Love PHP100I Love PHP100". Try it. Copy the code in an empty file, save
the file as php and run it on your browser.
Every language has its own semantics of defining variables. In PHP, we define a variable starting with a $ sign,
then write the variable name and finally assign a value to it. Here is an example below.
$variable_name = value;
echo $number;
?>
Example - PHP variable with a float or decimal value
<?php
$decimal_number = 100.01;
printf("%.2f", $decimal_number);
?>
In the above code we define a variable name $decimal_number, assign it a decimal value of 100.01 and print
its value onto the page.
?>
In the above example, we store the string value "I Love PHP" in a variable name $str and use echo to output
its value.
<?php
$name = "Matt";
echo "Hello $name!";
?>
?>
The above example will output "hello!"
6. PHP Operators
Welcome! In this section we’re going to cover different kinds of operators we use in programming. These
operators are common to ever language. So, in PHP they are no longer different. We will go through each type of
operators with examples on how they are done in PHP.
In the above example, we use the curly brackets to enclose the action part of the conditional statements
when we have more than one line in there.
?>
</body>
</html>
The code will execute the default code block since we don't carry ‘Briefcase’ and it is not part of our switch
statement cases. The code will output "Sorry, we don't carry Briefcase in our catalog".
[Tip: It is always good to include the default case in your switch statements. It will help you debug your code
better during testing. In case, none of your switch cases match in your switch statement during code execution, the
default case will be executed.]
9. PHP Arrays
Welcome! In this section we cover what arrays are, what they are used for and how to work with arrays in
PHP. What is PHP Array?
An array is a mean to store collection of values in a single variable. Imagine, if you own a shop and you want
to store the names of your employees. Now, instead of creating a separate variable to store each employee's name,
you can use an array to store the names of all your employees in a single variable. This is how you would do it.
Example - PHP Array
$employee_names[0] = "Dana";
$employee_names[1] = "Matt";
$employee_names[2] = "Susan";
Each value in the array above is stored as an element and each element is associated to an id or a key which
you see in the square brackets.
Hmmm, that's nice but how the heck would I store employees table in an array? Simple! PHP allows us to do
that using multidimensional arrays. Let's look at the examples below to see how we would do that.
$employee_title["Dana"] = "Owner";
$employee_title["Matt"] = "Manager";
$employee_title["Susan"] = "Cashier";
echo "<pre>";
print_r($employee_title);
echo "</pre>";
?>
The array result will print out as follow...
Array
(
[Dana] => Owner
[Matt] => Manager
[Susan] => Cashier
)
[Note: Always remember to use <pre></pre> tags while printing an array as shown above otherwise the
result is not very reader friendly.]
Summary
So, in this section we covered an important lesson on arrays. You will find yourself using arrays a lot when
programming in PHP because its the most easy and useful way of storing values. The usefulness of arrays will become
more apparent in the next lesson, PHP Loops.
Firefox
The above code will output our drop down box.
echo "<td>";
echo $article_body;
echo "</td>";
echo "</tr>";
}
echo "</table>";
?>
So, in the above example we define an array of articles with key being the article title and value being the
article body. Next we use foreach loop to print the array keys and values in a table.
The above example will print our articles in a table as below. Pretty neat eh? Loops can save a lot of time from doing
repetitive things.
[The operator "=>" represents the relationship between the key and value. So, in our example above, the
$article_title is our key and $article_body is the value.]
Output:
PHP A variable is a mean to store values such as strings or integers so we can easily reuse those values in
Variables our code...
PHP Strings A string is a sequence of letters, symbols, characters and arithmetic values...
PHP Loops In programming, we often repeat an action or a piece of code a number of times using loops to solve
a problem...
Now let's look at the next type of looping technique we use in php, the for loop.
echo "<tr>";
echo "<td style='background-color:green'>";
echo $i;
echo "</td>";
echo "</tr>";
}
}
echo "</table>";
?>
The above code sets different background color to the table cells depending on the value of $i. If $i is
divisible by 2, which means if it is even then display color green, otherwise display color red.
Now that we are familiar with PHP for loop. Now, let's take a look at the last type of loop, the while loop in PHP.
$i = $i + 1;
}
?>
In the above example, you see that the loop is run until the value of $i is less than or equal to 5 according to
the condition in the loop. The $i = $i + 1; statement increments the value of $i by 1 on each iteration of our while
loop.
Example - Print decimal number through 1.0 to 5.0 with PHP While Loop
Here is another example with decimal numbers.
Example below prints decimal numbers through 1.0 to 5.0
<?php
$i = 1.0;
while ($i <= 5.0 )
{
printf("%.1f<br>", $i);
$i = $i + 1.0;
}
?>
$i = 1;
while ($i <= 5 )
{
if($i == 4)
break;
echo $i . "<br>";
$i = $i + 1;
}
?>
In the above example, we break the loop when $i reaches 4. The loop outputs...
1
2
3
my_function(); //we call our function like this when we want to use it
?>
</body>
</html>
In the above code, we create our own function name my_function() and we call that function by just typing
the its name. The above code outputs "Hello! How are you?".
<?php
//we create a function named my_function
function my_function($first_name, $last_name, $message)
{
echo "$first_name $last_name once said " . $message;
}
?>
</body>
</html>
In the above example we created a function with three parameters, $first_name, $last_name and $message.
We used these parameters to send our custom arguments (values) to our function. The above example outputs...
Duke Nukem once said "It's time to kick some ass and chew bubble gum.".
[Note: In our function we can make as many parameters as we want. Parameters appear within the
parentheses "()". They are like normal PHP variable.]
Hopefully, now you're are beginning to see the use of functions and realizing how useful they are.
?>
</body>
</html>
The above function returns our string value instead echoing it inside. We call the function and echo its value
outside. The above code outputs "hello there Matt!"
Pretty neat eh! Let's look at more examples.
Example - PHP Function returning a Integer value
Let's create a function to return an integer value.
<html>
<body>
<?php
function my_function($price, $tax) //we create a function named my_function
{
$total_price = $price + $tax;
return $total_price;
}
[21]
?>
</body>
</html>
In the above function we calculate the total price and return it. The code outputs The total price after tax:
$55.
Summary
Hopefully now you can see how we use functions in our code. We can use functions to organize our code
into little meaningful chunks and use them as we need them in our code.
/*
* print_name: print message on the screen
* @param: $name - name to be used in the message
*/
[22]
function print_name($name)
{
// print hello there on the screen
echo "hello $name!";
}
?>
</body>
</html>
if (mail($to,$subject,$message,$headers) ) {
echo "email sent";
} else {
echo "email could not be sent";
}
}
$subject = "Hello!";
$message = "Hello! How are you today?";
send_email("youraddress@domain.com", "recpeient@domain.com",
"someone@domain.com", "hidden_email@domain.com",
$subject ,
[23]
$message);
?>
In our send_email function we set the appropriate headers. Reply-To and Return-Path points to the email
you want the recipient to reply to. Some server requires the use of Return-Path, so it's good to leave it in there.
Next we call the send_email function which sends out the email.
if (mail($to,$subject,$message,$headers) ) {
echo "email sent";
} else {
echo "email couldn't be sent";
}
}
$subject = "Helloooo!";
$message .= "<html><body>";
$message .= "<b>Hey! How are you today?</b>";
$message .= "<br>Regards";
$message .= "</body></html>";
send_email("youraddress@domain.com", "recpeient@domain.com",
$subject ,
$message);
?>
In our send_email function we set the content type headers to text/html. It is important to do so because it
tells the email server that the email contains html code and to format and display the email correctly when it is
opened.
/*
* since leap year falls ever 4 years so loop for 4 times
*/
for($i=0; $i<4; $i++)
{
//get day timestamp for feburary 29 for this year
$day = date("d", mktime(0, 0, 0, 2, 29, date("Y")+$i));
/*
* check if day equals 29.
[25]
* If day is 29 then it must be the leap year. if day is 01, then it not
a leap year.
*/
if($day == 29)
{
$year = date("Y")+$i;
break;
}
}
echo "next leap year is in year $year";
?>
Output
next leap year is in year 2012
The mktime takes 6 arguments. The parameters are explained as below.
1. hour - The number of the hour.
2. minute - The number of the minute.
3. second - The number of seconds past the minute.
4. month - The number of the month.
5. day - The number of the day.
6. year - The number of year.
</html>
Cookie username is set with value john which is set to expire after one hour on users computer.
The function time() retrieves the current timestamp. Appending 3600 seconds (one hour) to the current time
to make the cookie to expire after one hour.
[Note: A cookie must be set before any HTML code as shown above.]
<html>
<body>
</body>
</html>
When you start a session a unique session id (PHPSESSID) for each visitor/user is created. You can access the
session id using the PHP predefined constant PHPSESSID.
The code above starts a session for the user on the server, and assign a session id for that user's session.
[Note: The session_start() function must appear BEFORE the <html> tag]
$_SESSION["username"] = "johny";
$_SESSION["color"] = "blue";
?>
echo $_SESSION["username"];
echo "<br/>";
echo $_SESSION["color"];
?>
Output
Johny
Blue
Thank You