Código:
<html>
<head>
<title>::: upload your file :::</title>
<link href="style.css" rel="stylesheet" type="text/css" />
<style type="text/css">
<!--
.style1 {
font-family: Geneva, Arial, Helvetica, sans-serif;
font-weight: bold;
color: #CC9900;
font-size: 12px;
}
.style5 {
font-family: Geneva, Arial, Helvetica, sans-serif;
font-size: 12px;
color: #999999;
}
-->
</style>
</head>
<body>
<br /><br />
<div class="main">
<div id="left">
<table width="353" border="0">
<tr>
<td><div align="center" class="style1">
<p> </p>
<p> </p>
<p>Suba su archivo</p>
</div>
<table width="383" height="139" border="0">
<tr>
<td><div align="center">
<p align="center"> </p>
<p align="center" class="style5">
<?php
function pArray($array) {
print '<pre style="background:#faebd7">';
print_r($array);
print '</pre>';
}
require_once('upload.class.php');
$Upload = new Upload();
if (!Empty($_POST['submit'])) {
//formato del archivo
$Upload-> Extension = '.flv;.mp4;.wav;.mpeg;';
$Upload-> DirUpload = '.';
$Upload-> Execute();
if ($UploadError) {
print 'Ha ocurrido un error :';
pArray($Upload-> GetError());
} else {
print 'Su archivo ha sido cargado con exito, muchas gracias ::';
print 'La carga de su archivo ha generado el siguiente suceso::';
pArray($Upload-> GetSummary());
}
}
//tamaño del archivo a subir
$Upload-> MaxFilesize = '1024';
$Upload-> FieldOptions = 'style="border-color:black;border-width:1px;"';
$Upload-> Fields = 2;
$Upload-> InitForm();
?>
<form method="post" enctype="multipart/form-data" name="formulaire" id="formulaire" action="subir.php">
<?php
print $Upload-> Field[0];
print $Upload-> Field[1] . '<br>';
print $Upload-> Field[2];
?>
<br>
<input type="submit" value="Subir archivo" name="submit">
</form>
</p>
</div></td>
</tr>
</table>
<p> </p>
<p> </p>
<p> </p></td>
</tr>
</table>
<br/>
</div>
<div id="footer"></div>
</div>
</body>
</html>
este es el primer php para la subida de un archivo, pero para que funcione necesitas tener este otro...
este php debe estar con el nombre de upload.class.php
Código:
<?php
global $UploadError;
class Upload {
var $MaxFilesize;
var $ImgMaxWidth;
var $ImgMaxHeight;
var $ImgMinWidth;
var $ImgMinHeight;
var $DirUpload;
var $Debit;
var $Fields;
var $FieldOptions;
var $Required;
var $SecurityMax;
var $Filename;
var $Prefixe;
var $Suffixe;
var $WriteMode;
var $CheckReferer;
var $MimeType;
var $TrackError;
function Upload() {
$this-> Extension = '';
$this-> DirUpload = '';
$this-> MimeType = '';
$this-> Filename = '';
$this-> FieldOptions = '';
$this-> Fields = 1;
$this-> WriteMode = 0;
$this-> Debit = 33.6;
$this-> SecurityMax = false;
$this-> CheckReferer = false;
$this-> Required = false;
$this-> TrackError = true;
$this-> ArrOfError = Array();
$this-> MaxFilesize = ereg_replace('M', '', ini_get('upload_max_filesize')) * 1024;
}
function InitForm() {
$this-> SetMaxFilesize();
$this-> CreateFields();
}
function GetError($num_field='') {
if (Empty($num_field)) return $this-> ArrOfError;
else return $this-> ArrOfError[$num_field];
}
function GetSummary($num_field='') {
if ($num_field == '') return $this-> Infos;
else return $this-> Infos[$num_field];
}
function Execute(){
$this-> CheckConfig();
$this-> VerifyReferer();
$this-> SetTimeLimit();
$this-> CheckUpload();
}
function CheckUpload() {
global $UploadError;
for ($i=0; $i < count($_FILES['userfile']['tmp_name']); $i++) {
$this-> _field = $i+1;
$this-> _size = $_FILES['userfile']['size'][$i];
$this-> _type = $_FILES['userfile']['type'][$i];
$this-> _name = $_FILES['userfile']['name'][$i];
$this-> _temp = $_FILES['userfile']['tmp_name'][$i];
$this-> _ext = strtolower(substr($this-> _name, strrpos($this-> _name, '.')));
if (is_uploaded_file($_FILES['userfile']['tmp_name'][$i])) {
$this-> CheckSecurity();
$this-> CheckMimeType();
$this-> CheckExtension();
$this-> CheckImg();
} else $this-> AddError($_FILES['userfile']['error'][$i]);
if (!isset($this-> ArrOfError[$this-> _field])) $this-> WriteFile($this-> _name, $this-> _type, $this-> _temp, $this-> _size, $this-> _ext, $this-> _field);
else $UploadError = true;
}
}
function WriteFile($name, $type, $temp, $size, $ext, $num_field) {
$new_filename = NULL;
if (is_uploaded_file($temp)) {
if (Empty($this-> Filename)) $new_filename = $this-> CleanStr(substr($name, 0, strrpos($name, '.')));
else $new_filename = $this-> Filename;
$new_filename = $this-> Prefixe . $new_filename . $this-> Suffixe . $ext;
switch ($this-> WriteMode) {
case 0 : $uploaded = move_uploaded_file($temp, $this-> DirUpload . $new_filename);
break;
case 1 : if ($this-> AlreadyExist($new_filename)) $new_filename = 'copie_de_' . $new_filename;
$uploaded = move_uploaded_file($temp, $this-> DirUpload . $new_filename);
break;
case 2 : if ($this-> AlreadyExist($new_filename)) $uploaded = true;
else $uploaded = move_uploaded_file($temp, $this-> DirUpload . $new_filename);
break;
}
if ($uploaded != false) {
$this-> Infos[$num_field]['nom'] = $new_filename;
$this-> Infos[$num_field]['nom_originel'] = $name;
$this-> Infos[$num_field]['chemin'] = $this-> DirUpload . $new_filename;
$this-> Infos[$num_field]['poids'] = number_format(filesize($this-> DirUpload . $new_filename)/1024, 3, '.', '');
$this-> Infos[$num_field]['mime-type'] = $type;
$this-> Infos[$num_field]['extension'] = $ext;
}
return true;
}
return false;
}
function AlreadyExist($file) {
if (!file_exists($this-> DirUpload . $file)) return false;
else return true;
}
function CheckImg() {
if ($taille = @getimagesize($this-> _temp) ) {
if (!Empty($this-> ImgMaxWidth) && $taille[0] > $this-> ImgMaxWidth) $this-> AddError(8);
if (!Empty($this-> ImgMaxHeight) && $taille[1] > $this-> ImgMaxHeight) $this-> AddError(9);
if (!Empty($this-> ImgMinWidth) && $taille[0] < $this-> ImgMinWidth) $this-> AddError(10);
if (!Empty($this-> ImgMinHeight) && $taille[1] < $this-> ImgMinHeight) $this-> AddError(11);
}
return true;
}
function CheckExtension() {
$ArrOfExtension = explode(';', strtolower($this-> Extension));
if (!Empty($this-> Extension) && !in_array($this-> _ext, $ArrOfExtension)) {
$this-> AddError(7);
return false;
}
return true;
}
function CheckMimeType() {
$ArrOfMimeType = explode(';', $this-> MimeType);
if (!Empty($this-> MimeType) && !in_array($this-> _type, $ArrOfMimeType)) {
$this-> AddError(6);
return false;
}
return true;
}
function AddError($code_erreur) {
switch ($code_erreur) {
case 1 : $msg = 'Le fichier à charger excède la directive upload_max_filesize (php.ini) ('. $this-> _name .')';
break;
case 2 : $msg = 'Le fichier excède la directive MAX_FILE_SIZE qui a été spécifiée dans le formulaire ('. $this-> _name .')';
break;
case 3 : $msg = 'Le fichier n\'a pu être chargé complètement ('. $this-> _name .')';
break;
case 4 : $msg = 'Le champ du formulaire est vide';
break;
case 5 : $msg = 'Fichier potentiellement dangereux ('. $this-> _name .')';
break;
case 6 : $msg = 'Le fichier n\'est pas conforme à la liste des entêtes autorisés ('. $this-> _name .')';
break;
case 7 : $msg = 'Le fichier n\'est pas conforme à la liste des extensions autorisées ('. $this-> _name .')';
break;
case 8 : $msg = 'La largeur de l\'image dépasse celle autorisée ('. $this-> _name .')';
break;
case 9 : $msg = 'La hauteur de l\'image dépasse celle autorisée ('. $this-> _name .')';
break;
case 10 : $msg = 'La largeur de l\'image est inférieure à celle autorisée ('. $this-> _name .')';
break;
case 11 : $msg = 'La hauteur de l\'image est inférieure à celle autorisée ('. $this-> _name .')';
break;
}
if ($this-> Required && $code_erreur == 4) $this-> ArrOfError[$this-> _field][$code_erreur] = $msg;
else if ($code_erreur != 4) $this-> ArrOfError[$this-> _field][$code_erreur] = $msg;
}
function CheckSecurity() {
if ($this-> SecurityMax===true) {
if (ereg ('application/octet-stream', $this-> _type) || preg_match("/.php$|.inc$|.php3$/i", $this-> _ext) ) {
$this-> AddError(5);
return false;
}
}
return true;
}
function CheckDirUpload() {
if (Empty($this-> DirUpload)) $this-> DirUpload = dirname(__FILE__);
$this-> DirUpload = $this-> FormatDir($this-> DirUpload);
if (!is_dir($this-> DirUpload)) $this-> Error('Le répertoire de destination spécifiée par la propriété DirUpload n\'existe pas.');
if (!is_writeable($this-> DirUpload)) $this-> Error('Le répertoire de destination spécifiée par la propriété DirUpload est inaccessible en écriture.');
}
function FormatDir($Dir) {
if (function_exists('realpath')) {
if (realpath($Dir)) $Dir = realpath($Dir);
}
if ($Dir[strlen($Dir)-1] != DIRECTORY_SEPARATOR) $Dir .= DIRECTORY_SEPARATOR;
return $Dir;
}
function CleanStr($str) {
$return = '';
for ($i=0; $i <= strlen($str)-1; $i++) {
if (eregi('[a-z]',$str{$i})) $return .= $str{$i};
elseif (eregi('[0-9]', $str{$i})) $return .= $str{$i};
elseif (ereg('[àâäãáåÀÁÃÄÅ]', $str{$i})) $return .= 'a';
elseif (ereg('[æÆ]', $str{$i})) $return .= 'a';
elseif (ereg('[çÇ]', $str{$i})) $return .= 'c';
elseif (ereg('[éèêëÉÈÊËE]', $str{$i})) $return .= 'e';
elseif (ereg('[îïìíÌÍÎÏ]', $str{$i})) $return .= 'i';
elseif (ereg('[ôöðòóÒÓÔÕÖ]', $str{$i})) $return .= 'o';
elseif (ereg('[ùúûüÙÚÛÜ]', $str{$i})) $return .= 'u';
elseif (ereg('[ýÿÝŸ]', $str{$i})) $return .= 'y';
elseif (ereg('[ ]', $str{$i})) $return .= '_';
elseif (ereg('[.]', $str{$i})) $return .= '_';
else $return .= $str{$i};
}
return $return;
}
function VerifyReferer() {
if (!Empty($this-> CheckReferer)) {
$headerref = $_SERVER['HTTP_REFERER'];
if (ereg("\?",$headerref)){
list($url, $getstuff) = split('\?', $headerref);
$headerref = $url;
}
if ($headerref == $this-> CheckReferer) return true;
else $this-> Error('Accès refusé');
}
}
function SetTimeLimit(){
@set_time_limit(ceil(ceil($this-> $_POST['MAX_FILE_SIZE'] * 8) / ($this-> Debit * 1000) * count($_FILES) * 2));
}
function SetMaxFilesize() {
(is_numeric($this-> MaxFilesize)) ? $this-> MaxFilesize = $this-> MaxFilesize * 1024 : $this-> Error('la propriété MaxFilesize doit être une valeur numérique');
}
function CreateFields() {
if (!is_int($this-> Fields)) $this-> Error('la propriété Fields doit être un entier');
for ($i=0; $i <= $this-> Fields; $i++) {
if ($i == 0) $this-> Field[] = '<input type="hidden" name="MAX_FILE_SIZE" value="'. $this-> MaxFilesize .'">';
else $this-> Field[] = '<input type="file" name="userfile[]" '. $this-> FieldOptions .'>';
}
}
function CheckConfig() {
if (!version_compare(phpversion(), '4.2.0')) $this-> Error('la version de php sur ce serveur est trop ancienne. La classe ne peut fonctionner qu\'avec une version égale ou supérieure à la version 4.1.0');
if (!is_string($this-> Extension)) $this-> Error('la propriété Extension est mal configurée.');
if (!is_string($this-> MimeType)) $this-> Error('la propriété MimeType est mal configurée.');
if (!is_string($this-> Filename)) $this-> Error('la propriété Filename est mal configurée.');
if (!is_numeric($this-> Debit)) $this-> Error('la propriété Debit est mal configurée.');
if (!is_bool($this-> Required)) $this-> Error('la propriété Required est mal configurée.');
if (!is_bool($this-> SecurityMax)) $this-> Error('la propriété SecurityMax est mal configurée.');
if ($this-> WriteMode != 0 && $this-> WriteMode != 1 && $this-> WriteMode != 2) $this-> Error('la propriété WriteMode est mal configurée.');
if (!Empty($this-> CheckReferer) && !@fopen($this-> CheckReferer, 'r')) $this-> Error('la propriété CheckReferer est mal configurée.');
$this-> CheckImgPossibility();
$this-> CheckDirUpload();
}
function CheckImgPossibility() {
if (!Empty($this-> ImgMaxWidth) && !is_numeric($this-> ImgMaxWidth)) $this-> Error('la propriété ImgMaxWidth est mal configurée.');
if (!Empty($this-> ImgMaxHeight) && !is_numeric($this-> ImgMaxHeight)) $this-> Error('la propriété ImgMaxHeight est mal configurée.');
if (!Empty($this-> ImgMinWidth) && !is_numeric($this-> ImgMinWidth)) $this-> Error('la propriété ImgMinWidth est mal configurée.');
if (!Empty($this-> ImgMinHeight) && !is_numeric($this-> ImgMinHeight)) $this-> Error('la propriété ImgMinHeight est mal configurée.');
}
function Error($error_msg) {
if ($this-> TrackError) {
echo 'Erreur classe Upload : ' . $error_msg;
exit;
}
}
}
?>
Este codigo lo podés encontrar mas completo en www.desarrolloweb.com/scripts/php.php
para la proxima ves que postees al menos investiga por tu cuenta un poco y no vengas con las manos vacias.
--
OHK