Jump to content

[SOLVED] Problem:$_FILES always empty after uploading


Lefteris

Recommended Posts

Hello all!

 

It is my first time posting in this forum.Hope I have a nice stay here. Let me waste no time and inform you of the problem.

 

The problem:

Whenever I try to upload something to my server (which is at local host, using easyphp, apache php and MySQL all in a nice bundle) the $_FILES array is empty. I don't know what to do. I am sure that the problem is not with the html form or the php code ( since well ... I can't do many mistakes with print_r($_FILES) :P )

 

What I have tried:

I have checked php.ini for the usual file uploading = on and safe mode = off options. I also checked if php can write or read files from anywhere else by making test scripts. Then I made a test script to check if php can write in the servers tmp folder in particular. Turned out it could. I might have tried out something else too ... but I don't remember right now.

 

In short ... these past 2 days I have been trying to understand what this problem might be ... but I have absolutely no clue anymore. I just need help .. or at least guidance at how I should proceed troubleshooting from here and on. I am clueless. Any help would be really appreciated.

Link to comment
Share on other sites

Sorry for not posting code, but well as you can see the problem is not with the code. And no the file_max_size setting is not surpassed. From php.ini it is 2M and from the hidden input of the form it is a lot more than 5 KB (the file I am trying to upload).

 

So ... here goes :

...
...
...
<div id="userImage">
    <img src="getUImage.php?usname=<?php echo($username);?>" />
    </div> 
    <?php
}
?>
    <div id="imageEdit">
    	<!--The small form to submit a user image,if it is used refresh the settings page-->
        <form enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
        <input type="hidden" name="MAX_FILE_SIZE" value="200000" />
        Want to change your picture?<input type="file" name="userpic" id="userpic" />
        <input name="subpic" type="submit" value="Upload New Picture" />
        </form>
	<?php eleos();?>
...
...
...

 

Here is the code for the file upload form. I made a temporary function called eleos() to check the $_FILES value.

 

Here is the content of eleos function:

function eleos()
{
//if the user clicks the submit picture button
if(isset($_POST['subpic']))
{

print_r($_FILES);

  }
}?>

 

As you can see the eleos() function is empty right now. I used it the last 2 days to check for virtually anything I could think of. But ... if the $_FILES is empty .... I can't do anything . Also ... I noticed that in this forum lots of topics get posted. I went for 8 hours of sleep after I posted the topic and it ended up in the end of the second page >_<  . That's very nice, means there are many active people here ! I like it!

 

Any help would be really appreciated. I am at at a loss.

Link to comment
Share on other sites

hmm I looked at your code and it should work i think there is a error in your php.ini file

Could you post it please

 

also what OS are you on and is SELINUX Disabled ? also iptables.

also try

copy($_FILES['subpic'][.tmp_name'],".tmp/" . $_FILES['subpic']['name']);

This should place a copy of the file in the .tmp directory with the same filename as the original.

however this one will not be removed after the page loaded. will help check if it is a write protected error i think its chmod 1777 needed.

read the apache error log  ::)

Link to comment
Share on other sites

All of it? >_<  Or only the relevant rows?

 

Anyway, here is the file upload relevant rows but I know it can't be from here.

;;;;;;;;;;;;;;;;
; File Uploads ;
;;;;;;;;;;;;;;;;

; Whether to allow HTTP file uploads.
file_uploads = On

; Temporary directory for HTTP uploaded files (will use system default if not
; specified).
upload_tmp_dir = "${path}\\tmp\"

; Maximum allowed size for uploaded files.
upload_max_filesize = 5000M

 

Also I can't post all of the php.ini file it's too big. Should I upload it somewhere?

My OS is Windows XP .. I am just building my site-project in my computer before uploading it in a web host. As I said before I am using easyphp, a bundle of php-mysql-apache.

 

Also the code you proposed for me to use will not work. It will throw an undefined index 'userpic' error. I had already tried something similar before. The $_FILES array is empty.

 

It can't be a permissions problem since I tried with file_put_contents to write a simple .txt file in apache's tmp directory and I was succesfull.

 

 

Link to comment
Share on other sites

what is the web hosts OS? and no that is enough info from your php.ini file :P

 

also have u tried this

 

; Whether to allow HTTP file uploads.
file_uploads = On

; Temporary directory for HTTP uploaded files (will use system default if not
; specified).
;upload_tmp_dir = "${path}\\tmp\"

; Maximum allowed size for uploaded files.
upload_max_filesize = 5000M

Link to comment
Share on other sites

arrrrrrrrrrr "apache php and MySQL all in a nice bundle"

 

Ok i think i know what is the problem.

 

make a new file

 

info.php

inside it write

<?php

echo phpinfo();

?>

 

now view this page and look at (Loaded Configuration File) is this the php.ini file you have been edited? go check as them bundles normal have a few php.ini files.

 

Also do a search on that page for

file_uploads

upload_max_filesize

upload_tmp_dir

 

Link to comment
Share on other sites

Actually you were right but still this was not the problem. The php ini file I was editing was different but the one from phpinfo() had this on top of it :

 

;------------------------ IMPORTANT ! ----------------------
; This file is GENERATED by EasyPHP when needed so edit the
; file C:\PROGRA~1\EASYPH~1.0B1\conf_files\php.ini if you want to do
; modifications in this file
;-----------------------------------------------------------

 

Not to mention that C:\PROGRA~1\EASYPH~1.0B1\conf_files\php.ini was the one I was editing so everything is the same :(

Link to comment
Share on other sites

Yeah well mate I very much agree with you. I have been stuck with this for 3 days now. I can't stand it any more. I have nothing to lose by trying another package. I have everything saved and ready to transfer anyway. I can't stall my project anymore for such a silly mistake/bug.

 

 

Thanks for devoting your time trying to help me :)

Link to comment
Share on other sites

I am really sorry for bumping my own post but this is ridiculous. I completely uninstalled EasyPhP and saved all of my work in a  separate file. I downloaded the XAMPP php/apache/mysql bundle and installed it. Then moved all of my work in the new server, re-made all of my configurations and was good to go.

 

I really thought that it would work. BUT NO! Still ... $_FILES is empty after uploading. I don't know what to do anymore. This was like the last resort ... and it did not work.

 

I am including the whole .php file for which I am talking about ( the one where the user file upload form is ):

<?php session_start(); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><!-- InstanceBegin template="/Templates/mainSiteTemplate.dwt.php" codeOutsideHTMLIsLocked="false" -->
<head> 
<!-- InstanceBeginEditable name="headerstuff" -->
<title>Settings</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="/CSS/mainStyle.css" rel="stylesheet" type="text/css" />
<link href="/CSS/profileStyle.css" rel="stylesheet" type="text/css" />
<link href="/CSS/settingsStyle.css" rel="stylesheet" type="text/css" />
<script type='text/javascript' src='animateScript2.js'></script>
<!-- InstanceEndEditable -->
</head>

<body>
<div id="pageLogo"></div>

<div id="pageHead"></div>

<div id="leftMenu"> 

<?php
//With the page loading we make sure we instantiate a GLOBAL sql connection object
include ('sqlConnection.php');
global $sql;
$sql = new sqlConnection("localhost", "XXXX", "XXXX");
include("login.php");
displayLogin(); 
?>

</div>


                        <div id="tabMenu">
                                <ul>
                                        <!-- CSS Tabs -->
<li id="current"><a href="index.php"><span><h1>Home</h1></span></a></li>
<li><a href="register.php"><span><h1>REGISTER</h1></span></a></li>
<li><a href='#'><span><h1>USERS</h1></span></a></li>
<li><a href='#'><span><h1>PROJECTS</h1></span></a></li>
<li><a href='#'><span><h1>ABOUT</h1></span></a></li>
                                </ul>
                        </div>



<div id="centerOfPage">
<!-- InstanceBeginEditable name="head" -->
<?php
error_reporting(E_ALL);
global $sql;
//if no user is logged in then .. do now allow to edit setting ofcourse
if(!isset($_SESSION['username']))
echo"You are not logged in. Please log in or register first";
else
{
//get the user who is logged in now!
$username = $_SESSION['username'];
$resArray = $sql->selectUser($username);

//if the user has not uploaded an image for himself show the default
if($resArray['userImage'] == null)
{
?>
    <div id="userImage">
    </div> 
    <?php
}
else
{//else .. show the image he uploaded
?>
<div id="userImage">
    <img src="getUImage.php?usname=<?php echo($username);?>" />
    </div> 
    <?php
}
?>
    <div id="imageEdit">
    	<!--The small form to submit a user image,if it is used refresh the settings page-->
        <form enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
        <input type="hidden" name="MAX_FILE_SIZE" value="200000" />
        Want to change your picture?<input type="file" name="userpic" id="userpic" />
        <input name="subpic" type="submit" value="Upload New Picture" />
        </form>
	<?php eleos();?>
    </div>
    <?php
}

?>
  <!-- InstanceEndEditable -->
</div>


</body>
<!-- InstanceEnd --></html>

<?php
function eleos()
{
//if the user clicks the submit picture button
if(isset($_POST['subpic']))
{

//phpinfo(1);


print_r($_FILES);


}
}?>

 

And also the new php.ini part for the file uploading which I ofcourse checked if it is okay.

;;;;;;;;;;;;;;;;
; File Uploads ;
;;;;;;;;;;;;;;;;

; Whether to allow HTTP file uploads.
file_uploads = On

; Temporary directory for HTTP uploaded files (will use system default if not
; specified).
upload_tmp_dir = "C:\xampp\tmp"

; Maximum allowed size for uploaded files.
upload_max_filesize = 32M

 

I tried escaping the 2 slashes the tmp dir which would have caused a problem if I typed it as a path. Specifically \t and \x but

it did not work. Seems that php must do that automatically when reading where the server's tmp path is.

Link to comment
Share on other sites

Your form code works (tested) and the $_FILES array is set on a system where uploads are known to work.

 

Both the $_POST and $_FILES arrays would be empty if the post maximum size is exceeded. You don't actually state if the code using isset($_POST['subpic']) is executed. What exactly do your get for output from the print_r() statement?

 

Your php.ini settings only matter if php is actually reading and using them. Using a phpinfo(); statement what are the actual runtime values of the following -

 

Loaded Configuration File

file_uploads

post_max_size

upload_max_filesize

upload_tmp_dir

 

Put these two lines immediately after your first opening <?php tag -

 

ini_set ("display_errors", "1");
error_reporting(E_ALL);

 

Lastly, while this has nothing to do with the current problem, the global keyword only has meaning inside of a function definition. The following line (two separate places in your file) in your code has no effect and should be removed -

 

global $sql;

Link to comment
Share on other sites

Thank you very much for your reply. As for the global $sql. As you can see it represents an sqlConnection object ... just a helper object I have made with various sql functions for my project. And yes you are right! It is only for functions! I did not know that. I had used it in a function the first time and then I thought that global was needed everywhere.  Thanks a lot for pointing that out!

 

Now, on to the matter at hand:

 

Yes the code in the isset($_POST['subpic']) is executed. I print both $_POST and $_FILES.

 

With print_r :

Array ( )
Array ( [MAX_FILE_SIZE] => 100048576 [userpic] => schematic.jpg [subpic] => Upload New Picture ) 

 

The first array is the $_FILES ... unfortunately :( As you can see I changed the MAX_FILE_SIZE to around 100MB. I did so in php.ini too, for no particular reason.

 

Yes php is reading php.ini . Proof for that is the following straight from phpinfo();  :

 

Loaded Configuration File C:\xampp\apache\bin\php.ini

file_uploads On On

post_max_size 16M 16M

upload_max_filesize 100M 100M

upload_tmp_dir C:\xampp\tmp C:\xampp\tmp

 

As for the

ini_set ("display_errors", "1");
error_reporting(E_ALL);

 

I put it in the start of my first php code but nothing was shown :(.

 

Hope you can help me with this. Until I get a reply I will just keep googling and checking for every little thing.

Link to comment
Share on other sites

[userpic] is showing up in your $_POST array. For the code/form you posted, that is impossible. Either your form, your browser, or your web server/php is not processing the type="file" input field correctly.

 

I just went back and tested your form with both FF and IE and it submits the expected $_FILES array, so there is not a problem with the html.

 

Is there a chance that an earlier version of the code had a type="input" and somehow a cached version of that is getting used? Clear your browser cache and see what happens. Try a different browser if you have one available.

 

Basically, something with your browser or server/php is causing this.

Link to comment
Share on other sites

Thanks for the input mate but actually it can't be an older browser cache since I never made this form with type anything but file.

 

On the same time it can't be a php/server configuration matter! Since I completely uninstalled the easyphp configuration saved my htmldocs from it and reinstalled another bundle (XAMPP) and moved my project and made configurations from scratch there.

 

Still it did not work. I just tried 3 different browsers (IE,Opera,Firefox) and got the same empty $_FILES array. Yes, I got to admit that it sounds more and more like a php/server problem. But...

 

what problem? That was my line of thinking yesterday night too, and the result was a complete uninstallation and reinstallation with another package. Getting the same result with another package should rule out that possibility, right? But if it is not that then? What? I have to admit I am completely buffled as to what I am to do next.

 

Maybe ... try to find other ways to upload files via php .... if they exist? :/

Link to comment
Share on other sites

There are literally 100's of thousands of web sites uploading files using the method you are trying.

 

Since you are getting consistent results (failure), something has remained the same. In my testing, I commented out the include files and faked out the login since I did not have those pieces of code. At this point, I would say that either the code in include('sqlConnection.php'); or include("login.php"); is clearing or overwriting the $_FILES array and is setting [userpic] in the $_POST array. Posting those two files would help (perhaps there is some foreach loop that is attempting to sanitize form data.)

 

I would also recommend making a simple file with just your form and then doing a print_r($_FILES) on the page it submits to in order to see if just the basic code will work will work.

 

Another thing that could overwrite variables is register_globals. I hope that you don't have them turned on.

Link to comment
Share on other sites

OH MY GOD.

 

Why did it not cross my mind to just isolate the form in a separate file.

 

I followed your advice with this sample form :

<html>
<body>

<form enctype="multipart/form-data" name="testF" id="testF" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input type="hidden" id="MAX_FILE_SIZE" name="MAX_FILE_SIZE" value="100048576" />
Enter file:<input type="file" name="tfile" id="tfile" />
<input type="submit" name="sub" id="sub" value="Upload" />
</form>
<?php

if(isset($_POST['sub']))
{
echo("Sub clicked, got in!");
echo("<br />");
print_r($_FILES);
}

?>
</body>
</html>

 

Guess what I got?

Array ( [tfile] => Array ( [name] => eleos.png [type] => image/png [tmp_name] => C:\xampp\tmp\php19.tmp [error] => 0 [size] => 2397 ) )

 

It is actually the first time I see a $_FILES being displayed. I did not know what to expect until now :)

Which means ... that something in the other part of the code messes with ... $_FILES? Makes no sense ... this is the first time I tried to add anything file related to my site. login.php and sqlConnection both mess with my sql database and with session variables and cookies.

    That in mind, I will debug carefully, and debug CODE now. At least now I DO know it is not settings. It is a huge step forward. I will post again when and if I find what it was.

Link to comment
Share on other sites

OK HERE IT IS! :

 

Login.php contained 2 more forms. As one would expect of a login script ofcourse. I spent the last 2 days searching for empty $_FILES reasons so I learned many different reason why this would happen.

        One of those was that if you have more forms in the same file with your file upload form you have to add the enctype="multipart/form-data" attribute in them too. I just did that and it works now. So yeah ... ahem ... what can I say? I feel stupid for what I went through the last 2 days to find this. Even installing a different server .... *sigh*

 

Thanks all of you. Honestly. Especially PFMaBiSmAd, without your hint about running it standalone I would never have found it!

Link to comment
Share on other sites

Hm... that too. It WAS missing a </form> tag. So it was considering it the same form... and by putting a enctype attribute it got corrected(in a wrong way :P ).

 

Now by closing the open <form> tag no enctype attribute is needed. Even more solved than before. Phew ...

 

I can really sleep like a baby now :)

Link to comment
Share on other sites

  • 14 years later...

It's 2023 and I just had the exact same issue. Here is how I solved mine (hopefully stopping someone in the future from having a headache!)

<!doctype html>
<html lang="en" data-bs-theme="dark">

<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
</head>

<body>
	<form method="post" enctype="multipart/form-data" id="formid" action="php/submit_file.php">
		<div class="form-floating mb-3">
			<label for="job_file" class="form-label">Photos</label>
			<input type="file" id="job_file" name="job_file[]" placeholder="file" 
				class="form-control" aria-describedby="job_fileHelp" form="form" accept="image/*"
				onfocus="$('.help').hide();$('#job_fileHelp').show();" value="" multiple>
		</div>
		
		<button type="submit" id="submit" class="btn btn-primary">Submit</button>
	</form>
	<div id="message"></div>
	<script src="https://code.jquery.com/jquery-3.6.4.min.js" crossorigin="anonymous"
		integrity="sha256-oP6HI9z1XaZNBrJURtCoUT5SUnxFr8s3BzRl+cbzUq8="></script>
</body>
</html>

And for the PHP:

<?php

$data = array(
	'success' => false,
	'error' => '',
	'debug' => [
		'$_POST' => $_POST,
		'$_FILES' => $_FILES,
		'post_max_size' => ini_get('post_max_size'),
		'upload_max_filesize' => ini_get('upload_max_filesize'),
		'file_uploads' => ini_get('file_uploads')
	]
);

/*
Do some processing here
*/

if ($data['error'] == '') {
	$data['success'] = true;
}

header('Content-Type: application/json');
echo json_encode($data); //basically converts php arrays into js objects

On submitting the form, I would always get an empty $_FILES array:

{"success":true,"error":"","debug":{"$_POST":[],"$_FILES":[],"post_max_size":"20M","upload_max_filesize":"20M","file_uploads":"1"}}

 

What I did to solve my issue was the html form had an ID of "formid", but the input tag was attached to the form with ID of "form". I didn't think it actually mattered to PHP, but apparently it does.

Link to comment
Share on other sites

39 minutes ago, kurdtpage said:

What I did to solve my issue was the html form had an ID of "formid", but the input tag was attached to the form with ID of "form". I didn't think it actually mattered to PHP, but apparently it does.

It doesn't matter to PHP. It does matter to HTML and your browser. Because you told it that the button should be connected to some form named "form".

The real problem is that you were specifying a form attribute at all. 99% of the time you should not: just make sure the button is contained within the <form> and you're set. The only purpose of the form attribute is to associate the button (or other input element) with a <form> that's somewhere else on the page.

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.