programing

양식 제출시 PHP $ _POST 배열이 비어 있음

nasanasas 2020. 9. 4. 07:32
반응형

양식 제출시 PHP $ _POST 배열이 비어 있음


내 개발 상자 (Ubuntu / PHP5 + / MySQL5 +)에서 완벽하게 작동하는 사용자 지정 CMS가 있습니다.

방금 클라이언트의 프로덕션 상자로 옮겼고 이제 모든 양식 제출이 빈 $ _POST 배열로 표시됩니다.

데이터가 실제로 전달 file_get_contents('php://input');되고 있고 데이터가 잘 표시 되는지 확인하는 트릭을 찾았 습니다. $_POST/ $_REQUEST배열은 항상 비어 있습니다.

또한 방화범 ( application/x-www-form-urlencoded; charset=utf-8)을 통해 콘텐츠 유형 헤더가 올바른지 확인했습니다 .

이 문제는 양식이 AJAX를 통해 제출되는지 또는 일반 양식 제출인지에 관계없이 발생합니다.

어떤 도움이라도 대단히 감사합니다!


이 질문은 양식을 통한 POST에 관한 것이지만 JSON 콘텐츠 유형으로 게시 할 때 유사한 문제에 대한 답변을 찾고 있습니다. 시간이 많이 걸리므로 답을 찾고 공유하고 싶었습니다.

JSON 콘텐츠 유형을 사용할 때 $ _POST 배열이 채워지지 않습니다 (내가 믿는 다중 파트 형식에서만).

문제를 해결하기 위해 작업 한 내용은 다음과 같습니다.

$rest_json = file_get_contents("php://input");
$_POST = json_decode($rest_json, true);

이것이 누군가를 돕기를 바랍니다!


또 다른 가능한 원인이 있습니다. 제 양식이 WWW없이 domain.com에 제출되었습니다. "WWW"를 추가하기 위해 자동 리디렉션을 설정했습니다. 프로세스에서 $ _POST 배열이 비워졌습니다. 이 문제를 해결하려면 www.domain.com에 제출하기 만하면되었습니다.


비슷한 문제가있었습니다. 간단한 수정으로 판명되었습니다. 내가 가진 형태로

<form action = "directory"method = "post">

여기서 directory는 디렉토리의 이름입니다. 내 POST 어레이가 완전히 비어 있습니다. 내 브라우저에서 URL을 보았을 때 끝에 슬래시가 표시되었습니다.

내 작업 끝에 슬래시를 추가하면 트릭이 발생했습니다.

<form action = "directory /"method = "post">

내 $ _POST 어레이가 다시 가득 찼습니다!


php.ini에서 다음을 확인하십시오.

  • track_vars (아주 오래된 PHP 버전에서만 사용 가능) On
  • variables_order 편지를 포함 P
  • post_max_size 적절한 값 (예 : 8MB)으로 설정됩니다.
  • (수호신 패치를 사용하는 경우) suhosin.post.max_varssuhosin.request.max_vars대형 충분합니다.

내 두 번째 제안이 문제를 해결할 것이라고 생각합니다.


HTTP에서 HTTPS로 게시 할 때 $_POST비어있는 것으로 나타났습니다 . 이것은 양식을 테스트하는 동안 발생했지만 그것을 깨닫기까지 시간이 걸렸습니다.


비슷하지만 약간 다른 문제를 발견했으며 문제를 이해하는 데 2 ​​일이 걸렸습니다.

  • 제 경우에도 POST 배열이 비어 있습니다.

  • 그런 다음 file_get_contents ( 'php : // input'); 그리고 그것도 비어있었습니다.

나중에 브라우저가 POST 제출 후로드 된 페이지를 새로 고치면 양식 데이터를 다시 제출할지 확인을 요청하지 않는 것을 발견했습니다. 직접 새로 고침 페이지였습니다. 그러나 양식 URL을 다른 URL로 변경하면 POST를 제대로 전달하고 페이지를 새로 고치려고 할 때 데이터를 다시 제출하도록 요청했습니다.

그런 다음 실제 URL에 무엇이 잘못되었는지 확인했습니다. URL에 결함이 없었지만 URL에 index.php가없는 폴더를 가리키고 있으며 index.php에서 POST를 확인했습니다.

여기에서 /에서 /index.php 로의 리디렉션으로 인해 POST 데이터가 손실되고 URL에 index.php를 추가하여 테스트 된 URL이 발생하는지 의심했습니다.

작동했습니다.

누군가가 도움이 될 수 있도록 여기에 게시했습니다.


이 시점에서 우아한 해결책은 없지만이 문제에 직면 한 다른 사람들의 향후 참조를 위해 내 결과를 공유하고 싶었습니다. 문제의 원인은 .htaccess 파일에있는 2 개의 재정의 된 php 값이었습니다. 파일 업로드에 대한 파일 크기 제한을 기본 8MB에서 더 큰 값으로 늘리기 위해이 두 값을 간단히 추가했습니다. .

php_value post_max_size xxMB
php_value upload_max_filesize xxMB

모든 suhosin.post.xxx/suhosin.upload.xxx vars에 대한 제한을 높이기 위해 추가 변수를 추가했지만 불행히도이 문제에 영향을 미치지 않았습니다.

요약하면 여기서 "이유"를 설명 할 수는 없지만 근본 원인을 확인했습니다. 내 느낌은 이것이 궁극적으로 suhosin / htaccess 문제이지만 불행히도 위의 2 PHP 재정의 값을 제거하는 것 외에는 해결할 수 없었던 문제입니다.

내가 이것을 알아내는 데 몇 시간을 죽였을 때 이것이 미래의 누군가에게 도움이되기를 바랍니다. 시간을내어 도와 주신 모든 분들께 감사드립니다 (MrMage, Andrew)


기본값은 "text / plain"이므로 enctype = "application / x-www-form-urlencoded"를 사용하여 문제를 해결할 수 있습니다. $ DATA를 체크인 할 때 구분자는 "text / plain"을위한 공백과 "urlencoded"를위한 특수 문자입니다.

친절한 안부 프랭크


갖는 enable_post_data_reading설정을 비활성화하면이 발생합니다. 문서에 따르면 :

enable_post_data_reading

이 옵션을 비활성화하면 $ _POST 및 $ _FILES가 채워지지 않습니다. postdata를 읽는 유일한 방법은 php : // input 스트림 래퍼를 통하는 것입니다. 이는 요청을 프록시하거나 메모리 효율적인 방식으로 POST 데이터를 처리하는 데 유용 할 수 있습니다.


예를 들어 /api/index.php와 같은 디렉토리의 index.php 파일에 게시하는 경우 양식에서 파일에 대한 전체 디렉토리를 지정했는지 확인하십시오.

<form method="post" action="/api/index.php"> 
</form>

또는

<form method="post" action="/api/"> 
</form>

공장.

그러나 이것은 실패합니다

<form method="post" action="/api"> 
</form>

<form action="test.php" method="post">
                        ^^^^^^^^^^^^^

좋아, 이것은 어리석은 일이었고 공개적으로 내 자신을 당황하게 할 것입니다.하지만 PHP에서 무언가에 대한 약간의 테스트 스크립트를 $_POST깨뜨 렸고 배열이 비어 있을 때 StackOverflow가 내가 처음 보았고 필요한 답을 찾지 못했습니다. .

나는 단지 썼다

<form action="test.php">

방법을 POST! 로 지정하는 것을 잊었습니다 .

I am sure someone will snigger, but if this helps someone else who does the same thing, then I don't mind! We all do it from time to time!


same issue here!

i was trying to connect to my local server code via post request in postman, and this problem wasted my time alot!

for anyone who uses local project (e.g. postman): use your IPv4 address (type ipconfig in cmd) instead of the "localhost" keyword. in my case:

before:

localhost/app/login

after:

192.168.1.101/app/login

REFERENCE: http://www.openjs.com/articles/ajax_xmlhttp_using_post.php

POST method

We are going to make some modifications so POST method will be used when sending the request...

var url = "get_data.php";
var params = "lorem=ipsum&name=binny";
http.open("POST", url, true);

//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");

http.onreadystatechange = function() {//Call a function when the state changes.
  if(http.readyState == 4 && http.status == 200) {
    alert(http.responseText);
  }
}
http.send(params);

Some http headers must be set along with any POST request. So we set them in these lines...

http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");

With the above lines we are basically saying that the data send is in the format of a form submission. We also give the length of the parameters we are sending.

http.onreadystatechange = function() {//Call a function when the state changes.
  if(http.readyState == 4 && http.status == 200) {
    alert(http.responseText);
  }
}

We set a handler for the 'ready state' change event. This is the same handler we used for the GET method. You can use the http.responseText here - insert into a div using innerHTML(AHAH), eval it(JSON) or anything else.

http.send(params);

Finally, we send the parameters with the request. The given url is loaded only after this line is called. In the GET method, the parameter will be a null value. But in the POST method, the data to be send will be send as the argument of the send function. The params variable was declared in the second line as lorem=ipsum&name=binny - so we send two parameters - 'lorem' and 'name' with the values 'ipsum' and 'binny' respectively.


In my case it was because I was using jQuery to disable all inputs on the page just before using jQuery to submit the form. So I changed my "disable every input even the 'hidden' types":

$(":input").attr("disabled","disabled"); 

to "disable only the 'button' type inputs":

$('input[type=button]').attr('disabled',true);

This was so the user couldn't accidentally hit the 'go' button twice and hose up our DB! It seems that if you put the 'disabled' attribute on a 'hidden' type form input their values won't be sent over if the form is submitted!


For me, .htaccess was redirecting when mod_rewrite wasn't installed. Install mod_rewite and all is fine.

Specifically:

<IfModule !mod_rewrite.c>
  ErrorDocument 404 /index.php
</Ifmodule>

was executing.


I just spent hours to fix a similar issue. The problem in my case, was the the

max_input_vars = "1000"

by default, in the php.ini. I had a really huge form without uploads. php.ini is set to upload_max_filesize = "100M" and post_max_size = "108M" and it was surely not the issue in my case. PHP behavior is the same for max_input_vars when it exceeds 1000 variables in the form. It returns and empty _POST array. I wish I could have found that one hours, and hours ago.


I know this is old, but wanted to share my solution.

In my case the issue was in my .htaccess as I added variables to raise my PHP's max upload limit. My code was like this:

php_value post_max_size 50MB
php_value upload_max_filesize 50MB

Later I notice that the values should like xxM not xxMB and when I changed it to:

php_value post_max_size 50M
php_value upload_max_filesize 50M

now my $_POST returned the data as normal before. Hope this helps someone in the future.


In addition to MRMage's post:

I had to set this variable to solve the problem that some $_POST variables (with an large array > 1000 items) disappeared:

suhosin.request.max_vars = 2500

"request", not "post" was the solution...


Not the most convenient solution perhaps, but I figured it out that if I set the form action attribute to the root domain, index.php can be accessed and gets the posted variables. However if I set a rewritten URL as action, it does not work.


This is sort of similar to what @icesar said.

But I was trying to post stuff to my api, located in site/api/index.php, only posting to site/api since it gets passed on to index.php by itself. This however, apparently cause something to get messed up, as my $_POST got emptied on the fly. Simply posting to site/api/index.php directly instead solved it.


My problem was that I was using the HTML <base> tag to change the base URL of my test site. Once I removed that tag from the header, the $_POST data came back.


In my case (php page on OVH mutualisé server) enctype="text/plain" does not work ($_POST and corresponding $_REQUEST is empty), the other examples below work. `

<form action="?" method="post">
<!-- in this case, my google chrome 45.0.2454.101 uses -->
<!--     Content-Type:application/x-www-form-urlencoded -->
    <input name="say" value="Hi">
    <button>Send my greetings</button>
</form>

<form action="?" method="post" enctype="application/x-www-form-urlencoded">
    <input name="say" value="Hi">
    <button>Send my application/x-www-form-urlencoded greetings</button>
</form>

<form action="?" method="post"  enctype="multipart/form-data">
    <input name="say" value="Hi">
    <button>Send my multipart/form-data greetings</button>
</form>

<form action="?" method="post" enctype="text/plain"><!-- not working -->
    <input name="say" value="Hi">
    <button>Send my text/plain greetings</button>
</form>

`

More here: method="post" enctype="text/plain" are not compatible?


I was getting the following error from Mod Security:

Access denied with code 500 (phase 2). Pattern match "((select|grant|delete|insert|drop|alter|replace|truncate|update|create|rename|describe)[[:space:]]+[A-Z|a-z|0-9|\*| |\,]+[[:space:]]+(from|into|table|database|index|view)[[:space:]]+[A-Z|a-z|0-9|\*| |\,]|UNION SELECT.*\'.*\'.*,[0-9].*INTO.*FROM)" at REQUEST_BODY. [file "/usr/local/apache/conf/modsec2.user.conf"] [line "345"] [id "300013"] [rev "1"] [msg "Generic SQL injection protection"] [severity "CRITICAL"]

Once I removed my mod security configuration to test, it all worked as expected. Now I just need to modify my rules to stay secure but flexible enough for my needs :)


Make sure you use name="your_variable_name" in input tag.

I mistakenly use id="your_variable_name".

I spent much time to catch the bug.


In my case, when posting from HTTP to HTTPS, the $_POST comes empty. The problem was, that the form had an action like this //example.com When I fixed the url to https://example.com, the problem disappeared.


Make sure that the name property of each field is defined.

This create you an empty POST on PHP

<input type="text" id="Phone">

But, this will work

<input type="text" name="Phone" id="Phone">

OK, I thought that I should put my case here .... I was getting the post array empty in specific cases .. The form works well, but some times users complain that they hit submit button, and nothing happens ..... After digging for a while, I discovered that my hosting company has a security module that checks users inputs and clears the whole post array (not only the malicious data) if it discovers so. In my example, a math teacher was trying to enter the equation: dy + dx + 0 = 0; and data was wiped completely.

To fix this, I just advise him now to enter the data in the text area as dy + dx + 0 = zero, and now it works .... This can save someone some time ..

참고URL : https://stackoverflow.com/questions/1282909/php-post-array-empty-upon-form-submission

반응형