Using PHP for web development, the use of forms can be seen everywhere. Using its attributes Action and Method, you can specify the URL to which the content of the form is to be sent for processing and how to send the form data to the server. In most cases, we specify another URL address to process the form content to the Action attribute, but in some cases, we need to submit the form data to ourselves. How should we specify the Action attribute value at this time?
php
if(isset($_POST['action'])&&$_POST['action']=='submitted'){
print'
</span><span>'</span><span>;<br><img src="/static/imghw/default1.png" data-src="http://image.codes51.com/Article/image/20151009/20151009093544_9981.gif" class="lazy" alt="How to submit a form to itself in PHP" ><br><img src="/static/imghw/default1.png" data-src="http://image.codes51.com/Article/image/20151009/20151009093545_0762.gif" class="lazy" alt="How to submit a form to itself in PHP" ></span><span>print_r</span><span>(</span><span>$_POST</span><span>);<br><img src="/static/imghw/default1.png" data-src="http://image.codes51.com/Article/image/20151009/20151009093545_1387.gif" class="lazy" alt="How to submit a form to itself in PHP" ></span><span>print</span><span>'</span><span><ahref="</span><span >'</span><span >.</span><span >$_SERVER</span><span >[</span><span >'</span><span >PHP_SELF</span><span >'</span><span >]</span><span >.</span><span >'</span><span >">Pleasetryagain</a></span><span>'</span><span>;<br><img src="/static/imghw/default1.png" data-src="http://image.codes51.com/Article/image/20151009/20151009093545_2012.gif" class="lazy" alt="How to submit a form to itself in PHP" ><br><img src="/static/imghw/default1.png" data-src="http://image.codes51.com/Article/image/20151009/20151009093545_2793.gif" class="lazy" alt="How to submit a form to itself in PHP" ></span><span>print</span><span>'</span><span>
';}else{
?>
<formaction=""method="POST">
Name:<inputtype="text"name="personal[name]"><br>
Email:<inputtype="text"name="personal[email]"><br>
Beer:<br>
<selectmultiplename="beer[]">
<optionvalue="warthog">Warthog
<optionvalue="guinness">Guinness
select><br>
<inputtype="hidden"name="action"value="submitted">
<inputtype="submit"name="submit"value="submitme!">
form>
php
}
?>
上面的代码就实现了将表单提交给自己(注:在PHP4.1.0之前的版本请使用$_HTTP_POST_VARS替代下面代码中的$_Post变量)。这里使用了服务器变量$_Server获取当前页面的URL地址,并将其赋给表单的Action属性。这里使用了一个小小的技巧用以服务器在收到该URL请求是确定是POST请求还是GET请求。就是在表单中增加一个隐藏的变量,在处理请求时我们通过isset函数检测是否设置了这个隐藏变量,由此判断出该请求使用了POST还是GET方法。
版权声明:本文为博主原创文章,未经博主允许不得转载。
以上就介绍了PHP如何将表单提交给自己,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。