【汇总】异步POST数据【ajax,curl,sock】 博客分类: php ajaxcurlsock
程序员文章站
2024-03-23 15:33:40
...
整理下异步post表单的方法
被调用的程序,http://127.0.0.1/form.php
<?php if(!empty($_POST)) { print_r($_POST); } else { echo 'NO POST'; }
1.curl方法
<?php $url = 'http://127.0.0.1/form.php'; $post = 'key1=value1&key2=value2'; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $post); $data = curl_exec($ch); curl_close($ch); print_r($data);
2.sock方法
<?php $encoded = 'key1=value1&key2=value2'; $url = 'http://127.0.0.1/form.php'; $url = parse_url($url); if (!$url) return "couldn\'t parse url"; if (!isset($url['port'])) $url['port'] = ""; if (!isset($url['query'])) $url['query'] = ""; $port = $url['port'] ? $url['port'] : 80; $fp = fsockopen($url['host'], $port, $errno, $errstr); if (!$fp) return "Failed to open socket to $url[host] $port ERROR: $errno - $errstr"; fputs($fp, sprintf("POST %s%s%s HTTP/1.0\n", $url['path'], $url['query'] ? "?" : "", $url['query'])); fputs($fp, "Host: ". $url['host'] ."\n"); fputs($fp, "Content-type: application/x-www-form-urlencoded\n"); fputs($fp, "Content-length: " . strlen($encoded) . "\n"); fputs($fp, "Connection: close\n\n"); fputs($fp, $encoded . "\n"); $results = ""; $inheader = 1; while(!feof($fp)) { $line = fgets($fp,1024); if ($inheader && ($line == "\n" || $line == "\r\n")) { $inheader = 0; } elseif(!$inheader) { $results .= $line; } } fclose($fp); print_r($results);
3.javascript的ajax,会把url暴露在客户端
<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js"></script> <script> $(function(){ $.post('http://127.0.0.1/form.php', {'key1':'value1','key2':'value2'}, function(data){} ); }); </script>
上一篇: Java中final关键字的使用
下一篇: Vue学习:基础精讲