473,385 Members | 2,015 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Notice: Undefined index Error. Help!!!

Hello Folks. Thanks for all the help i have received here. I was trying to write an upload file. It was ok until i began error reporting. First i tried to inspect the file uploaded by asking the print_r to show the associate array of name, type, size, tmp_name and error. It works all right but it gives this error just as i load the page


Notice: Undefined index: file_upload in C:\wamp\www\btb_sandbox\upload.php on line 27



I didnt take it quite serious then i continues my error reporting. It gave the following errors


Notice: Undefined index: file_upload in C:\wamp\www\btb_sandbox\upload.php on line 18

Notice: Undefined index: in C:\wamp\www\btb_sandbox\upload.php on line 19


I understand that file_upload is undefined, but i dont know how to go around it. Or is it from my html tags? Please help out. Here is the code. Thanks


Expand|Select|Wrap|Line Numbers
  1. <?php
  2.  
  3.     //In an application, this could be moved to a config file
  4.     $upload_errors = array
  5.         (//http://www.php.net/manual/en/features.file-upload.errors.php
  6.  
  7.                 UPLOAD_ERR_OK           =>  "No Errors.", 
  8.                 UPLOAD_ERR_INI_SIZE     =>  "Larger than upload_max_filesize.", 
  9.                 UPLOAD_ERR_FORM_SIZE    =>  "Larger than form MAX_FILE_SIZE.", 
  10.                 UPLOAD_ERR_PARTIAL      =>  "Partial upload.", 
  11.                 UPLOAD_ERR_NO_FILE      =>  "No file.", 
  12.                 UPLOAD_ERR_NO_TMP_DIR   =>  "No temporary directory", 
  13.                 UPLOAD_ERR_CANT_WRITE   =>  "Can't write to disk",
  14.                 UPLOAD_ERR_EXTENSION    =>  "File upload stopped by extension."
  15.         );
  16.  
  17.  
  18.         $error = $_FILES['file_upload']['error'];
  19.         $message = $upload_errors[$error];
  20.  
  21.  
  22.  
  23.  
  24.  
  25.     //print_r( is the one giving me Notice:  Undefined index:  file_upload in C:\wamp\www\btb_sandbox\upload.php on line 4. Echo makes it go, nut show nothing because it aint redable by humans
  26.     echo "<pre>";
  27.     print_r($_FILES['file_upload']);
  28.     echo "</pre>";
  29.     echo "<hr/>";
  30.  
  31.  
  32. ?>
  33.  
  34.  
  35. <!DOCTYPE html>
  36.  
  37. <html lang="en">
  38.     <head>
  39.         <meta charset="utf-8" />
  40.         <title> Upload </title>
  41.     </head>
  42.     <body>
  43.  
  44.  
  45.         <?php if(!empty($message)){echo "<p>{$message}</p>";} //A means to pass messages to the the user about the from processing?>
  46.         <form action="upload.php" enctype="multipart/form-data" method="POST">
  47.  
  48.            <input type="hidden" name="MAX_FILE_SIZE" value="100000000"/> 
  49.  
  50.             <input type="file" name="file_upload"/>
  51.  
  52.             <input type="submit" value="Upload"/>
  53.  
  54.         </form>
  55.  
  56.  
  57.  
  58.  
  59.  
  60.     </body>
  61. </html>
  62.  
Feb 27 '15 #1
17 3244
Dormilich
8,658 Expert Mod 8TB
if you call the page in order to upload a file, the $_FILES array is empty.
Mar 1 '15 #2
Thanks Dormilich, so how can i solve it???
Mar 1 '15 #3
Dormilich
8,658 Expert Mod 8TB
you check if $_FILES is populated and only then run the upload code.
Mar 2 '15 #4
Dormilich
8,658 Expert Mod 8TB
FWD:
Expand|Select|Wrap|Line Numbers
  1. <?php 
  2.  
  3.  if(isset($_POST['file_upload'])) 
  4.     {   
  5.     $upload_errors = array 
  6.         ( 
  7.                 UPLOAD_ERR_OK           =>  "No Errors.",  
  8.                 UPLOAD_ERR_INI_SIZE     =>  "Larger than upload_max_filesize.",  
  9.                 UPLOAD_ERR_FORM_SIZE    =>  "Larger than form MAX_FILE_SIZE.",  
  10.                 UPLOAD_ERR_PARTIAL      =>  "Partial upload.",  
  11.                 UPLOAD_ERR_NO_FILE      =>  "No file.",  
  12.                 UPLOAD_ERR_NO_TMP_DIR   =>  "No temporary directory",  
  13.                 UPLOAD_ERR_CANT_WRITE   =>  "Can't write to disk", 
  14.                 UPLOAD_ERR_EXTENSION    =>  "File upload stopped by extension." 
  15.         ); 
  16.  
  17.  
  18.         $error = $_FILES['file_upload']['error'];//Notice:  Undefined index:  file_upload 
  19.         $message = $upload_errors[$error]; 
  20.  
  21.  
  22.     echo "<pre>"; 
  23.     print_r($_FILES['file_upload']);//Notice:  Undefined index:  file_upload  
  24.     echo "</pre>"; 
  25.     echo "<hr/>"; 
  26.     } 
  27.  
  28. ?> 
  29.  
  30.  
  31. <!DOCTYPE html> 
  32.  
  33. <html lang="en"> 
  34.     <head> 
  35.         <meta charset="utf-8" /> 
  36.         <title> Upload </title> 
  37.     </head> 
  38.     <body> 
  39.  
  40.  
  41.         <?php if(!empty($message)){echo "<p>{$message}</p>";}?> 
  42.         <form action="upload.php" enctype="multipart/form-data" method="POST"> 
  43.  
  44.            <input type="hidden" name="MAX_FILE_SIZE" value="100000000"/>  
  45.  
  46.             <input type="file" name="file_upload"/> 
  47.  
  48.             <input type="submit" value="Upload"/> 
  49.  
  50.         </form> 
  51.  
  52.  
  53.  
  54.     </body> 
  55. </html>
It removed the error, but it doesnt seem to process the form or even output the associative array that i asked it for. It was just like the all php above <!DOCTYPE html> were removed. The page just opens with only CHOOSE FILE and UPLOAD buttons, and when i try to upload, it refuses, telling me "No file chosen". Same thing happens with if(isset($_POST['file_upload'])){....My php code here..}. Is it because the page is submitting to itself?Or the the whole form processing is on one page?? Thanks
Mar 2 '15 #5
Dormilich
8,658 Expert Mod 8TB
your data is in $_FILES, not in $_POST.

there’s a pretty good example here.
Mar 2 '15 #6
Thanks Dormilich. You have really been helpful. i look at that php.net link that you showed to me and it was really helpful. Im pretty new to php. I spent all night working on this bug, yet no progress. Same error, or some other. Just now, i came up with an idea. If it was about the index 'file_upload' not being set,, or not being an array, why not a simple echo statement. Thus i took the initiative from the php.net site and did something like this

Expand|Select|Wrap|Line Numbers
  1.    if (
  2.         !isset($_FILES['file_upload']['error']) ||
  3.         is_array($_FILES['file_upload']['error'])
  4.            ) 
  5.  
  6.               {echo "File Upload is set";}
  7.  
It returned "File Upload is set", Thus i guess thats a step forward. Im stuck here. I have tried everything i could to weave syntax to accommodate the rest of the code yet, same stuff. Last stuff i tried was this

Expand|Select|Wrap|Line Numbers
  1. if (
  2.         !isset($_FILES['file_upload']['error']) ||
  3.         is_array($_FILES['file_upload']['error'])
  4.            ) 
  5.  
  6.               {  $upload_errors = array 
  7.                       ( 
  8.                 UPLOAD_ERR_OK           =>  "No Errors.",  
  9.                 UPLOAD_ERR_INI_SIZE     =>  "Larger than upload_max_filesize.",  
  10.                 UPLOAD_ERR_FORM_SIZE    =>  "Larger than form MAX_FILE_SIZE.",  
  11.                 UPLOAD_ERR_PARTIAL      =>  "Partial upload.",  
  12.                 UPLOAD_ERR_NO_FILE      =>  "No file.",  
  13.                 UPLOAD_ERR_NO_TMP_DIR   =>  "No temporary directory",  
  14.                 UPLOAD_ERR_CANT_WRITE   =>  "Can't write to disk", 
  15.                 UPLOAD_ERR_EXTENSION    =>  "File upload stopped by extension." 
  16.                      ); 
  17.  
  18.  
  19.         $error = $_FILES['file_upload']['error'];//Notice:  Undefined index:  file_upload 
  20.         $message = $upload_errors[$error]; 
  21.  
  22.  
  23.     echo "<pre>"; 
  24.     print_r($_FILES['file_upload']);//Notice:  Undefined index:  file_upload  
  25.     echo "</pre>"; 
  26.     echo "<hr/>"; 
  27.     } 
  28.  
  29. ?> 
  30.  
  31.  
  32. <!DOCTYPE html> 
  33.  
  34. <html lang="en"> 
  35.     <head> 
  36.         <meta charset="utf-8" /> 
  37.         <title> Upload </title> 
  38.     </head> 
  39.     <body> 
  40.  
  41.  
  42.         <?php if(!empty($message)){echo "<p>{$message}</p>";}?> 
  43.         <form action="upload.php" enctype="multipart/form-data" method="POST"> 
  44.  
  45.            <input type="hidden" name="MAX_FILE_SIZE" value="100000000"/>  
  46.  
  47.             <input type="file" name="file_upload"/> 
  48.  
  49.             <input type="submit" value="Upload"/> 
  50.  
  51.         </form> 
  52.     </body> 
  53. </html>
  54.  

Could you please help me weak the right syntax for this my code? Thanks a trillion :-)
Mar 3 '15 #7
Dormilich
8,658 Expert Mod 8TB
well, your if condition triggers if:
- $_FILES['file_upload']['error'] does not exist or
- $_FILES['file_upload']['error'] is an array
Mar 3 '15 #8
Dormilich
8,658 Expert Mod 8TB
compare what is written in the comment vs. what is written in your code!
Mar 3 '15 #9
OHH! My bad. I think isset && is_array would have been better

Expand|Select|Wrap|Line Numbers
  1.  
  2. <?php
  3.  
  4.  
  5.  $upload_errors = array
  6.         (
  7.                 UPLOAD_ERR_OK           =>  "No Errors.", 
  8.                 UPLOAD_ERR_INI_SIZE     =>  "Larger than upload_max_filesize.", 
  9.                 UPLOAD_ERR_FORM_SIZE    =>  "Larger than form MAX_FILE_SIZE.", 
  10.                 UPLOAD_ERR_PARTIAL      =>  "Partial upload.", 
  11.                 UPLOAD_ERR_NO_FILE      =>  "No file.", 
  12.                 UPLOAD_ERR_NO_TMP_DIR   =>  "No temporary directory", 
  13.                 UPLOAD_ERR_CANT_WRITE   =>  "Can't write to disk",
  14.                 UPLOAD_ERR_EXTENSION    =>  "File upload stopped by extension."
  15.         );
  16.  
  17.     if  (
  18.         isset($_FILES['file_upload']['error']) &&
  19.         is_array($_FILES['file_upload']['error'])
  20.         ) 
  21.  
  22.     {
  23.             echo "Defined and ready";
  24.     }
  25.  
  26.     else {echo "Undefined and Unready";}
  27.  
  28. ?>
  29.  
It returned Undefined and unready. So please, what should i do to define it and make it an array. Thanks in advance
Mar 3 '15 #10
Dormilich
8,658 Expert Mod 8TB
why—do you think—should $_FILES['file_upload']['error'] be an array?
Mar 3 '15 #11
No. $upload_errors is the array. What should i do to at least define 'file_upload'? Am confused right now
Mar 4 '15 #12
Dormilich
8,658 Expert Mod 8TB
$upload_errors is of no interest for the problem.

let’s have a look at the original snippet again

Expand|Select|Wrap|Line Numbers
  1. try {
  2.  
  3.     // Undefined | Multiple Files | $_FILES Corruption Attack
  4.     // If this request falls under any of them, treat it invalid.
  5.     if (
  6.         !isset($_FILES['upfile']['error']) ||
  7.         is_array($_FILES['upfile']['error'])
  8.     ) {
  9.         throw new RuntimeException('Invalid parameters.');
  10.     }
  11.  
  12.     // Check $_FILES['upfile']['error'] value.
  13.     switch ($_FILES['upfile']['error']) {
  14.         case UPLOAD_ERR_OK:
  15.             break;
  16.         case UPLOAD_ERR_NO_FILE:
  17.             throw new RuntimeException('No file sent.');
  18.         case UPLOAD_ERR_INI_SIZE:
  19.         case UPLOAD_ERR_FORM_SIZE:
  20.             throw new RuntimeException('Exceeded filesize limit.');
  21.         default:
  22.             throw new RuntimeException('Unknown errors.');
  23.     }
  24.  
  25.     // ...
  26.  
line #5 - #10 is a preliminary check for the code block (#13 - #23) following it. the key to understanding the check is to understand what the variable $_FILES['upfile']['error'] is used for.

it is used in a switch() that tests it for a single value (an integer, to be precise)! hence we should make sure that $_FILES['upfile']['error'] 1) exists and 2) it contains a primitive value (string, integer, boolean).

we know that user data (via $_GET, $_POST, etc.) come in exactly 2 types: string and array. an array is not a primitive, so it needs to be excluded.

these two tests are made before the switch. and due to the use of exceptions the test is made in reverse: it tests if one of the required conditions (existence, data type) fails and if one fails the error handling kicks in. (this is one way to prevent nesting hell) If both requirements are met, i.e. both failure conditions fail, the script can proceed.
Mar 4 '15 #13
Thanks Dormilich. You have been far too kind. I have cracked it. An elder colleague advised me to run the isset test after the $upload_errors array and not before it. I removed those <pre> tags that i used in inspecting the uploaded files and later decided against running the test on 'file_upload'. Instead i checked whether the $_POST variable was subumitted. Like this

Expand|Select|Wrap|Line Numbers
  1. if(isset($_POST['submit']))
  2.         {..my form processing code here..}
  3.  
It worked. I thus proceeded to move the uploaded file to a more permanent directory with the original name(basename) and give a success message or error message utilizing that $upload_errors array. The problem was never 'file_uploads'. I have pasted the full code below.

Expand|Select|Wrap|Line Numbers
  1.  
  2.  
  3. <?php
  4.  
  5.  
  6. $upload_errors = array(
  7.  
  8.     UPLOAD_ERR_OK             => "No errors.",
  9.     UPLOAD_ERR_INI_SIZE      => "Larger than upload_max_filesize.",
  10.   UPLOAD_ERR_FORM_SIZE      => "Larger than form MAX_FILE_SIZE.",
  11.   UPLOAD_ERR_PARTIAL         => "Partial upload.",
  12.   UPLOAD_ERR_NO_FILE         => "No file.",
  13.   UPLOAD_ERR_NO_TMP_DIR     => "No temporary directory.",
  14.   UPLOAD_ERR_CANT_WRITE     => "Can't write to disk.",
  15.   UPLOAD_ERR_EXTENSION         => "File upload stopped by extension."
  16. );
  17.  
  18.     if(isset($_POST['submit']))
  19.         {
  20.  
  21.     $tmp_file = $_FILES['file_upload']['tmp_name'];
  22.     $target_file = basename($_FILES['file_upload']['name']); 
  23.  
  24.  
  25.     $upload_dir = "uploads";
  26.  
  27.  
  28.         if(move_uploaded_file($tmp_file, $upload_dir."/".$target_file)) 
  29.             {
  30.                 $message = "File uploaded successfully.";
  31.             } 
  32.         else 
  33.             {
  34.                 $error = $_FILES['file_upload']['error'];
  35.                 $message = $upload_errors[$error];
  36.             }
  37.  
  38.         }
  39.  
  40.  
  41. ?>
  42. <html>
  43.     <head>
  44.         <title>Upload</title>
  45.     </head>
  46.     <body>
  47.  
  48.  
  49.         <?php if(!empty($message)) { echo "<p>{$message}</p>"; } ?>
  50.         <form action="upload.php" enctype="multipart/form-data" method="POST">
  51.  
  52.           <input type="hidden" name="MAX_FILE_SIZE" value="1000000" />
  53.           <input type="file" name="file_upload" />
  54.  
  55.           <input type="submit" name="submit" value="Upload" />
  56.         </form>
  57.  
  58.     </body>
  59. </html>
  60.  
  61.  

Thanks alot Dormilich. I appreciate. I learnt alot during this debugging process. I hope this helps someone that has a similar pitfall in the future. Gracias.
Mar 9 '15 #14
Dormilich
8,658 Expert Mod 8TB
An elder colleague advised me to run the isset test after the $upload_errors array and not before it.
that array is just a convenience to translate the PHP constants into readable text. it serves no purpose for the actual error checking.

I […] later decided against running the test on 'file_upload'. Instead i checked whether the $_POST variable was subumitted.
which makes you highly prone to upload errors.

imagine the following scenario: what happens in your code if the form is submitted, but no file uploaded?

starting with line #21 you’ll get warnings (missing index) to errors (no such file) all over the place. and only after everything has failed, you check what was actually the problem.

there is a reason for the UPLOAD_ERR_OK constant.
Mar 9 '15 #15
Oh. Thanks Dormilich. Sorry for the late reply. I have not been feeling too fine. This upload page was just a test, on how i could handle my uploads. When i was sure i could upload successfully, i wrote 2 public methods SAVE and ATTACH_FILE, that perfectly handles from file upload, to tmp_directory, to permanent directory, considering every exception i could think of. I flexed the muscles of the conditional statements on this one. Here are they. Anything i should add??


Expand|Select|Wrap|Line Numbers
  1.  
  2. public function attach_file($file) {
  3.         // Perform error checking on the form parameters
  4.         if(!$file || empty($file) || !is_array($file)) {
  5.           // error: nothing uploaded or wrong argument usage
  6.           $this->errors[] = "No file was uploaded.";
  7.           return false;
  8.         } elseif($file['error'] != 0) {
  9.           // error: report what PHP says went wrong
  10.           $this->errors[] = $this->upload_errors[$file['error']];
  11.           return false;
  12.         } else {
  13.             // Set object attributes to the form parameters.
  14.           $this->temp_path  = $file['tmp_name'];
  15.           $this->filename   = basename($file['name']);
  16.           $this->type       = $file['type'];
  17.           $this->size       = $file['size'];
  18.             // Don't worry about saving anything to the database yet.
  19.             return true;
  20.  
  21.         }
  22.     }
  23.  
  24.     public function save() {
  25.         // A new record won't have an id yet.
  26.         if(isset($this->id)) {
  27.             // Really just to update the caption
  28.             $this->update();
  29.         } else {
  30.             // Make sure there are no errors
  31.  
  32.             // Can't save if there are pre-existing errors
  33.           if(!empty($this->errors)) { return false; }
  34.  
  35.             // Make sure the caption is not too long for the DB
  36.           if(strlen($this->caption) <= 255) {
  37.                 $this->errors[] = "The caption can only be 255 characters long.";
  38.                 return false;
  39.             }
  40.  
  41.           // Can't save without filename and temp location
  42.           if(empty($this->filename) || empty($this->temp_path)) {
  43.             $this->errors[] = "The file location was not available.";
  44.             return false;
  45.           }
  46.  
  47.             // Determine the target_path
  48.           $target_path = SITE_ROOT .DS. 'public' .DS. $this->upload_dir .DS. $this->filename;
  49.  
  50.           // Make sure a file doesn't already exist in the target location
  51.           if(file_exists($target_path)) {
  52.             $this->errors[] = "The file {$this->filename} already exists.";
  53.             return false;
  54.           }
  55.  
  56.             // Attempt to move the file 
  57.             if(move_uploaded_file($this->temp_path, $target_path)) {
  58.               // Success
  59.                 // Save a corresponding entry to the database
  60.                 if($this->create()) {
  61.                     // We are done with temp_path, the file isn't there anymore
  62.                     unset($this->temp_path);
  63.                     return true;
  64.                 }
  65.             } else {
  66.                 // File was not moved.
  67.             $this->errors[] = "The file upload failed, possibly due to incorrect permissions on the upload folder.";
  68.             return false;
  69.             }
  70.         }
  71.     }
  72.  
  73.  
  74.  
  75.  
Mar 16 '15 #16
Dormilich
8,658 Expert Mod 8TB
on line #8 I’d use elseif($file['error'] !== \UPLOAD_ERR_OK), that way it becomes immediately clear what the test is for.

and on line #2 I’d use type hinting: public function attach_file(array $file) {
Mar 16 '15 #17
Thanks Dormilich, on Line #8 i kinda prefer the numeric error codes. Thats how they are understandable to me.

Line #2 is also a good idea.

Thanks Dormilich, you have really been helpful. :-)
Mar 17 '15 #18

Sign in to post your reply or Sign up for a free account.

Similar topics

6
by: jsgoodrich | last post by:
I am looking for some help if anyone can lend a hand. I have a simple php website that displays a table from my mysql database. To prep for my MCSE I moved my home server to Windows 2003...
3
by: number1yan | last post by:
Can anyone help me, i am creating a website and am using a php script that recomends the website to other people. I keep getting the same error and can not work out why. The error is: Notice:...
3
by: sickboy | last post by:
$channels=$_GET; if (empty($channels)) { $channels='blank'; } changechannels($channels); $theatre=$_GET; if (empty($theatre)) { $theatre='splash'; } changetheatre($theatre); $info=$_GET; if...
7
by: Philth | last post by:
Hey there, it has to be said that I am a complete novice in PHP, I know this is a common error and has probably been covered to some degree already - but my head really does hurt - so I couldn't...
1
by: francsutherland | last post by:
Notice: Undefined index: send in D:\Domains\workingdata.co.uk\wwwroot\contact_text.php on line 7 Hi, I've started getting this error in the contact page form of my website. The web hosting...
10
by: FutureShock | last post by:
I have since recently turned up my error reporting on a production site to E_ALL to ensure I am using 'best practices' when writing out code. So far it has helped me discipline myself with...
11
by: stealthmode666 | last post by:
New to .php so need script help. I want to know how to stop this being displayed when I click submit. Notice: Undefined index: homeowner in E:\domains\r\...\user\htdocs\...\form.php on line 166 ...
3
by: razvanel442 | last post by:
Hi all i am new here! I take a look on forum but i don't found a the answer for my problem ok this is my problem: Line47:$user = $_GET; Line48:$pass = $_GET; Line49:$char = $_GET;
2
by: norwichchris | last post by:
hi, I am having serious trouble with my PHP Postcard script. The error message i get is: Notice: Undefined index: Notice: Undefined variable Basically it does not send out the scripts at...
2
by: nyrzs | last post by:
"Notice: Undefined index: prod_rep in F:\xampp\htdocs\isys\products\process.php on line 153 Notice: Undefined variable: prod_id in F:\xampp\htdocs\isys\products\process.php on line 160 Warning:...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.