PHP로 파일을 업로드 할 때 $ _FILES가 비어있는 이유는 무엇입니까?
Windows 7 컴퓨터에 WampServer 2가 설치되어 있습니다. Apache 2.2.11 및 PHP 5.2.11을 사용하고 있습니다. 양식에서 파일을 업로드하려고하면 업로드하는 것처럼 보이지만 PHP에서는 $_FILES배열이 비어 있습니다. c:\wamp\tmp폴더에 파일이 없습니다 . php.ini파일 업로드 등을 허용 하도록 구성 했습니다. tmp폴더는 현재 사용자에 대한 읽기 / 쓰기 권한을하고있다. 나는 충격을 받았다.
HTML :
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<form enctype="multipart/form-data" action="vanilla-upload.php" method="POST">
Choose a file to upload: <input name="uploadedfile" type="file" /><br />
<input type="submit" value="Upload File" />
</form>
</body>
</html>
PHP :
<?php
echo 'file count=', count($_FILES),"\n";
var_dump($_FILES);
echo "\n";
?>
다음은 PHP에서 파일을 업로드하기위한 점검 목록입니다.
php.ini에서 다음을 확인하십시오.
file_uploads = On
post_max_size = 100M
upload_max_filesize = 100M- 공유 호스팅 을 사용
.htaccess중이거나에.user.ini액세스 할 수없는 경우 사용해야합니다php.ini. - 올바른 ini 파일을 편집하고 있는지 확인하십시오.이
phpinfo()기능을 사용하여 설정이 실제로 적용되는지 확인하십시오. - 또한 크기를 잘못 입력하지 않아야합니다 .
100M그렇지 않아야합니다100MB.
- 공유 호스팅 을 사용
<form>태그에enctype="multipart/form-data"속성 이 있는지 확인하십시오 . 다른 태그는 작동하지 않으며 FORM 태그 여야합니다. 철자 가 올바른지 다시 확인하십시오 . multipart / form-data가 Word 또는 웹 사이트 블로그에서 붙여 넣은 스마트 따옴표가 아닌 STRAIGHT QUOTES로 둘러싸여 있는지 다시 확인하십시오 (WordPress는 직선 따옴표를 각도 따옴표로 변환합니다!). 페이지에 여러 양식이있는 경우 둘 다이 속성이 있는지 확인하십시오. 수동으로 입력하거나 직접 입력 한 작은 따옴표를 사용해보십시오.동일한
name속성을 가진 두 개의 입력 파일 필드가 없는지 확인하십시오 . 여러 개를 지원해야하는 경우 이름 끝에 대괄호를 넣으십시오.<input type="file" name="files[]"> <input type="file" name="files[]">tmp 및 upload 디렉토리에 올바른 읽기 + 쓰기 권한이 설정되어 있는지 확인하십시오. 임시 업로드 폴더는 PHP 설정에서로 지정됩니다
upload_tmp_dir.파일 대상 및 tmp / upload 디렉토리에 공백이 없는지 확인하십시오.
<form>페이지의에 모두</form>가까운 태그 가 있는지 확인하십시오 .FORM 태그에가 있는지 확인하십시오
method="POST". GET 요청은 멀티 파트 / 양식 데이터 업로드를 지원하지 않습니다.파일 입력 태그에 NAME 속성이 있는지 확인하십시오. ID 속성으로는 충분하지 않습니다! ID 속성은 POST 페이로드가 아닌 DOM에서 사용하기위한 것입니다.
<input type="file">제출시 필드 를 비활성화하기 위해 Javascript를 사용하지 않아야 합니다.다음과 같은 양식을 중첩하지 않아야합니다.
<form><form></form></form>HTML 구조에서 유효하지 않거나 겹치는 태그가 있는지 확인하십시오.
<div><form></div></form>또한 업로드중인 파일에 영숫자가 아닌 문자가 없는지 확인하십시오.
한 번, 나는 이것이 왜 갑자기 이런 일이 일어나고 있는지 알아 내려고 몇 시간을 보냈습니다. 에서의 일부 PHP 설정을 수정했으며 그
.htaccess중 하나 (아직 확실하지 않음)로 인해 업로드가 실패하고$_FILES비어있는 것으로 나타 났습니다 .태그 속성
_에서 밑줄 ( )을 피할 수 있습니다.name=""<input>파일 크기 문제인지 여부를 좁히려면 아주 작은 파일을 업로드하십시오.
사용 가능한 디스크 공간을 확인하십시오. 매우 드물지만이 PHP 매뉴얼 페이지 주석에 언급되어 있습니다 .
양식이 올바른 것처럼 보이지만 $ _FILES 배열이 갑자기 신비 로워지면 임시 폴더 파티션에 사용 가능한 디스크 공간을 확인해야합니다. 설치시 모든 파일 업로드가 경고없이 실패했습니다. 치아가 많이 찢어지면 추가 공간을 확보하려고 시도한 후 파일 업로드가 갑자기 다시 작동했습니다.
페이지를 다시로드하는 일반적인 POST 요청 대신 AJAX POST 요청을 통해 양식을 제출하지 않아야합니다. 위의 목록에서 각각의 모든 포인트를 살펴보고 $ _FILES 변수가 비어있는 이유는 AJAX POST 요청을 사용하여 양식을 제출했기 때문이라는 것을 알았습니다. 나는 아약스를 사용하여 파일을 업로드하는 방법이 있다는 것을 알고 있지만 이것이 $ _FILES 배열이 비어있는 유효한 이유 일 수 있습니다.
Source for some of these points:
http://getluky.net/2004/10/04/apachephp-_files-array-mysteriously-empty/
As far as the HTML you appear to have set that part up correctly. You already have the enctype="multipart/form-data" which is very important to have on the form.
As far as your php.ini setup, sometimes on systems multiple php.ini files exist. Be sure you are editing the correct one. I know you said you have configured your php.ini file to have file uploads, but did you also set your upload_max_filesize and post_max_size to be larger than the file you are trying to upload? So you should have:
file_uploads = On; sounds like you already did this
post_max_size = 8M; change this higher if needed
upload_max_filesize = 8M; change this higher if needed
Does your directory: "c:\wamp\tmp" have both read and write permissions? Did you remember to restart Apache after you made the php.ini changes?
It is important to add enctype="multipart/form-data" to your form, example
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
Thank you everybody for the vary comprehensive replies. Those are all very helpful. The answer turned out to be something very odd. It turns out that PHP 5.2.11 doesn't like the following:
post_max_size = 2G
or
post_max_size = 2048M
If I change it to 2047M, the upload works.
Here another cause I found: When using JQuery Mobile and the form attribute data-ajax is set to true, the FILES array will be empty. So set data-ajax to false.
I have a same problem looking 2 hours ,is very simple to we check our server configuration first.
Example:
echo $upload_max_size = ini_get('upload_max_filesize');
echo $post_max_size=ini_get('post_max_size');
any type of file size is :20mb, but our upload_max_size is above 20mb but array is null. Answer is our post_max_size should be greater than upload_max_filesize
post_max_size = 750M
upload_max_filesize = 750M
Make sure your input element has a 'name' attribute. <input type="file" name="uploadedfile" />
If this is missing the $_FILES will be empty.
I was struggling with the same problem and testing everything, not getting error reporting and nothing seemed to be wrong. I had error_reporting(E_ALL) But suddenly I realized that I had not checked the apache log and voilà! There was a syntax error on the script...! (a missing "}" )
So, even though this is something evident to be checked, it can be forgotten... In my case (linux) it is at:
/var/log/apache2/error.log
No one mentioned this but it helped me out and not many places on the net mention it.
Make sure your php.ini sets the following key:
upload_tmp_dir="/path/to/some/tmp/folder"
You'll need to check with your webhost if they want you to use an absolute server file path. You should be able to see other directory examples in your php.ini file to determine this. As soon as I set it I got values in my _FILES object.
Finally make sure that your tmp folder and wherever you are moving files to have the correct permissions so that they can be read and written to.
If you are trying to upload an array of files then you may need to increase max_file_uploads in php.ini which is by default set to 20
Note: max_file_uploads can NOT be changed outside php.ini. See PHP "Bug" #50684
Another possible culprit is apache redirects. In my case I had apache's httpd.conf set up to redirect certain pages on our site to http versions, and other pages to https versions of the page, if they weren't already. The page on which I had a form with a file input was one of the pages configured to force ssl, but the page designated as the action of the form was configured to be http. So the page would submit the upload to the ssl version of the action page, but apache was redirecting it to the http version of the page and the post data, including the uploaded file was lost.
Check your php.ini for enable_post_data_reading=On , because:
Disabling this option causes $_POST and $_FILES not to be populated. The only way to read postdata will then be through the php://input stream wrapper. (... )
In http://php.net/manual/en/ini.core.php#ini.enable-post-data-reading
I ran into the same issue and found that it was my IDE was part of the issue. I was launching the debugger directly from the IDE (PHPStorm) instead of just using the browser directly. The IDE spawned URL was like this:
"...localhost:63342/CB_Upload/index.php?_ijt=j2hcbacqepj87bvg66ncuohvne"
and just using:
"...localhost/CB_Upload/index.php"
worked just fine. My set up is PC / Windows 10 / WAMPSERVER 3.0.6 64bit
Do not trust the temp folder location provided by sys_get_temp_dir if you're in a shared hosting environment.
Here is one more thing to check that has not yet been mentioned...
I assumed, naturally, that the folder where my PHP script stored temporary file uploads was /tmp. This belief was reinforced by the fact that echo sys_get_temp_dir() . PHP_EOL; returns/tmp. Also, echo ini_get('upload_tmp_dir'); returns nothing.
To verify that the uploaded file does in fact briefly appear in my /tmp folder, I added a sleep(30); statement to my script (as suggested here) and navigated to my /tmp folder in cPanel File Manager to locate the file. However, no matter what, the uploaded file was nowhere to be found there.
I spent hours trying to determine the reason for this, and implemented every suggestion that's been offered here.
Finally, after searching my website files for the query tmp, I discovered that my site contained other folders named tmp in different directories. I realized that my PHP script was actually writing the uploaded files to .cagefs/tmp. (The "Show Hidden Files" setting must be enabled in cPanel in order to view this folder.)
So, why does the sys_get_temp_dir function return inaccurate info?
Here's an explanation from the PHP.net webpage for sys_get_temp_dir (i.e., the top comment):
If running on a Linux system where systemd has PrivateTmp=true (which is the default on CentOS 7 and perhaps other newer distros), this function will simply return "/tmp", not the true, much longer, somewhat dynamic path.
This SO post delves into the issue, as well:
I got the same problem and none of theme was my error. Check in your .htaccess file, if you got one, if "MultiViews" are enabled. I had to disable them.
If your main script is http://Some_long_URL/index.php be carefull to specify the full URL (with explicit index.php and not only http://Some_long_URL) in the action field. Surprisingly, if not, the right script is executed, but with en empty $_FILES !
I had similar problem and the issue was in wrong value in htaccess as shamittomar mentioned.
Change php_value post_max_size 10MB to php_value post_max_size 10M
I was empty $_FILES because after <form enctype="multipart/form-data" method="post"> i placed
</div>
<div style="clear:both"></div>
Initial code was like
<span class="span_left">Photos (gif/jpg/jpeg/png) </span>
<form enctype="multipart/form-data" method="post">
<input name="files[]" type="file" id="upload_file" />
<input type="button" id="upload" value="Upload photo" />
</form>
I decided to modify and
<div>
<span class="span_left">Photos (gif/jpg/jpeg/png) </span>
<form enctype="multipart/form-data" method="post">
</div>
<div style="clear:both"></div>
<input name="files[]" type="file" id="upload_file" />
<input type="button" id="upload" value="Upload photo" />
</form>
<div style="clear:both"></div>
So conclusion is that after <form enctype="multipart/form-data" method="post"> must be <input name, type, id and must not be <div> or some other tags
In my situation correct code was
<div>
<span class="span_left">Photos (gif/jpg/jpeg/png) </span>
</div>
<div style="clear:both"></div>
<form enctype="multipart/form-data" method="post">
<input name="files[]" type="file" id="upload_file" />
<input type="button" id="upload" value="Upload photo" />
</form>
<div style="clear:both"></div>
I too had problems with $_FILES empty. The above check-list do not mention MultiViews in .htaccess, httpd.conf or httpd-vhost.conf.
If you have MultiViews set in the options directive for your directory containing the web site, $_FILES will be empty, even though Content-Length header if showing that the file i uploaded.
If you are using JQuery Mobile
Using a multipart form with a file input is not supported by Ajax. In this case you should decorate the parent form with data-ajax="false" to ensure the form is submitted properly to the server.
<form action="upload.php" method="post" enctype="multipart/form-data" data-ajax="false">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
참고URL : https://stackoverflow.com/questions/3586919/why-would-files-be-empty-when-uploading-files-to-php
'Programming' 카테고리의 다른 글
| ViewPager를 사용하여 Google Maps V2를 조각에 배치하는 방법 (0) | 2020.07.01 |
|---|---|
| 보기가 나타나기 전에 iPhone에서 UITableView의 맨 아래로 스크롤하는 방법 (0) | 2020.07.01 |
| “라이브러리를 찾을 수 없습니다”오류 (0) | 2020.07.01 |
| 일상 생활에서 가장 유용한 스크립트는 무엇입니까? (0) | 2020.07.01 |
| Java : int 배열은 0이 아닌 요소로 초기화됩니다. (0) | 2020.07.01 |