Wednesday, September 16, 2009

file uploads using PHP

write an HTML form that allows users to upload files. HTML makes this quite easy with its tag. By default, however, only the name of the file selected by the user is sent. To have the file itself submitted with the form data, we need to add enctype="multipart/form-data" to the tag in the SitePoint HTML Reference." href="http://reference.sitepoint.com/html/form">
tag:

enctype="multipart/form-data">







The $_FILES superglobal variable helps in uploading the file

// Pick a file extension
if (preg_match('/^image\/p?jpeg$/i', $_FILES['upload']['type']))
{
$ext = '.jpg';
}
else if (preg_match('/^image\/gif$/i', $_FILES['upload']['type']))
{
$ext = '.gif';
}
else if (preg_match('/^image\/(x-)?png$/i',
$_FILES['upload']['type']))
{
$ext = '.png';
}
else
{
$ext = '.unknown';
}

// The complete path/filename
$filename = 'C:/uploads/' . time() . $_SERVER['REMOTE_ADDR'] . $ext;

// Copy the file (if it is deemed safe)
if (!is_uploaded_file($_FILES['upload']['tmp_name']) or
!copy($_FILES['upload']['tmp_name'], $filename))
{
$error = "Could not save file as $filename!";
include $_SERVER['DOCUMENT_ROOT'] . '/includes/error.html.php';
exit();
}



No comments:

Post a Comment