Upload files, code on Osiris
I have produced these three files to demonstrate file uploading.
They are in /home/jensen/public_html
First, a form: (up.php)
<h2>Minimal file upload</h2>
<!-- The data encoding type, enctype, MUST be specified as below -->
<form enctype="multipart/form-data" action="upload.php" method="POST">
<!-- MAX_FILE_SIZE must precede the file input field -->
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
<!-- Name of input element determines name in $_FILES array -->
Your Linux username please: <input name=user>
<br> Send this file: <input name="mugshot" type="file" />
<br>
<input type="submit" value="Send File" align="center" />
</form>
<hr>
<a href=seeuploads.php>See uploaded files</a>
<br>Back to <a href=index.html>Jensen @ Osiris</a>
-----------The next file (upload.php) first authenticates, using
your appropriate method
A session is started, this means that authentication only has to be
done once
Then the actual file is uploaded. I chose to use the
username-filename combination, with the file name coming from the
user's choice.
You might want to also put the file name and some title, description
or "tags" in your database.
<?php
//------ authenticate user ------
session_start();
if (!isset($_SESSION['user']))
{ $linux = $_POST['user'] or die("Who are you?");
pg_connect("dbname=jensen user=xxxx password=zzzz") or die ("DB trouble");
$try = pg_query_params ("select given||' '||family from students where linux=$1",
array($linux));
$name = pg_fetch_result($try,0,0) or die ("I don't know you");
$_SESSION['user'] = $linux;
$_SESSION['name'] = $name;
}
$user = $_SESSION['user'];
$name = $_SESSION['name'];
//------------------------------ now save file
$file = $_FILES['mugshot'];
if ($file['size'] > 100000 || $file['size'] < 10)
die ("File too large (or small)\n");
if ($file['error'] != UPLOAD_ERR_OK) die ("File upload failed");
if (!move_uploaded_file($file['tmp_name'],"upload/$user-{$file['name']}"))
die ('Possible attack! File: ' . $file['name']."\n") ;
// -- now you could insert info about the file into your database
?>
File is uploaded.
<a href="upload/<?php print $user.'-'.$file['name'];?>">Look at it</a>
-------
Here (seeuploads.php) you could list the files. The list can
come from your database, and for instance be the result of a search
for particular sorts of files, topics, etc.
I took the simple method of just reading the upload/ directory, and
forming links. (This code is directly from the php documentation.)
<h1>All Uploaded files</h1>
<ul>
<?php
if ($handle = opendir('upload')) {
/* This is the correct way to loop over the directory. note that !== requires actual boolean */
while (false !== ($entry = readdir($handle)))
if ($entry != "." && $entry != "..") // don't want directories
echo "<li><a href=\"upload/$entry\">$entry</a></li>\n";
closedir($handle);
}
?>
</ul>
<a href=up.html>Upload a file</a>