Home >Backend Development >PHP Tutorial >How to implement cross-domain form submission in PHP

How to implement cross-domain form submission in PHP

墨辰丷
墨辰丷Original
2018-05-31 15:59:372473browse

This article mainly introduces the method of php to implement cross-domain form submission, and analyzes the operation skills of curl and ajax for cross-domain submission in the form of examples. Friends in need can refer to it

The example in this article describes how to implement cross-domain form submission in PHP. Share it with everyone for your reference, the details are as follows:

Sometimes for website security reasons, we do not allow direct cross-domain submission of form data. What if we have this need ourselves? Below we will introduce two cross-domain methods to solve direct cross-domain problems.

Let’s take a look at two methods of php cross-domain form submission

1. Through php curl

function curlPost($url,$params)
{
   $postData = '';
   foreach($params as $k => $v)
   {
     $postData .= $k . '='.$v.'&';
   }
   rtrim($postData, '&');
   $ch = curl_init();
   curl_setopt($ch,CURLOPT_URL,$url);
   curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
   curl_setopt($ch,CURLOPT_HEADER, false);
   curl_setopt($ch, CURLOPT_POST, count($postData));
   curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
   $output=curl_exec($ch);
   curl_close($ch);
   return $output;
}
echo curlPost("http://test.com",array('name'=>"tank"));

In the past, many people used curl to capture email addresses, but this is no longer possible. Ha ha.

2. Use jquery form, ajax submission

1. Download jquery.form.js

2. js code

$('#testform').submit(function() {
   $(this).ajaxSubmit({
   type: 'post', // 提交方式 get/post
   dataType:"json",//数据类型
   url: 'your url', // 需要提交的 url
   success: function(data) { // data 保存提交后返回的数据,一般为 json 数据
   // 此处可对 data 作相关处理
   alert('提交成功!');
   }
   $(this).resetForm(); // 提交后重置表单
   });
   return false; // 阻止表单自动提交事件
});

3. php code

header("Access-Control-Allow-Origin:*"); //跨域权限设置,允许所有
header("Access-Control-Allow-Origin:http://www.test.com"); //只允许test.com跨域提交数据

Summary: The above is the summary of this article All content, I hope it will be helpful to everyone's study.

Related recommendations:

Basic operations of php

PHP process signal processing

PHP determines whether a file exists in the specified directory

The above is the detailed content of How to implement cross-domain form submission in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn