Jump to content

Removing whitespace from uploaded filename?


livingfree

Recommended Posts

Hey, there. Huge n00b when it comes to this stuff and, while I'm trying to learn, I've just known enough to "get by". My problem is that I am using an upload form, and everything works dandy except whitespace remains in the filename rather than being taken out or converted to an underscore (I'd prefer to replace it with the underscore).

 

So here is my PHP page and I hope someone can help me. I've been working on this all day.

 

<?php
session_start();

require_once("getid3/getid3.php"); $id3 = new getID3();
$dir = isset($_GET['dir']) ? ($_GET['dir']) : 'files';
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Flash File Uploader</title>
<script type="text/javascript" src="http://www.era404.com/js/swfobject.js"></script>
<link href="_css/era404.css" rel="stylesheet" type="text/css" />
<script src="fume/test/_js/swfobject.js" type="text/javascript"></script>

<script type="text/javascript">
function formValidator()
{
	var up = document.getElementById("flash_uploader");
	var fb = document.getElementById('flash_block');
	var upload_button = document.theForm.action_upload;
	var upload_url = "upload.php";
	up.SetVariable("upload_to", upload_url);
	up.SetVariable("upload_dir", "<?php echo $dir ?>");
	up.SetVariable("ul", "100");
	upload_button.disabled='true';
	return false;
}
function upload_complete(name,size,type,ft,dir)
{
	window.location="index.php?name="+name+"&size="+size+"&type="+type+"&exts="+ft+"&dir="+dir;
}
function fileProps(name,size,type,cdate,mdate,dir)
{
	var props = document.getElementById('props');
	props.innerHTML = "<div class='sucErr'><div class='tableHeader' style='width: 400px; height: 20px; padding-top: 5px;'>Selected File:</div><br /><table border='0' cellspacing='0' cellpadding='0' style='margin:10px;'><tr><td width='100'><b>NAME:</b></td><td> "+dir+"/"+name+"</td></tr><tr><td><b>SIZE:</b></td><td> "+size+"</td></tr><tr><td><b>TYPE:</b></td><td> "+type+"</td></tr><tr><td><b>CREATED:</b></td><td> "+cdate+"</td></tr><tr><td><b>MODIFIED:</b></td><td> "+mdate+"</td></tr></table></div>";
	props.style.display = "block";
}
function thumbs()
{
	var mdir = '<?=(@$dir?"?dir=$dir":"")?>';
	var thumbs = document.getElementById('thm');
	if(thumbs.checked == true) { window.location = "index.php"+mdir+"&thm=1"; }
	else { window.location = "index.php"+mdir; }
}
</script>
</head>
<a name="top"></a>
<body>
<center>

	<p>
<div id='props' style='display:none;font: 8pt Verdana, Georgia, Sans-serif !important;width:360px;margin:10px;padding:10px;'></div>
<form method="post" enctype="multipart/form-data" name="theForm" id="theForm" onSubmit="return formValidator();">
<?


if(@!empty($_GET['name']))
{	$_GET['name'] = preg_replace("/[^A-Za-z0-9\-\_\.\ ]/",'',$_GET['name']);
echo "<div id='props' style='display:block;font: 8pt Verdana, Georgia, Sans-serif !important;width:360px;margin:10px;padding:10px;'>";
if(file_exists(getcwd().'/'.$dir.'/'.$_GET['name']))
{	echo "<div class='sucErr'><div class='tableHeader' style='width: 400px; height: 20px; padding-top: 5px;'>Success:</div><br />";
	echo "<span class='standardCopy'><i>{$_GET['name']}</i><br />has been successfully uploaded.</span><br />";
}
else
{
	echo "<div class='sucErr'><div class='tableHeader' style='width: 400px; height: 20px; padding-top: 5px;'>Error:</div><br />";
	$_GET['exts']   = explode(",",$_GET['exts']);
	$_GET['allowed'] = (in_array(LTRIM(strtolower($_GET['type']),"."),$_GET['exts']) ? "yes" : "no");
	$maxsize = return_bytes(ini_get('post_max_size'));
	echo "<span class='standardCopy'>The file could not be uploaded.</span><br />";
	if($_GET['allowed'] == "no")
	{
		echo "<span class='standardCopy'><b>Filetype (".$_GET['type'].") not permitted.</b></span><br /><br />";
	}
	else
	{
		echo ($_GET['size'] > $maxsize ? "<span class='standardCopy'><b>Filesize ({$_GET['size']}) is larger than permitted by this host ($maxsize).</b></span><br /><br />" : "<br /><br />");
	}

	echo "<span class='boldCopy'>FILE: </span><span class='standardCopy'>".$_GET['name']. "</span><br />";
	echo "<span class='boldCopy'>TYPE: </span><span class='standardCopy'>".$_GET['type']. "</span><br />";
	echo "<span class='boldCopy'>SIZE: </span><span class='standardCopy'>".$_GET['size']. "</span><br />";
	echo "<span class='boldCopy'>ALLOWED: </span><span class='standardCopy'>".$_GET['allowed']. "</span><br />";

}
echo "</div></div>";
$_GET = array();

}


//useful functions
function return_bytes($val) {
    $val = trim($val);
    $last = strtolower($val{strlen($val)-1});
    switch($last) {
        // The 'G' modifier is available since PHP 5.1.0
        case 'g':
            $val *= 1024;
        case 'm':
            $val *= 1024;
        case 'k':
            $val *= 1024;
    }
    return $val;
}
session_destroy();
?>
<div id="flash_block" style="display: visible;">
					<div id="flashcontent"></div>
				</div>
				<script type="text/javascript">
					var fo = new SWFObject("uploader.swf?ul=100", "flash_uploader", "435", "40", 8, "#FFFFFF", true);
					fo.addParam("allowScriptAccess", "sameDomain");
					fo.addParam("quality", "high");
					fo.addParam("scale", "noscale");
					fo.addVariable("to", "upload.php");
					fo.addVariable("upload_dir", "<?=$dir?>");
					fo.addVariable("limit", "100");
					fo.addVariable("types", "video|text|pdf|image|audio|archive");
					fo.write("flashcontent");
				</script>

	<!--<input name="action_upload" type="submit" value="Upload Video"><br>-->
</form>


<div style='display:block;font: 8pt Verdana, Georgia, Sans-serif !important;margin:10px;padding:10px; height: 565px; overflow: auto;'>
    <table width='95%' border='0' cellpadding="5" cellspacing="0" style="margin-left:10px;">
    <tr>
    <td colspan='5'></td>
    </tr>
    <tr>
	<td class="tableHeader" width="15"> </td>
	<td class="tableHeader">Filename</td>
	<td class="tableHeader">Modified</td>
	<td class="tableHeader">Size</td>
	<td class="tableHeader">Description</td>
    </tr>

<?php
$imgtypes = array("jpg"=>1,"jpeg"=>1,"gif"=>2,"png"=>3);
$showthumbs = (@isset($_GET['thm']) ? 1 : 0);
if(!file_exists(getcwd()."/$dir/.s/")) @mkdir(getcwd()."/$dir/.s/",0777);

    	if(file_exists("$dir/"))
		{
			if ($handle = opendir("$dir/"))
			{
				$count = 0;
	   			while (false !== ($file = readdir($handle)))
	   			{
	  		 		if($file != "." && $file != ".." && $file != ".s")
	  		 		{
	  		 			$count++;
	  		 			if(!file_exists(getcwd()."/$dir/.s/$file") && array_key_exists(strtolower(substr($file,-3)),$imgtypes))
	  		 			{
	  		 				$srcf = getcwd()."/$dir/$file";
	  		 				$dstf = getcwd()."/$dir/.s/$file";
	  		 				$type = $imgtypes[strtolower(substr($file,-3))];
	  		 				mcSaveImages(120,90,$srcf,$dstf,15,$type);
	  		 			}
	  		 			echo "<tr bgcolor='".($count%2?"#FFFFFF":"#EFEFEF")."'>
	  		 					<td valign='top'>$count.</td>
	  		 					<td valign='top'><a href='$dir/$file'>$file</a></td>
	  		 					<td valign='top'>".date("m/d/Y h:i:s A",filectime(getcwd()."/$dir/$file"))."</td>
	  		 					<td valign='top'>".niceSize(filesize(getcwd()."/$dir/$file"))."</td>";
					if($showthumbs)
					{
	  		 			if(array_key_exists(strtolower(substr($file,-3)),$imgtypes))
	  		 			{ echo "<td><a href='$dir/$file'><img src='$dir/.s/$file' border='0'></a><br />";
	  		 			} else { echo "<td align='left'>"; }
	  		 			$details = $id3->analyze(getcwd()."/$dir/$file");
	  		 			echo "<font size='-3'>";
	  		 			if(@array_key_exists("video",$details)) { echo "<b>IMAGE DETAILS:</b><hr width='200' align='left' style='border:1px solid #000;'></hr><ul>"; foreach($details['video'] as $k=>$v) { echo "<b>$k:</b> $v<br />"; } if(@$details['playtime_string']) { echo "<b>Playtime:</b> {$details['playtime_string']}<br />"; }echo "</ul>"; }
	  		 			if(@array_key_exists("audio",$details)) { echo "<b>AUDIO DETAILS:</b><hr width='200' align='left' style='border:1px solid #000;'></hr><ul>"; foreach($details['audio'] as $k=>$v) { echo "<b>$k:</b> $v<br />"; } echo "</ul>"; }
						echo "</td>";
					} else  { echo "<td> </td>"; }
	  		 			echo "</tr>";
	  		 		}
	  			}
	   			closedir($handle);
			}
		}
?>
	</table><div style="clear:both;"></div><br />
</div>
<table><tr>
		<td><input type='checkbox' name='thm' id="thm" onclick="javascript:thumbs();" <? echo($showthumbs ? "CHECKED" : ""); ?>></td>
		<td colspan="3"><p>Details?</p></td>
	</tr>
</table>
<?php
function mcSaveImages($forcedwidth, $forcedheight, $sourcefile, $destfile, $imgcomp, $type)
   {   //$type = 1: jpeg | $type = 2: gif | $type = 3: png
	   $g_imgcomp=100-$imgcomp;
   $g_srcfile=$sourcefile;
   $g_dstfile=$destfile;
   $g_fw=$forcedwidth;
   $g_fh=$forcedheight;

   if(file_exists($g_srcfile))
       {
       $g_is=getimagesize($g_srcfile);
       if(abs($g_is[0]-$g_fw)>=abs($g_is[1]-$g_fh))
           {
           $g_iw=$g_fw;
           $g_ih=abs($g_fw/$g_is[0])*$g_is[1];
           }
           else
           {
           $g_ih=$g_fh;
           $g_iw=abs($g_ih/$g_is[1])*$g_is[0];
           }
       if($type == 1) $img_src=imagecreatefromjpeg($g_srcfile);
       if($type == 2) $img_src=imagecreatefromgif($g_srcfile);
       if($type == 3) $img_src=imagecreatefrompng($g_srcfile);
       $img_dst=imagecreatetruecolor($g_iw,$g_ih);
       imagecopyresampled($img_dst, $img_src, 0, 0, 0, 0, $g_iw, $g_ih, $g_is[0], $g_is[1]);
       if($type == 1) imagejpeg($img_dst, $g_dstfile, $g_imgcomp);
       if($type == 2) imagegif($img_dst, $g_dstfile, $g_imgcomp);
       if($type == 3) imagepng($img_dst, $g_dstfile, $g_imgcomp);
       imagedestroy($img_dst);
       return true;
       }
       else
       return false;
   }

function niceSize($size) {
$sidestep = 1024.0;
static $sizeUnits = Array();
if (count($sizeUnits)==0) {
	$sizeUnits[] = " "."B";
	$sizeUnits[] = "KB";
	$sizeUnits[] = "MB";
	$sizeUnits[] = "GB";
	$sizeUnits[] = "TB";
}

if ($size==="")
	return "";

$unitIndex = 0;
while ($size>$sidestep) {
	$size = $size / $sidestep;
	$unitIndex++;
}

if ($unitIndex==0) {
	return number_format($size, 0)." ".$sizeUnits[$unitIndex];
} else {
	return number_format($size, 1, ".", ",")." ".$sizeUnits[$unitIndex];
}
}

?>

</center>
</body>
</html>

you can use

$filename = str_replace(" ","_",$filename);

 

this will replace any occurrence of " " with "_" i the variable $filename; you may need to change the variable name.

 

To demonstrate the severity of my lack of knowledge on this subject I must, embarrassingly, admit that I have no idea where to place this in the coding.

I take it this code displays a form, and handles the upload in itself?

 

When you upload the actual file, i believe you can use move_uploaded_file() to "rename" the file.

http://uk2.php.net/manual/en/function.move-uploaded-file.php

 

Additionally, you can rename a file using the rename() function.

http://uk2.php.net/manual/en/function.rename.php

 

More information on php uploading.

http://uk2.php.net/manual/en/features.file-upload.post-method.php

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.