PHP Tutorial
PHP Tutorial
Variables in PHP
Variables are used for storing values, like text strings, numbers or arrays.
When a variable is declared, it can be used over and over again in your script.
All variables in PHP start with a $ sign symbol.
The correct way of declaring a variable in PHP:
$var_name = value;
New PHP programmers often forget the $ sign at the beginning of the variable. In that case it will
not work.
Let's try creating a variable containing a string, and a variable containing a number:
<?php
$txt="Hello World!";
$x=16;
?>
A variable name should not contain spaces. If a variable name is more than one word, it
should be separated with an underscore ($my_string), or with capitalization ($myString )
Remark:
the point . is the concatenation operator (it allows you to "stick together" different strings; since
PHP is a very weakly typed language, the $var variable in the example above is interpreted as a
string when the concatenation operator is used).
Functions related to the types of variables in PHP
Several functions allow you to manipulate the type of a variable in PHP; we enumerate below a
few of them (the list is in no way exhaustive):
isset() returns TRUE if the PHP variable it receives has been set and FALSE otherwise.
unset() allows you to "empty" a variable (i.e. to reinitialize it, or in other words to "free" it; in
particular, the variable which is unset will lose its type and will be assigned the NULL value).
gettype() returns the type of the PHP variable it receives (cf. example above).
is_string() returns TRUE if the variable received is a string, FALSE otherwise. By the same token,
you can use the functions is_integer(), is_float(), is_array(), etc ...
PHP variables - Assignment of variables in PHP
There are two ways to assign a variable in PHP.
Assignment by value
With the assignment by value (which is the most often used way to define a variable), a variable
is assigned a value only. For instance, setting $var2 = $var1 will assign the value of $var1 to
the new variable $var2; if later on in the script the variable $var1 is changed, the variable $var2
will remain unchanged ($var2 will keep the value at which it was first defined). The example
below is illustrating the assignment of PHP variables by value.
Learn the HTML code:
<html>
<body>
<?php
$var1 = 1;
$var2 =
$var1;
echo $var2.'
';
$var1 = 0;
echo $var2;
?>
</body>
</html>
Assignment by reference
After you assign a variable by reference, the variable points to a location in memory instead of
merely storing a given value as in an assignment by value. A sa result, the value of this variable
will be modified whenever the value stored at this memory address is changed.
When you are assigning a variable $var1 by reference to another variable $var2, the only
difference in the PHP syntax is that you must add an ampersand & before $var1:
Learn the PHP code:
<html>
<body>
<?php
$var1 = 1;
$var2 =
~$var1;
echo
$var2.'<br>';
$var1 = 0;
echo $var2;
?>
</body>
</html>
print_between_stars();
?>
</body>
</html>
Explanation:
In the example above, $var1 is considered as a local variable within the function
print_between_stars(). Therefore, its previous definition won't be taken into account, so that
calling the function print_between_stars() will return nothing but two stars (along with a warning
stating that $var1 hasn't been set).
If you want to be able to use the first instantiation of $var1 within the function, you must first
declare it as global within the function:
Learn the PHP code:
<html>
$var1 = 1;
function
print_between_stars()
{
global $var1;
echo '*'.$var1.'*';
}
print_between_stars();
<body>
<?php
?>
</body>
</html>
Static variables
A static variable is local within a function but keeps its value after the function has been
executed (unlike purely local functions which are reinitialized upon execution of the function, i.e.
after a change in scope)).
PHP Constants
A constant is a name to which is assigned a constant value (constant because it won't be able to
be changed during the script execution; additionally, a constant automatically has a global
scope). It is defined according to the syntax define("CONSTANT_NAME",VALUE), where
CONSTANT_NAME is the name of your constant and VALUE its value.
Learn the PHP code:
<html>
<body>
<?php
define("MY_CONSTANT",
2);
echo MY_CONSTANT;
?>
</body>
</html>
introduced later in the next PHP tutorials), is automatically a global variable, meaning that it can
be accessed from anywhere in the script. For this reason, it is called a superglobal variable.
For instance, one of our examples above could be rewritten:
Learn the PHP code:
<html>
<body>
<?php
$var1 = 1;
function
print_between_stars()
{
echo '*'.
$GLOBALS['var1'].'*';
}
print_between_stars();
?>
</body>
</html>
The result returned is the same as if the variable $var1 had been declared global by using the
keyword global within the function.
</html>
Remarks:
A new PHP variable called $new has been created by the variable variable $$var.
In the same way, it is possible to define variable variable variables (of the form $$$var), etc ...
this is done iteratively starting from the definition of a variable variable.
A PHP variable can have different types but no definition of type is needed since it is
automatically determined when the variable is assigned a value: PHP is indeed a very weakly
typed programming language, which offers you great flexibility but also requires great attention
(because it is easier to make mistakes when types are not defined beforehand by the
programmer).
A PHP variable can be assigned by value (in which case the PHP variable simply stores a value)
or by reference (in which case the PHP variable stores a pointer to a location in memory;
therefore, the value of the variable will change whenever the value located at this memory
address is changed).
A PHP variable can have different scopes (local, global) and there exist some reserved predefined
variables which can be used anywhere in the script: because such variables are automatically
global, they are called superglobals (or superglobal variables).
Variable variables can be used to dynamically generate new PHP variables as the execution of
your PHP script unfolds: it can prove to be practical whenever you do not know beforehand the
names of the variables that will have to be generated.
Arrays
An array stores multiple values in one single variable.
What is an Array?
A variable is a storage area holding a number or text. The problem is, a variable will hold only
one value.
An array is a special variable, which can store multiple values in one single variable.
If you have a list of items (a list of car names, for example), storing the cars in single variables
could look like this:
However, what if you want to loop through the cars and find a specific one? And what if you had
not 3 cars, but 300?
The best solution
$cars1="Saab";
$cars2="Volvo";
$cars3="BMW";
here is to use an array!
An array can hold all your variable values under a single name. And you can access the values by
referring to the array name.
Each element in the array has its own index so that it can be easily accessed.
In PHP, there are three kind of arrays:
Numeric array - An array with a numeric index
Associative array - An array where each ID key is associated with a value
Multidimensional array - An array containing one or more array
Numeric Arrays
A numeric array stores each array element with a numeric index.
There are two methods to create a numeric array.
1. In the following example the index are automatically assigned (the index starts at 0):
$cars=array("Saab","Volvo","BMW","Toyota");
2. In the following example we assign the index manually:
$cars[0]="Saab";
$cars[1]="Volvo";
$cars[2]="BMW";
$cars[3]="Toyota";
Example
In the following example you access the variable values by referring to the array name and
index:
<?php
$cars[0]="Saab";
$cars[1]="Volvo";
$cars[2]="BMW";
$cars[3]="Toyota";
echo $cars[0] . " and " . $cars[1] . " are Swedish cars.";
?>
The code above will output:
Saab and Volvo are Swedish cars.
Associative Arrays
An associative array, each ID key is associated with a value.
When storing data about specific named values, a numerical array is not always the best way to
do it.
With associative arrays we can use the values as keys and assign values to them.
Example 1
In this example we use an array to assign ages to the different persons:
$ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34);
Example 2
This example is the same as example 1, but shows a different way of creating the array:
$ages['Peter'] = "32";
$ages['Quagmire'] = "30";
$ages['Joe'] = "34";
The ID keys can be used in a script:
<?php
$ages['Peter'] = "32";
$ages['Quagmire'] = "30";
$ages['Joe'] = "34";
echo "Peter is " . $ages['Peter'] . " years old.";
?>
Multidimensional Arrays
In a multidimensional array, each element in the main array can also be an array. And each
element in the sub-array can be an array, and so on.
Example
In this example we create a multidimensional array, with automatically assigned ID keys:
$families = array
(
"Griffin"=>array
(
"Peter",
"Lois",
"Megan"
),
"Quagmire"=>array
(
"Glenn"
),
"Brown"=>array
(
"Cleveland",
"Loretta",
"Junior"
) );
The array above would look like this if written to the output:
Array
(
[Griffin] => Array
(
[0] => Peter
[1] => Lois
output
Is Megan a part of the Griffin family?
</body>
</html>
Output could be something like this:
Welcome John!
You are 28 years old.
The PHP $_GET and $_POST functions will be explained in the next chapters.
Form Validation
User input should be validated on the browser whenever possible (by client scripts). Browser
validation is faster and reduces the server load.
You should consider server validation if the user input will be inserted into a database. A good
way to validate a form on the server is to post the form to itself, instead of jumping to a different
page. The user will then get the error messages on the same page as the form. This makes it
easier to discover the error.
output-
Hello World
Now, lets try to use some different functions and operators to manipulate the string.
If we look at the code above you see that we used the concatenation operator two times. This is
because we had to insert a third string (a space character), to separate the two strings.
output-12
The length of a string is often used in loops or other functions, when it is important to know when
the string ends. (i.e. in a loop, we would want to stop the loop after the last character in the
string).
output-6
The position of the string "world" in the example above is 6. The reason that it is 6 (and not 7), is
that the first character position in the string is 0, and not 1.
Description
servername
username
Optional. Specifies the username to log in with. Default value is the name of
the user that owns the server process
password
Note: There are more available parameters, but the ones listed above are the most important.
Example
In the following example we store the connection in a variable ($con) for later use in the script.
The "die" part will be executed if the connection fails:
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// some code
?>
Closing a Connection
The connection will be closed automatically when the script ends. To close the connection before,
use the mysql_close() function:
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// some code
mysql_close($con);
?>
Note that this configuration has to be done on the computer where your web site is located. If
you are running Internet Information Server (IIS) on your own computer, the instructions above
will work, but if your web site is located on a remote server, you have to have physical access to
that server, or ask your web host to to set up a DSN for you to use.
Connecting to an ODBC
The odbc_connect() function is used to connect to an ODBC data source. The function takes four
parameters: the data source name, username, password, and an optional cursor type.
The odbc_exec() function is used to execute an SQL statement.
Example
The following example creates a connection to a DSN called northwind, with no username and no
password. It then creates an SQL and executes it:
$conn=odbc_connect('northwind','','');
$sql="SELECT * FROM customers";
$rs=odbc_exec($conn,$sql);
Retrieving Records
The odbc_fetch_row() function is used to return records from the result-set. This function returns
true if it is able to return rows, otherwise false.
The function takes two parameters: the ODBC result identifier and an optional row number:
odbc_fetch_row($rs)
An ODBC Example
The following example shows how to first create a database connection, then a result-set, and
then display the data in an HTML table.
<html>
<body>
<?php
$conn=odbc_connect('northwind','','');
if (!$conn)
{exit("Connection Failed: " . $conn);}
$sql="SELECT * FROM customers";
$rs=odbc_exec($conn,$sql);
if (!$rs)
{exit("Error in SQL");}
echo "<table><tr>";
echo "<th>Companyname</th>";
echo "<th>Contactname</th></tr>";
while (odbc_fetch_row($rs))
{
$compname=odbc_result($rs,"CompanyName");
$conname=odbc_result($rs,"ContactName");
echo "<tr><td>$compname</td>";
echo "<td>$conname</td></tr>";
}
odbc_close($conn);
echo "</table>";
?>
</body>
Create a Database
The CREATE DATABASE statement is used to create a database in MySQL.
Syntax
CREATE DATABASE database_name
To learn more about SQL, please visit our.
To get PHP to execute the statement above we must use the mysql_query() function. This
function is used to send a query or command to a MySQL connection.
Example
The following example creates a database called "my_db":
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
if (mysql_query("CREATE DATABASE my_db",$con))
{
echo "Database created";
}
else
{
echo "Error creating database: " . mysql_error();
}
mysql_close($con);
?>
Create a Table
The CREATE TABLE statement is used to create a table in MySQL.
Syntax
CREATE TABLE table_name
(
column_name1 data_type,
column_name2 data_type,
column_name3 data_type,
....
)
To learn more about SQL, please visit our.
We must add the CREATE TABLE statement to the mysql_query() function to execute the
command.
Example
The following example creates a table named "Persons", with three columns. The column names
will be "FirstName", "LastName" and "Age":
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// Create database
if (mysql_query("CREATE DATABASE my_db",$con))
{
echo "Database created";
}
else
{
echo "Error creating database: " . mysql_error();
}
// Create table
mysql_select_db("my_db", $con);
$sql = "CREATE TABLE Persons
(
FirstName varchar(15),
LastName varchar(15),
Age int
)";
// Execute query
mysql_query($sql,$con);
mysql_close($con);
?>
Important: A database must be selected before a table can be created. The database is
selected with the mysql_select_db() function.
Note: When you create a database field of type varchar, you must specify the maximum length
of the field, e.g. varchar(15).
The data type specifies what type of data the column can hold. For a complete reference of all
the data types available in MySQL, go to our complete.
Example
$sql = "CREATE TABLE Persons
(
personID int NOT NULL AUTO_INCREMENT,
PRIMARY KEY(personID),
FirstName varchar(15),
LastName varchar(15),
Age int
)";
mysql_query($sql,$con);
(Adding Strings and Numbers)The rule is: If you add a number and
a string, the result will be a string!
Example
x=5+5;
document.write(x);
x="5"+"5";
document.write(x);
x=5+"5";
document.write(x);
x="5"+5;
document.write(x);
MySQL - Triggers
Write syntax for Creating triggers and Dropping Triggers along with example
for each of them.
Create trigger
Syntax:
Create trigger trigger_name
ON table_name
{
FOR [delete][update][insert]
AS
Sql statements
}
Example:
CREATE TRIGGER reminder
ON titles
FOR INSERT, UPDATE
AS some_function (50009, 16, 10)
Drop a trigger
Syntax
DROP TRIGGER Trigger_name
Example:
Drop trigger reminder
Sql statement
Update trigger: this trigger is invoked after or before an update on some table.
Example:
CREATE TRIGGER new_employee
After UPDATE ON employee
FOR EACH ROW
Sql statement
Delete trigger: this trigger is invoked after or before an delete on some table.
Example:
CREATE TRIGGER new_employee
After DELETE ON employee
FOR EACH ROW
Sql statement
2. What do you expect the trigger to do? This can be INSERT UPDATE DELETE
3. On which table you want the trigger to run? (using ON table_name)
4. Lastly, though not mandatory, is FOR EACH ROW if it is used then the trigger will fire once for
all records of the table. If it is not specified the trigger will fire once only regardless of the
number of records being updated
Using the show triggers statement. Show trigger lists the triggers currently defined for
tables in a database.
Example
SHOW TRIGGERS LIKE emp%\G
The Triggers table can be queried. The triggers table provides the information about the
triggers. The table has a variety of INFORMATION SCHEMA that can be queried.
</p>
<p align="left"> <br>
</p>
</form>
<?php
$totalprice = 0;
foreach($cd as $cd)
$totalprice += $cd;
echo "$totalprice";
/*if(isset($_POST['$cd']))
echo 'checked';*/
?>
PHP CODE FOR ACTION
}
include 'closedb.php';
?>
The while() loop will keep fetching new rows until mysql_fetch_array() returns FALSE, which
means there are no more rows to fetch. The content of the rows are assigned to the variable
$row and the values in row are then printed. Always remember to put curly brackets when you
want to insert an array value directly into a string.
In above example I use the constant MYSQL_ASSOC as the second argument to
mysql_fetch_array(), so that it returns the row as an associative array. With an
associative array you can access the field by using their name instead of using the
index . Personally I think it's more informative to use $row['subject'] instead of $row[1].
PHP also provide a function called mysql_fetch_assoc() which also return the row as an
associative array.
<?php
include 'config.php';
include 'opendb.php';
$query = "SELECT name, subject, message FROM contact";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result))
{
echo "Name :{$row['name']} <br>" .
"Subject : {$row['subject']} <br>" .
"Message : {$row['message']} <br><br>";
}
include 'closedb.php';
?>
You can also use the constant MYSQL_NUM, as the second argument to
mysql_fetch_array(). This will cause the function to return an array with numeric index.
<?php
include 'config.php';
include 'opendb.php';
$query = "SELECT name, subject, message FROM contact";
$result = mysql_query($query);
while($row = mysql_fetch_array($result, MYSQL_NUM))
{
echo "Name :{$row[0]} <br>" .
"Subject : {$row[0]} <br>" .
"Message : {$row[0]} <br><br>";
}
include 'closedb.php';
?>
Using the constant MYSQL_NUM with mysql_fetch_array() gives the same result as the
function mysql_fetch_row().
There is another method for you to get the values from a row. You can use list(), to
assign a list of variables in one operation.
<?php
include 'config.php';
include 'opendb.php';
$query = "SELECT name, subject, message FROM contact";
$result = mysql_query($query);
while(list($name,$subject,$message)= mysql_fetch_row($result))
{
echo "Name :$name <br>" .
"Subject : $subject <br>" .
"Message : $row <br><br>";
}
include 'closedb.php';
?>
In above example, list() assign the values in the array returned by mysql_fetch_row()
into the variable $name, $subject and $message.
Of course you can also do it like this
<?php
include 'config.php';
include 'opendb.php';
$query = "SELECT name, subject, message FROM contact";
$result = mysql_query($query);
while($row = mysql_fetch_row($result))
{
$name = $row[0];
$subject = $row[1];
$message = $row[2];
echo "Name :$name <br>" .
"Subject : $subject <br>" .
"Message : $row <br><br>";
}
include 'closedb.php';
?>
So you see you have lots of choices in fetching information from a database. Just
$tsv = array();
$html = array();
while($row = mysql_fetch_array($result, MYSQL_NUM))
{
$tsv[] = implode("\t", $row);
$html[] = "<tr><td>" .implode("</td><td>", $row) .
}
"</td></tr>";
$_SERVER['QUERY_STRING']
We should be very careful when appending new variables to query string, because as I showed
above, some time query string can be empty and sometimes it can already contains some
variables, because of this before appending new variable, we should check if we have to append
ampersand character (&) before or not. This can be done by simple if statement presented
below. Below code example also uses $_SERVER["PHP_SELF"], which returns script name
<?php
$self = $_SERVER["PHP_SELF"];
if($_SERVER["QUERY_STRING"]) {
$finalurl = $self . "?" . $_SERVER["QUERY_STRING"] .
"&myvariable=myvalue";
} else {
$finalurl = $self . "?" . "myvariable=myvalue";
}
?>
Query string can be accessed thru global array $_SERVER, more specific
$_SERVER['QUERY_STRING'] is the actual variable where query string is written, this variable
contains all data that is inputed after question mark in the URL. For example if we have URL
which looks like this:
http://someurl.com/page.php?a=1&b=2&c=3
Then echo $_SERVER['QUERY_STRING'] will display: a=1&b=2&c=3, such data is no use to us, we
need to parse it, or get it thru global array $_GET, in our case we could write:
echo $_GET['a'];
echo $_GET['b'];
echo $_GET['c'];
which would output:
1
2
3
Using $_GET array to access variables from query string is pretty simple, however we would want
to transform our URL to make it look like this:
A PHP function that will add the querystring variable $key with a value $value to $url. If $key is
already specified within $url, it will replace it.
plainpop-up
1. function add_querystring_var($url, $key, $value) {
2.
$url = preg_replace('/(.*)(?|&)' . $key . '=[^&]+?(&)(.*)/i', '$1$2$4', $url . '&');
3.
$url = substr($url, 0, -1);
4.
if (strpos($url, '?') === false) {
5.
return ($url . '?' . $key . '=' . $value);
6.
} else {
7.
return ($url . '&' . $key . '=' . $value);
8.
}
9. }
FOREACH Loop
FOREACH is used in PHP to loop over all elements of an array. The basic syntax of FOREACH is as
follows:
FOREACH ($array_variable as $value)
{
[code to execute]
}
or
FOREACH ($array_variable as $key => $value)
{
[code to execute]
}
In both cases, the number of times [code to execute] will be executed is equal to the number of
elements in the $array_variable array.
Let's look at an example. Assuming we have the following piece of code:
$array1 = array(1,2,3,4,5);
FOREACH ($array1 as $abc)
{
print "new value is " . $abc*10 . "<br>";
}
The output of the above code is:
new
new
new
new
new
value
value
value
value
value
is
is
is
is
is
10
20
30
40
50
The FOREACH loop above went through all 5 elements of array $array1, and each time prints out
a statement containing 10x the array element value.
PHP : $_SERVER
$_SERVER has following basic properties:
1. Set by web server.
2. Directly related to the runtime environment of the current php script.
3. It does the same job as $HTTP_SERVER_VARS used to do in previous versions of PHP
Here we discuss the elements which can exist within the $_SERVER.
PHP : $_SERVER['PHP_SELF']
You can find the filename of the currently executing script by using $_SERVER['PHP_SELF'].
Filename shown as output is relative to the root of the document.
Following php code used $_SERVER['PHP_SELF']
<?php
echo $SERVER['PHP_SELF'];
?>
Basic knowledge of array is a prerequisite of this example. You can get back to this
example after you learn php array. The following PHP code compares the array elements
with the $_SERVER['PHP_SELF'] and displays a message.
<?php
$findit=array('/php/super-variables/test.php',
'/php/super-variables/test1123.php',
'/php/super-variables/php-self-advanced-example1.php'
);
for ($j=0; $j<count($findit); $j++)
{
if ($_SERVER['PHP_SELF']==$findit[$j])
echo "You are learning PHP Super Globals";
}
?>
document.formName.submit();
}
// -->
</script>
<form name="formName" action="url" method="post">
<a href="javascript:mySubmit()>Submit Me</a>
</form>
PHP Cookies
A cookie is often used to identify a user.
What is a Cookie?
A cookie is often used to identify a user. A cookie is a small file that the server embeds on the
user's computer. Each time the same computer requests a page with a browser, it will send the
cookie too. With PHP, you can both create and retrieve cookie values.
How to Create a Cookie?
The setcookie() function is used to set a cookie.
Note: The setcookie() function must appear BEFORE the <html> tag.
Syntax
setcookie(name, value, expire, path, domain);
Example 1
In the example below, we will create a cookie named "user" and assign the value "Alex Porter" to
it. We also specify that the cookie should expire after one hour:
<?php
setcookie("user", "Alex Porter", time()+3600);
?>
<html>
.....
Note: The value of the cookie is automatically URLencoded when sending the cookie, and
automatically decoded when received (to prevent URLencoding, use setrawcookie() instead).
Example 2
You can also set the expiration time of the cookie in another way. It may be easier than using
seconds.
<?php
$expire=time()+60*60*24*30;
If your application deals with browsers that do not support cookies, you will have to use other
methods to pass information from one page to another in your application. One method is to
pass the data through forms (forms and user input are described earlier in this tutorial).
The form below passes the user input to "welcome.php" when the user clicks on the "Submit"
button:
<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="name" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
</body>
</html>
Retrieve the values in the "welcome.php" file like this:
<html>
<body>
Welcome <?php echo $_POST["name"]; ?>.<br />
You are <?php echo $_POST["age"]; ?> years old.
</body>
</html>
include()
The include() statement includes and evaluates the specified file.
For more information on how PHP handles including files and the include path, see the
documentation for include_path.
When a file is included, the code it contains inherits the variable scope of the line on which the
include occurs. Any variables available at that line in the calling file will be available within the
called file, from that point forward. However, all functions and classes defined in the included file
have the global scope.
If the include occurs inside a function within the calling file, then all of the code contained in the
called file will behave as though it had been defined inside that function. So, it will follow the
variable scope of that function. An exception to this rule are magic constants which are
evaluated by the parser before the include occurs.
?>
These two functions are used to create functions, headers, footers, or elements that will be
reused on multiple pages.
Server side includes saves a lot of work. This means that you can create a standard header,
footer, or menu file for all your web pages. When the header needs to be updated, you can only
update the include file, or when you add a new page to your site, you can simply change the
menu file (instead of updating the links on all your web pages).
href="/default.php">Home</a>
href="/tutorials.php">Tutorials</a>
href="/references.php">References</a>
href="/examples.php">Examples</a>
PHP Tools
Here is some PHP information that you may find useful.
Dynamic Site Map with PHP
Script: This is a script, written in PHP, that will generate a site map based on the directory
structure of the site. You can easily exclude files and/or directories.
Forcing a Download Dialog
A fairly common question is, "How can I force a file to download to the user?" The answer
is, you really cannot. What you can do is force a download dialog box that gives the user a
choice to open or save a linked file, or to cancel the request.
Form to E-mail Processing
Tutorial: A tutorial on how you can use PHP to process form submissions and send the
results to an e-mail address.
Multiple Page Forms
Tutorial: So you have this long, involved form. Rather than present the user with a myriad
of inputs on a single page, you want to break this up into separate form pages. So now
you're asking, "How do you make multiple page forms?"
Processing XML/RSS with PHP
In the beginning, the Internet was a simple mechanism for exchanging text data. Various
markup tags were devised to represent various levels of text headings, paragraphs, lists,
etc. At that time, those tags were sufficient to represent the data being exchanged. Now,
more types of data are being represented and that data is being displayed on a variety of
devices, not just visual web browsers.
Send a Link to a Friend
Script: Ready to run form that will allow you to put a link on your page to send a link to a
friend.
Setting up a virtual host in Apache
Tutorial: Setting up a virtual host in the Apache web server is not exactly a PHP topic, but
many PHP developers use the Apache web server to test web pages on their development
machine.
Error message:
Warning: include(wrongFile.php) [function.include]:
failed to open stream:
No such file or directory in C:\home\website\test.php on line 5
Warning: include() [function.include]:
Failed opening 'wrongFile.php' for inclusion
(include_path='.;C:\php5\pear')
in C:\home\website\test.php on line 5
Hello World!
Notice that the echo statement is executed! This is because a Warning does not stop the script
execution.
Error Example require() Function
Now, let's run the same example with the require() function.
<html>
<body>
<?php
require("wrongFile.php");
echo "Hello World!";
?>
</body>
</html>
Error message:
Warning: require(wrongFile.php) [function.require]:
failed to open stream:
No such file or directory in C:\home\website\test.php on line 5
Fatal error: require() [function.require]:
Failed opening required 'wrongFile.php'
(include_path='.;C:\php5\pear')
in C:\home\website\test.php on line 5
The echo statement is not executed, because the script execution stopped after the fatal error.
It is recommended to use the require() function instead of include(), because scripts should not
continue after an error.
alias. Even so, if youre writing a document which will contain a large number of underscore
characters, the prospect of typing \_ for every one of them will daunt most ordinary people.
Moderately skilled macro programmers can readily generate a quick hack to permit typing _ to
mean text underscore (the answer in defining characters as macros uses this example to
illustrate its techniques). However, the code is somewhat tricky, and more importantly there are
significant points where its easy to get it wrong. There is therefore a package underscore which
provides a general solution to this requirement.
There is a problem, though: OT1 text fonts dont contain an underscore character, unless theyre
in the typewriter version of the encoding (used by fixed-width fonts such as cmtt). In place of
such a character, LaTeX (in OT1 encoding) uses a short rule for the command \textunderscore, but
this poses problems for systems that interpret PDF for example those PDF-to-voice systems
used by those who find reading difficult.
So either you must ensure that your underscore characters only occur in text set in a typewriter
font, or you must use a more modern encoding, such as T1, which has the same layout for every
font, and thus an underscore in every font.
A stable procedure to achieve this is:
% (1) choose a font that is available as T1
% for example:
\usepackage{lmodern}
% (2) specify encoding
\usepackage[T1]{fontenc}
% (3) load symbol definitions
\usepackage{textcomp}
which will provide a command \textunderscore which robustly selects the right character. The
underscore package, mentioned above, will use this command.
What is Localhost?
"Localhost" refers to the local computer that a program is running on. For example, if you are running a
Web browser on your computer, your computer is considered to be the "localhost." While this does not
need to be specified when using a single computer, the localhost does need to be defined when running
programs from multiple computers. For example, a network administrator might use his local machine to
start a Web server on one system and use a remote access program on another. These programs would
run from computers other than the localhost.
In the example above, the two non-local computers must be defined by their IP addresses. The local
machine is defined as "localhost," which gives it an IP address of 127.0.0.1. This is considered a
"loopback" address because the information sent to it is routed back to the local machine. Localhost is
often used in Web scripting languages like PHP and ASP when defining what server the code should run
from or where a database is located.
enctype is an abbreviation of 'encoding type', it is used to tell the browser the MIME type of the
data being transferred, the default MIME type is 'application/x-www-form-urlencoded' and is not
even necessary to input, but if the form type is uploading an image or another media type then
the 'enctype' will have to be set for media encoding, 'multipart/form-data'.
The get method is different in that it passes the variables along to the "process.php" web page
by appending them onto the end of the URL. The URL, after clicking submit, would have this
added on to the end of it:
"?item=##&quantity=##"
The question mark "?" tells the browser that the following items are variables. Now that we
changed the method of sending information on "order.html", we must change the "process.php"
code to use the "$_GET" associative array.
After changing the array name the script will function properly. Using the get method displays the
variable information to your visitor, so be sure you are not sending password information or other
sensitive items with the get method. You would not want your visitors seeing something they are
not supposed to!
Example
<form action="welcome.php" method="post">
Name: <input type="text" name="fname" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
When the user clicks the "Submit" button, the URL will look like this:
http://www.w3schools.com/welcome.php
The "welcome.php" file can now use the $_POST function to collect form data (the names of the
form fields will automatically be the keys in the $_POST array):
Welcome <?php echo $_POST["fname"]; ?>!<br />
You are <?php echo $_POST["age"]; ?> years old.
POST - Review
In our PHP Forms Lesson we used the post method. This is what the pertinent line of HTML code
looked like:
This HTML code specifies that the form data will be submitted to the "process.php" web page
using the POST method. The way that PHP does this is to store all the "posted" values into an
associative array called "$_POST". Be sure to take notice the names of the form data names, as
they represent the keys in the "$_POST" associative array.
Now that you know about associative arrays, the PHP code from "process.php" should make a
litte more sense.
The form names are used as the keys in the associative array, so be sure that you never have
two input items in your HTML form that have the same name. If you do, then you might see some
problems arise.
Example
Welcome <?php echo $_REQUEST["fname"]; ?>!<br />
You are <?php echo $_REQUEST["age"]; ?> years old.
Description
PHP
addcslashes()
addslashes()
bin2hex()
chop()
Alias of rtrim()
chr()
chunk_split()
convert_cyr_string()
convert_uudecode()
convert_uuencode()
count_chars()
crc32()
crypt()
echo()
Outputs strings
explode()
fprintf()
get_html_translation_table()
hebrev()
hebrevc()
html_entity_decode()
htmlentities()
htmlspecialchars_decode()
htmlspecialchars()
implode()
join()
Alias of implode()
levenshtein()
localeconv()
ltrim()
md5()
md5_file()
metaphone()
money_format()
nl_langinfo()
nl2br()
number_format()
ord()
parse_str()
print()
Outputs a string
printf()
quoted_printable_decode()
quotemeta()
rtrim()
setlocale()
sha1()
sha1_file()
similar_text()
soundex()
sprintf()
sscanf()
str_ireplace()
str_pad()
str_repeat()
str_replace()
str_split()
str_word_count()
strcasecmp()
strchr()
strcmp()
strcoll()
strcspn()
strip_tags()
stripcslashes()
stripslashes()
stripos()
stristr()
strlen()
strnatcasecmp()
strnatcmp()
strncasecmp()
strncmp()
strpbrk()
strpos()
strrchr()
strrev()
Reverses a string
strripos()
strrpos()
strspn()
strstr()
strtok()
strtolower()
strtoupper()
strtr()
substr()
substr_compare()
substr_count()
substr_replace()
trim()
ucfirst()
ucwords()
vfprintf()
vprintf()
vsprintf()
Description
PHP
array()
Creates an array
array_change_key_case()
array_chunk()
array_combine()
array_count_values()
array_diff()
array_diff_assoc()
array_diff_key()
array_diff_uassoc()
array fill()
array filter()
array flip()
array intersect()
array_intersect_assoc()
array_intersect_key()
array_intersect_uassoc()
array_intersect_ukey()
array_key_exists()
array_keys()
array_map()
array_merge()
array_merge_recursive()
array_multisort()
array_pad()
array_pop()
array_product()
array_push()
array_rand()
array_reduce()
array_reverse()
array_search()
array_shift()
array_slice()
array_splice()
array_sum()
array_udiff()
array_udiff_assoc()
array_udiff_uassoc()
array_uintersect()
array_uintersect_assoc()
4
5
array_unique()
array_unshift()
array_values()
array_walk()
array_walk_recursive()
arsort()
asort()
compact()
count()
current()
each()
end()
extract()
in_array()
key()
krsort()
ksort()
list()
natcasesort()
natsort()
next()
pos()
Alias of current()
prev()
range()
reset()
rsort()
shuffle()
Shuffles an array
sizeof()
Alias of count()
sort()
Sorts an array
uasort()
uksort()
usort()
Runtime Configuration
The behavior of the date/time functions is affected by settings in php.ini.
Date/Time configuration options:
Name
Default
Description
Changeable
date.default_latitu "31.7667"
de
PHP_INI_ALL
date.default_longit "35.2333"
ude
date.sunrise_zenit "90.83"
h
PHP_INI_ALL
date.sunset_zenith "90.83"
PHP_INI_ALL
date.timezone
""
Description
PHP
checkdate()
date_default_timezone_get()
date_default_timezone_set()
date_sunrise()
date_sunset()
date()
getdate()
gettimeofday()
gmdate()
gmmktime()
gmstrftime()
idate()
localtime()
microtime()
mktime()
strftime()
strptime()
strtotime()
time()
Function
Description
PHP
chdir()
chroot()
dir()
closedir()
getcwd()
opendir()
readdir()
rewinddir()
scandir()
Description
PHP
debug_backtrace()
Generates a backtrace
debug_print_backtrace()
Prints a backtrace
error_get_last()
error_log()
error_reporting()
restore_error_handler()
restore_exception_handler()
set_error_handler()
set_exception_handler()
trigger_error()
user_error()
Alias of trigger_error()
Description
PHP
E_ERROR
E_WARNING
E_PARSE
E_NOTICE
16
E_CORE_ERROR
32
E_CORE_WARNING
64
E_COMPILE_ERROR
128 E_COMPILE_WARNING
256 E_USER_ERROR
512 E_USER_WARNING
function trigger_error()
1024 E_USER_NOTICE
2048 E_STRICT
4096 E_RECOVERABLE_ERROR
6143 E_ALL
PHP Functions
The real power of PHP comes from its functions.
In PHP, there are more than 700 built-in functions.
PHP Functions
In this chapter we will show you how to create your own functions.
To keep the script from being executed when the page loads, you can put it into a function.
A function will be executed by a call to the function.
You may call a function from anywhere within a page.
<body>
<?php
function writeName()
{
echo "Kai Jim Refsnes";
}
echo "My name is ";
writeName();
?>
</body>
</html>
Output:
My name is Kai Jim Refsnes
<html>
<body>
<?php
function writeName($fname,$punctuation)
{
echo $fname . " Refsnes" . $punctuation . "<br />";
}
echo "My name is ";
writeName("Kai Jim",".");
echo "My sister's name is ";
writeName("Hege","!");
echo "My brother's name is ";
writeName("Stle","?");
?>
</body>
</html>
Output:
My name is Kai Jim Refsnes.
My sister's name is Hege Refsnes!
My brother's name is Stle Refsnes?
Example
<html>
<body>
<?php
function add($x,$y)
{
$total=$x+$y;
return $total;
}
echo "1 + 16 = " . add(1,16);
?>
</body>
</html>
output
1 + 16 = 17
$Names = array ('a' => 'Angela', 'b' => 'Bradley', 'c' => array ('Cade', 'Caleb'));
print_r ($Names);
?>
The results would be something like:
Array
(
[a] => Angela
[b] => Bradley
[c] => Array
(
[0] => Cade
[1] => Caleb
)
)
Example:
$string="eggs sold here";
$newstring=trim($string,"e");
echo $newstring;
The above will output: ggs sold her
The e at the beginning of the string and the e at the end of the string are stripped out.
Say you only want to strip the e at the right (ie. at the end of the string), then use:
$string="eggs sold here";
$newstring=rtrim($string,"e"); // right trim
echo $newstring;
The above will output: eggs sold her
Say you only want to strip the e at the left (ie. at the start of the string), then use:
$string="eggs sold here";
$newstring=ltrim($string,"e"); // left trim
echo $newstring;
The above will output: ggs sold here
Parameter
Description
separator
Optional. Specifies what to put between the array elements. Default is "" (an
empty string)
array
The implode function will convert the entire array into a string and there is no optional argument
to limit this as there was in the explode function.
Please note the the empty() function only works on variables and it's use on anything else will
produce errors.
Example Usage:
<?
$username='';
if(empty($username))
{
echo "This variable is empty";
}
else
{
echo "This variable is not empty";
}
?>
In the above example, the output will be: This variable is empty. This is because $username has
an empty string '' as value.
PHP Sessions
A PHP session variable is used to store information about, or change settings for a user session.
Session variables hold information about one single user, and are available to all pages in one
application.
Before you can store user information in your PHP session, you must first start up the session.
Note: The session_start() function must appear BEFORE the <html> tag:
<?php session_start(); ?>
<html>
<body>
</body>
</html>
The code above will register the user's session with the server, allow you to start saving user
information, and assign a UID for that user's session.
Output:
Pageviews=1
In the example below, we create a simple page-views counter. The isset() function checks if the
"views" variable has already been set. If "views" has been set, we can increment our counter. If
"views" doesn't exist, we create a "views" variable, and set it to 1:
<?php
session_start();
if(isset($_SESSION['views']))
$_SESSION['views']=$_SESSION['views']+1;
else
$_SESSION['views']=1;
echo "Views=". $_SESSION['views'];
?>
Destroying a Session
If you wish to delete some session data, you can use the unset() or the session_destroy()
function.
The unset() function is used to free the specified session variable:
<?php
unset($_SESSION['views']);
?>
You can also completely destroy the session by calling the session_destroy() function:
<?php
session_destroy();
?>
Note: session_destroy() will reset your session and you will lose all your stored session data.
Runtime Configuration
The behavior of the MySQL functions is affected by settings in the php.ini file.
MySQL configuration options:
Name
Default
Description
Changeable
mysql.allow_persist "1"
ent
PHP_INI_SYSTEM
mysql.max_persiste "-1"
nt
PHP_INI_SYSTEM
mysql.max_links
"-1"
PHP_INI_SYSTEM
mysql.trace_mode
"0"
PHP_INI_ALL
NULL
PHP_INI_ALL
mysql.default_socke NULL
t
PHP_INI_ALL
mysql.default_host
NULL
PHP_INI_ALL
mysql.default_user
NULL
PHP_INI_ALL
mysql.default_pass NULL
word
PHP_INI_ALL
mysql.connect_time "60"
out
PHP_INI_ALL
Resource Types
There are two resource types used in the MySQL extension. The first one is the link_identifier for
a database connection, the second is a resource which holds the result of a query.
Note: Most MySQL functions accept link_identifier as the last optional parameter. If it is not
provided, the last opened connection is used
Description
PHP
mysql_affected_rows()
mysql_change_user()
mysql_client_encoding()
mysql_close()
mysql_connect()
mysql_create_db()
mysql_data_seek()
mysql_db_name()
mysql_db_query()
mysql_drop_db()
mysql_errno()
mysql_error()
mysql_escape_string()
mysql_fetch_array()
mysql_fetch_assoc()
mysql_fetch_field()
mysql_fetch_lengths()
mysql_fetch_object()
mysql_fetch_row()
mysql_field_flags()
mysql_field_len()
mysql_field_name()
mysql_field_seek()
mysql_field_table()
mysql_field_type()
mysql_free_result()
mysql_get_client_info()
mysql_get_host_info()
mysql_get_proto_info()
mysql_get_server_info()
mysql_info()
mysql_insert_id()
mysql_list_dbs()
mysql_list_fields()
mysql_list_processes()
mysql_list_tables()
mysql_num_fields()
mysql_num_rows()
mysql_pconnect()
mysql_ping()
mysql_query()
mysql_real_escape_string()
mysql_result()
mysql_select_db()
mysql_stat()
mysql_tablename()
mysql_thread_id()
Description
The variable being checked
Required /
Optional
Required
Type
Mixed*
*Mixed : Mixed indicates that a parameter may accept multiple (but not necessarily all) types.
Return value
TRUE if var is an array, FALSE otherwise.
Value Type : Boolean.
Example of php is_array() function
<?php
$var_name=array('A','B','C');
if (is_array($var_name))
echo 'This is an array....';
else
echo 'This is not an array....';
?>
Output of the example
This is an array....
Description
Strings
?>
The output of the code above will be:
This string was made with multiple parameters
Example 4
Difference of single and double quotes. Single quotes will print the variable name, not the value:
<?php
$color = "red";
echo "Roses are $color";
echo "<br />";
echo 'Roses are $color';
?>
The output of the code above will be:
Roses are red
Roses are $color
Example 5
Shortcut syntax:
<html>
<body>
<?php
$color = "red";
?>
<p>Roses are <?=$color?></p>
</body>
</html>
PHP - Echo
As you saw in the previous lesson, the PHP command echo is a means of outputting text to the
web browser. Throughout your PHP career you will be using the echo command more than any
other. So let's give it a solid perusal!
Outputting a String
To output a string, like we have done in previous lessons, use PHP echo. You can place either a
string variable or you can use quotes, like we do below, to create a string that the echo function
will output.
PHP Code:
<?php
$myString = "Hello!";
echo $myString;
echo "<h5>I love using PHP!</h5>";
?>
Display:
Hello!
I love using PHP!
In the above example we output "Hello!" without a hitch. The text we are outputting is being sent
to the user in the form of a web page, so it is important that we use proper HTML syntax!
In our second echo statement we use echo to write a valid Header 5 HTML statement. To do this
we simply put the <h5> at the beginning of the string and closed it at the end of the string. Just
because you're using PHP to make web pages does not mean you can forget about HTML sy ntax!
See our example below for the right and wrong use of echo:
PHP Code:
<?php
// This won't work because of the quotes around specialH5!
echo "<h5 class="specialH5">I love using PHP!</h5>";
// OK because we escaped the quotes!
echo "<h5 class=\"specialH5\">I love using PHP!</h5>";
// OK because we used an apostrophe '
echo "<h5 class='specialH5'>I love using PHP!</h5>";
?>
If you want to output a string that includes quotations, either use an apostrophe ( ' ) or escape
the quotations by placing a backslash in front of it ( \" ). The backslash will tell PHP that you want
the quotation to be used within the string and NOT to be used to end echo's string.
Echoing Variables
Echoing variables is very easy. The PHP developers put in some extra work to make the common
task of echoing all variables nearly foolproof! No quotations are required, even if the variable
does not hold a string. Below is the correct format for echoing a variable.
PHP Code:
<?php
$my_string = "Hello Bob. My name is: ";
$my_number = 4;
$my_letter = a;
echo $my_string;
echo $my_number;
echo $my_letter;
?>
Display:
Hello Bob. My name is: 4a
Note: The echo() function is not actually a function, so you are not required to use parentheses
with it. However, if you want to pass more than one parameter to echo(), using parentheses will
generate a parse error.
Tip: The echo() function is slightly faster than print().
Tip: The echo() function has the following shortcut syntax. See example 5.
Example 1
<?php
$str = "Who's Kai Jim?";
echo $str;
echo "<br />";
echo $str."<br />I don't know!";
?>
Difference of single and double quotes. Single quotes will print the variable name, not the value:
<?php
$color = "red";
echo "Roses are $color";
echo "<br />";
echo 'Roses are $color';
?>
Outputs
echo "John
Smith";
John Smith
echo 'John
Smith';
John Smith
echo 699;
699
echo "John
Smith"
echo John
Smith;
Parameter
Description
data
Required. Specifies which data pointer to use. The data pointer is the result
from the mysql_query() function
Example
<?php
$con = mysql_connect("localhost", "peter", "abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db("test_db",$con);
$sql = "SELECT * FROM person";
$result = mysql_query($sql,$con);
echo mysql_num_rows($result);
mysql_close($con);
?>
Parameter
Description
data
Required. Specifies which data pointer to use. The data pointer is the result
Refsnes
Kai Jim
Taugata 2
22
mysql_fetch_row
mysql_fetch_row Get a result row as an enumerated array
array mysql_fetch_row ( resource $result )
Returns a numerical array that corresponds to the fetched row and moves the internal data
pointer ahead.
The result resource that is being evaluated. This result comes from a call to mysql_query().
Returns an numerical array of strings that corresponds to the fetched row, or FALSE if there are
no more rows.
mysql_fetch_row() fetches one row of data from the result associated with the specified result
identifier. The row is returned as an array. Each result column is stored in an array offset, starting
at offset 0.
Parameter
Description
data
Required. Specifies which data pointer to use. The data pointer is the result
from the mysql_query() function
array_type
mysql_fetch_assoc
mysql_fetch_assoc Fetch a result row as an associative array
Report a bug
Description
array mysql_fetch_assoc ( resource $result )
Returns an associative array that corresponds to the fetched row and moves the internal data
pointer ahead. mysql_fetch_assoc() is equivalent to calling mysql_fetch_array() with
MYSQL_ASSOC for the optional second parameter. It only returns an associative array.
Parameters
result
The result resource that is being evaluated. This result comes from a call to mysql_query().
Return Values
Returns an associative array of strings that corresponds to the fetched row, or FALSE if there are
no more rows.
If two or more columns of the result have the same field names, the last column will take
precedence. To access the other column(s) of the same name, you either need to access the
result with numeric indices by using mysql_fetch_row() or add alias names. See the example at
the mysql_fetch_array() description about aliases.
Examples
Example #1 An expanded mysql_fetch_assoc() example
<?php
$conn = mysql_connect("localhost", "mysql_user", "mysql_password");
if (!$conn) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
if (!mysql_select_db("mydbname")) {
echo "Unable to select mydbname: " . mysql_error();
exit;
}
$sql = "SELECT id as userid, fullname, userstatus
FROM sometable
WHERE userstatus = 1";
$result = mysql_query($sql);
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
// While a row of data exists, put that row in $row as an associative array
// Note: If you're expecting just one row, no need to use a loop
// Note: If you put extract($row); inside the following loop, you'll
//
then create $userid, $fullname, and $userstatus
while ($row = mysql_fetch_assoc($result)) {
echo $row["userid"];
echo $row["fullname"];
echo $row["userstatus"];
}
mysql_free_result($result);
?>
Note: Performance
An important thing to note is that using mysql_fetch_assoc() is not significantly slower
than using mysql_fetch_row(), while it provides a significant added value.
Note: Field names returned by this function are case-sensitive.
Note: This function sets NULL fields to the PHP NULL value.
Parameter
Description
data
Required. Specifies which data pointer to use. The data pointer is the result
mysql_fetch_object
mysql_fetch_object Fetch a result row as an object
Description
object mysql_fetch_object ( resource $result [, string $class_name [, array $params ]] )
Returns an object with properties that correspond to the fetched row and moves the internal data
pointer ahead.
Parameters
result
The result resource that is being evaluated. This result comes from a call to mysql_query().
class_name
The name of the class to instantiate, set the properties of and return. If not specified, a stdClass
object is returned.
params
Notes
Note: Performance
Speed-wise, the function is identical to mysql_fetch_array(), and almost as quick as
mysql_fetch_row() (the difference is insignificant).
Note:
mysql_fetch_object() is similar to mysql_fetch_array(), with one difference - an
object is returned, instead of an array. Indirectly, that means that you can only
access the data by the field names, and not by their offsets (numbers are illegal
property names).
Note: Field names returned by this function are case-sensitive.
Note: This function sets NULL fields to the PHP NULL value.
Parameter
Description
data
Required. Specifies which data pointer to use. The data pointer is the result
from the mysql_query() function
{
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db("test_db",$con);
$sql = "SELECT * from Person";
$result = mysql_query($sql,$con);
while ($row = mysql_fetch_object($result))
{
echo $row->FirstName . "<br />";
}
mysql_close($con);
?>
Parameter
Description
message
Required. Specifies the message or status number to write before exiting the
script. The status number will not be written to the output.
Example
<?php
$site = "http://www.w3schools.com/";
fopen($site,"r")
or die("Unable to connect to $site");
?>
isset
Determine if a variable is set and is not NULL
bool isset ( mixed $var [, mixed $... ] )
Determine if a variable is set and is not NULL.
If a variable has been unset with unset(), it will no longer be set. isset() will return FALSE if
testing a variable that has been set to NULL. Also note that a NULL byte ("\0") is not equivalent
to the PHP NULL constant.
If multiple parameters are supplied then isset() will return TRUE only if all of the parameters are
set. Evaluation goes from left to right and stops as soon as an unset variable is encountered.
Returns TRUE if var exists and has value other than NULL, FALSE otherwise.
// TRUE
// FALSE
// FALSE
Description
Required /
Type
Optional
var_name
Required
Mixed*
*Mixed : Mixed indicates that a parameter may accept multiple (but not necessarily all) types.
Return value
TRUE if var is an array, FALSE otherwise.
Value Type : Boolean.
Example of php is_array() function
<?php
$var_name=array('A','B','C');
if (is_array($var_name))
echo 'This is an array....';
else
echo 'This is not an array....';
?>
Output of the example
This is an array....
Parameter
Description
file
newloc
move_uploaded_file
move_uploaded_file Moves an uploaded file to a new location
Description
bool move_uploaded_file ( string $filename , string $destination )
This function checks to ensure that the file designated by filename is a valid upload file (meaning
that it was uploaded via PHP's HTTP POST upload mechanism). If the file is valid, it will be moved
to the filename given by destination.
This sort of check is especially important if there is any chance that anything done with uploaded
files could reveal their contents to the user, or even to other users on the same system.
Parameters
filename
Return Values
Examples
Example #1 Uploading multiple files
<?php
$uploads_dir = '/uploads';
foreach ($_FILES["pictures"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["pictures"]["tmp_name"][$key];
$name = $_FILES["pictures"]["name"][$key];
move_uploaded_file($tmp_name, "$uploads_dir/$name");
}
}
?>
Note:
move_uploaded_file() is both safe mode and open_basedir aware. However, restrictions are
placed only on the destination path as to allow the moving of uploaded files in which filename
may conflict with such restrictions. move_uploaded_file() ensures the safety of this operation
by allowing only those files uploaded through PHP to be moved.
Warning
If the destination file already exists, it will be overwritten.
mssql_next_result
mssql_next_result Move the internal result pointer to the next result
Description
bool mssql_next_result ( resource $result_id )
When sending more than one SQL statement to the server or executing a stored procedure with
multiple results, it will cause the server to return multiple result sets. This function will test for
additional results available form the server. If an additional result set exists it will free the
existing result set and prepare to fetch the rows from the new result set.
Parameters
result_id
The result resource that is being evaluated. This result comes from a call to mssql_query()
Return Values
Returns TRUE if an additional result set was available or FALSE otherwise.
Examples
}
} while (mssql_next_result($query));
// Clean up
mssql_free_result($query);
mssql_close($link);
?>
$string ="John";
$string .=" ";
$string .="Smith";
echo $string;
This will output John Smith. Another way to add a space,
$string ="John";
$string .=" Smith";
echo $string;
This will output John Smith. Note the space before Smith in the se
Parameter
Description
to
subject
Required. Specifies the subject of the email. Note: This parameter cannot
contain any newline characters
message
Required. Defines the message to be sent. Each line should be separated with
a LF (\n). Lines should not exceed 70 characters
headers
Optional. Specifies additional headers, like From, Cc, and Bcc. The additional
headers should be separated with a CRLF (\r\n)
parameters
Note: For the mail functions to be available, PHP requires an installed and working email system.
The program to be used is defined by the configuration settings in the php.ini file. Read more in
our PHP Mail reference.
Message:<br />
<textarea name='message' rows='15' cols='40'>
</textarea><br />
<input type='submit' />
</form>";
}
?>
</body>
</html>
If it is set (after the form is filled out); send the email from the form
When submit is pressed after the form is filled out, the page reloads, sees that the email
input is set, and sends the email
Note: This is the simplest way to send e-mail, but it is not secure. In the next chapter of this
tutorial you can read more about vulnerabilities in e-mail scripts, and how to validate user input
to make it more secure.
</body>
</html>
Notice the following about the HTML form above:
The enctype attribute of the <form> tag specifies which content-type to use when
submitting the form. "multipart/form-data" is used when a form requires binary data, like
the contents of a file, to be uploaded
The type="file" attribute of the <input> tag specifies that the input should be processed
as a file. For example, when viewed in a browser, there will be a browse-button next to the
input field
Note: Allowing users to upload files is a big security risk. Only permit trusted users to perform
file uploads.
$_FILES["file"]["tmp_name"] - the name of the temporary copy of the file stored on the
server
This is a very simple way of uploading files. For security reasons, you should add restrictions on
what the user is allowed to upload.
Restrictions on Upload
In this script we add some restrictions to the file upload. The user may only upload .gif or .jpeg
files and the file size must be under 20 kb:
<?php
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 20000))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br />";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br />";
echo "Type: " . $_FILES["file"]["type"] . "<br />";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
echo "Stored in: " . $_FILES["file"]["tmp_name"];
}
}
else
{
echo "Invalid file";
}
?>
Note: For IE to recognize jpg files the type must be pjpeg, for FireFox it must be jpeg.
else
{
echo
echo
echo
echo
if (file_exists("upload/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
}
}
}
else
{
echo "Invalid file";
}
?>
The script above checks if the file already exists, if it does not, it copies the file to the specified
folder.
Note: This example saves the file to a new folder called "upload"
For column content we'll use BLOB data type. BLOB is a binary large object that can
hold a variable amount of data. MySQL have four BLOB data types, they are :
TINYBLOB
BLOB
MEDIUMBLOB
LONGBLOB
Example : upload.php
Source code : upload.phps
<form method="post" enctype="multipart/form-data">
<table width="350" border="0" cellpadding="1" cellspacing="1" class="box">
<tr>
<td width="246">
<input type="hidden" name="MAX_FILE_SIZE" value="2000000">
<input name="userfile" type="file" id="userfile">
</td>
<td width="80"><input name="upload" type="submit" class="box" id="upload"
value=" Upload "></td>
</tr>
</table>
</form>
An upload form must have encytype="multipart/form-data" otherwise it won't work at
all. Of course the form method also need to be set to method="post". Also remember
to put a hidden input MAX_FILE_SIZE before the file input. It's to restrict the size of
files.
After the form is submitted the we need to read the autoglobal $_FILES. In the example
above the input name for the file is userfile so the content of $_FILES are like this :
$_FILES['userfile']['name']
Example : upload.php
<?php
if(isset($_POST['upload']) && $_FILES['userfile']['size'] > 0)
{
$fileName = $_FILES['userfile']['name'];
$tmpName = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];
$fp
= fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = addslashes($content);
fclose($fp);
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
}
include 'library/config.php';
include 'library/opendb.php';
$query = "INSERT INTO upload (name, size, type, content ) ".
"VALUES ('$fileName', '$fileSize', '$fileType', '$content')";
mysql_query($query) or die('Error, query failed');
include 'library/closedb.php';
echo "<br>File $fileName uploaded<br>";
}
?>
Before you do anything with the uploaded file. You should not assume that the file
was uploaded successfully to the server. Always check to see if the file was successfully
uploaded by looking at the file size. If it's larger than zero byte then we can assume
that the file is uploaded successfully.
PHP saves the uploaded file with a temporary name and save the name in
$_FILES['userfile']['tmp_name']. Our next job is to read the content of this file and insert
the content to database. Always make sure that you use addslashes() to escape the
content. Using addslashes() to the file name is also recommended because you never
know what the file name would be.
That's it now you can upload your files to MySQL. Now it's time to write the script to
download those files.
}
include 'library/closedb.php';
?>
</body>
</html>
When you click the download link, the $_GET['id'] will be set. We can use this id to identify which
files to get from the database. Below is the code for downloading files from MySQL Database.
Example :
<?php
if(isset($_GET['id']))
{
// if id is set then get the file with the id from database
include 'library/config.php';
include 'library/opendb.php';
$id = $_GET['id'];
$query = "SELECT name, type, size, content " .
"FROM upload WHERE id = '$id'";
$result = mysql_query($query) or die('Error, query failed');
list($name, $type, $size, $content) =
mysql_fetch_array($result);
header("Content-length: $size");
header("Content-type: $type");
header("Content-Disposition: attachment; filename=$name");
echo $content;
include 'library/closedb.php';
exit;
}
?>
Before sending the file content using echo first we need to set several headers. They are :
1. header("Content-length: $size")
This header tells the browser how large the file is. Some browser need it to be able to
download the file properly. Anyway it's a good manner telling how big the file is. That way
anyone who download the file can predict how long the download will take.
2. header("Content-type: $type")
This header tells the browser what kind of file it tries to download.
3. header("Content-Disposition: attachment; filename=$name");
Tells the browser to save this downloaded file under the specified name. If you don't send
this header the browser will try to save the file using the script's name (download.php).
After sending the file the script stops executing by calling exit.
NOTE :
When sending headers the most common error message you will see is something like this :
Warning: Cannot modify header information - headers already sent by (output started at
C:\Webroot\library\config.php:7) in C:\Webroot\download.php on line 13
This error happens because some data was already sent before we send the header. As for the
error message above it happens because i "accidentally" add one space right after the PHP
closing tag ( ?> ) in config.php file. So if you see this error message when you're sending a
header just make sure you don't have any data sent before calling header(). Check the file
mentioned in the error message and go to the line number specified
How to set the images to be W= 288 pixels X H= 216 pixels ?
Thanks a lot.
###########################################
<?php
$dbname="your database";
$host="localhost";
$user="db user";
$pass="db password";
$link = mysql_connect($hostname, $user, $pass);
mysql_select_db($dbname, $link);
?>
<form method="post" enctype="multipart/form-data">
<table width="350" border="0" cellpadding="1" cellspacing="1" class="box">
<tr>
<td width="246">
<input type="hidden" name="MAX_FILE_SIZE" value="2000000">
<input name="userfile" type="file" id="userfile">
</td>
<td width="80"><input name="upload" type="submit" class="box" id="upload" value="
Upload "></td>
</tr>
</table>
</form>
<?php
if(isset($_POST['upload']) && $_FILES['userfile']['size'] > 0)
{
$fileName = $_FILES['userfile']['name'];
$tmpName = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];
$fp
= fopen($tmpName, 'r');
$content = addslashes($content);
fclose($fp);
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
}
$query = "INSERT INTO upload (name, size, type, content ) ".
"VALUES ('$fileName', '$fileSize', '$fileType', '$content')";
mysql_query($query) or die('Error, query failed');
echo "<br>File $fileName uploaded<br>";
}
?>
Need Help Downloading Files from MySQL Database
PHP Syntax
1.
2. <?php session_start();
3. $DBconnection = mysqli_connect("localhost", "<db_name>",
"<db_password>","<table_name>");
4.
5. if(isset($_SESSION["loggedin"]) && $_SESSION["loggedin"]){
6.
$prep = mysqli_prepare($DBconnection,'SELECT files.FILE_STORE,
files.FILE_TYPE FROM files JOIN applications ON files.appid = applications.appid JOIN
users ON users.userid=applications.userid WHERE (users.userid=? || "reviewer" = ? )
&& files.FILE_ID=?');
7.
mysqli_stmt_bind_param($prep,'sss',$_SESSION['userid'],$_SESSION['level'],
$_GET['itemid']);
8.
mysqli_stmt_execute($prep);
9.
mysqli_stmt_store_result($prep);
10.
11.
mysqli_stmt_bind_result($prep, $file, $filetype);
12.
mysqli_stmt_fetch($prep);
13.
14.
session_cache_limiter('no-cache');
15.
header('Content-type:'.$filetype);
16.
header('Content-Type:application-x/force-download');
17.
header('Content-Disposition: attachment; filename="$file"');
18.
header("Content-Transfer-Encoding: binary");
19. //
header('Content-Length: ' . filesize($file)); //
20. //
header("Cache-Control: no-store, no-cache, must-revalidate"); //
21.
header ("Cache-Control: post-check=0, pre-check=0", false);
22.
header("Cache-Control: max_age=0");
23.
header ("Pragma: no-cache");
24.
25. $file = @fopen($file,"rb");
26. if ($file) {
27. while(!feof($file)) {
28.
print(fread($file, 1024*8));
29.
flush();
30.
if (connection_status()!=0) {
31.
@fclose($file);
32.
die();
33.
}
34. }
35. @fclose($file);
36. }
37. //
echo $file; //
38. //
readfile($file); //
39.
40.
mysqli_stmt_free_result($prep);
41. }
42. else{
43. echo "You do not have permission to view this.";
44. }
45. ?>
help uploading and downloading files
from mysql database using php
Can anyone help me with my php script. i
have been trying to upload and download
files (images, pdfs etc) from mysql
database but i haven't been able to. i have
succeeded in uploading but the problem
now is to download. i have used this code
<?
//connect to the database
include "dbaseConnection.php";
$query = "SELECT * FROM images WHERE
id = 1";
$result = mysql_query($query) or
die(mysql_error());
// define results into variables
$name=mysql_result($result,0,"name");
$size=mysql_result($result,0,"size");
$type=mysql_result($result,0,"type");
$content=mysql_result($result,0,"content")
;
// give our picture the proper
headers...otherwise our page will be
confused
header("Content-Disposition: attachment;
filename=$name");
header("Content-length: $size");
header("Content-type: $type");
echo $content;
mysql_close();
?>
but its not giving me any results.
can anyone help me please? _