Jump to content

Adding a FOREACH to a whole php page


unistake

Recommended Posts

Hi all,

 

I have a long script that processes only one image at the moment.

 

What I am trying to do is put all the script in to a 'foreach' section so that I can process more than just one image.

 

Could someone show me how to do this, putting all the uploaded images in to an array (i guess is the best option) and tell me what the form input names need to be below.

 

The script I was trying to make in principle was:

 

<?php
$reg = "G-BAAA";
$count-number-of-files-being-uploaded = x ; // NUMBER OF FILES??


$number = 0;
foreach $_FILES {
     // THIS IS WHERE THE IMAGES ARE UPLOADED AND THUMBNAILS CREATED. THE NAMES OF THE FILES ARE $reg.$number."."$ext;
    $number++;
}
?>
<form name="newad" method="post" enctype="multipart/form-data" action="">
<table>
<tr><td><input type="file" name="image[]" ></td></tr>
<tr><td><input type="file" name="image[]" ></td></tr>
<tr><td><input name="Submit" type="submit" value="Upload image"></td></tr>
</table>
</form>

Link to comment
Share on other sites

<?php
if ( isset($_POST['Submit']) )
{
   $dir    = 'images/';

   $files  = array_values($_FILES);
   $number = count($files);

   for ($i = 0; $i < $number; $i++)
   {
      $name = basename($files[$i]['name']);
      $dir .= $name;
      //move uploaded file etc...
   }
}
?>
<form name="newad" method="post" enctype="multipart/form-data" action="">
<table>
<tr><td><input type="file" name="image" ></td></tr>
<tr><td><input type="file" name="image1" ></td></tr>
<tr><td><input name="Submit" type="submit" value="Upload image"></td></tr>
</table>
</form>

 

I have also attached a class I wrote to do this. Feel free to use it if you are comfortable with OOP, can't guarantee it's well written or anything but it works.

 

 

[attachment deleted by admin]

Link to comment
Share on other sites

Hi Andy,

 

Thanks for that.

 

Could you just walk me through what those variables are for?

 

I have a variable in my script

	$filename = stripslashes($_FILES['image']['name']);

 

How would I use your variable of

$name = basename($files[$i]['name']);

with this?

 

Thanks

 

 

The whole script I have is:

 


<?php

$reg = "G-BAAA";
if ( isset($_POST['Submit']) )
{
   $dir    = 'aircraft/';

   $files  = array_values($_FILES);
   $number = count($files);

   for ($i = 0; $i < $number; $i++)
   {
      $name = basename($files[$i]['name']);
      $dir .= $name;
  
//define a maxim size for the uploaded images
define ("MAX_SIZE","40000");
// define the width and height for the thumbnail
// note that theese dimmensions are considered the maximum dimmension and are not fixed,
// because we have to keep the image ratio intact or it will be deformed
define ("WIDTH","200");
define ("HEIGHT","100");

// this is the function that will create the thumbnail image from the uploaded image
// the resize will be done considering the width and height defined, but without deforming the image
function make_thumb($img_name,$filename,$new_w,$new_h)
{
//get image extension.
$ext=getExtension($img_name);
//creates the new image using the appropriate function from gd library
if(!strcmp("jpg",$ext) || !strcmp("jpeg",$ext))
$src_img=imagecreatefromjpeg($img_name);

if(!strcmp("png",$ext))
$src_img=imagecreatefrompng($img_name);

//gets the dimmensions of the image
$old_x=imageSX($src_img);
$old_y=imageSY($src_img);

// next we will calculate the new dimmensions for the thumbnail image
// the next steps will be taken:
// 1. calculate the ratio by dividing the old dimmensions with the new ones
// 2. if the ratio for the width is higher, the width will remain the one define in WIDTH variable
// and the height will be calculated so the image ratio will not change
// 3. otherwise we will use the height ratio for the image
// as a result, only one of the dimmensions will be from the fixed ones
$ratio1=$old_x/$new_w;
$ratio2=$old_y/$new_h;
if($ratio1>$ratio2) {
$thumb_w=$new_w;
$thumb_h=$old_y/$ratio1;
}
else {
$thumb_h=$new_h;
$thumb_w=$old_x/$ratio2;
}

// we create a new image with the new dimmensions
$dst_img=ImageCreateTrueColor($thumb_w,$thumb_h);

// resize the big image to the new created one
imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y);

// output the created image to the file. Now we will have the thumbnail into the file named by $filename
if(!strcmp("png",$ext))
imagepng($dst_img,$filename);
else
imagejpeg($dst_img,$filename);

//destroys source and destination images.
imagedestroy($dst_img);
imagedestroy($src_img);
}

// 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, print an error message
//and will not upload the file, otherwise we continue
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png"))
{
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=getimagesize($_FILES['image']['tmp_name']);
$sizekb=filesize($_FILES['image']['tmp_name']);

//compare the size with the maxim size we defined and print error if bigger
if ($sizekb > 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=$reg.$number.".".$extension;
//the new name will be containing the full path where will be stored (images folder)
$newname="aircraft/".$image_name;
$copied = copy($_FILES['image']['tmp_name'], $newname);
//we verify if the image has been uploaded, and print error instead
if (!$copied)
{
echo '<h1>Copy unsuccessfull!</h1>';
$errors=1;
}
else
{
// the new thumbnail image will be placed in images/thumbs/ folder
$thumb_name='aircraft/thumb_'.$image_name;
// call the function that will create the thumbnail. The function will get as parameters
//the image name, the thumbnail name and the width and height desired for the thumbnail
$thumb=make_thumb($newname,$thumb_name,WIDTH,HEIGHT);
}} }}

//If no errors registred, print the success message and show the thumbnail image created
if(isset($_POST['Submit']) && !$errors)
{
echo "<h1>Thumbnail created Successfully!</h1>";
echo '<img src="'.$thumb_name.'">';
}
}
}
?>
<!-- next comes the form, you must set the enctype to "multipart/form-data" and use an input type "file" -->

<form name="newad" method="post" enctype="multipart/form-data" action="">
<table>
<tr><td><input type="file" name="image" ></td></tr>
<tr><td><input type="file" name="image" ></td></tr>
<tr><td><input name="Submit" type="submit" value="Upload image"></td></tr>
</table>
</form>

Link to comment
Share on other sites

Basically what I'm doing there is storing multiple $_FILES arrays in a multi dimentional array named $files and making the indexes numeric, this way you can upload multiple files and loop through each files array using a for loop.

 

basename returns the last portion of the uploaded file name (after the last /) i.e. boeing747.jpg.

 

Your code is a little messy, if you want to explain exactly what you're trying to do I can rewrite it for you?

Link to comment
Share on other sites

Ok thanks andy.

 

The script uploads the image to '/aircraft' and creates a thumbnail to the same /aircraft directory.

 

The name of the image will be using the $reg variable (above $reg= "G-BAAA").

As there are more than one images that I am trying to get to upload, I want to rename all the images like G-BAAA1.jpg and G-BAAA2.jpg etc.  The thumbnails will be called G-BAAA_thumb.jpg respectively.

 

That is it. I am also going to try and cut the larger image to a size 600px x 400px but I will do this after I have got the script to store more than one image.

 

Thanks for your help.

 

Link to comment
Share on other sites

upload.php

<?php
include 'func.php';
define('MAX_SIZE', 40000 * 1024);
define('MAX_THUMB_WIDTH', 200);
define('MAX_THUMB_HEIGHT', 100);
define('MAX_WIDTH', 600);
define('MAX_HEIGHT', 400);
define('DIR', 'aircraft/');
define('REG', 'G_BAAA');

$allowedTypes = array( 'jpg' => 'image/jpg', 'jpeg' => 'image/jpeg', 'png' => 'image/png' );

if ( isset($_POST['Submit']) )
{
   $errors = array();
   $update = array();
   
   $files       = array_values($_FILES);
   unset($_FILES);
   $numUploaded = count($files);
   $err  = array();
   
   for($i = 0; $i < $numUploaded; $i++)
   {
      if ( empty($files[$i]['name']) )
      {
         continue;
      }
      $name = basename($files[$i]['name']);
      $ext  = explode('.', basename($name));
      $ext  = $ext[count($ext)-1];
      if ( array_key_exists($ext, $allowedTypes) )
      {
         $info = getimagesize($files[$i]['tmp_name']);
         if ( !in_array($info['mime'], $allowedTypes) )
         {
            $err[] = stripslashes(htmlentities($name, ENT_QUOTES)) . ' filetype not allowed, allowed mime types: ' . implode(', ', $allowedTypes) . '<br >';
         }
      }
      else
      {
         $err[] = stripslashes(htmlentities($name, ENT_QUOTES)) . ' file not an image, you can only upload .jp(e)g or .png files.<br >';
      }
      
      if ( filesize($files[$i]['tmp_name']) > MAX_SIZE )
      {
         $err[] = stripslashes(htmlentities($name, ENT_QUOTES)) . ' file exceeds maximum filesize, upto ' . number_format(MAX_SIZE / 1024, 2) . 'KB allowed.<br >';
      }
      
      if ( !count($err) )
      {
         $saveTo    = DIR . REG . $i;
         $saveThumb = $saveTo . '_thumb';
         $saveTo   .= '.' . $ext;
         $saveThumb.= '.' . $ext;
         scaleImg($info[0], $info[1], MAX_WIDTH, MAX_HEIGHT, $files[$i]['tmp_name'], $info['mime'], $saveTo);
         scaleImg($info[0], $info[1], MAX_THUMB_WIDTH, MAX_THUMB_HEIGHT, $files[$i]['tmp_name'], $info['mime'], $saveThumb);
         $update[] = '<h1>Thumbnail and image created successfully:</h1><br ><br ><img src="' . $saveThumb . '" ><br ><br ><img src="' . $saveTo . '" ><br ><br >';
      }
      else
      {
         $errors[] = $err;
      }
   }
   if ( count($errors) )
   {
      foreach($errors as $err)
      {
         echo implode('', $err);
      }
   }
   
   if ( count($update) )
   {
      echo implode('', $update);
   }
}
?>
<form name="newad" method="post" enctype="multipart/form-data" action="">
<table>
<tr><td><input type="file" name="image" ></td></tr>
<tr><td><input type="file" name="image1" ></td></tr>
<tr><td><input name="Submit" type="submit" value="Upload image"></td></tr>
</table>
</form>

 

func.php

<?php

function scaleImg($curW, $curH, $maxW, $maxH, $curName, $curType, $saveTo)
{

$ratio_orig = $curW / $curH;

   if ($maxW / $maxH > $ratio_orig)
   {
      $maxW = $maxH * $ratio_orig;
   }
   else
   {
      $maxH = $maxW / $ratio_orig;
   }

$image_p = imagecreatetruecolor($maxW, $maxH);

   if ($curType == 'image/png')
   {
      $image = imagecreatefrompng($curName);
   }
   else
   {
      $image = imagecreatefromjpeg($curName);
   }

imagecopyresampled($image_p, $image, 0, 0, 0, 0, $maxW, $maxH, $curW, $curH);

   // Save
   if ($curType == 'image/png')
   {
      imagepng($image_p, $saveTo, 100);
   }
   else
   {
      imagejpeg($image_p, $saveTo, 100);
   }

imagedestroy($image);
imagedestroy($image_p);

}
?>

 

Should work as desired. ;)

Link to comment
Share on other sites

Oh of course, change:

 

      $ext  = explode('.', basename($name));
      $ext  = $ext[count($ext)-1];

 

to:

 

      $ext  = explode('.', basename($name));
      $ext  = strtolower($ext[count($ext)-1]);

 

And it's no problem mate, gave me something to for a while lol.

Link to comment
Share on other sites

<div id="loading" style="display: none;"><img src="loading.gif"></div>
<form name="newad" method="post" enctype="multipart/form-data" action="">
<table>
<tr><td><input type="file" name="image" ></td></tr>
<tr><td><input type="file" name="image1" ></td></tr>
<tr><td><input name="Submit" type="submit" value="Upload image" onclick="document.getElementById('loading').style.display='block';"></td></tr>
</table>
</form>

 

Loading image attached. ;)

 

[attachment deleted by admin]

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.