Solved

Could you point how to obtain a value from an giving array?

Posted on 2016-09-02
7
36 Views
Last Modified: 2016-09-03
Hi Experts

Giving this array:

Array ( [0] => Array ( [name] => img_ee_004_020916.png [type] => image/png [tmp_name] => /tmp/phpm99HLL [error] => 0 [size] => 54025 ) ) 

Open in new window


What is the better way of obtain the value:  img_ee_004_020916.png

Thanks in advance
0
Comment
Question by:Eduardo Fuerte
  • 3
  • 3
7 Comments
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 41782327
assuming the array is called $data
Then
 $data[0]['name']

Open in new window


But this looks like a file submission for an upload - did you not name your file input - if so it would come through in the $_FILES array as the name of the control and you could address it by name.
0
 

Author Comment

by:Eduardo Fuerte
ID: 41782345
Hi

Yes, it really is. The 3rd. and last question of the test I'm attending.

Before to upload a file I need to check by its name/signature if has been updated before and give a warning.

After every upload an insert in a table is made with name/ signature.

Also if the name is found and the signature of the file has changed the file could have some kind of violation. So I have to obtain the name in advance to upload to warn about previous update/ violation, checking name/ signature with DB existing data.

// This command
print_r(array_values($_FILES));

//Produces
Array ( [0] => Array ( [name] => img_ee_004_020916.png [type] => image/png [tmp_name] => /tmp/phpaBnZah [error] => 0 [size] => 54025 ) ) 

//And this (that I still used before)
$arquivo =$_FILES[0]['name'];

// Produces this error

[b]Notice: Undefined offset: 0 in /home/mysite/www/class_upload_php/test/upload.php on line 90[/b]

Open in new window

0
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 250 total points
ID: 41782430
Please show us the contents of $_FILES, thanks.
// INSTEAD OF THIS,...
print_r(array_values($_FILES));

// PLEASE TRY THIS:
print_r($_FILES);

Open in new window


Here's my teaching example showing how to upload a single file:
<?php // demo/upload_single_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.post-method.php
 * http://php.net/manual/en/features.file-upload.common-pitfalls.php
 * http://php.net/manual/en/features.file-upload.errors.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 BIGGEST FILE SIZE WE CAN ACCEPT - ABOUT 8 MB
$max_file_size = '8000000';

// ESTABLISH THE KINDS OF FILE EXTENSIONS WE WANT (USE UPPERCASE ONLY)
$file_exts = array
( 'XLS'
, 'XLSX'
, 'PDF'
, 'JPG'
)
;
$f_exts = implode(', ', $file_exts);

// ESTABLISH THE NAME OF THE DESTINATION FOLDER
$my_dir = getcwd();

// OR USE THIS TO PUT UPLOADS IN A SEPARATE FOLDER
$my_dir = 'storage';
if (!is_dir($my_dir))
{
    mkdir($my_dir);
}

// LIST OF THE ERRORS THAT MAY BE REPORTED IN $_FILES[]["error"] (THERE IS NO #5)
$errors = array
( UPLOAD_ERR_OK         => "Success!"
, UPLOAD_ERR_INI_SIZE   => "The uploaded file exceeds the upload_max_filesize directive in php.ini"
, UPLOAD_ERR_FORM_SIZE  => "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form"
, UPLOAD_ERR_PARTIAL    => "The uploaded file was only partially uploaded"
, UPLOAD_ERR_NO_FILE    => "No file was uploaded"
, 5                     => "UNDEFINED ERROR #5"
, UPLOAD_ERR_NO_TMP_DIR => "Missing a temporary folder"
, UPLOAD_ERR_CANT_WRITE => "Cannot write file to disk"
, UPLOAD_ERR_EXTENSION  => "A PHP extension stopped the file upload"
)
;

// IF THERE IS INFORMATION POSTED
if (!empty($_POST))
{
    // IF THERE ARE ERRORS
    $error_code    = $_FILES["userfile"]["error"];
    if ($error_code)
    {
        trigger_error($errors[$error_code], E_USER_ERROR);
    }

    // GET THE FILE SIZE
    $fsize = number_format($_FILES["userfile"]["size"]);

    // SYNTHESIZE THE NEW FILE NAME FOR TEMPORARY STORAGE
    $fname = basename($_FILES['userfile']['name']);

    // FAIL IF THIS IS NOT AN ALLOWABLE EXTENSION
    $f_ext = explode('.', $fname);
    $f_ext = end($f_ext);
    $f_ext = strtoupper(trim($f_ext));
    if (!in_array($f_ext, $file_exts)) trigger_error("$f_ext NOT ALLOWED.  CHOOSE FROM $f_exts", E_USER_ERROR);

    // THE SERVER PATH TO THE FILE
    $my_path
    = getcwd()
    . DIRECTORY_SEPARATOR
    . $my_dir
    . DIRECTORY_SEPARATOR
    . $fname
    ;

    // THE URL PATH TO THE FILE
    $my_url
    = $my_dir
    . DIRECTORY_SEPARATOR
    . $fname
    ;

    // MESSAGES ABOUT THE UPLOAD STATUS, IF ANY
    $msg = NULL;

    // IF THE FILE IS NEW (DOES NOT EXIST)
    if (!file_exists($my_path))
    {
        // IF THE MOVE FUNCTION WORKED CORRECTLY
        if (move_uploaded_file($_FILES['userfile']['tmp_name'], $my_path))
        {
            $upload_success = 1;
        }
        // IF THE MOVE FUNCTION FAILED IT PROBABLY THREW A MESSAGE
        else
        {
            $upload_success = -1;
            trigger_error("MOVE TO $my_path FAILED", E_USER_ERROR);
        }
    }

    // IF THE FILE ALREADY EXISTS
    else
    {
        $msg .= "<br/><b><i>$my_url</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-His');
            $my_bak = $my_path . '.' . $now . '.bak';
            if (!copy($my_path, $my_bak))
            {
                $msg .= "<br/><strong>Attempted Backup Failed!</strong>" . PHP_EOL;
            }
            if (move_uploaded_file($_FILES['userfile']['tmp_name'], $my_path))
            {
                $upload_success = 2;
            }
            else
            {
                $upload_success = -1;
                trigger_error("MOVE TO $my_path FAILED", E_USER_ERROR);
            }
        }
    }

    // PREPARE A REPORT OF THE SCRIPT'S SUCCESS OR FAILURE
    if ($upload_success == 2) { $msg .= "<br/>A backup was made and the file was overwritten" . PHP_EOL; }
    if ($upload_success == 1) { $msg .= "<br/><strong>$my_url</strong> has been saved" . PHP_EOL; }
    if ($upload_success == 0) { $msg .= "<br/><strong>It was NOT overwritten.</strong>" . PHP_EOL; }
    if ($upload_success < 0)  { $msg .= "<br/><strong>ERROR: $my_url NOT SAVED - SEE WARNING FROM move_uploaded_file()</strong>" . PHP_EOL; }

    // ADD FILE SIZE AND PERMISSION INFORMATION
    if ($upload_success > 0)
    {
        $msg .= "<br/>$fsize bytes uploaded" . PHP_EOL;
        if (!chmod ($my_path, 0755))
        {
            $msg .= "<br/>chmod(0755) FAILED: fileperms() = ";
            $msg .= substr(sprintf('%o', fileperms($my_path)), -4);
        }
    }

    // SHOW THE SUCCESS OR FAILURE
    echo $msg;

    // SHOW A LINK TO THE FILE
    echo '<br/>'
    . '<a href="'
    . $my_url
    . '" target="_blank">'
    . "See: $my_url"
    . '</a>'
    ;
}


// CREATE THE FORM FOR INPUT (USING HEREDOC SYNTAX)
$form = <<<EOF
<h2>Upload a File</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 enctype="multipart/form-data" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="$max_file_size" />
Find a file to Upload ($f_exts): <input name="userfile" type="file" />
<br>Check this box
<input autocomplete="off" type="checkbox" name="overwrite" /> to <strong>overwrite</strong> existing files
<br><input type="submit" value="Upload" />
</form>
EOF;

echo $form;

Open in new window

0
Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

 
LVL 51

Assisted Solution

by:Julian Hansen
Julian Hansen earned 250 total points
ID: 41782549
array_values removes the keys of the array which are important in this context.

As Ray mentioned we need to see the whole array

What is happening here is this

You are doing a print_r on the array_keys - which removes the indices from the array - the names of the inputs. You are then using the output from the print_r to index the array which won't work because array_values returns a completely new array with 0 based indices - whereas the original $_FILES array has strings as the keys - the names of the inputs
Example
<input type="file" name="filename" />

Open in new window

The $_FILES['filename'] will have the data you are looking for.

Add this to your code
echo "<pre>" . print_r($_FILES, true) . "</pre>";

Open in new window

To see what I mean
0
 

Author Comment

by:Eduardo Fuerte
ID: 41782791
You are perfectly right!

Very well explained

Array
(
    [my_field] => Array
        (
            [name] => img_ee_002_270816.png
            [type] => image/png
            [tmp_name] => /tmp/phpuK8pmO
            [error] => 0
            [size] => 44367
        )

)

// And then
$arquivo = $_FILES["my_field"]["name"];

Open in new window


Produces

img_ee_002_270816.png
1
 

Author Closing Comment

by:Eduardo Fuerte
ID: 41782792
Thanks for the valuable help!
0
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 41782798
Welcome as always Eduardo,
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Author Note: Since this E-E article was originally written, years ago, formal testing has come into common use in the world of PHP.  PHPUnit (http://en.wikipedia.org/wiki/PHPUnit) and similar technologies have enjoyed wide adoption, making it possib…
Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
The viewer will learn how to count occurrences of each item in an array.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

707 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

15 Experts available now in Live!

Get 1:1 Help Now