Upload only certain types of files ie. jpg, gif etc.

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
billhobbs
Forum Newbie
Posts: 11
Joined: Thu Apr 27, 2006 4:08 pm

Upload only certain types of files ie. jpg, gif etc.

Post by billhobbs »

feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]


I've been working on this all day long, I still really new to php so I'm not sure where I'm making my mistake. I want the user to be able to upload only certain types of files. My code as it is allows the user to upload virtually anything. I want it to give them an error message before going any further when they try to upload anything that isn't in the array. Here is my code, any help would be greatly appreciated.

The number of files available to upload is determined by a form on the previously viewed page.

Code: Select all

<?
  // start of dynamic form
  $uploadNeed = $_POST['uploadNeed'];
  for($x=0;$x<$uploadNeed;$x++){
  ?>
                <input name="uploadFile<? echo $x;?>" type="file" id="uploadFile<? echo $x;?>">
              </p>
              <?
  // end of for loop
  }
  ?>
              <p>
                <input name="uploadNeed" type="hidden" value="<? echo $uploadNeed;?>">
                <input name="filename" type="hidden" id="filename" value="
<?
$UploadExts = array('gif','jpeg','jpg'); 
$uploadNeed = $_POST['uploadNeed'];
 
// start for loop
for($x=0;$x<$uploadNeed;$x++){

// strip file_name of slashes
$file_name = stripslashes($file_name);
$file_name = str_replace("'","",$file_name);
$file_name = $_FILES['uploadFile'. $x]['name']['type'];
$file_ext = strtolower(substr($file_name,strrpos($file_name,".")));

//File Extension Check
if (!in_array($file_ext, $FILE_EXTS))
$copy = copy($_FILES['uploadFile'. $x]['tmp_name'],$file_name);
else
$message = "Sorry, $file_name($file_type) is not allowed to be uploaded.";

 // check if successfully copied
 if($copy){
 echo "$file_name | uploaded Successfully!><br>";
 }else{
 echo "$file_name | Could Not Be Uploaded!<br>";
 }
} 
// end of loop
?>">

feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]
User avatar
s.dot
Tranquility In Moderation
Posts: 5001
Joined: Sun Feb 06, 2005 7:18 pm
Location: Indiana

Post by s.dot »

use getimagesize() to determine the type of the image

Code: Select all

//  allowed types
// 1 = gif
// 2 = jpg
// 3 = png
$allowed_types = array(1,2,3);

$imginfo = getimagesize($_FILES['uploadedfile']['tmp_name']);
if(!in_array($imginfo[2],$allowed_types){
    die('Invalid File Type.');
}
Set Search Time - A google chrome extension. When you search only results from the past year (or set time period) are displayed. Helps tremendously when using new technologies to avoid outdated results.
billhobbs
Forum Newbie
Posts: 11
Joined: Thu Apr 27, 2006 4:08 pm

Post by billhobbs »

Where do I put this code and do I have to modify it or is it fine just the way it is. I tried putting it in several places and it kept giving me a parse error.
User avatar
s.dot
Tranquility In Moderation
Posts: 5001
Joined: Sun Feb 06, 2005 7:18 pm
Location: Indiana

Post by s.dot »

add a ) right before the {

sorry, i made a typo.

also, you will need to change the value of the $_FILES['xxxxnameherexxx']
Set Search Time - A google chrome extension. When you search only results from the past year (or set time period) are displayed. Helps tremendously when using new technologies to avoid outdated results.
billhobbs
Forum Newbie
Posts: 11
Joined: Thu Apr 27, 2006 4:08 pm

Post by billhobbs »

feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]


Is this what you mean? I guess not since it's not working.

Code: Select all

<?
// start of dynamic form
$uploadNeed = $_POST['uploadNeed'];
for($x=0;$x<$uploadNeed;$x++){
?>
<input name="uploadFile<? echo $x;?>" type="file" id="uploadFile<? echo $x;?>">
</p>
<?
// end of for loop
}
?>
<p>
<input name="uploadNeed" type="hidden" value="<? echo $uploadNeed;?>">
<input name="filename" type="hidden" id="filename" value="
<?
 $uploadNeed = $_POST['uploadNeed'];
//  allowed types 
// 1 = gif 
// 2 = jpg 
// 3 = png 
$allowed_types = array(1,2,3); 

$imginfo = getimagesize($_FILES['uploadedfile']['tmp_name']); 
if(!in_array($imginfo[2],$allowed_types){ 
die('Invalid File Type.'); 
)
} 
// start for loop
for($x=0;$x<$uploadNeed;$x++){
$file_name = $_FILES['uploadFile'. $x]['name'];
// strip file_name of slashes
$file_name = stripslashes($file_name);
$file_name = str_replace("'","",$file_name);
$copy = copy($_FILES['uploadFile'. $x]['tmp_name'],$file_name);
 // check if successfully copied
 if($copy){
 echo "$file_name<br>";
 }else{
 echo "$file_name | could not be uploaded!<br>";
 }
} // end of loop
?>">

feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]
billhobbs
Forum Newbie
Posts: 11
Joined: Thu Apr 27, 2006 4:08 pm

Post by billhobbs »

Is there anyone who can help me with this I'm under the gun and could use some help.
User avatar
andym01480
Forum Contributor
Posts: 390
Joined: Wed Apr 19, 2006 5:01 pm

Post by andym01480 »

My understanding is that you need to allow the file to be uploaded whatever it is. Then check it and reject if it is not the right type. - the getimagesize() check is the best

Looking at your code, you are trying to do server side check, before the file has been submitted, while it is still on the users computer.

The php and html for uploading needs to be separate from the php to check and process it.
billhobbs
Forum Newbie
Posts: 11
Joined: Thu Apr 27, 2006 4:08 pm

Post by billhobbs »

feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]


I have moved this code all over the place and am still having problems. If it's not too much trouble could you adjust the code and send it back to me complete. Or if there is a better way please let me know. From what you've said this is what I think you mean.

Code: Select all

<? 
// start of dynamic form 
$uploadNeed = $_POST['uploadNeed']; 
for($x=0;$x<$uploadNeed;$x++){ 
?> 
<input name="uploadFile<? echo $x;?>" type="file" id="uploadFile<? echo $x;?>"> 
</p> 
<? 
// end of for loop 
} 
?> 
<p> 
<input name="uploadNeed" type="hidden" value="<? echo $uploadNeed;?>"> 
<input name="filename" type="hidden" id="filename" value=" 
<? 
 $uploadNeed = $_POST['uploadNeed']; 
// start for loop 
for($x=0;$x<$uploadNeed;$x++){ 
$file_name = $_FILES['uploadFile'. $x]['name']; 
// strip file_name of slashes 
$file_name = stripslashes($file_name); 
$file_name = str_replace("'","",$file_name); 
$copy = copy($_FILES['uploadFile'. $x]['tmp_name'],$file_name); 
 // check if successfully copied 
 if($copy){ 
 echo "$file_name<br>"; 
 }else{ 
 echo "$file_name | could not be uploaded!<br>"; 
 } 
} // end of loop 
?>">
<?
//  allowed types 
// 1 = gif 
// 2 = jpg 
// 3 = png 
$allowed_types = array(1,2,3); 
$imginfo = getimagesize($_FILES['uploadFile']['tmp_name']); 
if(!in_array($imginfo[2],$allowed_types)){ 
die('Invalid File Type.');  
} 
?>

feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]
User avatar
andym01480
Forum Contributor
Posts: 390
Joined: Wed Apr 19, 2006 5:01 pm

Post by andym01480 »

Everyone else - apologies for writing the Script - billhobs doesn't get to figure it out and learn, but it was a learning experience for me! I got to do some learning! Is there a clever way of working out

Code: Select all

$_SERVER['PHP_SELF']
and stripping out a posted variable, in this case ?uploadNeed=x - that would sure neaten it up a little!

Call the script upload.php
Change $fileposition to where the file is located
The upload directory is called images - make sure you can write to it!

Code: Select all

<?php
$fileposition="http://127.0.0.1/test/upload.php"; //name and location of this file! REMEMBER TO CHANGE
$uploadNeed=$_REQUEST['uploadNeed']; // your result from previous form for how many images, also used by script to count down
if ($uploadNeed<1){
echo "all done";
exit();
} 


if(isset( $_POST['submitted'] )) //check upload form submitted, if not print form out
{ 
 $iterationsleft=$uploadNeed-1; //iterartion variable for how many times left to do
//  allowed types 
// 1 = gif 
// 2 = jpg 
// 3 = png 
$allowed_types = array(1,2,3); 

$imginfo = getimagesize($_FILES['imagefile']['tmp_name']); 




//check that uploaded image is allowed
if(!in_array($imginfo[2],$allowed_types)){ //not allowed, reiterate without counting down
    $iterationsleft=$iterationsleft+1; 
    $extra = "?uploadNeed=$iterationsleft";
  header("Location:$fileposition$extra");
    exit();
} 

//otherwise move to images directory and reiterate
  copy ($_FILES['imagefile']['tmp_name'], "images/".$_FILES['imagefile']['name'])  or die ("Could not copy");  //copy to images directory
$extra = "?uploadNeed=$iterationsleft";
header("Location:$fileposition$extra");

exit();
}

?>
<?php echo "Images left to upload = $uploadNeed"; ?>
<p>Please upload your file - jpg, png or gif
<form name="form" method="post" action="<?php $_SERVER["PHP_SELF"];?>" enctype="multipart/form-data"> 
<input type="file" name="imagefile"> 
<br>
<input type=hidden name=submitted value=y> 
<input type="submit" name="Submit" value="Submit">
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post by John Cartwright »

andym01480 wrote:Everyone else - apologies for writing the Script - billhobs doesn't get to figure it out and learn, but it was a learning experience for me! I got to do some learning! Is there a clever way of working out

Code: Select all

$_SERVER['PHP_SELF']
and stripping out a posted variable, in this case ?uploadNeed=x - that would sure neaten it up a little!
http://ca3.php.net/basename :wink:
User avatar
andym01480
Forum Contributor
Posts: 390
Joined: Wed Apr 19, 2006 5:01 pm

Post by andym01480 »

Thanks. Interesting stuff. Where you pointing me there to use Basename :? or because of the posts underneath which lead me to come up with the following- which seems to strip out querys and provide what i need?

Code: Select all

$path= "http://".$_SERVER["SERVER_NAME"].$_SERVER["SCRIPT_NAME"];
:wink:

So many scripts ask you to set path to type variables manually, when the above would work. Why? Is it unreliable or have they not been pointed to http://ca3.php.net/basename :lol:
billhobbs
Forum Newbie
Posts: 11
Joined: Thu Apr 27, 2006 4:08 pm

Post by billhobbs »

feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]


I've tried this code and it doesn't give me the number of uploadable fields entered in  the previous page or uploads anything, but it acts like it uploaded something.

Code: Select all

<?php 
$path= "http://".$_SERVER["bsketched.com"].$_SERVER["1CarUploadForm.pphp"]; //name and location of this file! REMEMBER TO CHANGE 
$uploadNeed=$_REQUEST['uploadNeed']; // your result from previous form for how many images, also used by script to count down 
if ($uploadNeed<1){ 
echo "all done"; 
exit(); 
} 


if(isset( $_POST['submitted'] )) //check upload form submitted, if not print form out 
{ 
 $iterationsleft=$uploadNeed-1; //iterartion variable for how many times left to do 
//  allowed types 
// 1 = gif 
// 2 = jpg 
// 3 = png 
$allowed_types = array(1,2,3); 

$imginfo = getimagesize($_FILES['imagefile']['tmp_name']); 


//check that uploaded image is allowed 
if(!in_array($imginfo[2],$allowed_types)){ //not allowed, reiterate without counting down 
    $iterationsleft=$iterationsleft+1; 
    $extra = "?uploadNeed=$iterationsleft"; 
  header("Location:$fileposition$extra"); 
    exit(); 
} 

//otherwise move to images directory and reiterate 
  copy ($_FILES['imagefile']['tmp_name'], "images/".$_FILES['imagefile']['name'])  or die ("Could not copy");  //copy to images directory 
$extra = "?uploadNeed=$iterationsleft"; 
header("Location:$fileposition$extra"); 

exit(); 
} 

?>
    <?php echo "Images left to upload = $uploadNeed"; ?> </p>
  <p>Please upload your file - jpg, png or gif 
  
  <input type="file" name="imagefile">
  <br>
  <input type=hidden name=submitted value=y>
  <input type="submit" name="Submit" value="Submit">

feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]
Last edited by billhobbs on Fri Apr 28, 2006 7:33 pm, edited 1 time in total.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

My patience is wearing thin with your contempt for our request to post your code in the proper tags billhobbs.
billhobbs
Forum Newbie
Posts: 11
Joined: Thu Apr 27, 2006 4:08 pm

Post by billhobbs »

Sorry, this is only my second day on the forum, meant no offense. I've read the method to post and I think I got it. Once again sorry for the mistakes.
User avatar
andym01480
Forum Contributor
Posts: 390
Joined: Wed Apr 19, 2006 5:01 pm

Post by andym01480 »

Check the variable $path - you don't need the

Code: Select all

$_SERVER['']
bits just the address as is
Post Reply