PHP Script – Uploading multiple files to a directory

Below is a little script I came up with for uploading multiple files to a directory. With some basic PHP knowledge, you can alter it very easily. For beginners, just change the variables that I have given for you at the beginning of the file.

The ultimate goal of this is to show webmasters how to handle files being uploaded through forms. If you have any comments about my code, please feel free to post.

PHP Code:


 <html>

<head>

<title>File Upload Script</title>

<style type="text/css">

<!--

bodytd font-familyverdanagenevaarialhelveticasans-seriffont-size70%; colorblack; }

.button  background-color#eeeeee; border: 1px ridge gray; font-family: verdana, geneva, arial, helvetica, sans-serif; font-weight: bold; }

.input   background-color#eeeeee; border: 1px solid black; font-family: verdana, geneva, arial, helvetica, sans-serif; font-weight: bold; }

-->

</style>

<script language="javascript">

<!--

function uploadprompt()

{

var uploads prompt("How many upload fields would you like? Min: 1 Max: 10""3");

if (uploads == null || uploads || uploads 10)

{

return 0;

}

else

{

window.location "<?php echo $_SERVER['PHP_SELF']; ?>?uploads="+uploads;

}

}

//-->

</script>

</head>

<body>

<?php

// Some variables for you to set

$dir      './files';      // Path to directory to get and upload files

$fdate    'M j y, h:i a'// Format for dates

$uploads  2;              // Default number of uploads

$max_size 3000;           // Maximum file size allowed (in bytes)

// Do not change

$update    = (isset($_POST['update'])) ? true false;

$files     = array();

$row_class '';

// If the prompt was used, adjust $uploads accordingly

if (isset($_GET['uploads']))

{

if (!($_GET['uploads'] <= || $_GET['uploads'] > 10))

{

$uploads intval($_GET['uploads']);

}

}

// If the directory doesn't exist, attempt to create it

if (!file_exists($dir))

{

@mkdir($dir0776);

}

if (!$handle opendir($dir))

{

echo 'Cannot open directory.';

exit;

}

?>

<table width="100%">

<tr>

<td valign="top">

<table cellspacing="1" cellpadding="4" style="border: 1px solid #494949">

<tr>

<td bgcolor="#EEEEF9">

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">

<input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max_size?>" />

<b>File Upload</b> [<a href="#" onclick="uploadprompt()">change number of fields</a>]<br /><br />

<table>

<tr>

<td valign="top">File(s)</td>

<td>

<?php

for ($i 1$i <= $uploads$i++)

{

echo '<input type="file" name="file[]" class="input" /><br /><br />';

}

?></td>

</tr>

</table>

<div align="right"><input class="button" type="submit" name="update" value="Upload" /></div>

</form></td>

</tr>

</table><br />

<?php

// Was the form updated?

if ($update)

{

// Make sure we can write to the directory

if (!is_writable($dir))

{

if (!chmod($dir0776))

{

echo 'Can\'t change mode of directory.';

exit;

}

}

// Loop through uploaded files and decide what to do with each one

for ($i 0$i <= sizeof($_FILES['file']); $i++)

{

if ($_FILES['file']['tmp_name'][$i] == '')

{

continue;

}

if (!is_uploaded_file($_FILES['file']['tmp_name'][$i]))

{

echo 'Possible file upload attack, stopping execution.';

exit;

}

if ($_FILES['file']['size'][$i] == 0)

{

echo $_FILES['file']['name'][$i] . ': <span style="color: #ff0000">skipped (zero length)</span><br />';

continue;

}

if ($_FILES['file']['size'][$i] > $max_size)

{

echo $_FILES['file']['name'][$i] . ': <span style="color: #ff0000">skipped (exceeds maximum size of ' $max_size ' bytes)</span><br />';

continue;

}

if (file_exists("{$dir}/{$_FILES['file']['name'][$i]}"))

{

echo $_FILES['file']['name'][$i] . ': <span style="color: #ff0000">skipped (filename already exists)</span><br />';

continue;

}

if ([email protected]copy($_FILES['file']['tmp_name'][$i], "{$dir}/{$_FILES['file']['name'][$i]}"))

{

echo $_FILES['file']['name'][$i] . ': <span style="color: #ff0000">could not move file into directory</span><br />';

continue;

}

echo $_FILES['file']['name'][$i].': uploaded<br />';

}

}

?>

    </td>

<td style="vertical-align: top" width="100%">

<table width="100%" cellspacing="1" cellpadding="4">

<tr>

<td style="background-color: #8F9AB7"><b>File name</b></td>

<td style="background-color: #8F9AB7" width="130"><b>File Size (bytes)</b></td>

<td style="background-color: #8F9AB7" width="130"><b>Last Accessed</b></td>

<td style="background-color: #8F9AB7" width="130"><b>Last Modified</b></td>

</tr>

<tr>

<td style="background-color: #8F9AB7" colspan="4"><b><?php echo $dir?></b></td>

</tr>

<?php

// Get information on each file and store as array

while ($file readdir($handle))

{

$file_path "{$dir}/{$file}";

if($file != '.' && $file != '..' && is_file($file_path))

{

$stat stat($file_path);

$files[$file]['filesize']  = $stat['size'];

$files[$file]['fileatime'] = date($fdate$stat['atime']);

$files[$file]['filectime'] = date($fdate$stat['ctime']);

}

}

ksort($filesSORT_REGULAR);

reset($files);

// Display files

foreach ($files as $filename => $fileinfo)

{

$row_class = ($row_class != '#DCE2F2') ? '#DCE2F2' '#CFD5E5';

echo '      <tr>';

echo "        <td style=\"background-color: {$row_class}\">{$filename}</td>";

echo "        <td style=\"background-color: {$row_class}\">{$fileinfo['filesize']}</td>";

echo "        <td style=\"background-color: {$row_class}\">{$fileinfo['fileatime']}</td>";

echo "        <td style=\"background-color: {$row_class}\">{$fileinfo['filectime']}</td>";

echo '      </tr>';

}

?>

    </table></td>

</tr>

</table>

</body>

</html>


 

Write a Comment

Your email address will not be published. Required fields are marked *