PHP: undefined index in $_FILES[] [duplicate] - php

This question already has answers here:
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
Closed 5 years ago.
I tried to create an upload script in PHP. I getting this error message:
Notice: Undefined index: file in path\upload\index.php on line 3
This is my form (pretty basic):
<form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="fileUpload">
<input type="submit" value="Upload Image" name="submitt">
</form>
This is my (not working) upload script:
<?php
$name = $_FILES['file']['name'];
$temp_name = $_FILES['file']['tmp_name'];
if(isset($name)){
if(!empty($name)){
$location = '../data/';
if(move_uploaded_file($temp_name, $location.$name)){
echo 'File uploaded successfully';
}
}
} else {
echo 'You should select a file to upload !!';
}
?>
This is my php.ini config:
; Whether to allow HTTP file uploads.
; http://php.net/file-uploads
file_uploads=On
; Maximum allowed size for uploaded files.
; http://php.net/upload-max-filesize
upload_max_filesize=40M
; Maximum number of files that can be uploaded via a single request
max_file_uploads=20
; Maximum size of POST data that PHP will accept.
; Its value may be 0 to disable the limit. It is ignored if POST data reading
; is disabled through enable_post_data_reading.
; http://php.net/post-max-size
post_max_size=50M
So what did I do wrong. I checked every previously asked question but didn't find an answer.
EDIT 1:
After checking out this and altering my code the problem still consists.
<?php
if (isset($_POST['submitt'])) {
if (isset($_FILES['file']) && isset($_FILES['file']['name']) && isset($_FILES['file']['tmp_name'])) {
$name = $_FILES['file']['name'];
$temp_name = $_FILES['file']['tmp_name'];
if(!empty($name)){
$location = '../data/';
if(move_uploaded_file($temp_name, $location.$name)){
echo 'File uploaded successfully';
}
} else {
echo 'You should select a file to upload !!';
}
}
}
?>
EDIT 2:
I found the problem: Replacing action upload with upload/index.php resolved the problem. I am using XAMPP on my local machine to test my code. This is an error due to an incorrect Apache config by XAMPP itself.

When user submit form and didn't pick file to upload your global variable (array) $_FILES won't have item file, hence you have this error, and you have to check if this key available, like this:
if (isset($_FILES['file']) && isset($_FILES['file']['name']) && isset($_FILES['file']['tmp_name'])) {
// Now you have strict and robust code!
$name = $_FILES['file']['name'];
$temp_name = $_FILES['file']['tmp_name'];
// Rest of your code ...
}

In your 'upload' logic, you need to ensure that the form has been submitted before declaring the values. Otherwise, it's attempting to set variables with a value that does not yet exist;
<?php
//ensures the form was submitted before declaring variable values
if (isset($_POST['submitt']) {
$name = $_FILES['file']['name'];
$temp_name = $_FILES['file']['tmp_name'];
if(isset($name)){
if(!empty($name)){
$location = '../data/';
if(move_uploaded_file($temp_name, $location.$name)){
echo 'File uploaded successfully';
}
}
} else {
echo 'You should select a file to upload !!';
}
}
?>
Secondly, Change your form code so that the 'action' is it self (in this case, we're leaving action="" as blank):
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="fileUpload">
<input type="submit" value="Upload Image" name="submitt">
</form>

Related

Upload images using php

I have a an input type file which is hidden and triggered using another button .. the input must upload images only to a folder named Covers but the code is not working and not uploading any image..
html code
<div class="cover">
<img src="Layout/images/cover.jpg" alt="cover" name="cover-img" class="cover-img">
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="POST" enctype="multipart/form-data">
<button type="submit" name="submit-cover" id="cover-btn">Change Cover</button>
<input type="file" name="avatar" id="cover-img-input" class="hidden" />
</form>
php codes:
if($_SERVER['REQUEST_METHOD'] == 'POST') {
if(isset($_POST['submit-cover'])) {
$avatarName = $_FILES['avatar']['name'];
$avatarTempName = $_FILES['avatar']['tmp_name'];
// List of allowed image extensions
$avatarAllowedExtensions = array("jpeg","jpg","png","gif");
// Get avatar extension
$avatarExtension = strtolower(end(explode('.',$avatarName)));
// Check if uploaded image extension is in allowed image extensions
$formErrors=array();
if(! empty($avatarName) && ! in_array($avatarExtension, $avatarAllowedExtensions)) {
$formErrors[]='This extension is <strong>not allowed</strong>';
}
if(empty($avatarName)) {
$formErrors[]='No image <strong>uploaded</strong>';
}
if(empty($formErrors)) {
// Create random number between zero to million to concatinate it with image name
$avatar = rand(0,1000000) . '_' . $avatarName;
// Move image into Covers folder
move_uploaded_file($avatarTempName, "Uploads\Covers\\" . $avatar);
}
}
}
I get
Fatal error: Undefined class constant 'MYSQL_ATTR_INIT_COMMAND' in D:\XAMPP\htdocs\Warina\connect.php on line 7
after that I searched for a solution and get this: extension=php_pdo_mysql.dll should be uncommented in my php.ini and it is uncommented now I'm confused about this error too.
This line sends a notice:
$avatarExtension = strtolower(end(explode('.',$avatarName)));
Notice: Only variables should be passed by reference in file.php on line xx
Replace with
$avatarExtension = explode('.',$avatarName);
$avatarExtension = strtolower(end($avatarExtension));
Fix this path:
move_uploaded_file($avatarTempName, "Uploads\Covers\\" . $avatar);
With
move_uploaded_file($avatarTempName, "Uploads\\Covers\\" . $avatar);
And make sure it exists

Notice: Undefined index: $error in C:\wamp\www\btb_sandbox\upload_2.php on line 35 [duplicate]

This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 7 years ago.
I'm having this kind of Error stated below, I don't understand completely about it. If I press upload button without selecting files!
Notice: Undefined index: $error in C:\wamp\www\btb_sandbox\upload_2.php on line 35
<?php
// In an application, this could be moved to a config file
$upload_errors = array(
// http://www.php.net/manual/en/features.file_upload.errors.php
UPLOAD_ERR_OK => "No errors.",
UPLOAD_ERR_INI_SIZE => "Larger than upload_max_filesize.",
UPLOAD_ERR_FORM_SIZE => "Larger than form MAX_FILE_SIZE.",
UPLOAD_ERR_PARTIAL => "Partial upload.",
UPLOAD_ERR_NO_FILE => "No file.",
UPLOAD_ERR_NO_TMP_DIR => "No temporary directory.",
UPLOAD_ERR_CANT_WRITE => "Can't write to disk.",
UPLOAD_ERR_EXTENSION => "File upload stopped by extension."
);
if(isset($_POST['submit']))
{
// process the form data
$tmp_file = $_FILES['file_upload']['tmp_name'];
$target_file = basename($_FILES['file_upload']['name']);
$upload_dir = "uploads";
// You will probably want to first use file_exists() to
// make sure there isn't already a file by the same name
// move_uploaded_file will return false if $tmp_file is
// not a valid upload file or if it cannot be moved for
// any same name
if(isset($_FILES['file_upload']) || isset($_FILES['file_upload']['error']))
{
if(move_uploaded_file($tmp_file, $upload_dir."/".$target_file))
{
$message = "File uploaded successfully.";
} else {
$error = $_FILES['file_upload']['error'];
$message = $upload_errors['$error'];
// echo "<pre>";
// print_r($_FILES['file_upload']);
// echo "</pre>";
// echo "<hr />";
}
}
}
?>
<html>
<head>
<title>Upload</title>
</head>
<body>
<?php
// The maximum file size (in bytes) must be declared before the file input field
// and can't be larger than the setting for upload_max_filesize in php.ini.
//
// This form value can be manipulated. You should still use it, but you rely
// on upload_max_filesize as the absolute limit.
//
// Think of it as a polite declaration: "Hey PHP, here comes a file less than X..."
// PHP will stop and complain once X is exceeded.
//
// 1 megabyte is actually 1,048,576 bytes.
// You can round it unless the precision matters.
?>
<?php if(!empty($message)) { echo "<p>{$message}</p>"; } ?>
<form action="upload_2.php" enctype="multipart/form-data" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="1000000" />
<input type="file" name="file_upload" />
<input type="submit" name="submit" value="Upload" />
</form>
</body>
</html>
Please help me, and tell me in details!
You made a mistake apparently. In the doc (http://php.net/manual/en/features.file-upload.errors.php), you'll find :
UPLOAD_ERR_INI_SIZE
and you did specify in your script :
UPLOAD_ERR_INT_SIZE
That's why the script tells you this constant does not exist :)

Warning: getimagesize() [function.getimagesize]: Filename cannot be empty warning message?

Up until recently I've been using some PHP to upload photos to a site. But suddenly it's started triggering all sorts of error messages.
I use a form that on action runs the following code:
$uploaddir = "../../user_content/photo/";
$allowed_ext = array("jpeg", "jpg", "gif", "png");
if(isset($_POST["submit"])) {
$file_temp = $_FILES['file']['tmp_name'];
$info = getimagesize($file_temp);
} else {
print "File not sent to server succesfully!";
exit;
}
The file upload part of the form has the following elements:
<input name="file" type="file" class="photo_file_upload">
The submit button for uploading has the following attributes:
<button type="submit" name="submit" class="photo_upload">Upload</button>
But whenever I run this, I always get the following warning:
Warning: getimagesize() [function.getimagesize]: Filename cannot be empty in (upload PHP file) on line 10
(line 10 is this part: $info = getimagesize($file_temp);)
Anyone have any ideas on what the cause of this is?
You checked if the form was submitted, but didn't check if the file was sent. In some cases, a form could be submitted but the file will not sent (i.e. file size is bigger then file size limit in config).
Use this:
if(isset($_POST["submit"]) && isset($_FILES['file'])) {
$file_temp = $_FILES['file']['tmp_name'];
$info = getimagesize($file_temp);
} else {
print "File not sent to server succesfully!";
exit;
}
You see && isset($_FILES['file']) is new
Or you can extend it
if(isset($_POST["submit"]) && isset($_FILES['file'])) {
$file_temp = $_FILES['file']['tmp_name'];
$info = getimagesize($file_temp);
}
elseif(isset($_POST["submit"]) && !isset($_FILES['file'])) {
print "Form was submitted but file wasn't send";
exit;
}
else {
print "Form wasn't submitted!";
exit;
}
Change these parameters in your php.ini file; (Currently it allow only 2Mb size to
upload and post). Sometimes it's reason for these errors.
upload_max_filesize = 500M
post_max_size = 500M
max_execution_time = 120
Warning: getimagesize() [function.getimagesize]: Filename cannot be empty in
Verify the MAX_SIZE variable,
example to define it for a 2Mo image:
define('MAX_SIZE', 2000000);
<form enctype="multipart/form-data" method="post" action="upload.php">
<input type="hidden" name="MAX_FILE_SIZE" value="<?php echo MAX_SIZE; ?>" />
<input name="fichier" type="file" id="fichier_a_uploader" /> <br>
<input type="submit" name="submit" value="Uploader" />
</form>
you can also verify the Maximum size of POST data that PHP will accept and Maximum allowed size for uploaded files in PHP.ini :
post_max_size = ?
upload_max_filesize = ?
After you upgrade 'upload-max-filesize' , Restart all Services of wamp or xampp ! it will right !
you should change the form enctype to "multipart/form-data"
<form method="post" enctype="multipart/form-data">
....
</form>
Notice: Undefined index: fileToUpload in D:\xampp\htdocs\public_html\php\form_php\application\process_application.php on line 38
Notice: Undefined index: fileToUpload in D:\xampp\htdocs\public_html\php\form_php\application\process_application.php on line 43
Warning: getimagesize(): Filename cannot be empty in D:\xampp\htdocs\public_html\php\form_php\application\process_application.php on line 43
File is not an image.Sorry, file already exists.
Notice: Undefined index: fileToUpload in D:\xampp\htdocs\public_html\php\form_php\application\process_application.php on line 58
Sorry, only JPG, JPEG, PNG & GIF files are allowed.Sorry, your file was not uploaded.
If You Get Errors like this one you should check you have added form enctype to "multipart/form-data"
<form method="post" enctype="multipart/form-data">
....
</form>
Use to catch me out quite a lot to begin with.

Upload script in php [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Unable to do File Upload in PHP
I am trying to learn to write file upload script in PHP. I don't know why this doesn't work. Please have a look
<?php
$name=$_FILES["file"]["name"];
if(isset($name)) {
if(!empty($name)) {
echo $name;
}
else {
echo 'Please choose a file';
}
}
?>
It gives an error message Notice: Undefined index: file in
The html part is
<form action="submissions.php" method="POST" enctype="multipart/form-data">
<input type="file" name="file" id="file" />
<input type="submit" name="submit" value="Submit" /></form>
I am using wamp on Windows. What may be the cause for the error ?
You need to check if the form was submitted before executing your PHP code:
<?php
if (isset($_POST["submit"]) && $_POST["submit"] === "Submit") {
if (isset($_FILES["file"]["name"])) {
$name = $_FILES["file"]["name"];
if(!empty($name)) {
echo $name;
}
else {
echo 'Please choose a file';
}
}
}
?>
The clue is in the error message. The index 'file' doesn't exist in the FILES array. At a guess because you have this code before you've sumitted the form?
check if it exists first,
if(isset($_FILES['FormFieldNameForFile']) && $_FILES['FormFieldNameForFile']['size']>0){ # will be 0 if no file uploaded
then check your use of the field components.
$_FILES['userfile']['name'] # The original name of the file on the client machine.
$_FILES['userfile']['type'] # The mime type of the file, if the browser provided this information. An example would be "image/gif". This mime type is however not checked on the PHP side and therefore don't take its value for granted.
$_FILES['userfile']['size'] # The size, in bytes, of the uploaded file.
$_FILES['userfile']['tmp_name'] # The temporary filename of the file in which the uploaded file was stored on the server.
$_FILES['userfile']['error'] # The error code associated with this file upload

Undefined variable in upload script

I get following errors and I don't know why.
Notice: Undefined index: uploaded in C:\xampp\htdocs\site\upload.php on line 3
Notice: Undefined variable: uploaded_size in C:\xampp\htdocs\site\upload.php on line 7
Notice: Undefined variable: uploaded_type in C:\xampp\htdocs\site\upload.php on line 14
Notice: Undefined index: uploaded in C:\xampp\htdocs\site\upload.php on line 29
I tried to include the source of the php in this post but couldn't.
Here is link to pastebin: My source code
<?php
$target = "upload/";
$target = $target . basename( $_FILES['uploaded']['name']) ;
$ok=1;
//This is our size condition
if ($uploaded_size > 350000)
{
echo "Your file is too large.<br>";
$ok=0;
}
//This is our limit file type condition
if ($uploaded_type =="text/php")
{
echo "No PHP files<br>";
$ok=0;
}
//Here we check that $ok was not set to 0 by an error
if ($ok==0)
{
Echo "Sorry your file was not uploaded";
}
//If everything is ok we try to upload it
else
{
if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target))
{
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded";
}
else
{
echo "Sorry, there was a problem uploading your file.";
}
}
?>
Edit 1 : I got the code from about.com about.com
1.) In your $FILES array, there's no uploaded index defined. Possibly because it's $_FILES That's the first one. Try
<pre>
print_r($FILES);
print_r($_FILES);
</pre>
to see what is in there.
2.) ¿Where are you initializing those variables being used in the conditionals? You must extract data from the file element in the array and assign it to the variables before using it.
The first notice is telling you that on this line:
$target = $target . basename( $_FILES['uploaded']['name']) ;
There is no 'uploaded' index into the $_FILES array because no file was uploaded in a form with the file input named uploaded.
The next notice is telling you that on this line:
if ($uploaded_size > 350000)
You are accessing a variable named $uploaded_size which has never previously been defined, so how could it possibly hold some value greater than 350000?
Same issue with the next two notices. You seem to be missing some code, and are testing code for handling uploaded files without uploading a file, or without using a form with the enctype and input names it expects.
If you find that the $_FILES array does not contain any reference to your uploaded file, make sure your form tag includes enctype="multipart/form-data".

Categories