Log in

View Full Version : File Upload keeping track



bluewalrus
11-07-2008, 05:47 PM
This code is suppose to keep track of how many files have been uploaded increasing at each file. The image name is also suppose to match the # file it is. If the image were the 46th one being uploaded it would be named image46.jpg the name(image) and the extension(.jpg) are gathered else where. but right now i'm getting an error message "Unknown extension!

Fatal error: Cannot redeclare getextension() (previously declared in /hsphere/local/home/crazychr/bluewalrus.net/test/files.php:23) in /hsphere/local/home/crazychr/bluewalrus.net/test/files.php on line 23"

It is going threw the code once but failing. The unknown extenstion is not true its a jpg. This is a mashing of different things I've tried to pick up. I'm new to php as a few of you have noticed i'm sure. Thanks for your time and any ideas you have.

<?php
for($m = 0; $m < count($_FILES['image']); $m++) {
$image = $_FILES['image'][$m];
$counterfile = "number.txt";
$fp = fopen($counterfile,"r");
$hits = fgets($fp,100);
fclose($fp);
$hits++;
$fp = fopen($counterfile,"w");
fputs($fp, $hits);
fclose($fp);
//define a maxim size for the uploaded images in Kb
define ("MAX_SIZE","9000000");
//This function reads the extension of the file. It is used to determine if the file is an image by checking the extension.
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
//This variable is used as a flag. The value is initialized with 0 (meaning no error found)
//and it will be changed to 1 if an errro occures.
//If the error occures the file will not be uploaded.
$errors=0;
//checks if the form has been submitted
if(isset($_POST['Submit']))
{
//reads the name of the file the user submitted for uploading
$image=$_FILES['image']['name'];
//if it is not empty
if ($image)
{
//get the original name of the file from the clients machine
$filename = stripslashes($_FILES['image']['name']);
//get the extension of the file in a lower case format
$extension = getExtension($filename);
$extension = strtolower($extension);
//if it is not a known extension, we will suppose it is an error and will not upload the file,
//otherwise we will do more tests
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif"))
{
//print error message
echo '<h1>Unknown extension!</h1>';
$errors=1;
}
else
{
//get the size of the image in bytes
//$_FILES['image']['tmp_name'] is the temporary filename of the file
//in which the uploaded file was stored on the server
$size=filesize($_FILES['image']['tmp_name']);

//compare the size with the maxim size we defined and print error if bigger
if ($size > MAX_SIZE*1024)
{
echo '<h1>You have exceeded the size limit!</h1>';
$errors=1;
}

//we will give an unique name, for example the time in unix time format
$image_name=$image;
//the new name will be containing the full path where will be stored (images folder)
$newname="/".$image_name . $hits;
//we verify if the image has been uploaded, and print error instead
$copied = copy($_FILES['image']['tmp_name'], $newname);
if (!$copied)
{
echo '<h1>Copy unsuccessfull!</h1>';
$errors=1;
}}}}

//If no errors registred, print the success message
if(isset($_POST['Submit']) && !$errors)
{
echo "<h1>File Uploaded Successfully! Upload Another?</h1>";
}
}
?>
<form name="newad" method="post" enctype="multipart/form-data" action="">
Name:<br /><input name="name" type="text" />
<br />Age:<br /><input name="age" type="text" />
<br />Denim:<br /><input name="denim" type="text" />
<br />Lifestyle:<br /><input name="lifestyle" type="text" /><br />
<input type="file" name="image[]" /><br />
<input type="file" name="image[]" /><br />
<input type="file" name="image[]" /><br />
<input name="Submit" type="submit" value="Upload images" />

dj30324
11-08-2008, 06:14 PM
bro i ran your script 000webhost.com i got this problem


Unknown extension!

PHP Error Message

Fatal error: Cannot redeclare getextension() (previously declared in /home/username/public_html/transload/file2.php:15) in /home/username/public_html/transload/file2.php on line 15



it has something to do with this code here for me

function getExtension($str) {
i toke look at that section of closed bracket script

if (!$i) { return ""; }
that portion of the script giving me errors that need to be corrected. hope this helps a little i nt an expert php just a beginner, forgive me .

bluewalrus
11-08-2008, 06:58 PM
Thanks for the reply I actual gave up on this whole script because there were too many things not working however i do now have this script which works 97% the only i dont know is where its getting the name of the file from and if i can add a number to it after like an id to keep track of all the images that have been uploaded. I found script in here that is keeping track its varible is $hits but i dont know where to put that in the upload part of this any help i appreciate. Thanks


<?php
if (empty($denim) || empty($age) || empty($lifestyle)) {
die ('Please Enter all required fields.<form enctype="multipart/form-data" action="upload.php" method="post">
Name:<br /><input name="name" type="text" />
<br />Age:*<br /><input name="age" type="text" />
<br />Denim*:<br /><input name="denim" type="text" />
<br />Lifestyle:*<br /><input name="lifestyle" type="text" /><br />
Image1: <input name="userfile[]" type="file" /><br />
Image2: <input name="userfile[]" type="file" /><br />
Image3: <input name="userfile[]" type="file" /><br />
<input type="submit" value="Upload" />
</form>
</body>
</html>
');
}
else
{
//increase the number of files uploaded
$counterfile = "number.txt";
$fp = fopen($counterfile,"r");
$hits = fgets($fp,100);
fclose($fp);
$hits++;
$myFile = "uploads.txt";
$fh = fopen($myFile, 'a+');
$data = "ID=\n" . $hits . '\n' . $name . '\n' . $denim . '\n' . $age . '\n' . $lifestyle;
fwrite($fh, $data);
fclose($fh);
$fp = fopen($counterfile,"w");
fputs($fp, $hits);
fclose($fp);
$success = 0;
$fail = 0;
$uploaddir = 'uploads/';
for ($i=0;$i<3;$i++)
{
if($_FILES['userfile']['name'][$i])
{
$uploadfile = $uploaddir . basename($_FILES['userfile']['name'][$i]);
$ext = strtolower(substr($uploadfile,strlen($uploadfile)-3,3));
if (preg_match("/(jpg|gif|png|bmp)/",$ext))
{
if (move_uploaded_file($_FILES['userfile']['tmp_name'][$i], $uploadfile))
{
$success++;
}
else
{
echo "Error Uploading the file. Retry after sometime.\n";
$fail++;
}
}
else
{
$fail++;
}
}
}
echo "<br> Number of files Uploaded:".$success;
echo "<br> Number of files Failed:".$fail;
}
?>

JasonDFR
11-09-2008, 09:15 AM
In your original script you had defined the function inside your loop. Don't do that.

You can use:


$ext = substr($file_name, strrpos($file_name, '.') + 1); // File extension ex 'jpeg'

to get the extension of a file.

Check out the code I wrote below for handling multiple photo uploads. If you can use any of it, great!

You should also learn to use a MySQL database for keeping track of stuff like this. If I can do it, you can too!

Good luck,

Jason


$errors = array();

foreach ($_FILES['photos']['error'] as $key => $error) {

if ( $_FILES['photos']['size'][$key] > 0 ){

if ($error == UPLOAD_ERR_OK ) {

$tmp_name = $_FILES["photos"]["tmp_name"][$key];
$file_name = basename($_FILES['photos']['name'][$key]); // File name ex: 'theme.jpg'
$ext = substr($file_name, strrpos($file_name, '.') + 1); // File extension ex 'jpeg'

$upload_dir = UPLOAD_DIR;

$allowed_ext = array("jpg", "jpeg"); // Allowed file extensions
$allowed_type = array("image/jpeg", "image/pjpeg"); // Allowed mime types

$photo_info = getimagesize($tmp_name);

if ( !in_array($ext, $allowed_ext) ) { // Check for allowed file extension

$errors[] = '<p class="error">Uploaded files must have a .jpg or .jpeg extension. Your file: ' . "$file_name" . ' has an extenstion of ' . ".$ext" . '</p>';
}

if ( in_array($photo_info['mime'], $allowed_type) ) {
$type = "photo";
} else {
$errors[] = '<p class="error">Uploaded files must be of the correct type ("image/jpeg" or "image/pjpeg"). Your file: ' . "$file_name" . ' is being reported as ' . $photo_info['mime'] . '</p>';
}

if ($_FILES['photos']['size'][$key] <= 2000000 ) { // Check for maximum allowed size 2 MB 1000 K 2000000 bytes
$file_size = ($_FILES['photos']['size'][$key]/1000);
} else { // File size is NOT ok
$errors[] = "<p class=\"error\">Uploaded files must be less than 2000 KB ( 2 MB ). $file_name is $file_size KB.</p>";
}

if ( empty($errors) ) {

$new_file_name = substr(md5($_SESSION['U_ID'] . rand(0,999)),0,6) . "$type" . ".$ext";

// Move file
if ( move_uploaded_file("$tmp_name", UPLOAD_DIR . "$new_file_name") ) { // Move file to final storage directory


$q = "INSERT INTO `files` (
`file_id` ,
`file_name` ,
`file_location` ,
`file_type` ,
`file_date`
)
VALUES (
NULL , '$new_file_name', '$upload_dir', '$type', NOW( )
) ";

mysql_query($q) or die(mysql_error());

$success_msg = "<p></p>" ;

} else {

$errors[] = "<p>There was a problem saving this file: $file_name .</p>";
}
}

} else {
$errors[] = "<p>There was a problem saving one of your photos. Each photo must be less than 2000 KB.</p>";
}
}
}

bluewalrus
11-09-2008, 02:27 PM
umm which function are you referring to for not to have in the loop? The code i have works I just dont know where its getting the filename from. I know its checking the extension of the image file so i want while its seperated there to add in the $hits then re-add the extension like image.jpg....check does equal .jpg......adding image49.jpg

JasonDFR
11-09-2008, 02:54 PM
I was referring to


function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}

in your first post.

It looks like it is inside this loop: for($m = 0; $m < count($_FILES['image']); $m++) {

I would recommend using a foreach loop instead of a for loop to loop through each submitted file.

Then you can get the file name like this:


$file_name = basename($_FILES['image']['name']['$key']); // File name ex: 'theme.jpg'

Then you can get the extension from:


$ext = substr($file_name, strrpos($file_name, '.') + 1); // File extension ex 'jpeg'

Check out the script I posted originally.

If I misunderstood your question or code, please forgive me.

Good luck!

Jason

bluewalrus
11-09-2008, 05:51 PM
OO I changed my code into this (in 2nd post) don't know if your refering to that code or this code to add that into?
I don't have a filename variable in this new code though. I dont kow if i confused you with that extension question. I know its already checking the extension so to me it seems like its separated the code from the filename and then the extension while its separated there i want to add in the $hits variable which is keeping track of the files.

<?php
if (empty($denim) || empty($age) || empty($lifestyle)) {
die ('Please Enter all required fields.<form enctype="multipart/form-data" action="upload.php" method="post">
Name:<br /><input name="name" type="text" />
<br />Age:*<br /><input name="age" type="text" />
<br />Denim*:<br /><input name="denim" type="text" />
<br />Lifestyle:*<br /><input name="lifestyle" type="text" /><br />
Image1: <input name="userfile[]" type="file" /><br />
Image2: <input name="userfile[]" type="file" /><br />
Image3: <input name="userfile[]" type="file" /><br />
<input type="submit" value="Upload" />
</form>
</body>
</html>
');
}
else
{
//increase the number of files uploaded
$counterfile = "number.txt";
$fp = fopen($counterfile,"r");
$hits = fgets($fp,100);
fclose($fp);
$hits++;
$myFile = "uploads.txt";
$fh = fopen($myFile, 'a+');
$data = "ID=\n" . $hits . '\n' . $name . '\n' . $denim . '\n' . $age . '\n' . $lifestyle;
fwrite($fh, $data);
fclose($fh);
$fp = fopen($counterfile,"w");
fputs($fp, $hits);
fclose($fp);
$success = 0;
$fail = 0;
$uploaddir = 'uploads/';
for ($i=0;$i<3;$i++)
{
if($_FILES['userfile']['name'][$i])
{
$uploadfile = $uploaddir . basename($_FILES['userfile']['name'][$i]);
$ext = strtolower(substr($uploadfile,strlen($uploadfile)-3,3));
if (preg_match("/(jpg|gif|png|bmp)/",$ext))
{
if (move_uploaded_file($_FILES['userfile']['tmp_name'][$i], $uploadfile))
{
$success++;
}
else
{
echo "Error Uploading the file. Retry after sometime.\n";
$fail++;
}
}
else
{
$fail++;
}
}
}
echo "<br> Number of files Uploaded:".$success;
echo "<br> Number of files Failed:".$fail;
}
?>

bluewalrus
11-09-2008, 11:12 PM
or if there's a way to rename the file at the end of that loop that'd work too.

JasonDFR
11-10-2008, 07:32 AM
I think you are asking how to include the $hits variable in the file name? If not, I don't understand, sorry.


or if there's a way to rename the file at the end of that loop that'd work too.

You are renaming the file in your code here:


$uploadfile = $uploaddir . basename($_FILES['userfile']['name'][$i]);

So just change how you are naming $uploadfile and you'll be all set. Instead of using the 'userfile' ['name'], create your own name. See below.

The following code is inside the loop that loops through the uploaded images:


// Get temporary file name
$tmp_name = $_FILES["image"]["tmp_name"];

// Create new file name
$new_file_name = substr(md5(rand(0,999)),0,6) . "$type" . ".$ext";

// Move file to final storage directory
move_uploaded_file("$tmp_name", UPLOAD_DIR . "$new_file_name")

When you create the new file name inside your loop, make $hits part of it.

The reason you use random stuff "substr(md5(rand(0,999)),0,6)" in the new file name is because it is more secure this way. If a harmful file gets uploaded, the user who uploaded it will no longer know it's name. And it is even better if you put your upload directory outside of your web root so the public can not access it.

I hope this helps.

Good luck,

J

bluewalrus
11-10-2008, 02:57 PM
Yea thats what I trying to do but failing. I tried changing this:

$uploadfile = $uploaddir . basename($_FILES['userfile']['name'][$i]);
to

$uploadfile = $uploaddir . 'image' .$hits;
but now the upload doesn't function so i tried changing this also


if (move_uploaded_file($_FILES['userfile']['tmp_name'][$i], $uploadfile)) to this

if (move_uploaded_file($uploadfile))
because i thought that might have been looking for old the name but that did not work either.