Function can see variable

… you sure its finding the file you think it’s finding? (I’ma guess there’s a config.php file inside the directory of your main page.)

include/require is not “oh go run this code out in this page and get me the results/functions/variables”, it’s “copy and paste the code in that file in here, then keep going.”

Your function can see only three types of variables:

1- Those which were defined in the function body (local variables);

function myFunc() { 
    $foo = 'bar'; 
    echo $foo; 
}

2- Those which were defined outside the function and declared as global inside the function:

$foo = 'bar';
function myFunc() {
    global $foo;
    echo $foo;
}

3- Those which were passed to the function as arguments:

$foo = 'bar';
function myFunc($param){
    echo $param;
}
myFunc($foo);

So, to make external variables visible by the function you should either declare them as global in the function body (that is a bad practice and not recommended usually) or pass them as arguments (standard practice).

your right megazoid, and thanks starlion for your help
Heres my function to create a thumbnail

<?php
function createThumbnail($filename) {

$providerID = $_POST['id'];

require 'config.php';

if(preg_match('/[.](jpg)$/', $filename)) {
    $im = imagecreatefromjpeg($path_to_image_directory . $filename);
} else if (preg_match('/[.](gif)$/', $filename)) {
    $im = imagecreatefromgif($path_to_image_directory . $filename);
} else if (preg_match('/[.](png)$/', $filename)) {
    $im = imagecreatefrompng($path_to_image_directory . $filename);
} else {
    $im = imagecreatefromwbmp($path_to_image_directory . $filename);
}
 
$ox = imagesx($im);
$oy = imagesy($im);
 
$nx = $final_width_of_image;
$ny = floor($oy * ($final_width_of_image / $ox));
 
$nm = imagecreatetruecolor($nx, $ny);
 
imagecopyresized($nm, $im, 0,0,0,0,$nx,$ny,$ox,$oy);
 
imagejpeg($nm, $path_to_thumbs_directory . $filename);
$tn = '<img src="' . $path_to_thumbs_directory . $filename . '" alt="image" />';
echo $tn;
}
?>

Now that I think of it, it wouldn’t hurt to force the thumbnail to be a jpg (I dont want overly complicated thumbnails).
Here the page where I can upload an image

<?php
session_start();

if(isset($_FILES['image'])) {

$providerID = $_POST['id'];
} else {
$providerID = $_GET['id'];
}

require '../providers/config.php';
require '../providers/functions.php';

?>
...(begin HTML)
<?php
if(isset($_FILES['image'])) {


 
if(preg_match('/[.](jpg)|(gif)|(png)|(bmp)$/', $_FILES['image']['name'])) {
     
    $filename = $_FILES['image']['name'];
    $source = $_FILES['image']['tmp_name'];   
    $target = $path_to_image_directory . $filename;
     
    move_uploaded_file($source, $target);
     
    createThumbnail($filename);     
}
echo '<br style="clear:both">';
echo '<a class="btn btn-primary" href="edit_provider.php?id='.$providerID.'" role="button">';
echo '<span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span> Provider';
echo '</a>';
} else {
?>  
...(HTML form)
<?php
}
?>
...(end HTML)

Heres what it looks like


then,

I want to make sure the user uploads a file of those for extensions, so I guess the if statement above is good, but I also want to make sure the uploaded image is lass than 1000K

I would use pathinfo() to get file extension and check it:

$ext = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));

if (in_array($ext, ['jpg', 'jpeg', 'gif', 'png', 'bmp'])) { .... }

Also note that JPEG file can have .jpeg extension (4 letters) which is valid too

If you are allowing the general public to upload images, Google for,
php secure file uploads

ok, got the code to upload 1 file,

$ext = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));

if( (in_array($ext, ['jpg', 'jpeg', 'gif', 'png', 'bmp']) &&  ($_FILES["image"]["size"] < 512000)) ){ 
     
    $filename = $_FILES['image']['name'];
    $source = $_FILES['image']['tmp_name'];   
    $target = $path_to_image_directory . $filename;
     
    move_uploaded_file($source, $target);
     
    createThumbnail($filename);     
} else {
	echo "<p class='text-danger'><span class='glyphicon glyphicon-remove'></span>&nbsp;&nbsp;Error: File too big ( < 500Kb) or wrong type (gif, jpg, bmp, or png)</p>";
}
echo '<br style="clear:both">';
echo '<a class="btn btn-primary" href="edit_provider.php?id='.$providerID.'" role="button">';
echo '<span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span> Provider';
echo '</a>';

But now lets say I have a form which allows up to 8 images


There set up as an array like this

<input type="file" name="images[]" id="pic1">
<input type="file" name="images[]" id="pic2">
<input type="file" name="images[]" id="pic3">
<input type="file" name="images[]" id="pic4">
<input type="file" name="images[]" id="pic5">
<input type="file" name="images[]" id="pic6">
<input type="file" name="images[]" id="pic7">
<input type="file" name="images[]" id="pic8">

Since I only want to use the inputs that are used, a foreach statement is in order (then an quick if statement to even see if that variable is being used
Is this ok?

foreach ($images as $image) {
    if(empty($image)) {
    //code to upload 1 image/create thumbnail
    }
}

$image would never be empty - if a file is uploaded, that element simply doesnt exist, so the foreach will only operate on existing elements. Note that this is NOT the same behavior as a text box, but IS the same behavior as a checkbox.

Assuming $images is tied to $_FILES[‘images’], this would work.

is this right?

    foreach ($images as $image) {

	$ext = strtolower(pathinfo($image['name'], PATHINFO_EXTENSION));

if( (in_array($ext, ['jpg', 'jpeg', 'gif', 'png', 'bmp']) && ($image["size"] < 512000)) ){ 
     
    $filename = $image['name'];
    $source = $image['tmp_name'];   
    $target = $path_to_image_directory . $filename;
     
    move_uploaded_file($source, $target);
         
    createThumbnail($filename);     
} else {
	echo "<p class='text-danger'><span class='glyphicon glyphicon-remove'></span>&nbsp;&nbsp;Error: File too big ( < 500Kb) or wrong type (gif, jpg, bmp, or png)</p>";
}
} 

Cause that seems like it should work, cept I tried it and nothing

How do I do that?

Just iterate through $_FILES[‘images’]:

foreach ($_FILES['images'] as $image) {
   // ... all your loop code here ...
}

or make an assignment before loop if you don’t want to change it:

$images = $_FILES['images'];

undefined index???

Got this strange error

Notice: Undefined index: name in /home/luke69/public_html/admin/insert_provider.php on line 154
(5 times)

when I tried to upload 3 images out of a possible 8, heres the code

  foreach ($_FILES['images'] as $image) {
  

	  $ext = strtolower(pathinfo($image['name'], PATHINFO_EXTENSION));

	  if( (in_array($ext, ['jpg', 'jpeg', 'gif', 'png', 'bmp']) && ($image["size"] < 512000)) ){ 

But I thought the foreach loop wouldnt even run if nothing was uploaded, so do you know why the error then?

Standard Debug Protocols.

var_dump($_FILES);

I tried it again (this time I uploaded 4 images.
when I did the var_dump($_FILES)
I got

<pre>array(1) {
["images"]=>
  array(5) {
  ["name"]=>
    array(8) {
    [0]=>
    string(22) "640x480_phpQqKALD.jpeg"
    [1]=>
    string(22) "640x480_phpbZW7zd.jpeg"
    [2]=>
    string(22) "600x450_phpoUO9n5.jpeg"
    [3]=>
    string(0) ""
    [4]=>
    string(0) ""
    [5]=>
    string(0) ""
    [6]=>
    string(22) "600x450_phpVtLKgY.jpeg"
    [7]=>
    string(0) ""
}
["type"]=>
array(8) {
  [0]=>
  string(10) "image/jpeg"
  [1]=>
  string(10) "image/jpeg"
  [2]=>
  string(10) "image/jpeg"
  [3]=>
  string(0) ""
  [4]=>
  string(0) ""
  [5]=>
  string(0) ""
  [6]=>
  string(10) "image/jpeg"
  [7]=>
  string(0) ""
}
["tmp_name"]=>
array(8) {
  [0]=>
  string(14) "/tmp/phpepJyFh"
  [1]=>
  string(14) "/tmp/phpawoJpm"
  [2]=>
  string(14) "/tmp/phpjlXU9q"
  [3]=>
  string(0) ""
  [4]=>
  string(0) ""
  [5]=>
  string(0) ""
  [6]=>
  string(14) "/tmp/php7sE7Tv"
  [7]=>
  string(0) ""
}
["error"]=>
array(8) {
  [0]=>
  int(0)
  [1]=>
  int(0)
  [2]=>
  int(0)
  [3]=>
  int(4)
  [4]=>
  int(4)
  [5]=>
  int(4)
  [6]=>
  int(0)
  [7]=>
  int(4)
}
["size"]=>
array(8) {
  [0]=>
  int(52015)
  [1]=>
  int(78430)
  [2]=>
  int(58013)
  [3]=>
  int(0)
  [4]=>
  int(0)
  [5]=>
  int(0)
  [6]=>
  int(38768)
  [7]=>
  int(0)
    }
  }
}

But I still have 5

Notice: Undefined index: name in /home/luke69/public_html/admin/insert_provider.php on line 153
Error: File too big ( < 500Kb) or wrong type (gif, jpg, bmp, or png)
(heres my foreach loop,

  foreach ($_FILES['images'] as $image) {
  

	  $ext = strtolower(pathinfo($image['name'], PATHINFO_EXTENSION));

	  if( (in_array($ext, ['jpg', 'jpeg', 'gif', 'png', 'bmp']) && ($image["size"] < 512000)) ){ 
		   
		  $filename = $image['name'];
		  $source = $image['tmp_name'];   
		  $target = $path_to_image_directory . $filename;
		   
		  move_uploaded_file($source, $target);
			   
	  } else {
		  echo "<p class='text-danger'><span class='glyphicon glyphicon-remove'></span>&nbsp;&nbsp;Error: File too big ( < 500Kb) or wrong type (gif, jpg, bmp, or png)</p>";
	  }
	} 

shouldn’t it only run 4 times, and give no error?

Odd, it empty-sent the array elements that wernt uploaded. Oh well.

To fix this, add this line immediately after the beginning of your foreach:

if(empty($image['name'])) { continue; }

EDIT: Wait… no. I forgot files is a arse-backwards array construction. Thats why.

foreach($images['name'] AS $key => $name) {
      if(empty($name)) { continue; }
  	  $ext = strtolower(pathinfo($name, PATHINFO_EXTENSION));

	  if( (in_array($ext, ['jpg', 'jpeg', 'gif', 'png', 'bmp']) && ($images["size"][$key] < 512000)) ){ 
		  $source = $image['tmp_name'][$key];   
		  $target = $path_to_image_directory . $filename;

		  move_uploaded_file($source, $target);
         }
}

got this error

Notice: Undefined variable: images in /home/luke69/public_html/admin/insert_provider.php on line 150

Warning: Invalid argument supplied for foreach() in /home/luke69/public_html/admin/insert_provider.php on line 150

Should I define it like

$images = $_FILES['images'];

just before the loop?

Yes, or else change $images (and $image, because i’ve just noticed i’ve got a typo in there) in the code block to $_FILES[‘images’]

ok, fixed that so now when I fill out the form, I get a new error.

Warning: move_uploaded_file(…/providers/{dbh->lastInsertId()}/10429382_10152512724491223_7833921182302805412_n (1).jpg): failed to open stream: No such file or directory in /home/luke69/public_html/admin/insert_provider.php on line 160

Warning: move_uploaded_file(): Unable to move ‘/tmp/php2gzBkO’ to ‘…/providers/{dbh->lastInsertId()}/10429382_10152512724491223_7833921182302805412_n (1).jpg’ in /home/luke69/public_html/admin/insert_provider.php on line 160

Heres the foreach loop

$path_to_image_directory = "../providers/{dbh->lastInsertId()}/";

$images = $_FILES['images'];

foreach($images['name'] AS $key => $name) {
  if(empty($name)) { continue; }
  $ext = strtolower(pathinfo($name, PATHINFO_EXTENSION));

  if( (in_array($ext, ['jpg', 'jpeg', 'gif', 'png', 'bmp']) && ($images["size"][$key] < 512000)) ){ 
	  $source = $images['tmp_name'][$key];   
	  $target = $path_to_image_directory . $images['name'][$key];

	  move_uploaded_file($source, $target);
     }

}
I guess theres something wrong with $target
Why does {dbh->lastInsertId()} not work?

You haven’t showed us the database calls preceding that statement in the code. If the database insert failed then that would explain why you cannot retrieve the id of that last insert.

oh ok…
Oh… I just forgot the $ in in dbh

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.