Question about undefined index in uploading files

0 dor sarel · June 19, 2015
Hii, 
i saw the tutorials about Uploading files and i have a questions.
I wrote code exactly as alex wrote:
<CODE>

<?php

$name = $_FILES['file']['name'];
$tmp_name = $_FILES['file']['tmp_name'];
$type = $_FILES['file']['type'];
$size = $_FILES['file']['size'];

$extension = strtolower(substr($name, strpos($name, '.') + 1));

if(isset($name)){
if(!empty($name)){
if($extension == 'png' AND $type = 'image/png'){

$location = 'upload/';

if(move_uploaded_file($tmp_name, $location.$name)){
echo 'The file '.$name.' has been uploaded';
}else{
echo 'There were an error with the uploading';
}


}else{
echo 'the file must be with png extension';
}
}else{
echo 'File has not been chosen'."\n".'Choose file!';
}
}



?>


<form action="upload.php" method="POST" enctype="multipart/form-data">
<input type="file" name="file"><br><br>
<input type="submit" value="Submit">
</form>

</CODE>
but when i opening the file i got this:
Notice: Undefined index: file in C:\xampp\htdocs\projects\upload.php on line 3

Notice: Undefined index: file in C:\xampp\htdocs\projects\upload.php on line 4

Notice: Undefined index: file in C:\xampp\htdocs\projects\upload.php on line 5

Notice: Undefined index: file in C:\xampp\htdocs\projects\upload.php on line 6

why i got this error?

Post a Reply

Replies

Oldest  Newest  Rating
0 dor sarel · June 20, 2015
updated
0 Alan Johnson · June 20, 2015
I'll have a look now.
0 Alan Johnson · June 20, 2015
You're trying to get the file name before the form was submitted. You should only look for the uploaded file after the user has submitted the form. The PHP code at the top of your script should be:

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$name = $_FILES['file']['name'];
$tmp_name = $_FILES['file']['tmp_name'];
$type = $_FILES['file']['type'];
$size = $_FILES['file']['size'];

$extension = strtolower(substr($name, strpos($name, '.') + 1));

if (isset($name)) {
if (!empty($name)) {
if ($extension == 'png' AND $type = 'image/png'){

$location = 'upload/';

if (move_uploaded_file($tmp_name, $location.$name)){
echo 'The file '.$name.' has been uploaded';
} else {
echo 'There were an error with the uploading';
}
} else {
echo 'the file must be with png extension';
}
} else {
echo 'File has not been chosen'."\n".'Choose file!';
}
}
}

0 dor sarel · June 20, 2015
thank you very much!!
now its work - and i learned something new :)
0 Alan Johnson · June 20, 2015
:)
0 Alan Johnson · June 19, 2015
The code block is blank, edit your post.
  • 1

PHP

107,119 followers
About

Server-side, HTML embedded scripting language used to create dynamic Web pages.

Links
Moderators