Jump to content


gabsbs

Member Since 08/10/2004
Offline Last Active 05/05/2009, 17:52
-----

Topics I've Started

Lista De Arquivos No Servidor

04/05/2009, 18:55

Olá pessoal!!

blz?!

seguinte.. peguei um script php que lista os arquivos e pastas de um determinado local no servidor e cria um link para download ou navegação... Adaptei o script ao site que estou desenvolvendo, acrescentei várias modificações, criei o layout e pá.. agora que vou lançar o sistema ao publico, descubro que o script está com um problema que não consigo, por nada, resolver...

é o seguinte:

no script original, se as pastas ou arquivos tivessem espaços e/ou acentuações, o link quebrava, pois o código gerava um link com o nome real do arquivo ou pasta:


para solucionar este problema, eu alterei o código para que ele codificasse os nomes para o formato rawurlencode:


beleza!! isto resolveu todos os problemas de acesso as pastas ou download dos arquivos que tivessem acentos e etc... mas, em contrapartida, agora, todos os links darquivos dentro de "sub-sub-pastas" são gerados errados, pois, no lugar da " / " no endereço do link, é colocado o código referente a barra " %2F "

isto só acontece na segunda subpasta... veja o exemplo dos links gerados para um mesmo arquivo em diferentes pastas:

Pasta raiz: http://gabrielbueno....eno/arquivo.doc
Subpasta 1: http://gabrielbueno....201/arquivo.doc
Subpasta 1-2: http://gabrielbueno......no/subpasta 1%2Fsubpasta2/arquivo.doc

Como eu posso solucionar este problema sem que eu tenha que tirar o rawurencode?!


o codigo completo segue:

<?PHP$getfolder = $_GET["folder"];if ( $_SESSION["adm_tipo"] == "1" ) {    $dir_to_browse = "upload/files/Professores/".$_SESSION["adm_pasta"]."/";} else {     $dir_to_browse = "upload/files/Alunos/".$_SESSION["adm_pasta"]."/";}if(!empty($_GET["action"]))if($_GET["action"] == "upload"){    if($_GET["folder"] == "")	{		extract($_POST);		$fileup = $_FILES["upload"]["name"];		$sep1 = explode(".",$fileup);	    $up = move_uploaded_file($_FILES["upload"]["tmp_name"],"$dir_to_browse$fileup");		}	else {		extract($_POST);		$fileup = $_FILES["upload"]["name"];		$sep1 = explode(".",$fileup);	    $up = move_uploaded_file($_FILES["upload"]["tmp_name"],"$dir_to_browse$_GET[folder]/$fileup");	}}if(!empty($_GET["action"]))if($_GET["action"] == "del_file"){	unlink("$_GET[on]$_GET[file]");}if(!empty($_GET["action"]))if($_GET["action"] == "newfolder"){    if($_GET["folder"] == "")	{        $old_mask = umask(0); 	    mkdir("$dir_to_browse$_POST[foldername]", 0777); 	    umask($old_mask); 		}	else {	     $old_mask = umask(0); 	    mkdir("$dir_to_browse$_GET[folder]/$_POST[foldername]", 0777); 	    umask($old_mask);	}}//Exclude this file from being listed? 1:Yes 2:No$exclude_this_file = 1;//Files or folders to exclude from listing - note:index.php is this file by default.$exclude = array('.','..','.ftpquota','.htaccess','.fcimages');//Files to exclude based on extension (eg: '.jpg' or '.PHP') and weather to be case sensative. 1:Enable 0:Disable$exclude_ext = array('');$case_sensative_ext = 1; //default = 1//Enable/Disable statistics/legend/load time. 1:Enable 0:Disable$statistics = 1; //default = 1$legend = 1; //default = 1$load_time = 1; //default = 1//Show folder size? Disabling this will greatly improve performance if there are several hundred folders/files. However, size of folders wont show. 1:Enable 0:Disable$show_folder_size = 1; //default = 1$color_1 = "#F3F5F1";$color_2 = "#F8F9F7";$folder_color = "#DDE3D7";//Table formatting$top_row_bg_color = "#649126";$top_row_font_color = "#FFFFFF";$width_of_files_column = "417";$width_of_sizes_column = "70";$width_of_del_column = "48";$width_of_dates_column = "125";$cell_spacing = "2";$cell_padding = "2";if($load_time){	$mtime = microtime();	$mtime = explode(" ",$mtime);	$mtime = $mtime[1] + $mtime[0];	$starttime = $mtime;}//Start load time -doneif(get_magic_quotes_gpc())$folder = stripslashes($_GET['folder']);else$folder = $_GET['folder'];$dir_to_browse_original = $dir_to_browse;if(!empty($folder)){	$dir_to_browse = $dir_to_browse.$folder."/";	$folder_slash = $folder."/";}?><!-- Output basic HTML code --><style type="text/css"><!--a:link {	color: #5B8222;	text-decoration: none;}a:visited {	text-decoration: none;	color: #5B8222;}a:hover {	text-decoration: underline;	color: #5B8222;}a:active {	text-decoration: none;	color: #5B8222;}a.link2 {	color: #2D4011;	text-decoration: none;}a.link2:visited {	text-decoration: none;	color: #2D4011;}a.link2:hover {	text-decoration: underline;	color: #2D4011;}a.link2:active {	text-decoration: none;	color: #2D4011;}.top_row {    color: <?PHP echo $top_row_font_color; ?>;    font-weight: bold; 	font-size: 12px; }.table_border {	border: 1px dashed #666666;}.path_font {font-family: "Courier New", Courier, monospace}--></style><table width="100%" border="0" cellspacing="0" cellpadding="5">  <tr>     <td height="25"><font class="text2">	  :: Seus Arquivos </font>	</td>  </tr></table><!-- Output basic HTML code -done --><?php//Check if directory is valid$folder_exists = 1;if(!is_dir($dir_to_browse)) {	$folder = "";	$folder_exists = 0;}if($folder_exists == 0){	echo display_error_message2("<div align='center'><b>Erro!</b><br><br>Esta pasta não existe ou você não tem permissão para acessá-la<br><br><br> Isto pode ter ocorrido caso você tenha digitado o endereço manualmente</div>");	exit;}//Chcek if directory is valid -done//This is a VERY important security feature. It wont allow people to browse directories above $dir_to_browse. Edit this part at your own risk$folders_in_URL_security = explode("../",$folder);if(count($folders_in_URL_security) > 1){	echo display_error_message2("<b>Acesso Proibído</b>");	exit;}//Seurity feature -done//Create navigation links$this_file_name_array = explode("/","principal.php?pag=arq_lista");$this_file_name = array_pop($this_file_name_array);$folders_in_URL = explode("/",rawurldecode($folder));$depth = count($folders_in_URL);foreach($folders_in_URL as $key => $val){	$_temp = $_temp."/".$val;	$folders_in_URL_array[$key] = $_temp;	if($key == 0)	{		$_temp = $folders_in_URL[0];		$folders_in_URL_array[0] = $folders_in_URL[0];	}}$nav_links = "<a href=\"$this_file_name\">".$_SESSION["adm_nome"]."</a>&nbsp;/&nbsp;";for($i=0;$i<$depth;$i++){	if(!empty($folder))	$nav_links = $nav_links."<a href=\"principal.php?pag=arq_lista&folder=".rawurlencode($folders_in_URL_array[$i])."\">$folders_in_URL[$i]</a>&nbsp;/&nbsp;";	else	$nav_links = $nav_links."<a href=\"principal.php?pag=arq_lista&folder=".rawurlencode($folders_in_URL_array[$i])."\">$folders_in_URL[$i]</a>";}echo "<div style='padding-left:15px; padding-top:7px'>".$nav_links."</div><br>";if(!empty($_GET["action"]))if($_GET["action"] == "del_folder"){    $foldername = $_GET["name"];	if(file_exists($foldername."/")){ //Verifica se a pasta existe	$openfolder = opendir($foldername); //Abre a pasta	while($files = readdir($openfolder)) {		if(is_dir($foldername."/".$filename) && ! ($files == "." || $files == "..")){ //Abre pastas	@rmdir($foldername."/".$files) or $erro = 1;	}else if(is_file($foldername."/".$filename) && ! ($files == "." || $files == "..")){ //Abre arquivos	@unlink($foldername."/".$files) or $erro = 1;    }}    closedir($openfolder); //Fecha a pasta    @rmdir($foldername);    }else{    echo display_error_message("<div align='center'>Esta pasta não existe ou já foi excluída</div>");    }    if($erro == "1"){    echo display_error_message("<div align='center'>Esta pasta contém subpastas e/ou arquivos<br>Exclua primeiro seu conteúdo</div>");    }}//Get directory content (filtered(without the excluded specified above)) and seperate files and folders to 2 arrays$dir_content = get_dir_content($dir_to_browse);if($case_sensative_ext == 0){	foreach($exclude_ext as $key => $val)	{		$temp_ext = $val;		$exclude_ext[$key] = strtolower($temp_ext);	}}//If file extensions are NOT case sensative -done//Filter content$filtered_content = array();$filter_count = 0;foreach($dir_content as $key => $val){	$file_ext = explode(".",$val);	$file_ext = ".".array_pop($file_ext);	if(!in_array($val, $exclude) && !in_array($file_ext,$exclude_ext))	{		$filtered_content[$filter_count] = $val;		$filter_count++;	}}if($exclude_this_file == 1){	$array_with_this_file_name = array();	$temp_filtered_content = $filtered_content;	$filtered_content = array();	foreach($temp_filtered_content as $key => $val)	{		if($val == $this_file_name)		{			array_push($array_with_this_file_name, $key);			}		else		$filtered_content[$key] = $val;		}	foreach($array_with_this_file_name as $key => $val)	{		$temp_path = $folder."/".$this_file_name;		if(substr($temp_path,0,1) == "/") $temp_path = substr($temp_path,1);		if(is_file($temp_path))		{			$md5_temp_path = md5_file($temp_path);			$md5_this_file = md5_file($_SERVER['SCRIPT_FILENAME']);			if($md5_temp_path != $md5_this_file)			{			array_push($filtered_content, $this_file_name);			}		}		else		array_push($filtered_content, $this_file_name);			}}	//Filter content -done//Get directory content and seperate files and folders into 2 arrays -doneif(!empty($filtered_content)){	$folders_count = 0;	$files_count = 0;		$folders_array = array();	$files_array = array();			foreach($filtered_content as $key => $val)	{		$path = $dir_to_browse.$val;		if(is_dir($path))		{			array_push($folders_array, $val);		}		else		{			array_push($files_array, $val);		}	}		//Sort the files and folders arrays		if(!empty($folders_array)) natcasesort($folders_array);		if(!empty($files_array)) natcasesort($files_array);		$folders_array_temp = array();		$files_array_temp = array();		foreach($folders_array as $key => $val)		{			array_push($folders_array_temp, $val);		}		foreach($files_array as $key => $val)		{			array_push($files_array_temp, $val);		}		$folders_array = $folders_array_temp;		$files_array = $files_array_temp;	//Sort the files and folders arrays -done		//Determin OS PHP is running on	if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') 	$OS = "windows";		//Get files and folders sizes and creation dates		$folders_cdate_array = array();		$files_cdate_array = array();		$folders_size_array = array();		$folders_del_array = array();		$files_size_array = array();		$files_del_array = array();		$files_del_folder_array = array();		$files_total_size = 0;		$folders_total_size = 0;				foreach($files_array as $key => $val)		{			$path = $dir_to_browse.$val;			$files_cdate_array[$key] = date("d F Y", filectime($path));			$file_bytes = filesize($path);			$files_size_array[$key] = letter_size($file_bytes);			$files_del_array[$key] = $val;			$files_del_folder_array[$key] = $dir_to_browse;			$files_total_size = $files_total_size + $file_bytes;		}				foreach($folders_array as $key => $val)		{			$path = $dir_to_browse.$val;			$path_slash = $dir_to_browse.$val."/";			$folder_del_array[$key] = $dir_to_browse.$val;			$folders_cdate_array[$key] = date("d F Y", filectime($path));			if($show_folder_size)			{				if($OS == "windows")				$folder_bytes = folder_size_windows($path_slash);				else				$folder_bytes = folder_size($path);				$folders_size_array[$key] = letter_size($folder_bytes);				$folders_total_size = $folders_total_size + $folder_bytes;			}			else			$folders_size_array[$key] = "-";		}	//Get files and folders sizes and creation dates -done	//Generate content links to an array		$folders_links_array = array();		$files_links_array = array();		$files_del_links_array = array();				foreach($folders_array as $key => $val)		{			$folders_links_array[$key] = '<a class="link2" href="'.$this_file_name.'&folder='.rawurlencode($folder_slash).rawurlencode($val).'">'.$val."</a><br>";		}				foreach($files_array as $key => $val)		{			if(empty($folder))			$files_links_array[$key] = '<a href="'.$dir_to_browse_original.rawurlencode($val).'">'.$val."</a><br>";			else			$files_links_array[$key] = '<a href="'.$dir_to_browse_original.rawurlencode($folder)."/".rawurlencode($val).'">'.$val."</a><br>";		}				//Generate content links to an array -done	//Calculate table dimensions	$table_width = (6*$cell_padding) + (4*$cell_spacing) + $width_of_files_column + $width_of_sizes_column + $width_of_del_column;	//calculate table dimensions -done		//Palce the content into a table	echo"<table align=\"center\" width=\"$table_width\" border=\"0\" cellspacing=\"$cell_spacing\" cellpadding=\"$cell_padding\">	  <tr>		<td width=\"$width_of_files_column\" bgcolor=\"$top_row_bg_color\"><span class=\"top_row\"><div style=\"padding-left:10px\">Arquivo</div></span></td>		<td width=\"$width_of_sizes_column\" bgcolor=\"$top_row_bg_color\"><span class=\"top_row\"><div align=\"center\">Tamanho</div></span></td>		<td width=\"$width_of_del_column\" bgcolor=\"$top_row_bg_color\"><span class=\"top_row\"></span></td>	  </tr>";	 		foreach($folders_links_array as $key => $val)	{		echo"<tr>		<td height=\"22px\" width=\"$width_of_files_column\" bgcolor=\"$folder_color\"><div style=\"padding-left:3px\">$val</div></td>		<td height=\"22px\" width=\"$width_of_sizes_column\" bgcolor=\"$folder_color\"><div align=\"center\"><font color=\"#454545\">$folders_size_array[$key]</font></div></td>		<td height=\"22px\" width=\"$width_of_del_column\" bgcolor=\"$folder_color\"><div align=\"center\"><font color=\"#454545\"><a href='principal.php?pag=arq_lista&action=del_folder&folder=$getfolder&name=$folder_del_array[$key]'>Excluir</a></font></div></td></tr>";	}	foreach($files_links_array as $key => $val)	{		if($key%2 == 0) $color = $color_1; else $color = $color_2;		echo"<tr>		<td height=\"22px\" width=\"$width_of_files_column\" bgcolor=\"$color\"><div style=\"padding-left:3px\">$val</div></td>		<td height=\"22px\" width=\"$width_of_sizes_column\" bgcolor=\"$color\"><div align=\"center\"><font color=\"#454545\">$files_size_array[$key]</font></div></td>		<td height=\"22px\" width=\"$width_of_del_column\" bgcolor=\"$color\"><div align=\"center\"><font color=\"#454545\"><a href='principal.php?pag=arq_lista&action=del_file&file=$files_del_array[$key]&folder=$getfolder&on=$files_del_folder_array[$key]'>Excluir</a></font></div></td></tr>";	}	echo "</table>";		if($statistics) 	{	echo'<br><table align="center" border="0" cellpadding="2" class="table_border">';	  if($show_folder_size)	  echo'<tr>		<td width="65" bgcolor="#649126"><font style="padding-left:3px" color="#FFFFFF"><strong>Pastas </strong></font></td>		<td>'.count($folders_array).', tamanho: '.letter_size($folders_total_size).'</td>	  </tr>';	  echo'	  <tr>		<td width="65" bgcolor="#649126"><strong><font style="padding-left:3px" color="#FFFFFF">Arquivos </font></strong></td>		<td>'.count($files_array).', tamanho: '.letter_size($files_total_size).'</td>	  </tr>';	  if($show_folder_size)	  echo'<tr>		<td width="65" bgcolor="#649126"><strong><font style="padding-left:3px" color="#FFFFFF">Total  </font></strong></td>		<td>'.(count($folders_array)+count($files_array)).', tamanho: '.letter_size(($files_total_size+$folders_total_size)).'</td>	  </tr></table><br>';}	//Palce the content into a table -done	//Closing curley brace for the if(!empty($filtered_content))}//Get directory content (filtered(without the excluded specified above)) and seperate files and folders to 2 arrays -done//Output if there is no contentif(empty($filtered_content)) echo display_error_message("<div align='center'>Esta pasta não possui arquivos</div>");//Output if there is no content -done//Functionsfunction get_dir_content($path){	$php_version = substr(phpversion(),0,1);	if($php_version > 4)	{		$content = scandir($path);		return $content;	}	elseif($php_version == 4)	{		$content = array();		if ($handle = opendir($path)) 		{			while (false !== ($file = readdir($handle))) 			{				array_push($content,$file);			}			closedir($handle);		}		return $content;	}}function folder_size($path){	$folder_size = `du -s $path`;	$size_array = explode("\t", $folder_size);	return $size_array[0]*1024;}function folder_size_windows($path){	$exclude = array('.','..');	$content = scandir($path);		//Filter content	$filtered_content = array();	$filtered_content = array();	foreach($content as $key => $val)	{		if(!in_array($val, $exclude))		{			array_push($filtered_content, $val);		}	}	//Filter content -done			foreach($filtered_content as $key => $val)	{		$content_path = $path.$val;		if(is_dir($content_path))		{						$content_path = $path.$val."/";			$directory_size = folder_size_windows($content_path);			$total_directory_size = $total_directory_size + $directory_size ;					}		else		{			$file_size = filesize($content_path);			$total_file_size = $total_file_size + $file_size;		}	}	return ($total_file_size + $total_directory_size);}function letter_size($byte_size){	$file_size = $byte_size/1024;		if ($file_size >=  1048576)	{		$file_size = $file_size/1048576;		$file_size = sprintf("%01.2f", $file_size);		$file_size = $file_size." GB";	}	elseif ($file_size >=  1024)	{		$file_size = $file_size/1024;		$file_size = sprintf("%01.2f", $file_size);		$file_size = $file_size." MB";	}	else	{		$file_size = sprintf("%01.1f", $file_size);		$file_size = $file_size." KB";		}	return $file_size;}function display_error_message($message){	return "<table align=\"center\" width=\"80%\" cellpadding=\"5\" cellspacing=\"1\" class=\"table_border\">  <tr>    <td bgcolor=\"#FFBBBD\">$message</td>  </tr></table><br>";}	function display_error_message2($message){	return "<br><br><table align=\"center\" width=\"80%\" cellpadding=\"5\" cellspacing=\"1\" class=\"table_border\">  <tr>    <td bgcolor=\"#FFBBBD\">$message</td>  </tr></table><br>";}	?><table width="100%" border="0" cellspacing="0" cellpadding="5">  <tr>   <td>  </td>  </tr>  <form name="newfolder" method="post" action="principal.php?pag=arq_lista&action=newfolder&folder=<? echo $_GET["folder"]; ?>"><tr>    <td height="25">      <p>        <font class="text2">Nova Pasta: </font><input type="text" name="foldername" class="input" size="40"> <input type="submit" name="Submit" value="Criar" class="botao_sistema" />      </p>   	</td>  </tr></form>  <form enctype="multipart/form-data" name="upload" method="post" action="principal.php?pag=arq_lista&action=upload&folder=<? echo $_GET["folder"]; ?>"><tr>    <td height="25">      <p>        <font class="text2">Envio Rápido: </font>        <input name="upload" type="file" class="input" /> <input type="submit" name="Submit" value="Enviar" class="botao_sistema" />      </p>   	</td>  </tr></form></table><br /><!-- Output basic HTMl code --></body></html>

Quem quiser ver o funcionamento pra entender melhor:

http://www.gabrielbueno.com/una
RA: wmonline
senha: wmonline


obs: acesso pelo firefox está avacalhado por causa da CSS


valeeeew pessoal!!

Saudações cinematográficas!!

Comando If + Echo - Como Retornar Apenas 1 Echo

29/03/2009, 17:19

Olá amigos!

Estou desenvolvendo um sistema de gerenciamento de arquivos em PHP.

No código a seguir, quando a pessoa dá um comando para exclusão de uma pasta, o código analiza se a pasta está vázia, excluindo-a, ou, caso encontre arquivos nela, retorna uma mensagem de qe o usuário precisa excluir o conteúdo dela primeiro:

[codebox]if(!empty($_GET["action"]))
if($_GET["action"] == "del_folder")
{
$foldername = $_GET["name"];
if(file_exists($foldername."/")){ //Verifica se a pasta existe
$openfolder = opendir($foldername); //Abre a pasta
while($files = readdir($openfolder)) {

if(is_dir($foldername."/".$filename) && ! ($files == "." || $files == "..")){ //Abre pastas
@rmdir($foldername."/".$files) or $erro = 1;
}else if(is_file($foldername."/".$filename) && ! ($files == "." || $files == "..")){ //Abre arquivos
@unlink($foldername."/".$files) or $erro = 1;
}
if($erro == "1"){
echo display_error_message("<div align='center'>Esta pasta contém subpastas e/ou arquivos<br>Exclua primeiro seu conteúdo</div>");
}
}
closedir($openfolder); //Fecha a pasta
@rmdir($foldername);
}else{
echo display_error_message("<div align='center'>Esta pasta não existe ou já foi excluída</div>");
}
}[/codebox]

meu problema é que ele está retornando um "echo" pra cada arquivo ou subpasta encontrado. Logo, se houver um arquivo dentro, ele retorna 1 único aviso (conforme deveria ser), mas se tiverem 10, aparecem 10 avisos abaixo um do outro...

imagino que deva ser simples mas nunca trabalhei nesta parte... Como fazer pra que este aviso seja mostrado apenas uma vez?

obs: eu preciso que o aviso seja dado através de "echo", não pode ser "or die", pois este para o carregamento da página e não me oferece o retorno da mensagem de erro dentro de meu template, como é o caso do "echo" que envia o erro para a variável "display_error_message"...


Desde já agradeço a ajuda!!

Forte abraço!

Impedir Que Vídeo On-line Seja Baixado

23/03/2009, 16:16

Olá amigos...

Desculpem estar postando esta dúvida aqui, gastei uns 30 minutos pesquisando em todos os foruns e não encontrei um lugar adequado pra ela... Então, como estou desenvolvendo o sistema em PHP, resolvi postar aqui mesmo (corrijam, se necessário)...

Bem, preciso montar um sistema de aulas via internet. Tudo seria simples, mas acontece que os `expectadores` não podem fazer o download do arquivo de vídeo (o que acaba deixando todos os players e formatos de vídeo online que conheço obsoletos, já que todos eles são vulneráreis a certos programas ou até a uma bisbilhotada básica no código-fonte, viabilizando que o internauta baixe o arquivo do vídeo para sua máquina)


:excl: Existe alguma solução técnica ou algum novo formato de vídeo on-line que não permita este download?



Desde já agradeço!

IPB Skin By Virteq