Jump to content

[SOLVED] How to restrict image upload file names


RyanSF07

Recommended Posts

Hello,

 

I have an image upload form -- how do I restrict file names to contain letters, numbers, hyphens, dashes, and/or periods only, and restrict also the length of the file name? That is, if the file uploaded has accent marks, foreign characters, etc, an error message will trigger (file names cannot contain special characters) and if too long trigger an error (file names must be no longer than 40 characters)?

 

In my validation script I have this kind of set up where $fieldname is the variable that would need to be checked:

 

	if (getimagesize($_FILES[$fieldname]['tmp_name'])){
	$h = TRUE;
} else {
	$h = FALSE;
	$content .= "<p>Only GIF, JPEG, and PNG image uploads are allowed. Max file size 50K.</p>\n";
}

 

Thank you for your help!

I'm trying this -- yet the error is not being triggered -- any ideas?

 

if(preg_match('^[a-zA-Z0-9_\s-]+$', $fieldname) ) {
	$k = TRUE;
} else {
	$k = FALSE;
	echo "<p>File Name :: Letters and numbers only please. Space, underscore, and hyphen characters also supported.</p>\n";
}

Try changing the plus sign to the min and max number of characters you want to allow - encased in curly braces. I would assume the minimum would be 5 characters: a single letter file name, the period and a three character extension. So, you would use "{5,64}" to allow 5 to 64 characters.

 

Example:

preg_match('^[a-zA-Z0-9_s-]{5, 64}$', $fieldname)

I got back to this post too late -- All is working now. Can you check this though?

 

I added "allow a dot" to the reg ex, but don't mean for the dot to represent any character -- did I do that right?

 

Also went with a limit variable to limit the length -- yours is much cleaner though...

 

$pic=$now++.'-'.$_FILES[$fieldname]['name'];

if(preg_match('#^[a-z0-9_\s-\.]*$#i', $pic) ) {
	$k = TRUE;
} else {
	$k = FALSE;
	$content .= "<p>There is a problem with the image filename. Letters and numbers only please. Space, underscore, and hyphen characters also supported.</p>\n";
}


$desc_length = strlen($pic);
        $limit = 40; 
        if ($desc_length <= $limit) {
        $l = TRUE;
} else {
	$l = FALSE;
	$content .= "<p>There is a problem with the image filename -- It's too long. Make it shorter please.</p>\n";
}

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.