Buscando más información en internet con respecto a subir archivos con PHP, encontré un código para subir archvos validando la extensión del mismo.

<?php
// Declare variables
// Get the basic file information
$userfile = $_FILES[‘userfile’][‘name’];
$file_size = $_FILES[‘userfile’][‘size’];
$file_temp = $_FILES[‘userfile’][‘tmp_name’];
$file_err = $_FILES[‘userfile’][‘error’];
$path = ‘images/’;

// Create a new file name
// This is so if other files on the server have the same name, it will be renamed
$randomizer = rand(0000, 9999);
$file_name = $randomizer.$userfile;

// Get the file type
// Using $_FILES to get the file type is sometimes inaccurate, so we are going
// to get the extension ourselves from the name of the file
// This also eliminates having to worry about the MIME type
$file_type = $userfile;
$file_type_length = strlen($file_type) – 3;
$file_type = substr($file_type, $file_type_length);

if(!empty($userfile)) {
echo ‘<div style=”font-weight: bold; padding: 6px;”>File Uploaded  Information</div>
<ul>
<li>Original File Name: ‘ .$userfile. ‘</li>
<li>New File Name: ‘ .$file_name. ‘</li>
<li>File Type: ‘ .$file_type.'</li>
<li>File Size: ‘ .$file_size. ‘</li>
<li>File Temporary Name: ‘ .$file_temp. ‘</li>
<li>Fille Error: ‘ . $file_err. ‘</li>
</ul>’;

// limit the size of the file to 200KB
if($file_size > 25600) {
echo ‘FILE SIZE TO LARGE<BR />’;
exit();
}

// Set allowed file types
// Set case of all letters to lower case
$file_type = strtolower($file_type);
$files = array();
$files[] = ‘jpeg’;
$files[] = ‘jpg’;
$files[] = ‘gif’;
$files[] = ‘png’;
// Search the array for the allowed file type
$key = array_search($file_type, $files);
if($key) {
echo ‘<b>File allowed!</b><br />’;
} else {
echo ‘<b>ILLEGAL FILE TYPE</b><br />’;
exit();
}

// Check for errors and upload the file
$error_count = count($file_error);
if($error_count > 0) {
for($i = 0; $i <= $error_count; ++$i) {
echo $_FILES[‘userfile’][‘error’][$i];
}
} else {
if(move_uploaded_file($file_temp, ‘images/’ .$file_name.”)) {
echo ‘<h3>Upload Successful!</h3>’;
} else {
echo ‘<h3>ERROR</h3>’;
}
}

} else {
echo ‘<h3>No file has been selected.</h3>’;
}
?>

Anuncios