"Undefined index: data" error in php - php

I have the following form that allows user to upload the image:
<form name='form1' method="POST" action="" id="registration_form">
<input type="file" name="data" id="data">
<input type="Submit" name="Upload1" value="Upload1">
</form>
And following php code that does the actual upload:
<?php if(isset($_POST['Upload1']))
{
$errors=array();
$allowed_ext= array('pdf','jpg','jpeg');
$file_name =$_FILES['data']['name']; //error shows in this line
$file_ext = strtolower( end(explode('.',$file_name)));
$file_size=$_FILES['data']['size'];
$file_tmp= $_FILES['data']['tmp_name'];
$type = pathinfo($file_tmp, PATHINFO_EXTENSION);
$data = file_get_contents($file_tmp);
if(in_array($file_ext,$allowed_ext) === false){
$errors[]='Extension not allowed';
}
if($file_size > 2097152){
$errors[]= 'File size must be under 2mb';
}
if(empty($errors))
{
if( move_uploaded_file($file_tmp, 'images/'.$file_name));
{
$ct='application/' .$file_ext.'<br/>' ;
$base64 = base64_encode($data);
//json part is here
}
}
else {
foreach($errors as $error) {
echo $error , '<br/>';
}
}
}
When I select the file and hit "UPLOAD", it shows error as "Undefined index: data". But what is interesting to note is that 1 out of 10 times, it works! Where am I doing wrong?

According to your form you are not using multiparty/form-data in form tag.
You just need to use
enctype="multipart/form-data" 
Inside the form tag for input type file.
Example:
<form enctype="multipart/form-data">
Why it's needed? Why is form enctype=multipart/form-data required when uploading a file?
If you are using JavaScript for submit the form than you can use formData for getting data from input either post or file.
var formData = new FormData(formId);

Related

When uploading a file is_uploaded_file returns false?

im using a simple input file type to upload a pdf to the server:
<form action="subirCircular.php" method="post" enctype="multipart/form-data">
<input type="file" name="userfile" accept="application/pdf">
<br><br>
<button type="submit" class="btn btn-default">Subir</button>
</form>
And I receive the file in the php for uploading:
<?php
define ("FILEREPOSITORY","./uploads/");
if (is_uploaded_file($_FILES['userfile']['tmp_name'])) {
if ($_FILES['userfile']['type'] != "application/pdf") {
echo "<p>Class notes must be uploaded in PDF format.</p>";
} else {
$name = $_POST['name'];
$result = move_uploaded_file($_FILES['userfile']['tmp_name'], FILEREPOSITORY."/$name.pdf");
if ($result == 1) echo "<p>File successfully uploaded.</p>";
else echo "<p>There was a problem uploading the file.</p>";
} #endIF
}else{
echo 'ERROR!';
}
?>
The thing is the condition never gets called, I always get a false 'is_uploaded_file'.
I would like to know what Im doing wrong, thanks!
I rather use :
$_FILES['userfile']['error']
to check if every thing is ok, and if yes then I use
move_uploaded_file($_FILES['userfile']['tmp_name'],$pathname)
to move the uploaded file.
And so far it works.
Check your request method - it should be POST, not PUT/PATCH/...

Image upload form inside larger form?

I have a form that allows users to create events. Inside this form I have a form for an image upload. The HTML looks like this:
<form id="upload_event" method="post" action="system/upload_event.php">
<input type="text" name="title">
<textarea name="description"></textarea>
<form id="upload_image" method="post" action="system/upload_image.php">
<!-- code -->
</form>
Upload event
<input style="display:none" type="submit" id="submit_upload_event" name="submit_upload_event">
</form>
This is what my upload_image.php, which processes the image upload, looks like:
// A list of permitted file extensions
$allowed = array('png', 'jpg', 'gif','zip');
if(isset($_FILES['upl']) && $_FILES['upl']['error'] == 0){
$extension = pathinfo($_FILES['upl']['name'], PATHINFO_EXTENSION);
if(!in_array(strtolower($extension), $allowed)){
echo '{"status":"error"}';
exit;
}
if(move_uploaded_file($_FILES['upl']['tmp_name'], 'uploads/'.$_FILES['upl']['name'])){
echo '{"status":"success"}';
exit;
}
}
echo '{"status":"error"}';
exit;
As I found out, it is not possible to nest a form into another one. What would be the solution here?
If you're using Ajax you could return a value from your upload form to your main form. Like putvande said you can't have a form inside a form.

How to upload one excel file and display all its rows and columns on the web page via php

I am writing a code for uploading one excel file.And displaying its full content on a webpage.But whenever user clicks on the submit button it shows the error-
"Your File Type is:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
File type must be text(.txt) or msword(.doc)."
Below is my code.
<?php
if( isset($_POST['submit1'])) {
// $_FILES is the array auto filled when you upload a file and submit a form.
$userfile_name = $_FILES['file1']['name']; // file name
$userfile_tmp = $_FILES['file1']['tmp_name']; // actual location
$userfile_size = $_FILES['file1']['size']; // file size
$userfile_type = $_FILES['file1']['type'];
$userfile_error = $_FILES['file1']['error']; // any error!. get from here
// Content uploading.
$file_data = '';
if ( !empty($userfile_tmp))
{
$file_data=base64_encode(#fread(fopen($userfile_tmp,'r'), filesize($userfile_tmp)));
}
switch (true)
{
// Check error if any
case ($userfile_error == UPLOAD_ERR_NO_FILE):
case empty($file_data):
echo 'You must select a document to upload before you can save this page.';
exit;
break;
case ($userfile_error == UPLOAD_ERR_INI_SIZE):
case ($userfile_error == UPLOAD_ERR_FORM_SIZE):
echo 'The document you have attempted to upload is too large.';
break;
case ($userfile_error == UPLOAD_ERR_PARTIAL):
echo 'An error occured while trying to recieve the file. Please try again.';
break;
}
if( !empty($userfile_tmp))
{
// only MS office and text file is accepted.
if( !(($userfile_type=="application/msword") || ($userfile_type=="text/plain") || ($userfile_type=="application/vnd.ms-excel")) )
{echo 'Your File Type is:'. $userfile_type;
echo '<br>File type must be text(.txt) or msword(.doc).';
exit;
}
}
echo filesize($userfile_tmp);
}
?>
<HTML>
<HEAD>
<TITLE> PHP File Upload Script </TITLE>
</HEAD>
<BODY>
<form name="profile" method="POST" action="<?php echo $_SERVER['PHP_SELF'] ?>" target="_self" enctype="multipart/form-data" >
<P align ="center"><input type="hidden" name="MAX_FILE_SIZE" value="1000000">
<input name="file1" type="file" accept="application/vnd.openxmlformats- officedocument.spreadsheetml.sheet" />
<input type="submit" name="submit1" value="Submit" />
</P>
</form>
</BODY>
</HTML>
Please help .
Thank you in advance.
You need to add following in your if condition as well
because your are checking for application/vnd.ms-excel and application/msword but file is having its header different as
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheetyour" So if you add this inside if like
if(($userfile_type=="application/vnd.openxmlformats-officedocument.spreadsheetml.sheetyour") || ($userfile_type=="application/msword") || ($userfile_type=="text/plain") ||
($userfile_type=="application/vnd.ms-excel")){
// code
}
Because server will interpret the file type based on headers it receives.
If you want to show Excel file contents on your page then you should think of using PHPExcel. It is very easy to use.
Link: https://phpexcel.codeplex.com/
Examples: https://phpexcel.codeplex.com/wikipage?title=Examples&referringTitle=Home

PHP file upload suddenly stopped working

I had file upload working fine this morning and did a couple of test uploads using small csv files, but when I did another test it has stopped working.
var_dump of $_FILES['file'] is NULL, and trying if($_FILES) produces nothing.
No one else uses my server so I know nothing's been changed.
Here is my form which posts to the same page.
<form method="post" enctype="multipart/form-data" style="border:1px solid #999">
<input type="file">
<input type="hidden" name="customerID" value="<?=$_GET['customerID']?>">
<input type="submit" value="Import">
</form>
Php handler:
if($_FILES)
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{
$path = "files/".$_POST['customerID']."/";
echo $path."<br>";
if(!file_exists($path)) mkdir($path);
$path = $path.basename($_FILES['file']['name']);
echo $path."<br>".$_FILES['file']['tmp_name']."<br>";
if(is_uploaded_file($_FILES['file']['tmp_name']))
{
if(move_uploaded_file($_FILES['file']['tmp_name'], $path)) echo "Upload success";
else echo "Upload failed";
}
else echo "No temp file";
}
You had to change something... because $_FILES['file'] should be undefined in code you gave. No file is sent at all by most browsers in the case when file input has no name attribute in HTML form.
Simply change:
<input type="file">
to
<input type="file" name="file">
You need to add a "name" attribute to your <input type="file">. The name you give to the input will be the index of the array element in $_FILES that contains the uploaded file data.

Failed to upload an image

I made a form at HTML with an option to upload an image. The problem is that when I check the $_FILES array at the php code, it is not found.
The HTML form:
<form method="POST" action="addProduct.php" onsubmit="return checkValidation()">
Image(optional): <input type="file" name="fileImg" accept="image/*" id="fileImg">
<input id="submitProduct" type="submit" name="submitBtn" value="Submit product" onclick="checkValidation()"/>
</form>
The checkValidation() function:
function checkValidation(){
var regex = /\.(jpg|JGP|jpeg|JPEG|png|PNG|gif|GIF)$/;
if (($('#fileImg').val()) && (!(regex.test($('#fileImg').val()))))
{
return false;
}
}
And the php code:
if(isset($_POST["submitBtn"])){
if(!(empty($_FILES)))
{
if (file_exists('uploads/'.$_FILES["fileImg"]["name"]))
{
echo $_FILES["fileImg"]["name"]." already exists. ";
}
else
{
move_uploaded_file($_FILES["fileImg"]["tmp_name"], 'uploads/'. $_FILES["fileImg"]["name"]);
$path = $_FILES["fileImg"]["name"];
}
}
else
$path = 'no_photo.jpg';
The problem is that at the php code, it always jumps to the else branch (which gives me some default image).
Thanks in advance.
Your form lacks the enctype='multipart/form-data' attribute. Without it, $_FILES would always be empty.
Read more about it here: What does enctype='multipart/form-data' mean?

Categories