En este código fuente, puede aprender a Subir y Descargar Archivos en PHP y MYSQL. El proyecto puede almacenar diferentes tipos u formatos de archivos y también el usuario puede descargar el archivo cargado. El código fuente puede detectar si el nombre del archivo tiene duplicados y agregará automáticamente un número, por ejemplo, si el nombre de archivo «sample.pdf» ya existe en la base de datos, el sistema almacenará el archivo como «sample_2.pdf» y si alguna vez el usuario lo cargará un archivo con el mismo nombre de archivo, el sistema también comprobará si el nuevo nombre de archivo no tiene duplicados. Además del escenario de ejemplo, si el usuario carga «sample.php», el sistema lo cambiará a «sample_3».
Extensiones de formato de archivo aceptables:
pdf
TXT
html
htm
exe
Código Postal
Doc
xls
ppt
gif
png
jpeg
jpg
php
Configurar un servidor web local
Primero, descargue e instale XAMPP para ejecutar un script PHP en su máquina local.
Después de la instalación exitosa, ejecute el Panel de control de XAMPP e inicie «Apache» y «MYSQL».
Luego, abra un navegador web y busque «localhost/phpmyadmin»
Cree una nueva base de datos y asígnele el nombre «demo». Luego haga clic en la navegación SQL y copie / pegue el código a continuación:
CREATE TABLE `upload` ( `id` int(11) NOT NULL, `fname` text NOT NULL, `name` varchar(200) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Formulario de carga de archivos
<form enctype="multipart/form-data" action="" name="form" method="post">
Seleccione Archivo
<input type="file" name="file" id="file" /></td>
<input type="submit" name="submit" id="submit" value="Subir" />
</form>
Script PHP de subida de archivos
<?php
$conn=new PDO('mysql:host=localhost; dbname=demo', 'root', '2012116664') or die(mysql_error());
if(isset($_POST['submit'])!=""){
$name=$_FILES['file']['name'];
$size=$_FILES['file']['size'];
$type=$_FILES['file']['type'];
$temp=$_FILES['file']['tmp_name'];
// $caption1=$_POST['caption'];
// $link=$_POST['link'];
$fname = date("YmdHis").'_'.$name;
$chk = $conn->query("SELECT * FROM upload where name = '$name' ")->rowCount();
if($chk){
$i = 1;
$c = 0;
while($c == 0){
$i++;
$reversedParts = explode('.', strrev($name), 2);
$tname = (strrev($reversedParts[1]))."_".($i).'.'.(strrev($reversedParts[0]));
// var_dump($tname);exit;
$chk2 = $conn->query("SELECT * FROM upload where name = '$tname' ")->rowCount();
if($chk2 == 0){
$c = 1;
$name = $tname;
}
}
}
$move = move_uploaded_file($temp,"upload/".$fname);
if($move){
$query=$conn->query("insert into upload(name,fname)values('$name','$fname')");
if($query){
header("location:index.php");
}
else{
die(mysql_error());
}
}
}
?>
Listado en una tabla de archivos subidos
<table cellpadding="0" cellspacing="0" border="0" class="table table-striped table-bordered" id="example">
<thead>
<tr>
<th width="90%" align="center">Archivos</th>
<th align="center">Accion</th>
</tr>
</thead>
<?php
$query=$conn->query("select * from upload order by id desc");
while($row=$query->fetch()){
$name=$row['name'];
?>
<tr>
<td>
<?php echo $name ;?>
</td>
<td>
<button class="alert-success"><a href="download.php?filename=<?php echo $name;?>&f=<?php echo $row['fname'] ?>">Descargar</a></button>
</td>
</tr>
<?php }?>
</table>
Script para descargador archivos subidos
<?php
// exit;
function output_file($file, $name, $mime_type='')
{
if(!is_readable($file)) die('File not found!');
$size = filesize($file);
$name = rawurldecode($name);
$known_mime_types=array(
"pdf" => "application/pdf",
"txt" => "text/plain",
"html" => "text/html",
"htm" => "text/html",
"exe" => "application/octet-stream",
"zip" => "application/zip",
"doc" => "application/msword",
"xls" => "application/vnd.ms-excel",
"ppt" => "application/vnd.ms-powerpoint",
"gif" => "image/gif",
"png" => "image/png",
"jpeg"=> "image/jpg",
"jpg" => "image/jpg",
"php" => "text/plain"
);
if($mime_type==''){
$file_extension = strtolower(substr(strrchr($file,"."),1));
if(array_key_exists($file_extension, $known_mime_types)){
$mime_type=$known_mime_types[$file_extension];
} else {
$mime_type="application/force-download";
};
};
@ob_end_clean();
if(ini_get('zlib.output_compression'))
ini_set('zlib.output_compression', 'Off');
header('Content-Type: ' . $mime_type);
header('Content-Disposition: attachment; filename="'.$name.'"');
header("Content-Transfer-Encoding: binary");
header('Accept-Ranges: bytes');
header("Cache-control: private");
header('Pragma: private');
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
if(isset($_SERVER['HTTP_RANGE']))
{
list($a, $range) = explode("=",$_SERVER['HTTP_RANGE'],2);
list($range) = explode(",",$range,2);
list($range, $range_end) = explode("-", $range);
$range=intval($range);
if(!$range_end) {
$range_end=$size-1;
} else {
$range_end=intval($range_end);
}
$new_length = $range_end-$range+1;
header("HTTP/1.1 206 Partial Content");
header("Content-Length: $new_length");
header("Content-Range: bytes $range-$range_end/$size");
} else {
$new_length=$size;
header("Content-Length: ".$size);
}
$chunksize = 1*(1024*1024);
$bytes_send = 0;
if ($file = fopen($file, 'r'))
{
if(isset($_SERVER['HTTP_RANGE']))
fseek($file, $range);
while(!feof($file) &&
(!connection_aborted()) &&
($bytes_send<$new_length)
)
{
$buffer = fread($file, $chunksize);
print($buffer);
flush();
$bytes_send += strlen($buffer);
}
fclose($file);
} else
die('Error - cannot open file.');
die();
}
set_time_limit(0);
$file_path='upload/'.$_REQUEST['f'];
output_file($file_path, ''.$_REQUEST['filename'].'', 'text/plain');
?>
Ese código fuente de Subir y Descargar Archivos en PHP y MYSQL es un script importante que necesitará para desarrollar un sistema de archivos de subida y descarga. También puede utilizar bootstrap para el diseño de su proyecto. Siéntase libre de copiar y pegar los códigos fuente anteriores e intente desarrollar un sistema simple de carga y descarga de archivos por su cuenta.
DESCARGAR TODO EL CODIGO FUENTE


Me encanto, muchas gracias.
Hola, muchas gracias. Estoy conociendo Bootstrap y quisiera consultarle como puedo modificar los textos «Search:» y «register per page». Podría orientarme por favor?. Saludos
hola enrique los puede modificar directamente desde el html con etiquetas de boop o para modificarlo totalmente lo puede hacer desde el css llamando los div e id que le parezcan en consola cuando inspeccione los elementos
muy buena ayuda
Es muy útil, me pueden ayudar a resolver una duda, ¿Qué se almacena en «fname» y en «name»?