Сваляне на файл чрез php

proba

Registered
Здравейте.
Скоро бях видял подобна тема но я изгубих.
Да речем имам папка files
В нея има примерно test.php , muzika.rar , picture.png и т.н. - няма значение какви файлове (ще има форма за ъплоуд).
Идеята е с .htaccess да се забрани достъпа до папката.
И също така чрез php фаил да се свалят файловете.
Примерно:
download.php?file=test.php
Как може да стане това?
Пробвах с един код , но нещо не ми се получи.
Дайте идеи. ;)
 
Код:
<Files "config.php">
Order Allow,Deny
Deny from All
</Files>

<Files "common.php">
Order Allow,Deny
Deny from All
</Files>
Защити тоя download.php
 
EDIT:

Ето кода за download.php

<?php
$a = $_GET["file"];
$b = "files/";
$file = $b.$a;
if (isset($a) and !empty($a))
{
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/jpg');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit;
}
}
else
{
}
?>

Как да направя ако някой отвори /files/muzika.rar да не му пише примерно access denied (т.е. error 403 като при deny from all).
А когато опита чрез ?file=muzika.rar да си сваля файла.
Това е големия въпрос - как да стане ? ..
 
На бързо подбрах функции ето:
download.php
Код:
<?php
$path = 'papkata/';
	$browser = (!empty($_SERVER['HTTP_USER_AGENT'])) ? htmlspecialchars((string) $_SERVER['HTTP_USER_AGENT']) : '';
	$file = $path . basename($_GET['file']);

function header_filename($file)
{
	global $browser;
	// There be dragons here.
	// Not many follows the RFC...
	if (strpos($browser, 'MSIE') !== false || strpos($browser, 'Safari') !== false || strpos($browser, 'Konqueror') !== false)
	{
		return "filename=" . rawurlencode($file);
	}

	// follow the RFC for extended filename for the rest
	return "filename*=''" . rawurlencode($file);
}
    function get_mimetype($filename)
	{

        $mime_types = array(

            'txt' => 'text/plain',
            'htm' => 'text/html',
            'html' => 'text/html',
            'php' => 'text/html',
            'css' => 'text/css',
            'js' => 'application/javascript',
            'json' => 'application/json',
            'xml' => 'application/xml',
            'swf' => 'application/x-shockwave-flash',
            'flv' => 'video/x-flv',

            // images
            'png' => 'image/png',
            'jpe' => 'image/jpeg',
            'jpeg' => 'image/jpeg',
            'jpg' => 'image/jpeg',
            'gif' => 'image/gif',
            'bmp' => 'image/bmp',
            'ico' => 'image/vnd.microsoft.icon',
            'tiff' => 'image/tiff',
            'tif' => 'image/tiff',
            'svg' => 'image/svg+xml',
            'svgz' => 'image/svg+xml',

            // archives
            'zip' => 'application/zip',
            'rar' => 'application/x-rar-compressed',
            'exe' => 'application/x-msdownload',
            'msi' => 'application/x-msdownload',
            'cab' => 'application/vnd.ms-cab-compressed',

            // audio/video
            'mp3' => 'audio/mpeg',
            'qt' => 'video/quicktime',
            'mov' => 'video/quicktime',

            // adobe
            'pdf' => 'application/pdf',
            'psd' => 'image/vnd.adobe.photoshop',
            'ai' => 'application/postscript',
            'eps' => 'application/postscript',
            'ps' => 'application/postscript',

            // ms office
            'doc' => 'application/msword',
            'rtf' => 'application/rtf',
            'xls' => 'application/vnd.ms-excel',
            'ppt' => 'application/vnd.ms-powerpoint',

            // open office
            'odt' => 'application/vnd.oasis.opendocument.text',
            'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
        );

        $ext = strtolower(array_pop(explode('.',$filename)));
		if (empty($ext))
		{
            return 'application/octet-stream';
		}
        if (array_key_exists($ext, $mime_types)) {
            return $mime_types[$ext];
        }
        elseif (function_exists('finfo_open')) {
            $finfo = finfo_open(FILEINFO_MIME);
            $mimetype = finfo_file($finfo, $filename);
            finfo_close($finfo);
            return $mimetype;
        }
        else {
		$ext = substr(strrchr($filename, '.'), 1); 
	   if (empty($ext)) return (false); 
	   $regex = "/^([\w\+\-\.\/]+)\s+(\w+\s)*($fileext\s)/i"; 
	   $mime_types = file("$mimePath/mime.types"); 
	   foreach($mime_types as $line) { 
		  if (substr($line, 0, 1) == '#') continue; // skip comments 
		  $line = rtrim($line) . " "; 
		  if (!preg_match($regex, $line, $matches)) continue; // no match to the extension 
		  return ($matches[1]); 
	   } 
				return 'application/octet-stream';
		}
	}

	if ((@file_exists($file) && @is_readable($file)))
	{
			header('Pragma: public');
			header('Content-Type: ' . get_mimetype($file));
		if (strpos(strtolower($browser), 'msie') !== false && strpos(strtolower($browser), 'msie 8.0') === false)
		{
			header('Content-Disposition: attachment; ' . header_filename($file));

			if (strpos(strtolower($browser), 'msie 6.0') !== false)
			{
				header('Expires: -1');
			}
			else
			{
				header('Expires: ' . gmdate('D, d M Y H:i:s \G\M\T', time() + 31536000));
			}
		}
		else
		{
			header('Content-Disposition: inline; ' . header_filename($file));
			header('Expires: ' . gmdate('D, d M Y H:i:s \G\M\T', time() + 31536000));
		}

		$size = @filesize($file);
		if ($size)
		{
			header("Content-Length: $size");
		}

		if (@readfile($file) == false)
		{
			$fp = @fopen($file, 'rb');

			if ($fp !== false)
			{
				while (!feof($fp))
				{
					echo fread($fp, 8192);
				}
				fclose($fp);
			}
		}
		exit;
	}
	header('HTTP/1.0 404 Not Found');

Код:
<Files *>
	Order Allow,Deny
	Deny from All
</Files>
 
Кода не работи..
При rar файлове работи.
Но като опитам .txt не става.
Изкарва ми кода на файловете (като са .txt)
Примерно във файла sad.txt пише това "sada " и като отворя ?file=sad.txt ми изписва "sada " в бялата страница.. Вместо да свали файла.
Пък уж трябва да става.. Някаква идея как да се управи ?
 
Пробвай така..

Код:
<?php
$a = $_GET["file"];
$b = "files/";
$file = $b.$a;
if (isset($a) and !empty($a))
{
if (file_exists($file)) {
header('Content-Description: File Transfer');
// archives
header('Content-Type: application/zip');
header('Content-type: application/x-rar-compressed');
header('Content-Type: application/vnd.ms-cab-compressed');
header('Content-type: application/x-msdownload');

//txt, php
header('Content-type: text/plain');
header('Content-type: text/html');

header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit;
}
}
else
{
}
?>

Прочети за header функцията тук: http://php.net/manual/en/function.header.php
 
Въпроса ми беше как да забраня достъпа до папката , а иначе да си ги тегля с моя скрипт.
Както се оказа с моя скрипт ги тегля , а ги забраних чрез
<Files *>
Order Allow,Deny
Deny from All
</Files>

Ще си ползвам моя код за download.php
Благодаря и на двамата , но cnoko получава +1 , зааради кода за htaccess-a който ми даде...........
 
Е да като за бърза работа
скрипт за сваляне на файлове не се прави толкова лесно а и като се има напредвид че PHP не дава функция за разпознаване на типа на файла ест става с exec но повечето хостове я забраняват.
След това идва кой тип файл какви headeri му трябват
И накрая работа с браузера (headers).
 

Back
Горе