Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 13 of 13
  1. #1
    Regular Coder
    Join Date
    Feb 2006
    Posts
    110
    Thanks
    23
    Thanked 0 Times in 0 Posts

    disallow characters like %$& in a file name in an upload form

    i have a html/php form which let users upload pictures onto my server. the problem with it is, it says the picture has been uploaded but if the file name contains any of character apart from text (A-z) and numbers, the picture never shows up in the admin panel.

    is there a way using ajax or jquery to disallow certain file names in the upload field of the html which uses these characters !@#$%^'&*()"?

    how do i go on about this?

  • #2
    Regular Coder
    Join Date
    Aug 2010
    Posts
    967
    Thanks
    19
    Thanked 211 Times in 209 Posts
    maybe this will help ?

    Code:
    <html>
    <head>
    <script>
    restictIt = (function(){
    	this.args = arguments;
    	return function(el){
    		for(var i=args.length;i--;){
    			if (el.value.indexOf(args[i]) != -1){
    				el.value = el.value.substring(0,el.value.length-1);			}		}
    }})('a','b','c')// put disallowed chars here</script>
    </head>
    <body>
    <input type=text onkeyup="restictIt(this)">
    </body>
    </html>

  • #3
    Regular Coder
    Join Date
    Feb 2006
    Posts
    110
    Thanks
    23
    Thanked 0 Times in 0 Posts
    i'm referring to an "upload" field and not some text field. there's no field for the user to type it out. henceforth this won't work.

    thanx anyway

    for your info, here's the form i'm using:
    PHP Code:
    <center
    <
    form enctype="multipart/form-data" action="upload.php" id="form"  method="post" onsubmit="a=document.getElementById('form').style;a.display='none';b=document.getElementById('part2').style;b.display='inline';" style="display: inline;"
    <
    input type="file" name="upfile" size="30" /><br
    <
    input type="submit" value="Upload Now" id="upload" /></form
    <
    div id="part2" style="display: none;">wait while being uploaded..</div
    <
    br><br
    </
    center
    Last edited by hackerzlab; 08-30-2010 at 07:45 PM.

  • #4
    Regular Coder
    Join Date
    Feb 2006
    Posts
    110
    Thanks
    23
    Thanked 0 Times in 0 Posts
    anyone out there? google doesn't seem to help and i haven't been able to find any solution for this.

    thanx

  • #5
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,189
    Thanks
    75
    Thanked 4,341 Times in 4,307 Posts
    Code:
    <html>
    <head>
    <script type="text/javascript">
    function validateFileName( field )
    {
        // in MSIE the file name will include the path, so strip that:
        var fname = field.value;
        // handle either kind of slash:
        var lastSlash = fname.lastIndexOf("/");
        if ( lastSlash < 0 ) lastSlash = fname.lastIndexOf("\\");
        if ( lastSlash >= 0 ) fname = fname.substring( lastSlash + 1 );
    
        // okay, now test the name, only, for validity:
        var validRE = /^\w+\.(jpg|jpeg|png|gif)$/i ;
        if ( ! validRE.test( fname ) )
        {
            alert("invalid file name...\n"
                  + "only letters, digits, underline allowed with jpg/jpeg/png/gif extension");
            return false;
       }
       return true;
    }
    function validateForm( form )
    {
        if ( ! validateFileName(form.upfile) ) return false;
        /* put other validation here */
    
        /* if all validation passes: */
        document.getElementById('form').style.display='none';
        document.getElementById('part2').style.display='block';
        return true; 
    }
    </script>
    </head>
    <body>
    <div id="form">
    <form enctype="multipart/form-data" action="upload.php" 
          method="post" onsubmit="return validateForm(this);">
    <input type="file" name="upfile" size="30" /><br> 
    <input type="submit" value="Upload Now" />
    </form> 
    </div>
    <div id="part2" style="display: none;">
        wait while being uploaded..
    </div> 
    </body>
    </html>
    Edit: Added the missing */
    Last edited by Old Pedant; 09-02-2010 at 07:34 AM.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #6
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,189
    Thanks
    75
    Thanked 4,341 Times in 4,307 Posts
    Of course, there is a simpler answer: In your PHP code, change the filename before storing it to disk. Just zap any invalid characters or maybe change them into underlines.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #7
    Regular Coder
    Join Date
    Feb 2006
    Posts
    110
    Thanks
    23
    Thanked 0 Times in 0 Posts
    tried and tested. its not working but thanx anyway

    btw, if you got some few minutes, could u check this out.
    PHP Code:
    <?
    include("config.php");
    $fileshosted=sizeof(file("./fls.txt"));
    $sizehosted 0
    $handle opendir("./zpics/");
    while(
    $file readdir($handle)) {
    $sizehosted $sizehosted filesize ("./zpics/".$file);
    if((
    is_dir("./zpics/".$file.'/')) && ($file != '..')&&($file != '.'))
    {
    $sizehosted $sizehosted total_size("./zpics/".$file.'/');
    }
    }
    $sizehosted round($sizehosted/1024/1024,2);
    ?>
    <center>
    <form enctype="multipart/form-data" action="upload.php" id="form"  method="post" onsubmit="a=document.getElementById('form').style;a.display='none';b=document.getElementById('part2').style;b.display='inline';" style="display: inline;"> 
    <input type="file" name="upfile" size="30" /><br> 
    <input type="submit" value="Upload Now" id="upload" /></form> 
    <div id="part2" style="display: none;">wait while being uploaded..</div> 
    <br><br> 
    </center>
    and here's the upload.php
    PHP Code:
    <?php
    include("config.php");
    $filename $_FILES['upfile']['name'];
    $filesize $_FILES['upfile']['size'];
    $checkfiles=file("./fls.txt");
    foreach(
    $checkfiles as $line)
    {
    $thisline explode('|'$line);
    if (
    $thisline[0]==$filename){
    echo 
    "<br><br><center>That file has already been uploaded here.<br></center>";
    echo 
    "<center>Try to rename it or some...<br></center>";
    echo 
    "<center><a href=\"index.php\">Back</a></center>";
    die();
    }
    }
    if(isset(
    $allowedtypes)){
    $allowed 0;
    foreach(
    $allowedtypes as $ext) {
    if(
    substr($filename, (- (strlen($ext)+1) )) == ".".$ext)
    $allowed 1;
    }
    if(
    $allowed==0) {
    echo 
    "<br><br><center>That file type is not allowed, sorry.<br></center>";
    echo 
    "<center><a href=\"index.php\">Back</a></center>";
    die();
    }
    }
    if(
    $filesize==0) {
    echo 
    "<br><br><center>You didn't pick a file...<br></center>";
    echo 
    "<center><a href=\"index.php\">Back</a></center>";
    die();
    }
    $filesize $filesize 1048576;
    if(
    $filesize $maxfilesize) {
    echo 
    "<br><br><center>Too large, sorry.<br></center>";
    echo 
    "<center><a href=\"index.php\">Back</a></center>";
    die();
    }
    $userip $_SERVER['REMOTE_ADDR'];
    $time time();
    if(
    $filesize $nolimitsize) {
    $uploaders fopen("./upl.txt","r+");
    flock($uploaders,2);
    while (!
    feof($uploaders)) { 
    $user[] = chop(fgets($uploaders,65536));
    }
    fseek($uploaders,0,SEEK_SET);
    ftruncate($uploaders,0);
    foreach (
    $user as $line) {
    @list(
    $savedip,$savedtime) = explode("|",$line);
    if (
    $savedip == $userip) {
    if (
    $time $savedtime + ($uploadtimelimit*60)) {
    echo 
    "<br><br><center>U're trying to upload again too soon! Chill out, try later...<br></center>";
    echo 
    "<center><a href=\"index.php\">Back</a></center>";
    die();
    }
    }
    if (
    $time $savedtime + ($uploadtimelimit*60)) {
    fputs($uploaders,"$savedip|$savedtime\n");
    }
    }
    fputs($uploaders,"$userip|$time\n");
    }
    $filelist fopen("./fls.txt","a+");
    fwrite($filelist$filename ."|"basename($_FILES['upfile']['name']) ."|"$userip ."|"$time."|0|\n");
    $movefile "./zpics/" $filename;
    move_uploaded_file($_FILES['upfile']['tmp_name'], $movefile);
    echo 
    "<br><br><center>Your image has been uploaded!</center>";
    ?>
    Last edited by hackerzlab; 09-02-2010 at 05:56 AM.

  • #8
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,189
    Thanks
    75
    Thanked 4,341 Times in 4,307 Posts
    I don't use PHP. Can't help you with it.

    The only thing wrong with my code was I missed the */ on the end of one comment.

    I went back and changed the code. It's now a complete working page, as it sits.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #9
    Regular Coder
    Join Date
    Nov 2009
    Posts
    247
    Thanks
    4
    Thanked 22 Times in 22 Posts
    hackerzlab:

    Try this instead:


    Code:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
    <html>
    <head>
    <title> Upload Images </title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <script type="text/javascript">
    	
    	var maxImages = 5;
    
    /* **** Do not edit below this line ****  */
    
    /*   Dynamic Image File Upload Form */
    /*   Copyright 2010, Michael J. Hill.  Used with permission. www.javascript-demos.com */
    /*   Free use of the code, so long as both copyright notices are kept intact */
    
    	var root = "";
    	var nInput = "";
    	var IE = navigator.appName == "Microsoft Internet Explorer" ? true : false;
    	
    	function insertInput(){
    
    		if (nInput.length > Number(maxImages)+Number(2))
    			{
    			 alert('Maximum '+maxImages + ' images');
    			 return false;
    			}
    		var nextUpload = document.createElement('input');
    		nextUpload.type = "file";
    		nextUpload.name = "userImg[]";
    		nextUpload.size = "25";
    		nextUpload.className = 'fInput';
    		nextUpload.onchange = function(){buildList()}
    		var lastUpload = root.getElementsByTagName('input');
    		lastUpload = lastUpload[lastUpload.length-3];
    		root.insertBefore(nextUpload,lastUpload);
    	}
    
    	function removeInput(){
    		
    		if (nInput.length > 4)
    			{
    			 root.removeChild(nInput[nInput.length-4]);
    			}
    		buildList();
    	}
    
    	function buildList(){
    
    		var nContainer = document.getElementById('nameList');
    		while (nContainer.lastChild)
    			{
    			 nContainer.removeChild(nContainer.lastChild);
    			}
    		var listCollection = [];
    		for (i=0; i<nInput.length; i++)
    			{
    			 if (nInput[i].type == "file")
    				{
    				 var fullName = nInput[i].value;
    				 var fileName = fullName.match(/[^\/\\]+$/);
    				 var splitName = fullName.split(".");
    				 var fileType = splitName[splitName.length-1];
    				 if (!fileType){return false}
    				 fileType = fileType.toLowerCase();				
    				 if (fileType == 'jpg' || fileType == 'jpeg' || fileType == 'gif')
    					{
    					 listCollection[i] = fileName;
    					}
    				 else   {
    					 alert('Invalid file type\nMust be jpg, jpeg or gif');
    					}
    				}
    			}
    		for (i=0; i<listCollection.length; i++)
    			{
    			 var newItem = document.createElement('li');
    			 newItem.appendChild(document.createTextNode(i+1+'- '+listCollection[i]));
    			 nContainer.appendChild(newItem);
    			}
    		var nBox = document.getElementById('listBox');
    		if (nBox.scrollHeight > 0)
    			{
    			 nBox.scrollTop = nBox.scrollHeight;
    			}
    	}
    
    	function validate(currForm){
    
    		var fileName = "";
    		var nForm = currForm.getElementsByTagName('input');		
    		for (i=0; i<nForm.length; i++)
    			{
    			 if (nForm[i].name = "userImg" && nForm[i].value == "")
    				{
    				 alert('Complete all fields');
    				 return false;
    				}
    			 fileName = nForm[i].value.match(/[^\/\\]+$/);
    			 fileName = fileName[0].split(".");
    			 fileName[1] = fileName[1].toLowerCase();
    			 if (/[^\w ]/.test(fileName[0]) || fileName.length > 2)
    				{
    				 alert('A file name must not contain any special characters\nlike an apostrophe, period or hyphen');
    				 return false;
    				}
    			 if (fileName[1] != 'jpg' && fileName[1] != 'jpeg' && fileName[1] != 'gif')
    				{
    				 alert('One or more of the selections\n is an invalid file type');
    				 return false;
    				}
    			}
    		return true;
    	}
    
    	function init(){
    
    		root = document.getElementsByTagName('fieldset')[0];
    		nInput = root.getElementsByTagName('input');
    		var nForm = document.forms['img_upload'];
    		nForm.onsubmit = function()
    			{
    			 return validate(this);
    			}
    		nForm['userImg[]'].onchange = function()
    			{
    			 buildList();
    			}		
    		nForm['next'].onclick = function()
    			{
    			 insertInput();
    			}
    		nForm['remove'].onclick = function()
    			{
    			 removeInput();
    			}
    	}
    
    	IE ? attachEvent('onload', init, false) : addEventListener('load', init, false);	
    
    </script>
    <style type="text/css">
    
    	 body 
    		{
    		 margin-top: 60px; 
    		 background-color: #fffacd;
    		}
    
    	.headline
    		{
    		 width: 200px;
    		 text-align: center;
    		 font-weight: bold;
    		 margin-left: auto;
    		 margin-right: auto;
    		 margin-bottom: 5px;
    		}
    
    	 form 
    		{
    		 margin-top: 0px;
    		 padding: 0px;
    		}
    	
    	 fieldset 
    		{
    		 width: 279px;
    		 margin-left: auto;
    		 margin-right: auto;
    		 padding: 0px; 		 
    		 background-color: #f0f8ff;
    		 border: 1px solid #87ceeb;
    		}
    
    	 legend 
    		{
    		 font-family: helvetica;
    		 font-size: 10pt; 
    		 font-weight: bold;
    		 color: #00008b; 
    		 background-color: #87ceeb; 
    		 padding-left: 3px; 
    		 padding-right: 3px; 
    		 margin-bottom: 5px;
    		}
    
    	 ul 
    		{
    		 margin-top: 2px;
    		}
    
    	.blank
    		{
    		 display: none;
    		}
    
    	.list_container
    		{
    		 display: block; 
    		 margin: auto; 
    		 border: 1px solid #87ceeb;
    		 font-family: tahoma; 
    		 font-size: 10pt;
    		 color: #00008b; 
    		 width: 425px; 
    		 height: 100px; 
    		 overflow: auto;		
    		 background-color: #ffffe0;
    		 padding: 2px;
    		}	
    
    	.review_msg
    		{
    		 width: 123px;
    		 margin-left: auto;
    		 margin-right: auto;
    		}
    
    	.fInput 
    		{
    		 font-family: times;
    		 font-size: 10pt; 
    		 margin-bottom: 3px;
    		 margin-left: 16px;
    		}	
    
    	.nextBtn
    		{
    		 width: 75px;
    		 font-family: veranda; 
    		 font-size: 9pt; 
    		 font-weight: bold;
    		 margin-left: 21px; 
    		 margin-top: 5px;
    		 margin-bottom: 8px;
    		 background-color: #fff8dc; 
    		 border: solid 1px black;
    		 letter-spacing: 1px;
    		}
    
    	.submitBtn
    		{
    		 width: 75px;
    		 font-family: veranda; 
    		 font-size: 9pt; 
    		 font-weight: bold; 
    		 margin-top: 5px;
    		 margin-bottom: 8px;
    		 background-color: #fff8dc; 
    		 border: solid 1px black;
    		 letter-spacing: 1px;
    		}
    
    	.removeBtn
    		{
    		 width: 75px;
    		 font-family: veranda; 
    		 font-size: 9pt; 
    		 font-weight: bold; 
    		 margin-top: 5px;
    		 margin-bottom: 8px;
    		 background-color: #fff8dc; 
    		 border: solid 1px black;
    		 letter-spacing: 1px;
    		}
    	
    	.copyright_MJH 
    		{
    		 width: 92%;
    		 margin-left: auto;
    		 margin-right: auto;
    		 margin-top: 35px; 
    		 background-color: transparent;
    		 text-align: center; 
    		 font-family: veranda;
    		 font-size: 8pt;
    		 color: #d3d3d3;
    		}
    
    	.copyright_MJH  a 
    		{
    		 color: #b0e0e6;
    		 text-decoration: none;
    		}
    
    </style>
    </head>
    	<body>
    		<div class="headline"> Upload Your Images </div>
    
    		<div id="listBox" class="list_container">
    			<div class="review_msg">Review Your Choices</div>
    			<ul id="nameList">
    				<li class="blank"></li>
    			</ul>
    		</div>
    
    		<form name="img_upload" method="post" action="" enctype="multipart/form-data">
    		   <fieldset>
    			<legend> Image Upload </legend>
    				<input type="file" name="userImg[]" size="25" class="fInput">
    				<input type="button" name="next" value="Next" class="nextBtn">
    				<input type="submit" name="submit" value="Submit" class="submitBtn">
    				<input type="button" name="remove" value="Remove" class="removeBtn">
    		   </fieldset>
    		</form>
    
    <!-- This copyright notice must be included in the document where the code is used -->
    		<div class="copyright_MJH">
    			Dynamic Image File Upload Form, Copyright &copy; 2010 Michael J. Hill
    			<a href="http://www.javascript-demos.com">JavaScript Demos</a>
    			All rights reserved. Used with permission.
    		</div>
    <!-- This copyright notice must be included in the document where the code is used -->
    	</body>
    </html>

  • #10
    Senior Coder Spudhead's Avatar
    Join Date
    Jun 2002
    Location
    London, UK
    Posts
    1,856
    Thanks
    8
    Thanked 110 Times in 109 Posts
    I know this is PHP rather than JS, but:

    In your PHP file, replace this line:

    PHP Code:
    $filename $_FILES['upfile']['name']; 
    with this:

    PHP Code:
    $filename preg_replace("/[^A-Za-z0-9\._]/",'',$_FILES['upfile']['name']); 
    Result: your users can upload files with whatever filenames they like, but the server saves them with any characters that aren't alphanumeric, underscores or a dot, removed.

  • #11
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,189
    Thanks
    75
    Thanked 4,341 Times in 4,307 Posts
    Yeah, SpudHead's answer is *clearly* the better way to go. See my post #6. I just didn't know the PHP code to do it.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #12
    Regular Coder
    Join Date
    Feb 2006
    Posts
    110
    Thanks
    23
    Thanked 0 Times in 0 Posts
    PHP Code:
    $filename preg_replace("/[^A-Za-z0-9\._]/",'',$_FILES['upfile']['name']); 
    works perfectly with this:


    PHP Code:
    $filename preg_replace("/[^A-Za-z0-9\._]/",'_',$_FILES['upfile']['name']); 
    thank you guys. really appreciate all your input
    Last edited by hackerzlab; 09-04-2010 at 10:49 PM.

  • #13
    Senior Coder Dormilich's Avatar
    Join Date
    Jan 2010
    Location
    Behind the Wall
    Posts
    3,251
    Thanks
    12
    Thanked 340 Times in 336 Posts
    Quote Originally Posted by hackerzlab View Post
    PHP Code:
    $filename preg_replace("/[^A-Za-z0-9\._]/",'_',$_FILES['upfile']['name']); 
    small note on the RegEx:

    PHP Code:
    $filename preg_replace("#[^\w.]#",'_',$_FILES['upfile']['name']); 
    maybe even that would work
    PHP Code:
    $filename preg_replace("/#\W|\.#",'_',$_FILES['upfile']['name']); 
    The computer is always right. The computer is always right. The computer is always right. Take it from someone who has programmed for over ten years: not once has the computational mechanism of the machine malfunctioned.
    André Behrens, NY Times Software Developer


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •