Basic file upload is not working that i created.

Created a basic file upload in php, but  it didn't put the image into the folder I created in  the C directory

<?php
// set the maximum upload size in bytes
$max = 51200;
if (isset($_POST['upload'])) {
  // define the path to the upload folder
  $destination = 'C:/upload_test/';
  // move the file to the upload folder and rename it
  move_uploaded_file($_FILES['image']['tmp_name'], $destination . $_FILES['image']['name']);
}
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset=utf-8">
<title>Upload File</title>
</head>

<body>
<form action="" method="post" enctype="multipart/form-data" id="uploadImage">
  <p>
    <label for="image">Upload image:</label>
    <input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max; ?>">
    <input type="file" name="image" id="image">
  </p>
  <p>
    <input type="submit" name="upload" id="upload" value="Upload">
  </p>
</form>
</body>
</html>

Open in new window

imagekrazyAsked:
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.

Chris StanyonWebDevCommented:
Remove your hidden input (MAX_FILE_SIZE) and it'll work fine...
0
Ray PaseurCommented:
What is the question?

This is how I upload files.  It makes it possible to visualize errors, if any.

<?php // RAY_upload_one_file.php
error_reporting(E_ALL);


// MANUAL REFERENCE PAGES YOU MUST UNDERSTAND TO UPLOAD FILES
// 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/reserved.variables.files.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 BIGGEST FILE SIZE WE CAN ACCEPT - ABOUT 8 MB
$max_file_size = '8000000';

// ESTABLISH THE KINDS OF FILE EXTENSIONS WE CAN ACCEPT (USE UPPERCASE ONLY)
$file_exts = array
( 'XLS'
, 'XLSX'
)
;
$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 = 'RAY_junk';
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
( 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 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 = end(explode('.', $fname));
    $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 = <<<ENDFORM
<p>Upload one file
<form enctype="multipart/form-data" method="post">
<!-- MAX_FILE_SIZE MUST PRECEDE THE FILE INPUT FIELD -->
<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>
</p>
ENDFORM;

echo $form;

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
Chris StanyonWebDevCommented:
Your current script will only accept files less than 51k (MAX_FILE_SIZE = 51200)
0
Big Business Goals? Which KPIs Will Help You

The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.

imagekrazyAuthor Commented:
I did that but it gave me this warning:

Warning: move_uploaded_file(C:/upload_test/IMG_3535.JPG) [function.move-uploaded-file]: failed to open stream: No such file or directory in /home/content/64/11583764/html/summer/test2/upload3.php on line 8

Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move '/tmp/phpkQMxeN' to 'C:/upload_test/IMG_3535.JPG' in /home/content/64/11583764/html/summer/test2/upload3.php on line 8

but i created the folder in C:\upload_test
0
Ray PaseurCommented:
See lines 68-69 in my script.  That gives me the file name.

See lines 76-83.  That gives me the full server path name.

The handy thing about creating a string variable is that you can print it out with var_dump() and see if it contains what you think it should contain.  

My guess is that move_uploaded_file() is trying to do its work relative to its current working directory.  If C:/upload_test is above the WWW root, you might want to rethink that strategy and move the file to something that will have the right permissions.
0
imagekrazyAuthor Commented:
Wow Ray, your script kicks ass!, in your script I change the file ext to JPG and GIF,and it worked!!, but my question is,I created the  folder (upload_test)  but in your script it sated to click the link to see the image an it shows the image,but  i went to look for the image with out  the link, but i couldn't find it, any suggestion will be help.
0
imagekrazyAuthor Commented:
Boy I am stupid, I found the file, it wasn't on my local computer it was on my server:)
0
Ray PaseurCommented:
Try printing out the value of $my_path and see if you can find the image there.
0
imagekrazyAuthor Commented:
Again thank you!!
0
Ray PaseurCommented:
wasn't on my local computer...
Ha!  I've done that before, too.  Thanks for the points and best of luck with your project, ~Ray
0
imagekrazyAuthor Commented:
Ray final question, I applied your script into my page with the css, but when i open the file ,this is what i see:

//CREATE THE FORM FOR INPUT (USING HEREDOC SYNTAX) $form = <<Upload one file
Find a file to Upload ($f_exts):

did I not close  tag or something?
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.