SlideShare a Scribd company logo
1 of 5
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
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 .= '&nbsp; <span class="pagNumActive">' . $pn . '</span> &nbsp;';
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1 . '">' . $add1 . '</a> &nbsp;';
} else if ($pn == $lastPage) {
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub1 . '">' . $sub1 . '</a> &nbsp;';
$centerPages .= '&nbsp; <span class="pagNumActive">' . $pn . '</span> &nbsp;';
} else if ($pn > 2 && $pn < ($lastPage - 1)) {
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub2 . '">' . $sub2 . '</a> &nbsp;';
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub1 . '">' . $sub1 . '</a> &nbsp;';
    $centerPages .= '&nbsp; <span class="pagNumActive">' . $pn . '</span> &nbsp;';
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1 . '">' . $add1 . '</a> &nbsp;';
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add2 . '">' . $add2 . '</a> &nbsp;';
} else if ($pn > 1 && $pn < $lastPage) {
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub1 . '">' . $sub1 . '</a> &nbsp;';
    $centerPages .= '&nbsp; <span class="pagNumActive">' . $pn . '</span> &nbsp;';
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1 . '">' . $add1 . '</a> &nbsp;';
}
// 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. '&nbsp; &nbsp; &nbsp; ';
    // If we are not on page 1 we can place the Back button
    if ($pn != 1) {
        $previous = $pn - 1;
        $paginationDisplay .= '&nbsp; <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 .= '&nbsp; <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;
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 ------------------------------------------------------------
// 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
?>

More Related Content

Recently uploaded

Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 

Recently uploaded (20)

Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 

Featured

How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Applitools
 
12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at WorkGetSmarter
 
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...DevGAMM Conference
 
Barbie - Brand Strategy Presentation
Barbie - Brand Strategy PresentationBarbie - Brand Strategy Presentation
Barbie - Brand Strategy PresentationErica Santiago
 
Good Stuff Happens in 1:1 Meetings: Why you need them and how to do them well
Good Stuff Happens in 1:1 Meetings: Why you need them and how to do them wellGood Stuff Happens in 1:1 Meetings: Why you need them and how to do them well
Good Stuff Happens in 1:1 Meetings: Why you need them and how to do them wellSaba Software
 
Introduction to C Programming Language
Introduction to C Programming LanguageIntroduction to C Programming Language
Introduction to C Programming LanguageSimplilearn
 

Featured (20)

How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
 
12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work
 
ChatGPT webinar slides
ChatGPT webinar slidesChatGPT webinar slides
ChatGPT webinar slides
 
More than Just Lines on a Map: Best Practices for U.S Bike Routes
More than Just Lines on a Map: Best Practices for U.S Bike RoutesMore than Just Lines on a Map: Best Practices for U.S Bike Routes
More than Just Lines on a Map: Best Practices for U.S Bike Routes
 
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...
 
Barbie - Brand Strategy Presentation
Barbie - Brand Strategy PresentationBarbie - Brand Strategy Presentation
Barbie - Brand Strategy Presentation
 
Good Stuff Happens in 1:1 Meetings: Why you need them and how to do them well
Good Stuff Happens in 1:1 Meetings: Why you need them and how to do them wellGood Stuff Happens in 1:1 Meetings: Why you need them and how to do them well
Good Stuff Happens in 1:1 Meetings: Why you need them and how to do them well
 
Introduction to C Programming Language
Introduction to C Programming LanguageIntroduction to C Programming Language
Introduction to C Programming Language
 

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 .= '&nbsp; <span class="pagNumActive">' . $pn . '</span> &nbsp;'; $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1 . '">' . $add1 . '</a> &nbsp;'; } else if ($pn == $lastPage) { $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub1 . '">' . $sub1 . '</a> &nbsp;';
  • 3. $centerPages .= '&nbsp; <span class="pagNumActive">' . $pn . '</span> &nbsp;'; } else if ($pn > 2 && $pn < ($lastPage - 1)) { $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub2 . '">' . $sub2 . '</a> &nbsp;'; $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub1 . '">' . $sub1 . '</a> &nbsp;'; $centerPages .= '&nbsp; <span class="pagNumActive">' . $pn . '</span> &nbsp;'; $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1 . '">' . $add1 . '</a> &nbsp;'; $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add2 . '">' . $add2 . '</a> &nbsp;'; } else if ($pn > 1 && $pn < $lastPage) { $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub1 . '">' . $sub1 . '</a> &nbsp;'; $centerPages .= '&nbsp; <span class="pagNumActive">' . $pn . '</span> &nbsp;'; $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1 . '">' . $add1 . '</a> &nbsp;'; } // 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. '&nbsp; &nbsp; &nbsp; '; // If we are not on page 1 we can place the Back button if ($pn != 1) { $previous = $pn - 1; $paginationDisplay .= '&nbsp; <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 .= '&nbsp; <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 ?>