Descarga archivos mediante PHP
24/8/10
Pues ya que algunos hosting gratuitos no permiten que descargues archivos con extensión .exe y similar, he buscado un script en PHP para ello y viendo que no cumplía todos los requisitos que yo necesitaba, pues se los he añadido.
La versión original se puede encontrar en http://www.finalwebsites.com/forums/topic/php-file-download
Las cosas que he añadido han sido prohibición de extensiones y de ciertos archivos. Esto es útil sobre todo para evitar que se descarguen archivos interpretados que puedan poner en peligro la seguridad del portal, por ejemplo .php o .pl.
El link de descarga es el siguiente, espero que lo disfruten: download.zip
Aquí el código:
<?php
//@original from: http://www.finalwebsites.com/forums/topic/php-file-download
//@modified by: A.Sánchez (plutec.net) (asanchez@plutec.net)
$ban_ext=array("php","exe"); //Banned extensions
$ban_files=array("file1.php","file2.php"); //Banned files/paths
$path = $_SERVER['DOCUMENT_ROOT']."/"; // Change the path to fit your websites document structure
if (!isset($_GET['file'])) {
echo "Sintax error.
";
echo "Example: http://".$_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF']."?file=example.txt";
return;
} else {
$filename=$_GET['file'];
$fullPath = $path.$_GET['file'];
}
//First, banned files or paths.
foreach($ban_files as $i => $bfile) {
if ($bfile == $filename) {
echo "Banned file.";
return;
}
} //Second, banned extensions.
foreach($ban_ext as $i => $ext) {
$pattern="/\.$ext$/";
preg_match($pattern, $filename, $match, PREG_OFFSET_CAPTURE);
if ($match) {
echo "Banned extension.";
return;
}
}
if (!file_exists($fullPath)) {
echo "File not found!";
return;
} else {
if ($fd = fopen ($fullPath, "r")) {
$fsize = filesize($fullPath);
$path_parts = pathinfo($fullPath);
$ext = strtolower($path_parts["extension"]);
switch ($ext) {
case "pdf":
header("Content-type: application/pdf"); // add here more headers for diff. extensions
header("Content-Disposition: attachment; filename=\"".$path_parts["basename"]."\""); // use 'attachment' to force a download
break;
default;
header("Content-type: application/octet-stream");
header("Content-Disposition: filename=\"".$path_parts["basename"]."\"");
}
header("Content-length: $fsize");
header("Cache-control: private"); //use this to open files directly
while(!feof($fd)) {
$buffer = fread($fd, 2048);
echo $buffer;
}
}
fclose ($fd);
}
// example: place this kind of link into the document where the file download is offered:
// <a href="download.php?file=some_file.pdf">Download here</a>
?>
Un saludo!
Sección Robocode
25/6/10
Como bien dice el título, estrenamos sección de Robocode, un juego bastante divertido para el que sepa programar, y para el que no sepa, ¿a qué esperas? ;)
Últimas entradas Blog
- Descarga archivos mediante PHP 24/8/10
- Sección Robocode 25/6/10
- UniverPiso 14/1/09
- Hosting 31/8/07