Link to home
Start Free TrialLog in
Avatar of Richard Korts
Richard KortsFlag for United States of America

asked on

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?
SOLUTION
Avatar of gr8gonzo
gr8gonzo
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Richard Korts

ASKER

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
I would think that the index still needs to be quoted like $_FILES["$fn"]['name'] .
Dave,

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

Thanks
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.
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.
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
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?
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
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.
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
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Did you try Fiddler yet?
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

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!
Thanks, Richard.  Just how 'expert' do you expect us 'experts' to be???  Like actually read the questions?
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
especially you & Ray based on both of yours experience & depth of knowledge

(sits in the corner and quietly sings "All by Myself")
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.....................
^^^ Sometimes it's just your turn... or not.
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.
I'm only kidding around. :) I'm happy whenever anyone gets their answer.
"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.
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.
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?
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
For just viewing headers, you can use the Live HTTP Headers add-on.  http://livehttpheaders.mozdev.org/