1.get请求 (使用file_get_contents()函数也可以实现get请求)
//http_build_query() 构造一个url字符串 function http_get($url) { //1.初始化curl $ch = curl_init(); //2.设置参数 curl_setopt($ch, CURLOPT_URL, $url);//指定网址 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//返回信息的数据类型为字符串 //3.执行 $output = curl_exec($ch); echo $output; //4.关闭 curl_close($ch); } //调用get $data = array( "data" =>"123456" ); $url = "http://www.test.com/curl/curl_login.php?".http_build_query($data); http_get($url);
2.post模拟登陆
/*post 已经封装*/ function login($url,$post_data) { //初始化curl $ch = curl_init(); //跳转网址 curl_setopt($ch, CURLOPT_URL, $url); //设置头文件 curl_setopt($ch, CURLOPT_HEADER, 0); //返回信息的数据类型为字符串 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //设置post curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data); //执行命令 $output = curl_exec($ch); return $output; //关闭curl curl_close($ch); } /*调用封装好的方法*/ $url = "http://www.test.com/curl/curl_login.php"; $post_data = array( "name"=>"wangwu", "password"=>"1234567" ); $resultarr = login($url,$post_data); $result = json_decode($resultarr,true); if($result[‘status‘]==1){ echo $result[‘info‘]; }else{ echo $result[‘info‘]; }
处理页面
//声明方法 function info($status=0,$data="",$lan="1"){ $info=array( "status"=>"$status", "info"=>"$lan", "data"=>"$data" ); echo json_encode($info); die(); } //接值 $name = $_POST[‘name‘]; $password = $_POST[‘password‘]; //PDO链接数据库 $dsn = "mysql:host=127.0.0.1;port=3306;charset=utf8;dbname=news"; $pdo = new PDO($dsn,"root","root"); //sql语句 $sql = "select * from user where name = ‘$name‘"; $namedata = $pdo->query($sql); $nameresult = $namedata->fetch(PDO::FETCH_ASSOC); if($nameresult){ if($nameresult[‘password‘]==$password){ info("1","","登陆成功"); }else{ info("3","","登陆失败 原因是:密码有误"); } }else{ info("2","","登录失败 原因是:不存在的账户"); }
原文地址:https://www.cnblogs.com/zhangxu-fasu/p/11528585.html
时间: 2024-10-27 11:51:41