Php File Upload Fails

I have a php File Upload that fails; I cannot see the error, I have done this hundreds of times.

The HTML on the form:
_______________________________________________________________
<form action="POST" name="cd" action="base_cust_updt.php" onSubmit="return chk_vals_cd();" enctype="multipart/form-data">
...
<input type="file" name="asbuiltf" size="25">
________________________________________________________________

The processing code in base_cust_updt.php:

$fn = "asbuiltf";
$file = "";
echo "files name = " . $_FILES[$fn]['name'] . "<br>";
if ($_FILES[$fn]['name'] != "") {
      $file = basename($_FILES[$fn]['name']);
      $abfile = "asbuilts/" . $file;
      echo "file = " . $abfile . "<br>";
      move_uploaded_file($_FILES[$fn]['tmp_name'], $abfile);
      //echo "parts file: " . $partsfile . "<br>";
}
_____________________________________________________
php result with
error_reporting(E_ALL);
ini_set('display_errors', 1);
_____________________________________________________
Notice: Undefined index: asbuiltf in /home/fwsprinkler/public_html/fwsprinklercdb.info/base_cust_updt.php on line 52
files name =

Notice: Undefined index: asbuiltf in /home/fwsprinkler/public_html/fwsprinklercdb.info/base_cust_updt.php on line 53

Notice: Undefined index: pstr in /home/fwsprinkler/public_html/fwsprinklercdb.info/base_cust_updt.php on line 61

Notice: Undefined index: type in /home/fwsprinkler/public_html/fwsprinklercdb.info/base_cust_updt.php on line 62

Notice: Undefined index: bfname in /home/fwsprinkler/public_html/fwsprinklercdb.info/base_cust_updt.php on line 66

Notice: Undefined index: blname in /home/fwsprinkler/public_html/fwsprinklercdb.info/base_cust_updt.php on line 67

Notice: Undefined index: baddr in /home/fwsprinkler/public_html/fwsprinklercdb.info/base_cust_updt.php on line 68
__________________________________________________
Whats wrong?
Richard KortsAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

gr8gonzoConsultantCommented:
Try dumping $_FILES:

print_r($_FILES);

...and check the output. That might lead you to the problem. If I had to guess, maybe you're hitting this controller without the correct file upload data. You're not checking the results before using them, e.g.:

if(array_key_exists($fn, $_FILES))
{

  $file = "";
  echo "files name = " . $_FILES[$fn]['name'] . "<br>";
  if ($_FILES[$fn]['name'] != "") {
      $file = basename($_FILES[$fn]['name']);
      $abfile = "asbuilts/" . $file;
      echo "file = " . $abfile . "<br>";
      move_uploaded_file($_FILES[$fn]['tmp_name'], $abfile);
      //echo "parts file: " . $partsfile . "<br>";
  }
}

Maybe you're in a form within a form, or maybe the onSubmit Javascript is messing with the data... Could be any number of reasons. If you post the full code, it might help.

Also, it never hurts to have Fiddler running while you test, so you can see the actual request that is being sent to the server.
0
Richard KortsAuthor Commented:
It produces this:

Array ( )

Which tells me there is nothing there. It is true there are 3 forms on the page but their <form> .. </form> tags are not nested; all separate.

The submitting form page is attached; the middle form is the one being used here (called "cd").

I don't know what this means: "Also, it never hurts to have Fiddler running while you test, so you can see the actual request that is being sent to the server. "

Thanks
cust-wonsn.php
0
Dave BaldwinFixer of ProblemsCommented:
I would think that the index still needs to be quoted like $_FILES["$fn"]['name'] .
0
Cloud Class® Course: Amazon Web Services - Basic

Are you thinking about creating an Amazon Web Services account for your business? Not sure where to start? In this course you’ll get an overview of the history of AWS and take a tour of their user interface.

Richard KortsAuthor Commented:
Dave,

I have numerous other places where it is structured like $_FILES[$fn]['name'] and it works.

Thanks
0
gr8gonzoConsultantCommented:
Fiddler is just a popular, free web debugger. You install it and it acts as a web proxy in your browser, so when you're testing your script, it captures and logs the raw data used in the request and also in the response. So you can see exactly what data your browser is sending, to where, and what the server is sending back (and a lot of other information, too).

That can help you quickly see if the data is actually being posted as expected. Basically, you:

1. Install Fiddler:
http://www.telerik.com/fiddler

2. Run it, and it should start capturing requests in your IE and Chrome browsers right away (Firefox has its own proxy settings).

3. Execute your test to get the error messages (just upload a small file), and then switch back to Fiddler and go to the File menu and uncheck the capture traffic option.

4. Look for a line in the log that corresponds to your form POST and click on it.

5. On the right side, you'll have a set of "inspectors" that let you look at the request and response and analyze it. The request inspector is at the top and the response is at the bottom.

6. Look at the request data and look to see if your browser is posting the correct data to the correct URL.

One other quick way to rule out Javascript is to simply comment out the onSubmit validation temporarily and run a test without that Javascript and see if it still breaks or if it works.
0
Dave BaldwinFixer of ProblemsCommented:
With all of those index errors in a row... are you sure you're looking at the right part of the code?  Most of those errors are not in the code you posted.
0
Richard KortsAuthor Commented:
Dave,

Attached is the complete program that processes the form data. This is EXACTLY as it was when the php errors (as in the original posting) were displayed.

It seems clear to me that the $_FILE array is NOT available, for some odd reason.

Thanks
base-cust-updt.php
0
Dave BaldwinFixer of ProblemsCommented:
I'm curious what your form looks like.  Since it has to be a POST to upload a file, aren't the $_GET variables on lines 61-63 always going to be an error since they should never exist?  All the $_REQUEST lines should probably be $_POST.  And didn't I show you last week how to use 'isset' to make sure there is a default value for all of those variables?
0
Richard KortsAuthor Commented:
Dave,

No, because it passes the indicated values in the Query String.

The entire source of the form page (actually 3 forms) was posted as cust_wonsn.php. The middle form called ("cd") is the applicable one in this case.

The two pages work correctly in ALL cases EXCEPT when there is a file specified for upload.

I know about isset, I don't think that will help. Based on my first response to gr8gonzo, I think the $_FILES array is empty.

Thanks,

Richard
0
Dave BaldwinFixer of ProblemsCommented:
If they were passed in the 'query string', you would not be seeing that error.  The $_FILES array may be empty.  You still have other errors and I wouldn't be surprised if they are all coming from the same source.  In fact... it looks like you ran that page without posting from the form.

PS:  I consider the use of 'isset' to be a standard programming practice.  I ALWAYS use it to make sure I don't get those 'index' errors.
0
Richard KortsAuthor Commented:
Dave,

There are 3 items passed in the Query String; the rest are passed as $_POST items.

Maybe that in itself is the issue, ya think??

Richard
0
Dave BaldwinFixer of ProblemsCommented:
Yes, I do but even the other items are showing 'index' errors.  Every one of the 'Undefined index:' notices in your post means that that item was Not passed to your PHP page.  They just weren't there.  And that includes your $_FILE index.  That's why I'm curious about your form.

Temporarily put this as the 'action' page for that form.  Save as 'postdump.php'.  It will tell you what you are actually submitting.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
 "http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<title>POST Dump</title>
</head>
<body>
<pre>
<?php 
var_dump($_POST);

foreach($_POST as $key => $value) {
    echo $key.' = '.$value."<br>";
}

?>
</pre>
</body>
</html>

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
gr8gonzoConsultantCommented:
Did you try Fiddler yet?
0
Ray PaseurCommented:
This is my teaching example that shows how to handle multi-file uploads.  Maybe it can shed some light on the issues.

<?php // demo/upload_multiple_example.php

/**
 * Demonstrate how to upload a single file in PHP
 *
 * REQUIRED: Man Page References
 * http://php.net/manual/en/reserved.variables.files.php
 * http://php.net/manual/en/features.file-upload.php
 * http://php.net/manual/en/features.file-upload.common-pitfalls.php
 * http://php.net/manual/en/function.move-uploaded-file.php
 *
 * IMPORTANT: If dealing with large files
 * http://php.net/manual/en/ini.core.php#ini.upload-max-filesize
 * http://php.net/manual/en/ini.core.php#ini.post-max-size
 * http://php.net/manual/en/info.configuration.php#ini.max-input-time
 */
error_reporting(E_ALL);

// PHP 5.1+  SEE http://php.net/manual/en/function.date-default-timezone-set.php
date_default_timezone_set('America/Chicago');

// ESTABLISH THE NAME OF THE DESTINATION FOLDER ('uploads' DIRECTORY)
$uploads = 'storage';
if (!is_dir($uploads))
{
    mkdir($uploads);
}

// ESTABLISH THE BIGGEST FILE SIZE WE WILL ACCEPT - ABOUT 8 MB
$max_file_size = 8 * 1024 * 1024;

// ESTABLISH THE MAXIMUM NUMBER OF FILES WE WILL UPLOAD
$nf = 3;

// ESTABLISH THE KINDS OF FILE EXTENSIONS WE WILL ACCEPT
$file_exts = array
( 'jpg'
, 'gif'
, 'png'
, 'txt'
, 'pdf'
, 'doc'
, 'docx'
)
;

// LIST OF THE ERRORS THAT MAY BE REPORTED IN $_FILES[]["error"] (THERE IS NO #5)
$errors = array
( 0 => "Success!"
, 1 => "The uploaded file exceeds the upload_max_filesize directive in php.ini"
, 2 => "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form"
, 3 => "The uploaded file was only partially uploaded"
, 4 => "No file was uploaded"
, 5 => "UNDEFINED ERROR"
, 6 => "Missing a temporary folder"
, 7 => "Cannot write file to disk"
)
;


// IF WE HAVE GOT SOMETHING IN $_POST - RUN THE ACTION SCRIPT
if (!empty($_POST))
{
    echo "<h2>Results: File Upload</h2>" . PHP_EOL;

    // ACTIVATE THIS TO SEE WHAT IS COMING THROUGH
    // echo "<pre>"; var_dump($_FILES); var_dump($_POST); echo "</pre>";

    // ITERATE OVER THE CONTENTS OF $_FILES
    foreach ($_FILES as $my_uploaded_file)
    {
        // SKIP OVER EMPTY SPOTS - NOTHING UPLOADED
        $error_code = $my_uploaded_file["error"];
        if ($error_code == 4) continue;

        // SYNTHESIZE THE NEW FILE NAME
        $f_type = explode('.', basename($my_uploaded_file['name']));
        $f_type = end($f_type);
        $f_type = trim(strtolower($f_type));

        $f_name = explode('.', basename($my_uploaded_file['name']));
        $f_name = current($f_name);
        $f_name = trim(strtolower($f_name));

        $my_new_file
        = getcwd()
        . DIRECTORY_SEPARATOR
        . $uploads
        . DIRECTORY_SEPARATOR
        . $f_name
        . '.'
        . $f_type
        ;
        $my_file
        = $uploads
        . DIRECTORY_SEPARATOR
        . $f_name
        . '.'
        . $f_type;

        // OPTIONAL TEST FOR ALLOWABLE EXTENSIONS
        if (!in_array($f_type, $file_exts))
        {
            trigger_error("$f_type Not allowed", E_USER_WARNING);
            continue;
        }

        // IF THERE ARE ERRORS
        if ($error_code != 0)
        {
            $error_message = $errors[$error_code];
            trigger_error("Upload error code: $error_code: $error_message", E_USER_WARNING);
            continue;
        }

        // GET THE FILE SIZE
        $file_size = number_format($my_uploaded_file["size"]);

        // IF THE FILE IS NEW (DOES NOT EXIST)
        if (!file_exists($my_new_file))
        {
            // IF THE MOVE FUNCTION WORKED CORRECTLY
            if (move_uploaded_file($my_uploaded_file['tmp_name'], $my_new_file))
            {
                $upload_success = 1;
            }
            // IF THE MOVE FUNCTION FAILED
            else
            {
                $upload_success = -1;
            }
        }

        // IF THE FILE ALREADY EXISTS
        else
        {
            echo "<br/><b><i>$my_file</i></b> already exists." . PHP_EOL;

            // SHOULD WE OVERWRITE THE FILE? IF NOT
            if (empty($_POST["overwrite"]))
            {
                $upload_success = 0;
            }
            // IF WE SHOULD OVERWRITE THE FILE, TRY TO MAKE A BACKUP
            else
            {
                $now    = date('Y-m-d\THis');
                $my_bak = $my_new_file . '.' . $now . '.bak';
                if (!copy($my_new_file, $my_bak))
                {
                    trigger_error("Backup Failed for $my_file", E_USER_WARNING);
                }
                if (move_uploaded_file($my_uploaded_file['tmp_name'], $my_new_file))
                {
                    $upload_success = 2;
                }
                else
                {
                    $upload_success = -1;
                }
            }
        }

        // REPORT OUR SUCCESS OR FAILURE
        if ($upload_success == 2) { echo "<br/>It has been overwritten." . PHP_EOL; }
        if ($upload_success == 1) { echo "<br/><b>$my_file</b> has been saved." . PHP_EOL; }
        if ($upload_success == 0) { echo "<br/><b>It was NOT overwritten.</b>" . PHP_EOL; }
        if ($upload_success < 0)  { echo "<br/><b>ERROR: $my_file NOT SAVED - SEE WARNING FROM move_uploaded_file() COMMAND</b>" . PHP_EOL; }
        if ($upload_success > 0)
        {
            echo "$file_size bytes uploaded." . PHP_EOL;
            if (!chmod ($my_new_file, 0755))
            {
                echo '<br/>chmod(0755) FAILED: fileperms() = ';
                echo substr(sprintf('%o', fileperms($my_new_file)), -4);
            }
            echo '<br/><a target="_blank" href="' . $my_file . '">See the file ' . $my_file . '</a>' . PHP_EOL;
        }
    // END FOREACH ITERATOR - EACH ITERATION PROCESSES ONE FILE
    }
// END ACTION SCRIPT
}


// FORM SCRIPT: CREATE THE INPUT STATEMENTS FOR THE FILES
$inputs = NULL;
for ($n = 0; $n < $nf; $n++)
{
    $inputs .= '<input name="userfile' . $n . '" type="file" size="80" /><br/>' . PHP_EOL;
}

// CREATE THE HTML FORM USING HEREDOC NOTATION
$form = <<<EOF
<h2>Upload from 1 to $nf file(s)</h2>
<!--
    SOME IMPORTANT THINGS TO NOTE ABOUT THIS FORM...
    ENCTYPE= ATTRIBUTE IN THE HTML <FORM> TAG
    MAX_FILE_SIZE HIDDEN CONTROL MUST PRECEDE THE FILE INPUT CONTROLS
    INPUT NAME= IN TYPE=FILE DETERMINES THE NAME YOU FIND IN _FILES ARRAY
    ABSENCE OF ACTION= ATTRIBUTE IN <FORM> TAG CAUSES POST TO SAME URL
-->
<form name="UploadForm" enctype="multipart/form-data" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="$max_file_size" />
<p>
Find the file(s) you want to upload and click the "Upload" button below.
</p>

$inputs

<br/>Check this box <input autocomplete="off" type="checkbox" name="overwrite" /> to <b>overwrite</b> existing files.
<input type="submit" value="Upload" />
</form>
EOF;

echo $form;

Open in new window

0
Richard KortsAuthor Commented:
To All,

As was unnoticed by all, including me, at the VERY top of this question, I listed:

<form action="POST" name="cd" action="base_cust_updt.php" onSubmit="return chk_vals_cd();" enctype="multipart/form-data">

Note I had form, action="POST", no method, then action again.

That's OBVIOUSLY a screw up (by me).

I changed the <form> statement to be proper & it works.

I am awarding most of the points to Dave because his suggestion of using postdump.php is what led me to find this.

Thanks!
0
Dave BaldwinFixer of ProblemsCommented:
Thanks, Richard.  Just how 'expert' do you expect us 'experts' to be???  Like actually read the questions?
0
Richard KortsAuthor Commented:
To Dave,

It would help, & yes, I assume that you do, especially you & Ray based on both of yours experience & depth of knowledge.

FYI, I've actually thought about signing up as an "expert" myself, I have pretty good knowledge in several areas. But, generally, I don't have the time.

Richard
0
gr8gonzoConsultantCommented:
especially you & Ray based on both of yours experience & depth of knowledge

(sits in the corner and quietly sings "All by Myself")
0
Richard KortsAuthor Commented:
To gr8gonzo,

I did not intend to slam you by that comment.

Ray & Dave have been responding to my questions on several subjects for years. I think other than this one you MIGHT have responded to 1 or 2 other of my questions.

I appreciated your input (& I gave you some points).

Let's face it, nobody saw the "real" problem until I accidentally discovered it.

One of the benefits of EE is it provides other sets of eyes to see things like the obvious issue in this case.

But in this case.....................
0
Dave BaldwinFixer of ProblemsCommented:
^^^ Sometimes it's just your turn... or not.
0
Dave BaldwinFixer of ProblemsCommented:
Thinking that I had typed something correctly and being blind to it like that is my first biggest mistake.  Second is the problem of testing things the way they are supposed to work instead of the other ways that people may use them.
0
gr8gonzoConsultantCommented:
I'm only kidding around. :) I'm happy whenever anyone gets their answer.
0
Richard KortsAuthor Commented:
"the problem of testing things the way they are supposed to work instead of the other ways that people may use them. "

I tell all my customers that an independent tester should be used to test all functionality, I tell them I am the WORST person to test because I know how it's supposed to work.
0
gr8gonzoConsultantCommented:
Also, for what it's worth, this is where running that Fiddler test would have revealed important information that could have led you to the answer faster. Fiddler's an invaluable tool for debugging, easy to use, and well worth the time to install and use. Even if you're not debugging data issues, it also tells you all sorts of valuable information about each connection (the timing of each part of the request and response, the protocol type, headers, etc...). Just saying that even though you solved this issue already, it's still a good tool in your belt.
0
Richard KortsAuthor Commented:
To gr8gonzo

I'll check it out.

I looked at it earlier and you (or it) said something about Firefox, which is where I do almost ALL my testing. Looked messy to install & understand.

Does it work with FireFox?
0
gr8gonzoConsultantCommented:
Yes, it works with Firefox, but it takes a few extra steps:
http://blogs.telerik.com/fiddler/posts/13-04-01/configuring-firefox-for-fiddler
0
Dave BaldwinFixer of ProblemsCommented:
For just viewing headers, you can use the Live HTTP Headers add-on.  http://livehttpheaders.mozdev.org/
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.