1 / 17

File upload

File upload. http://www.flickr.com/photos/torkildr/3462607995/. Overview of file upload. File upload is where a file is copied from the client to the server Useful for uploading Images PDFs Videos Audio Pretty much anything that can't be copied-and-pasted into a TEXTAREA.

giovannar
Download Presentation

File upload

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. File upload http://www.flickr.com/photos/torkildr/3462607995/

  2. Overview of file upload • File upload is where a file is copied from the client to the server • Useful for uploading • Images • PDFs • Videos • Audio • Pretty much anything that can't be copied-and-pasted into a TEXTAREA

  3. Process of file upload Storage location Browser Server Fill form withinput type=file Encode & upload Access file Store file some place safe,such as on the file sys or in a db

  4. Setting up the form correctly <form method="post" action="filetest.php" enctype="multipart/form-data"> Choose file: <input type="file" name="myfile"> <input type="submit" value="OK"> </form>

  5. Receiving the file on the server side <?php $dir = "mydirectory"; if ($_SERVER['REQUEST_METHOD'] == "POST") { $errorinfo = $_FILES["myfile"]["error"]; $filename = $_FILES["myfile"]["name"]; $tmpfile = $_FILES["myfile"]["tmp_name"]; $filesize = $_FILES["myfile"]["size"]; $filetype = $_FILES["myfile"]["type"]; if ($filetype == "image/jpeg" && $filesize < 1048576) { move_uploaded_file($tmpfile, "$dir/" . $filename); chmod("$dir/" . $filename, 0644); } else echo "Only jpegs under 1MB are invited to this party."; } $jpgs = glob("$dir/*.*"); sort($jpgs); echo "<table>"; foreach($jpgs as $jpg) { echo "<tr><td><a href='$dir/" . rawurlencode(substr($jpg, strlen($dir)+1)) . "' target='n'>" . htmlspecialchars(substr($jpg, strlen($dir)+1)) . "</a></td></tr>"; } echo "</table>"; ?>

  6. Checking that the file is legit • Be sure to validate the inputs • Otherwise, people could be uploading stuff that you really don't want on your server • Such as .exe, .dll or .so files containing viruses • Or enormous files that waste your server space and maybe your bandwidth • Or they could be uploading bad data that will break your web app when you use data later • <img src="blahblah.exe"> doesn't look too good

  7. Storing a file in the database • A file is an array of bytes, so storing it in the database is very similar to storing a string • But you need to declare the column as a blob • http://dev.mysql.com/doc/refman/5.0/en/blob.html • mediumblob is usually good (around 16MB)

  8. Lengthy examplePart 1 – Storing files away if ($_SERVER['REQUEST_METHOD'] == "POST") { $errorinfo = $_FILES["myfile"]["error"]; $filename = $_FILES["myfile"]["name"]; $tmpfile = $_FILES["myfile"]["tmp_name"]; $filesize = $_FILES["myfile"]["size"]; $filetype = $_FILES["myfile"]["type"]; $mysqli->query('create table if not exists myuploads(fid integer not null auto_increment, filename varchar(256), filedatamediumblob, primary key(fid))'); if ($filetype == "image/jpeg" && $filesize < 1048576) { $filedata = file_get_contents($tmpfile); $query = $mysqli->prepare("insert into myuploads(filename, filedata) values (?,?)"); $empty = NULL; $query->bind_param("sb", $filename, $empty); $query->send_long_data(1, $filedata); $query->execute(); } else { echo "Only jpegs under 1MB are invited to this party."; } }

  9. Lengthy examplePart 2 – Listing the files if (!isset($_GET['id'])) { print('<form method="post" action="filetest.php" enctype="multipart/form-data"> Choose file: <input type="file" name="myfile"> <input type="submit" value="OK"> </form>'); if ($result = $mysqli->query("select fid, filename from myuploads")) { echo "<style>img {max-height: 1in;}</style>"; echo "<hr>Your files...<table>"; while ($obj = $result->fetch_object()) echo "<tr><td><a target=n href='filetest.php?id=". htmlspecialchars($obj->fid). "'><img src='filetest.php?id=". htmlspecialchars($obj->fid). "'>". "</a></td><td>". htmlspecialchars($obj->filename). "</td></tr>"; echo "</table>"; $result->close(); } } else { $fid = $_GET['id']; if ($fid <= 0) echo ""; else if (!preg_match('/^[0-9]+$/', $fid)) echo "Invalid fid"; else { header('Content-type: image/jpeg'); if ($result = $mysqli->query("select filedata from myuploads where fid = $fid")) { if ($obj = $result->fetch_object()) echo $obj->filedata; $result->close(); } } }

  10. Let's dig into what is really happening • File upload differs from a typical http POST in the way that data sent to data are encoded • Differences in the "content type" • Differences in how the content is represented • And also when the server sends data back • Differences in the content type

  11. Example of a simple GET request GET /list.php?category=apple HTTP/1.1 Host: www.myfancypantswebsite.com User-Agent: Safari/4.0

  12. Example of a simple POST operation POST /login.php HTTP/1.1 Host: www.myfancypantswebsite.com User-Agent: Safari/4.0 Content-Length: 26 Content-Type: application/x-www-form-urlencoded usernm=cs&password=mypass

  13. Example of a simple POST file upload POST /filehandler.phpHTTP/1.0Host: www.myfancypantswebsite.com User-Agent: Safari/4.0 Content-Type: multipart/form-data; boundary=BbC15x --BbC15x Content-Disposition: form-data; name="someregularparameter" OSU --BbC15x Content-Disposition: form-data; name="files" Content-Type: multipart/mixed; boundary=CcD15y --CcD15y Content-Disposition: file; filename="somefile.jpeg" Content-Type: image/jpeg dGhlIHRlbnVyZSBzeXN0ZW0gaXMgcmVhbGx5IGphY2tlZA== --CcD15y Content-Disposition: file; filename="anotherfile.gif" Content-Type: image/gif Content-Transfer-Encoding: base64 dGVhY2hpbmcgaXMgdW5kZXJyYXRlZA== --CcD15y-- --BbC15x--

  14. Content type (MIME type) tells how to interpret data • As some sort of text • text/plain, text/html, text/javascript, text/css • As some sort of image • image/jpeg, image/gif, image/png • As some sort of multi-part package • multipart/form-data; boundary=BbC15x For others, see http://www.iana.org/assignments/media-types/index.html

  15. Detailed breakdown of file upload Your PHP program Storage location Browser Web server Fill form withinput type=file Multipart encode; upload Pass data to your PHP Store data to some safe place Read content type; Decode upload; Store files to temp

  16. Detailed breakdown of sending data back Your PHP program Storage location Browser Web server Click a link GET with parameter Pass data to your PHP Read parameters Retrieverequested data Pass content type & data Pass content type & data Interpret data Show to user

  17. Making file upload look slick • For a great "How-To" topic, search the web for one of the many slick AJAX file upload libraries • HINT: The file can be sent via AJAX; full page refresh isn't needed!

More Related