Building a file upload application using html form and php script
1. Building a File Upload Application Using HTML Form and PHP Script
In this PHP form processing lesson we will demonstrate how to program a simple HTML form that allows file upload dialogue and
system folder browsing. Then we will show you the PHP that will check the file and upload it.
First you will need an HTML upload form, here is one for you to play with. The PHP you will require is below it.
The HTML File Upload Form
<form enctype="multipart/form-data" method="post" action="file_upload_script.php">
Choose your file here:
<input name="file1" type="file" /><br /><br />
<input type="submit" value="Upload It" />
</form>
enctype="multipart/form-data" is required in that form tag above to enable file uploading.
The PHP Form Processing File
Now we just need a PHP parse script named "file_upload_script.php" to handle the uploaded file. It will access the
global $_FILES variable array so we can easily grab specific values about the file being uploaded.
$_FILES Stores any file upload specific variables in an array
<?php
// Set local PHP vars from the POST vars sent from our form using the array
// of data that the $_FILES global variable contains for this uploaded file
$fileName = $_FILES["file1"]["name"]; // The file name
$fileTmpLoc = $_FILES["file1"]["tmp_name"]; // File in the PHP tmp folder
$fileType = $_FILES["file1"]["type"]; // The type of file it is
$fileSize = $_FILES["file1"]["size"]; // File size in bytes
$fileErrorMsg = $_FILES["file1"]["error"]; // 0 for false... and 1 for true
// Specific Error Handling if you need to run error checking
if (!$fileTmpLoc) { // if file not chosen
echo "ERROR: Please browse for a file before clicking the upload button.";
exit();
} else if($fileSize > 50000) { // if file is larger than we want to allow
echo "ERROR: Your file was larger than 50kb in file size.";
unlink($fileTmpLoc);
exit();
} else if (!preg_match("/.(gif|jpg|png)$/i", $fileName) ) {
// This condition is only if you wish to allow uploading of specific file types
echo "ERROR: Your image was not .gif, .jpg, or .png.";
unlink($fileTmpLoc);
exit();
}
// Place it into your "uploads" folder mow using the move_uploaded_file() function
move_uploaded_file($fileTmpLoc, "uploads/$fileName");
// Check to make sure the uploaded file is in place where you want it
if (!file_exists("uploads/$fileName")) {
echo "ERROR: File not uploaded<br /><br />";
echo "Check folder permissions on the target uploads folder is 0755 or looser.<br /><br />";
echo "Check that your php.ini settings are set to allow over 2 MB files, they are 2MB by default.";
exit();
}
// Display things to the page so you can see what is happening for testing purposes
2. echo "The file named <strong>$fileName</strong> uploaded successfuly.<br /><br />";
echo "It is <strong>$fileSize</strong> bytes in size.<br /><br />";
echo "It is a <strong>$fileType</strong> type of file.<br /><br />";
echo "The Error Message output for this upload is: <br />$fileErrorMsg";
?>
NOTE : Be sure that you have a folder named "uploads" because this script is set to put the uploaded file there.
I commented most lines in the above PHP script to let you know what is going on in that script so I do not have to explain it again
below. I hope it is clear enough. If not just ask a question in the forums.
...Gorge
United States of America
Page 6 of 39 Back 4 5 6 7 8 Next
Below is the PHP, MySQL, HTML, and CSS code that renders the output above.
You have to put your mysql connection data, and alter the SQL queries(both queries).
<?php
// Adam's Custom PHP MySQL Pagination Tutorial and Script
// You have to put your mysql connection data and alter the SQL queries(both queries)
// This script is in tutorial form and is accompanied by the following video:
// http://www.youtube.com/watch?v=K8xYGnEOXYc
mysql_connect("DB_Host_Here","DB_Username_Here","DB_Password_Here") or die (mysql_error());
mysql_select_db("DB_Name_Here") or die (mysql_error());
////////////// QUERY THE MEMBER DATA INITIALLY LIKE YOU NORMALLY WOULD
$sql = mysql_query("SELECT id, firstname, country FROM myTable ORDER BY id ASC");
//////////////////////////////////// Adam's Pagination Logic ////////////////////////////////////////////////////////////////////////
$nr = mysql_num_rows($sql); // Get total of Num rows from the database query
if (isset($_GET['pn'])) { // Get pn from URL vars if it is present
$pn = preg_replace('#[^0-9]#i', '', $_GET['pn']); // filter everything but numbers for security(new)
//$pn = ereg_replace("[^0-9]", "", $_GET['pn']); // filter everything but numbers for security(deprecated)
} else { // If the pn URL variable is not present force it to be value of page number 1
$pn = 1;
}
//This is where we set how many database items to show on each page
$itemsPerPage = 10;
// Get the value of the last page in the pagination result set
$lastPage = ceil($nr / $itemsPerPage);
// Be sure URL variable $pn(page number) is no lower than page 1 and no higher than $lastpage
if ($pn < 1) { // If it is less than 1
$pn = 1; // force if to be 1
} else if ($pn > $lastPage) { // if it is greater than $lastpage
$pn = $lastPage; // force it to be $lastpage's value
}
// This creates the numbers to click in between the next and back buttons
// This section is explained well in the video that accompanies this script
$centerPages = "";
$sub1 = $pn - 1;
$sub2 = $pn - 2;
$add1 = $pn + 1;
$add2 = $pn + 2;
if ($pn == 1) {
$centerPages .= ' <span class="pagNumActive">' . $pn . '</span> ';
$centerPages .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1 . '">' . $add1 . '</a> ';
} else if ($pn == $lastPage) {
$centerPages .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub1 . '">' . $sub1 . '</a> ';
3. $centerPages .= ' <span class="pagNumActive">' . $pn . '</span> ';
} else if ($pn > 2 && $pn < ($lastPage - 1)) {
$centerPages .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub2 . '">' . $sub2 . '</a> ';
$centerPages .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub1 . '">' . $sub1 . '</a> ';
$centerPages .= ' <span class="pagNumActive">' . $pn . '</span> ';
$centerPages .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1 . '">' . $add1 . '</a> ';
$centerPages .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add2 . '">' . $add2 . '</a> ';
} else if ($pn > 1 && $pn < $lastPage) {
$centerPages .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub1 . '">' . $sub1 . '</a> ';
$centerPages .= ' <span class="pagNumActive">' . $pn . '</span> ';
$centerPages .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1 . '">' . $add1 . '</a> ';
}
// This line sets the "LIMIT" range... the 2 values we place to choose a range of rows from database in our query
$limit = 'LIMIT ' .($pn - 1) * $itemsPerPage .',' .$itemsPerPage;
// Now we are going to run the same query as above but this time add $limit onto the end of the SQL syntax
// $sql2 is what we will use to fuel our while loop statement below
$sql2 = mysql_query("SELECT id, firstname, country FROM myTable ORDER BY id ASC $limit");
//////////////////////////////// END Adam's Pagination Logic ////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////// Adam's Pagination Display Setup /////////////////////////////////////////////////////////////////////
$paginationDisplay = ""; // Initialize the pagination output variable
// This code runs only if the last page variable is ot equal to 1, if it is only 1 page we require no paginated links to display
if ($lastPage != "1"){
// This shows the user what page they are on, and the total number of pages
$paginationDisplay .= 'Page <strong>' . $pn . '</strong> of ' . $lastPage. ' ';
// If we are not on page 1 we can place the Back button
if ($pn != 1) {
$previous = $pn - 1;
$paginationDisplay .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $previous . '"> Back</a> ';
}
// Lay in the clickable numbers display here between the Back and Next links
$paginationDisplay .= '<span class="paginationNumbers">' . $centerPages . '</span>';
// If we are not on the very last page we can place the Next button
if ($pn != $lastPage) {
$nextPage = $pn + 1;
$paginationDisplay .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $nextPage . '"> Next</a> ';
}
}
///////////////////////////////////// END Adam's Pagination Display Setup ///////////////////////////////////////////////////////////////////////////
// Build the Output Section Here
$outputList = '';
while($row = mysql_fetch_array($sql2)){
$id = $row["id"];
$firstname = $row["firstname"];
$country = $row["country"];
$outputList .= '<h1>' . $firstname . '</h1><h2>' . $country . ' </h2><hr />';
} // close while loop
?>
<html>
<head>
<title>Adam's Pagination</title>
<style type="text/css">
<!--
.pagNumActive {
color: #000;
border:#060 1px solid; background-color: #D2FFD2; padding-left:3px; padding-right:3px;
}
.paginationNumbers a:link {
color: #000;
text-decoration: none;
4. border:#999 1px solid; background-color:#F0F0F0; padding-left:3px; padding-right:3px;
}
.paginationNumbers a:visited {
color: #000;
text-decoration: none;
border:#999 1px solid; background-color:#F0F0F0; padding-left:3px; padding-right:3px;
}
.paginationNumbers a:hover {
color: #000;
text-decoration: none;
border:#060 1px solid; background-color: #D2FFD2; padding-left:3px; padding-right:3px;
}
.paginationNumbers a:active {
color: #000;
text-decoration: none;
border:#999 1px solid; background-color:#F0F0F0; padding-left:3px; padding-right:3px;
}
-->
</style>
</head>
<body>
<div style="margin-left:64px; margin-right:64px;">
<h2>Total Items: <?php echo $nr; ?></h2>
</div>
<div style="margin-left:58px; margin-right:58px; padding:6px; background-color:#FFF; border:#999 1px solid;"><?php echo
$paginationDisplay; ?></div>
<div style="margin-left:64px; margin-right:64px;"><?php print "$outputList"; ?></div>
<div style="margin-left:58px; margin-right:58px; padding:6px; background-color:#FFF; border:#999 1px solid;"><?php echo
$paginationDisplay; ?></div>
</body>
</html>
<?php
/* Script written by Adam Khoury at www.developphp.com */
/* VIDEO GUIDE - http://www.developphp.com/view.php?tid=1057 */
/* See video guide above for full explanation if you want full understanding */
// Obtain user agent which is a long string not meant for human reading
$agent = $_SERVER['HTTP_USER_AGENT'];
// Get the user Browser now -----------------------------------------------------
// Create the Associative Array for the browsers we want to sniff out
$browserArray = array(
'Windows Mobile' => 'IEMobile',
'Android Mobile' => 'Android',
'iPhone Mobile' => 'iPhone',
'Firefox' => 'Firefox',
'Google Chrome' => 'Chrome',
'Internet Explorer' => 'MSIE',
'Opera' => 'Opera',
'Safari' => 'Safari'
);
foreach ($browserArray as $k => $v) {
if (preg_match("/$v/", $agent)) {
break;
} else {
$k = "Browser Unknown";
}
}
$browser = $k;
// -----------------------------------------------------------------------------------------
// Get the user OS now ------------------------------------------------------------
5. // Create the Associative Array for the Operating Systems to sniff out
$osArray = array(
'Windows 98' => '(Win98)|(Windows 98)',
'Windows 2000' => '(Windows 2000)|(Windows NT 5.0)',
'Windows ME' => 'Windows ME',
'Windows XP' => '(Windows XP)|(Windows NT 5.1)',
'Windows Vista' => 'Windows NT 6.0',
'Windows 7' => '(Windows NT 6.1)|(Windows NT 7.0)',
'Windows NT 4.0' => '(WinNT)|(Windows NT 4.0)|(WinNT4.0)|(Windows NT)',
'Linux' => '(X11)|(Linux)',
'Mac OS' => '(Mac_PowerPC)|(Macintosh)|(Mac OS)'
);
foreach ($osArray as $k => $v) {
if (preg_match("/$v/", $agent)) {
break;
} else {
$k = "Unknown OS";
}
}
$os = $k;
// At this point you can do what you wish with both the OS and browser acquired
echo '<h1>PHP Tutorial : Get User Browser and Operating System Using Arrays</h1>';
echo $agent;
echo "<h2>You are using: <em>$browser - $os</em></h2>";
?>
<?php
// PHP file that renders perfect Dynamic XML for any image applications
// Script written by Adam Khoury @ www.developphp.com - April 05, 2010
// View the video that is tied to this script for maximum understanding
// -------------------------------------------------------------------
header("Content-Type: text/xml"); //set the content type to xml
// Initialize the xmlOutput variable
$xmlBody = '<?xml version="1.0" encoding="ISO-8859-1"?>';
$dir = "images/gallery1/"; // Specify Directory where images are
$xmlBody .= "<XML>"; // Start XMLBody output
// open specified directory using opendir() the function
$dirHandle = opendir($dir);
// Create incremental counter variable if needed
$i = 0;
while ($file = readdir($dirHandle)) {
// if file is not a folder and if file name contains the string .jpg
if(!is_dir($file) && strpos($file, '.jpg')){
$i++; // increment $i by one each pass in the loop
$xmlBody .= '
<Picture>
<picNum>' . $i . '</picNum>
<picURL>' . $dir . '' . $file . '</picURL>
</Picture>';
} // close the if statement
} // End while loop
closedir($dirHandle); // close the open directory
$xmlBody .= "</XML>";
echo $xmlBody; // output the gallery data as XML file for flash
?>