We help IT Professionals succeed at work.

php upload and insert into database not working

jonofat
jonofat used Ask the Experts™
on
I get this error when running the attached code:

PHP Notice: Undefined index: Photo in upload.php on line 4

Line 4 reads: if($_file['Photo']!=""){
<?php
foreach($_FILES as $files => $_file){
$_POST[$files]=""; 
if($_file['Photo']!=""){
$pathinfo=pathinfo($_file['Photo']);
$file_name_array = explode(".", basename($_file['Photo']));
$filename = $file_name_array[count($file_name_array)-2]; 
$_POST[$files]=$file_prefix.$filename.$file_suffix.$date_stamp.".".$pathinfo['extension']; 
}
}
if (isset($_POST['MM_insert'])) {
	$upload_error_codes=array("",
		"The uploaded file exceeds the upload_max_filesize directive in php.ini.","",
		"The uploaded file was only partially uploaded.",
		"No file was uploaded.","Missing a temporary folder.",
		"Failed to write file to disk.","File upload stopped by extension.");
	$allowed_ext_string="";
	$allowed_extensions=explode(",",$allowed_ext_string);
	$upload_status = "";
	$allowed_size =  5+0;
	$success_page = "";
	$thumbs_dir = "";
	$resize_image = "yes";
	$resize_width = 800+0;
	$resize_height = 600+0;
	$thumb_width = +0;
	$thumb_height = +0;		
	$make_thumbs = "";
	$thumb_prefix = "";
	$thumb_suffix = "";
	$file_prefix = "";
	$file_suffix = "";
	$append_date_stamp = "";
	$date_stamp=($append_date_stamp=="1")?date(time()):"";
	$haulted = false;
	$upload_folder="../Photos";
	//Check for restrictions
	//Check if upload folder exists
	if(!file_exists($upload_folder)){die("Upload folder doesn't exist");}
	if(!is_writable($upload_folder)){die("Upload folder is not writable");}
	if($make_thumbs == "yes" && !file_exists($thumbs_dir)){die("Thumbnails folder doesn't exist");}
	if($make_thumbs == "yes" && !is_writable($thumbs_dir)){die("Thumbnails folder is not writable");}
	foreach($_FILES as $files => $_file){
		//Check if it's not empty
		if($_file['name']!=""){
			$pathinfo = pathinfo($_file['name']);
			//If allowed extension or no extension restriction
			if(!in_array(strtolower($pathinfo['extension']),$allowed_extensions) && $allowed_ext_string!=""){
				die(strtoupper($pathinfo['extension'])." files are not allowed.
				<br>No files have been uploaded.");
			}
			if($_file['size']>$allowed_size*1048576 && $allowed_size!=0){
				die("The file size of ".basename($_file['name'])." is ".round($_file['size']/1048576,2)."MB,
				which is larger than allowed ".$allowed_size."MB.<br>No files have been uploaded.");
			}		
		}
	}
	//All checks passed, attempt to upload
	foreach($_FILES as $files => $_file){
		//Check if it's not empty
		if($_file['name']!=""){
			$pathinfo = pathinfo($_file['name']);
			$file_name_array = explode(".", basename($_file['name']));
			$filename = $file_name_array[count($file_name_array)-2];
			$target = $upload_folder;
			$file_uploaded = false;
			$target = $target."/".$file_prefix.$filename.$file_suffix.$date_stamp.".".$pathinfo['extension'];
			//if image
			if(strtolower($pathinfo['extension'])=="jpeg" || strtolower($pathinfo['extension'])=="jpg"){
				//if needs resizing or a thumbnail
				if(($resize_image == "yes" && ($resize_width!="" || $resize_height!="")) || ($make_thumbs == "yes" && ($thumb_width!="" || $thumb_height!=""))){
					$src = imagecreatefromjpeg($_file['tmp_name']);
					list($width,$height)=getimagesize($_file['tmp_name']);
					//if needs thumbnail
					if ($make_thumbs == "yes" && ($thumb_width!="" || $thumb_height!="")){
						$thumb_newwidth=($thumb_width!=0)?$thumb_width:(($width/$height)*$thumb_height);
						$thumb_newheight=($thumb_height!=0)?$thumb_height:(($height/$width)*$thumb_width);
						$tmp=imagecreatetruecolor($thumb_newwidth,$thumb_newheight);
						imagecopyresampled($tmp,$src,0,0,0,0,$thumb_newwidth,$thumb_newheight,$width,$height);
						$thumb_name=$thumb_prefix.$filename.$thumb_suffix.$date_stamp.".".$pathinfo['extension'];
						if(imagejpeg($tmp,$thumbs_dir."/".$thumb_name,100)){
							$upload_status=$upload_status."Thumbnail for ".basename($_file['name'])." was created successfully.<br>";
						}else{
							die($upload_status."There was a problem creating a thumbnail for ". basename($_file['name']).".
							Upload was interrupted.<br>");
						}
					}
					//if needs resizing
					if($resize_image == "yes" && ($resize_width!="" || $resize_height!="")){
						$newwidth=($resize_width!=0)?$resize_width:(($width/$height)*$resize_height);
						$newheight=($resize_height!=0)?$resize_height:(($height/$width)*$resize_width);
						$tmp=imagecreatetruecolor($newwidth,$newheight);
						imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height); 
						if(imagejpeg($tmp,$target,100)){
							$upload_status=$upload_status.basename($_file['name'])." was successfully resized.<br>";
							$file_uploaded=true;
						}else{
							die($upload_status.basename($_file['name'])." could not be resized. Upload was interrupted.<br>");
						}
					}
				}
			}
			if(!$file_uploaded){
				if(move_uploaded_file($_file['tmp_name'], $target)){
					$upload_status=$upload_status.basename($_file['name'])." was uploaded successfully.<br>";
				}else{
					$haulted=true;
				}
			}
			//Cleanup
			if(isset($src)){imagedestroy($src);unset($src);}
			if(isset($tmp)){imagedestroy($tmp);unset($tmp);}
			if($haulted){die($upload_status."There was a problem uploading ". basename($_file['name']).".
						Error: ".$upload_error_codes[basename($_file['error'])].". Upload was interrupted.<br>");}
		}
	}
	if($success_page!="" && $upload_status!=""){
		header("Location: ".$success_page);
	}
}
?>
<?php require_once('../Connections/floor.php'); ?>
<?php
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  $theValue = (!get_magic_quotes_gpc()) ? addslashes($theValue) : $theValue;

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}

$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
  $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}

if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
  $insertSQL = sprintf("INSERT INTO photos (CatID, PhotoName, Photo) VALUES (%s, %s, %s)",
                       GetSQLValueString($_POST['CatID'], "text"),
                       GetSQLValueString($_POST['PhotoName'], "text"),
                       GetSQLValueString($_POST['Photo'], "text"));

  mysql_select_db($database_floor, $floor);
  $Result1 = mysql_query($insertSQL, $floor) or die(mysql_error());

  $insertGoTo = "index.php";
  if (isset($_SERVER['QUERY_STRING'])) {
    $insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
    $insertGoTo .= $_SERVER['QUERY_STRING'];
  }
  header(sprintf("Location: %s", $insertGoTo));
}

mysql_select_db($database_floor, $floor);
$query_Recordset1 = "SELECT * FROM category";
$Recordset1 = mysql_query($query_Recordset1, $floor) or die(mysql_error());
$row_Recordset1 = mysql_fetch_assoc($Recordset1);
$totalRows_Recordset1 = mysql_num_rows($Recordset1);
?>

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
First, it should be $_FILE (capital letters)
Second, check whether there is a field named "Photo" in the HTML form that you are having

Author

Commented:
OKay, I changed it to if($_FILE['Photo']!=""){

and yes, I do have a field named "Photo"

<input name="Photo" type="file" id="Photo" />

Author

Commented:
And I still get the same error.

Commented:
In your form tag, do you have enctype="multipart/form-data"?

Author

Commented:
<form action="<?php echo $editFormAction; ?>" method="POST" enctype="multipart/form-data" name="form1" id="form1">

Commented:
Have you tried echoing the $_file array before line 4 to see what it contains?

print_r($_file);

Author

Commented:
I did what you suggested:

<?php
foreach($_FILES as $files => $_file){
$_POST[$files]="";
print_r($_FILE);
if($_FILE['Photo']!=""){
$pathinfo=pathinfo($_file['Photo']);
$file_name_array = explode(".", basename($_file['Photo']));
$filename = $file_name_array[count($file_name_array)-2];
$_POST[$files]=$file_prefix.$filename.$file_suffix.$date_stamp.".".$pathinfo['extension'];
}
}

and I get this error

PHP Notice: Undefined variable: _FILE in upload.php on line 4 PHP Notice:
Undefined variable: _FILE in upload.php on line 5

Commented:
It should be print_r($_file).

Author

Commented:
PHP Notice: Undefined variable: _FILE in upload.php on line 5

Line 5 = if($_FILE['Photo']!=""){

Commented:
Going back to your original post, I believe line 4 should read:

if($_file['Photo']['name']!=""){

The $_FILES array is an associative array. Let's say your upload box is the following:

<input type="file" name="Photo" size="52" />

The $_FILES array will contain:

$_FILES['Photo']['name'] The original name of the file as it exists on the your computer
$_FILES['Photo']['type'] The mime type of the file.
$_FILES['Photo']['size'] The size, in bytes, of the file.
$_FILES['Photo']['tmp_name'] The temporary filename of the file that was created when the file was uploaded to the server




Author

Commented:
Getting exactly the same error :(
Which version of PHP are you using? $_FILE may not be supported in older versions of PHP. You may have to use $HTTP_POST_FILES if PHP version is less than 5

Author

Commented:
I am using version 5 I think. How can I double check?

Author

Commented:
Never mind. I just checked in my PHP directory and I am definately using version 5.

Commented:
At the top of your page, try printing out $_FILES

<?php print_r($_FILES); ?>

This will at least show you what's in the array.
Try this: Do they print any values?? If so,

print_r($_FILES);

echo "********";

foreach($_FILES as $files => $_file)
{
    print_r($_file);
 
    if($_file['Photo']!="")
 ...

}

Open in new window

Sorry cdrugly, cross-posted

Author

Commented:
When I load the page it shows

Array ( )

Commented:
Something things are afoot at the Circle K.

The $_FILES array is not being populated by your form. Can you post the HTML?

Commented:
Another shot in the dark might be this:

http://getluky.net/2004/10/04/apachephp-_files-array-mysteriously-empty/

"A file upload form that’s been working for a long time, suddenly fails. No file uploads work on the entire apache installation. Checking the drive space in the /tmp folder, even though 85MB are left, freeing up space reveals that if there isn’t a lot of free space left for /tmp, the $_FILES array just goes empty without further explanation. No useful error messages, or anything.

Freeing up space for /tmp solves the problem effectively."

Author

Commented:

<form action="<?php echo $editFormAction; ?>" method="POST" enctype="multipart/form-data" name="form1" id="form1">
  <label>
  <input name="Photo" type="file" id="Photo" />
  </label>
  <p>
    <label>
    <select name="CatID" id="CatID">
      <?php
do {  
?>
      <option value="<?php echo $row_Recordset1['CatID']?>"><?php echo $row_Recordset1['CatName']?></option>
      <?php
} while ($row_Recordset1 = mysql_fetch_assoc($Recordset1));
  $rows = mysql_num_rows($Recordset1);
  if($rows > 0) {
      mysql_data_seek($Recordset1, 0);
	  $row_Recordset1 = mysql_fetch_assoc($Recordset1);
  }
?>
    </select>
    </label>
  </p>
  <p>
    <label>
    <input name="PhotoName" type="text" id="PhotoName" />
    </label>
  </p>
  <p>
    <label>
    <input type="submit" name="Submit" value="Submit" />
    </label>
  </p>
  
  <input type="hidden" name="MM_insert" value="form1">
</form>

Open in new window

Commented:
I simplified things a bit to test.

HTML:
<form action="index_proc.php" method="POST" enctype="multipart/form-data" name="form1" id="form1">
<input name="Photo" type="file" id="Photo" />
</form>

PHP:
<?php
print_r($_FILES);
?>

Returns:
Array
(
    [Photo] => Array
        (
            [name] => Toasty Cat.JPG
            [type] => image/jpeg
            [tmp_name] => /tmp/phpCzDcWp
            [error] => 0
            [size] => 158070
        )

)

So, your HTML appear to be fine. Is it possible through continuous testing you filled the /tmp directory?

Commented:
Sorry, I forgot the submit button. So the HTML should read:

<form action="index_proc.php" method="POST" enctype="multipart/form-data" name="form1" id="form1">
<input name="Photo" type="file" id="Photo" /><br>
<input type="submit" name="Submit" value="Submit" />
</form>
Can you please tell the output of http:#33109339

Author

Commented:
Where do I find the /tmp directory and see if it is full?

Commented:
I've been assuming all along you're using a Linux system. If so, the /tmp folder should be at the server root.

Author

Commented:
Um, nope. I am using windows and PHP with IIS
Sorry.. I meant
 Can you please tell the output of http://#33109339

Author

Commented:
mgh mgharish, that link doesn't work

Commented:
He replied in an earlier post. When he echoes $_FILES, he gets:

Array ( )
cdrugly, I don't think $_FILE is empty array. If it is empty, foreach wouldn't get executed, and hence he won't get error (PHP Notice:  Undefined index: Photo in upload.php on line 4) at all in the first place. So it MUST be going inside, which may not have got printed properly. That's why I suggested an print_r inside the loop., and also echo to make sure that the prints are displayed on the page

Commented:
Gotcha.

Take a peek in  WINDOWS\TEMP and make sure the user has read/write permissions to this folder.

Author

Commented:
Thanks guys. Will check it out when I get home, am at work now. Will let you know.

Commented:
Most likely you have your error reporting too high. There are two solutions:

1) Check if the variable is set before using it.

<?php

if (isset($_file['Photo'])) {
     if($_file['Photo']!=""){
        //code .......

?>

2) Turn down your error reporting (I highly recommend this one)

<?php
// put this at the start of your php code
error_reporting(E_ALL & ~E_NOTICE);

?>

Author

Commented:
Hi all. When I got home from work yesterday my internet was dead. I have called for a technician to come and check my line but don't know when they will arrive. As soon as they do I will test out the code in your comments and get back to you. Sorry for the delay.

Author

Commented:
regality, when I use your code from 2) it now has a different error:

Column 'Photo' cannot be null

Commented:
You must have a not null constraint on that column in your MySQL table.
In your function GetSQLValueString() change the' "NULL" to "''"  (that's two single quotes surrounded by two double quotes), or run the following sql command once:

alter table photo modify column photo text;

or you might consider using a BLOB instead of text if you are storing binary images in there.

Author

Commented:
OKay, now we are getting somewhere. However, the PHOTO column in the database is now empty where it should have the name of the file I uploaded. So, when I click BROWSE on the file field and I for example choose test.jpg it should show test.jpg in the PHOTO column but it is blank?

Commented:
What is the outpput of:

var_dump($_POST['Photo']);

?

It looks like it's not being posted correctly.

Author

Commented:
Should I put that code in here? Not sure where you want me to put it

if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
  $insertSQL = sprintf("INSERT INTO photos (CatID, PhotoName, Photo) VALUES (%s, %s, %s)",
                       GetSQLValueString($_POST['CatID'], "text"),
                       GetSQLValueString($_POST['PhotoName'], "text"),
                       GetSQLValueString($_POST['Photo'], "text"));

Commented:
You just need to check what is in the post variables. There may be something inconsistent with the form you are submitting. All of your questions so far are just basic debugging. You will need to learn this skill for yourself, as you won't be able to bring every issue you encounter to a forum.

print_r($_POST);  or var_dump($_POST['photo']); will just show you what is in those variables. If they are correct you know the problem is with your code, otherwise it is probably with the form you are submitting.

Learn some basic debugging, everyone here is glad to help, but you will need to be able to do this on your own if you ever want to get your code working.

I found a few good websites that go over the basics on this topic:
http://www.ibm.com/developerworks/library/os-debug/
http://onlamp.com/pub/a/php/2004/08/12/DebuggingPHP.html

------ A few minutes later ----------

Although you still need to look at those websites, I think I realized that the form pust the Photo input into $_FILES, not $_POST. You need to get it from there.
// ......code
GetSQLValueString($_FILES['Photo']['name'], "text"));
// code...........

Author

Commented:
HI regality. I do agree with you, I have a lot to learn. It is my own fault by relying on dreamweaver to do all the work for me and when I get problems then I am screwed because I don't know what to do. I have bought a PHP book which I received on Friday. I am on chapter 5 already and have learnt a good few things. I am also going to from now start typing out all my code from scratch instead of using dreamweaver and it's extensions. I thought it would make things quicker but it actually makes things slower because if I new what the code actually meant, I would be able to debug it properly. Saying that though, I really need some spoon feeding just to get this page running as it is for my personal website and I can't add my photos so if you could just bear with me a bit longer. (it is quite urgent as it is for my band and I have sent my cd to record labels who might look at the site this week) I am at least making an effor to start learning to code properly as we can all see that dreamweaver can only take you so far. I do appreciate everyone's help. I am not being lazy, I just don't know what to look for!  THanks for those links. I will print those pages out and read them.

I tried what I think you meant and changed the lines I posted above your post to this: In the database column, instead of being blank, it now says ARRAY.

if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
  $insertSQL = sprintf("INSERT INTO photos (CatID, PhotoName, Photo) VALUES (%s, %s, %s)",
                       GetSQLValueString($_POST['CatID'], "text"),
                       GetSQLValueString($_POST['PhotoName'], "text"),
                       GetSQLValueString($_FILES['Photo'], "text"));
Commented:
Sounds like you are learning quickly, keep studying and you will figure everything out.

$_FILES is an array of arrays, so $_FILE['Photo'] is an array. $_FILE['Photo']['name'] is the name of the photo.

I'm not entirely sure I know what you want in that 3rd column of your table, but I'm assuming it is the filename of the image, and that PhotoName is a separate name that describes the file. If this is correct then you need this code:

if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
  $insertSQL = sprintf("INSERT INTO photos (CatID, PhotoName, Photo) VALUES (%s, %s, %s)",
                       GetSQLValueString($_POST['CatID'], "text"),
                       GetSQLValueString($_POST['PhotoName'], "text"),
                       GetSQLValueString($_FILES['Photo']['name'], "text"));

Author

Commented:
Awesome! That works but why do you have to put ['Photo']['name'] together like that if you only want the text from the PHOTO textfield ?

Commented:
It's a multidimensional array. The structure of $_FILES can be found here: http://php.net/manual/en/reserved.variables.files.php

If you wanted a tutorial just on multidimensional arrays, I found a good one here: http://www.webcheatsheet.com/PHP/multidimensional_arrays.php

Author

Commented:
How long did it take you to learn so much. It feels like there is so much to learn and it would take me years!!! :(