Uploading Files

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
watson516
Forum Contributor
Posts: 198
Joined: Mon Mar 20, 2006 9:19 pm
Location: Hamilton, Ontario

Uploading Files

Post by watson516 »

I have attempted to allow users to upload pictures to my website but I can not figure it out.

Here is what I currently have...

Code: Select all

if (isset($_GET['sat']))
{
	if(!empty($_FILES["userfile"]))
	{
		$dir = opendir("pictures/");
		$counter = 0;
		while($file = readdir($dir)){
   			if($file != '.' && $file != '..')
			{
      				$counter++;
   			}
		}
		closedir($dir);
    		$uploaddir = "/pictures/";
    			
		if (move_uploaded_file($_FILES["userfile"]["tmp_name"], $uploaddir . $_FILES["userfile"]["$counter"]))
		{
			echo "File Uploaded";
		}else{
			echo "Error";
		}
	}
}
I would like it to count the number of files in pictures/ and name the uploaded file the number it comes up with.
When I try this I get the following warmings...
Warning: move_uploaded_file(/pictures/): failed to open stream: Permission denied in /home/watson516/public/www/adminpanel.php on line 235

Warning: move_uploaded_file(): Unable to move '/tmp/phpfC1gO1' to '/pictures/' in /home/watson516/public/www/adminpanel.php on line 235
I checked the folder permissions and as far as I can tell, all is good.
watson516
Forum Contributor
Posts: 198
Joined: Mon Mar 20, 2006 9:19 pm
Location: Hamilton, Ontario

Post by watson516 »

Ok well I figured it out somewhat....

Code: Select all

if(!empty($_FILES["userfile"]))
		{
			$gallery = opendir("pictures/");
			$counter = 0;
			while($file = readdir($gallery)){
   				if($file != '.' && $file != '..')
				{
      					$counter++;
   				}
			}
			closedir($gallery);
    			$uploaddir = "pictures/";
    			
			if (move_uploaded_file($_FILES["userfile"]["tmp_name"], $uploaddir . $counter . ".jpg"))
			{
				echo "File Uploaded";
			}else{
				echo $count;
				echo "Error";
			}
		}
Is there any good way to not have to include that last .jpg so it can support any image file?
litebearer
Forum Contributor
Posts: 194
Joined: Sat Mar 27, 2004 5:54 am

Post by litebearer »

I didn't test it, but should work.


insert this line...

Code: Select all

$ext = strtolower(strrchr($_FILES["userfile"]["tmp_name"], '.'));
between these lines...

Code: Select all

$uploaddir = "pictures/"; 

                
                        if (move_uploaded_file($_FILES["userfile"]["tmp_name"], $uploaddir . $counter . $ext))

like so...

Code: Select all

$uploaddir = "pictures/"; 

               $ext = strtolower(strrchr($_FILES["userfile"]["tmp_name"], '.'));
                
                        if (move_uploaded_file($_FILES["userfile"]["tmp_name"], $uploaddir . $counter . $ext))
Post Reply