170 likes | 184 Views
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.
E N D
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
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
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>
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>"; ?>
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
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)
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."; } }
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(); } } }
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
Example of a simple GET request GET /list.php?category=apple HTTP/1.1 Host: www.myfancypantswebsite.com User-Agent: Safari/4.0
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
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--
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
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
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
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!