Solved

php get array

Posted on 2014-01-02
10
423 Views
Last Modified: 2014-01-17
Code:
-------------------------------------
<?php
$file = $_GET['xmlfile'];



?>
<body>
<form action="fileform.php" method="get" enctype="multipart/form-data">
  Send these files:<br />
  <input name="xmlfile[]" type="file" /><br />
  <input name="xmlfile[]" type="file" /><br />
<input name="xmlfile[]" type="file" /><br />
<input name="xmlfile[]" type="file" /><br />
  <input type="submit" value="Send files" />
</form>

<?php echo $file; ?>

</body>
-------------------------------------
The above code is in a page called "fileform.php"
When the file select boxes are selected and the form is submitted to the same page, the url has all the correct files names as a GET string

I need to echo out these files names as the first part of this project
The following command does not show anything:
<?php echo $file; ?>
0
Comment
Question by:doctorbill
  • 5
  • 3
  • 2
10 Comments
 
LVL 74

Expert Comment

by:käµfm³d 👽
Comment Utility
You need to be "post"ing your form, not "get"ing it:

<form action="fileform.php" method="POST" enctype="multipart/form-data">

Open in new window


Naturally, that would change how you retrieve it on the back-end:

$file = $_POST['xmlfile'];

Open in new window

0
 
LVL 108

Assisted Solution

by:Ray Paseur
Ray Paseur earned 417 total points
Comment Utility
Use var_dump() instead of echo.  It will show you the data structure.
0
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 417 total points
Comment Utility
You may also want to read these pages (and the ones that are linked):
http://www.php.net/manual/en/features.file-upload.php
http://www.php.net/manual/en/reserved.variables.files.php

Here is an example that shows how to upload multiple files.
<?php // RAY_upload_example.php
error_reporting(E_ALL);


// MANUAL REFERENCE PAGES YOU MUST UNDERSTAND TO UPLOAD FILES
// 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
// http://php.net/manual/en/function.getimagesize.php

// MANUAL PAGES THAT ARE IMPORTANT IF YOU ARE 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


// 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 = 'RAY_junk';
if (!is_dir($uploads))
{
    mkdir($uploads);
}

// ESTABLISH THE BIGGEST FILE SIZE WE CAN ACCEPT - ABOUT 8 MB
$max_file_size = '8000000';

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

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

// 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 THERE IS NOTHING IN $_POST, PUT UP THE FORM FOR INPUT
if (empty($_POST))
{
    ?>
    <h2>Upload <?php echo $nf; ?> file(s)</h2>

    <!--
        SOME THINGS TO NOTE ABOUT THIS FORM...
        ENCTYPE IN THE HTML <FORM> STATEMENT
        MAX_FILE_SIZE MUST PRECEDE THE FILE INPUT FIELD
        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="<?php echo $max_file_size; ?>" />
    <p>
    Find the file(s) you want to upload and click the "Upload" button below.
    </p>

    <?php // CREATE INPUT STATEMENTS FOR UP TO $n FILE NAMES
    for ($n = 0; $n < $nf; $n++)
    {
        echo "<input name=\"userfile$n\" type=\"file\" size=\"80\" /><br/>\n";
    }
    ?>

    <br/>Check this box <input autocomplete="off" type="checkbox" name="overwrite" /> to <strong>overwrite</strong> existing files.
    <input type="submit" value="Upload" />
    </form>
    <?php
    die();
}
// END OF THE FORM SCRIPT



// WE HAVE GOT SOMETHING IN $_POST - RUN THE ACTION SCRIPT
else
{
    // THERE IS POST DATA - PROCESS IT
    echo "<h2>Results: File Upload</h2>\n";

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

    // 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    = trim(strtolower(end    (explode( '.', basename($my_uploaded_file['name'] )))));
        $f_name    = trim(strtolower(current(explode( '.', basename($my_uploaded_file['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)) die("Sorry, $f_type files not allowed");

        // IF THERE ARE ERRORS
        if ($error_code != 0)
        {
            $error_message = $errors[$error_code];
            die("Sorry, Upload Error Code: $error_code: $error_message");
        }

        // 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.\n";

            // 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');
                $my_bak = $my_new_file . '.' . $now . '.bak';
                if (!copy($my_new_file, $my_bak))
                {
                    echo "<br/><strong>Attempted Backup Failed!</strong>\n";
                }
                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.\n"; }
        if ($upload_success == 1) { echo "<br/><strong>$my_file</strong> has been saved.\n"; }
        if ($upload_success == 0) { echo "<br/><strong>It was NOT overwritten.</strong>\n"; }
        if ($upload_success < 0)  { echo "<br/><strong>ERROR: $my_file NOT SAVED - SEE WARNING FROM move_uploaded_file() COMMAND</strong>\n"; }
        if ($upload_success > 0)
        {
            echo "$file_size bytes uploaded.\n";
            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>\n";
        }
    // END FOREACH ITERATOR - EACH ITERATION PROCESSES ONE FILE
    }
}

Open in new window

0
 

Author Comment

by:doctorbill
Comment Utility
Code:
----------------------------
<?php
$file = $_POST['xmlfile'];

var_dump($file);

?>
<body>
<form action="multixml.php" method="post" enctype="multipart/form-data">
  Send these files:<br />
  <input name="xmlfile[]" type="file" /><br />
  <input name="xmlfile[]" type="file" /><br />
<input name="xmlfile[]" type="file" /><br />
<input name="xmlfile[]" type="file" /><br />
  <input type="submit" value="Send files" />
</form>


</body>
---------------------------
The var_dump produces no output at all (note - the file has been renaimed to multixml.php)
0
 
LVL 108

Assisted Solution

by:Ray Paseur
Ray Paseur earned 417 total points
Comment Utility
Yeah, I kind of figured that.  Browsers may not really understand how to create the array of arrays that would be needed.  And it could be perceived to be a security issue.  File uploads sometimes fail silently in PHP.  Check my code sample above.  It's not bullet-proof, but it's pretty workable.  If you install the script and run it, then use view source to see the form and the input controls you'll understand what the script is doing.
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 

Author Comment

by:doctorbill
Comment Utility
The reason why I was testing this file was to import multiple files as opposed to singloe files to an existing php processing page

I have attached the existing processor which works fine for one xml file import

I want to be able to import either multiple xml files from a folder or up to 10 xml files and process each one as the single file import processes them
xmlimport-form-loop.php
0
 
LVL 74

Assisted Solution

by:käµfm³d 👽
käµfm³d   👽 earned 83 total points
Comment Utility
Browsers may not really understand how to create the array of arrays that would be needed.
It's not so much the browser as it is the web server software, I believe. I have created lists of items (not files, but the concept should be the same) from form posts before. However, this was in ASP.NET, against an IIS server.
0
 
LVL 108

Assisted Solution

by:Ray Paseur
Ray Paseur earned 417 total points
Comment Utility
@kaufmed® I think you're right about that.  The way PHP handles external request variables is a little different from other scripting languages.  The concept of the $_POST array is a good one, but it also mungs the POST-request variables.
0
 
LVL 108

Assisted Solution

by:Ray Paseur
Ray Paseur earned 417 total points
Comment Utility
I understand what you want, DoctorBill.  I think if you'll take a close reading of the script I posted you will see how this is done.  There are other ways, too.  I am not sure you can import a folder -- for security reasons (I think) the client must select each and every file that is to be uploaded.

You might be able to get around this if you use a "flash uploader" script or maybe something like UpLoadify.

To build upon your existing script you would want to do something like the following:

1. Upload the files
2. With each file, move_uploaded_file() to put the files into a folder on the server
3. Use scandir() to get the names of the files in the folder
4. Iteratively process each file in the way the script works now.
0
 

Author Closing Comment

by:doctorbill
Comment Utility
This works:

-----------------------

<?php

$dbh = new PDO("mysql:host=localhost;dbname=1callorders", "xxxx", "xxxx");
            
$i = 1;

do {
   echo $i;

if($_GET['xmlfile'.$i] !="") { // check if the value is empty

$file = $_GET['xmlfile'.$i];

// SKIP THE EMPTY FILE POSITIONS
//if (empty($file)) continue;

$filepath = "xmlimport/";

$xml = file_get_contents($filepath . $file);
$obj = simplexml_load_string($xml);

//echo out statements from xml
//$name = (string)$obj->header->manifest->document->name;
//$orderdesc = (string)$obj->body->ORDER->ORDERHEAD->ORDERDESC;
//$orderdesc2 = (string)$obj->body->ORDER->ORDERHEAD->FUNCDESC;

$space = "&nbsp;";
//echo "Name: " . $name . $space;
//echo "Desc: " . $orderdesc . $space;
//echo "Desc2: " . $orderdesc2 . $space;
//end statements
            
//prepare the query
$stmt = $dbh->prepare("INSERT INTO ret_orders (ret_id, ord_prodtpe, ord_prodcdedesc, ord_proddesc) VALUES (:ret_id, :name, :orderdesc, :orderdesc2)");

//bind the named parameter to a PHP variable (called $name and $orderdesc etc )
$stmt->bindParam('ret_id', $ret_id);
$stmt->bindParam('name', $name);
$stmt->bindParam('orderdesc', $orderdesc);
$stmt->bindParam('orderdesc2', $orderdesc2);

$ret_id = "DRM";
$name = (string)$obj->header->manifest->document->name;
$orderdesc = (string)$obj->body->ORDER->ORDERHEAD->ORDERDESC;
//$orderdesc2 = (string)$obj->body->ORDER->ORDERHEAD->FUNCDESC;

//loop through the orderline to get each product description
foreach ($obj->body->ORDER->ORDERLINE as $orderline):
             
      $orderdesc2 = $orderline->PRODUCT->DESCRIPTION;      

      //execute the query
      $stmt->execute();      
endforeach;

//run the second query
//$stmt2 = $dbh->prepare("INSERT INTO ret_orders (ord_linetype) VALUES (:name)");
//$stmt2->bindParam('name', $name);
///$stmt2->execute();
}
$i++;
} while ($i <= 5);

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>

<body><br /><br />


<?php
$i = 1;
$break = "<br />";
$space = "&nbsp;";

do {
   //echo $i;
if($_GET['xmlfile'.$i]!=""){ // check if the value is empty
$filenames = $_GET['xmlfile'.$i];

echo "File Imported:".$space.$filenames.$break;
}
$i++;
} while ($i <= 5);

?>

</body>
</html>
0

Featured Post

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

Suggested Solutions

Developers of all skill levels should learn to use current best practices when developing websites. However many developers, new and old, fall into the trap of using deprecated features because this is what so many tutorials and books tell them to u…
Part of the Global Positioning System A geocode (https://developers.google.com/maps/documentation/geocoding/) is the major subset of a GPS coordinate (http://en.wikipedia.org/wiki/Global_Positioning_System), the other parts being the altitude and t…
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

771 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now