Home > Article > Backend Development > PHP write file - save user-submitted data to a file on the server
First write the html page:
<!DOCTYPE html> <html> <head lang="zh_CN"> <meta charset="UTF-8"> <title>订单页面</title> </head> <body> <h2>Jason的购物清单</h2> <form method="post" action="processorder.php"> <label>男装:</label><input type="text" name="cloths"/> <label>鞋子:</label><input type="text" name="shoes"/> <label>眼镜:</label><input type="text" name="glasses"/> <label>收货地址:</label><input type="text" name="address"/> <input type="submit" value="提交" id="btn1"> </form> </body> </html>
Then use PHP to write the server-side script fileprocessorder.php
<?php $cloths=$_POST['cloths']; $shoes=$_POST['shoes']; $glasses=$_POST['glasses']; $address=$_POST['address']; $DOCUMENT_ROOT=$_SERVER['DOCUMENT_ROOT']; //设置时区 date_default_timezone_set('Asia/Shanghai'); //按指定格式输出日期 $date=date('Y-m-d H:i'); ?> <!DOCTYPE html> <html> <head lang="zh_CN"> <meta charset="UTF-8"> <title>订单结果</title> </head> <body> <h2>Jason的购物车</h2> <h3>订单结果</h3> <?php echo '<p>订单提交中时间:'.$date.'</p>'; echo '<p>您的具体购物清单是:</p>'; //获取商品总数量 $total_qty=0; $total_qty=$cloths+$shoes+$glasses; echo '商品总数量:'.$total_qty.'<br/>'; if($total_qty==0){ echo '您没有购买任何商品!'; }else{ if($cloths>0){ echo $cloths.'件男装<br/>'; } if($shoes>0){ echo $shoes.'双鞋子<br/>'; } if($glasses>0){ echo $glasses.'副眼镜<br/>'; } } //获取商品总价 $total_amount=0.00; const CLOTHS_PRICE=100; const SHOES_PRICE=300; const GLASSES_PRICE=28; $total_amount=$cloths*CLOTHS_PRICE+$shoes*SHOES_PRICE+$glasses*GLASSES_PRICE; $total_amount=number_format($total_amount,2,'.',' '); echo '<p>商品总价:¥'.$total_amount.'</p>'; echo '<p>收货地址:'.$address.'</p>'; //设置文件输出内容和格式 $out_put_string=$date."\t".$cloths."件男装\t".$shoes."双鞋子\t".$glasses."副眼镜\t\总价:¥".$total_amount." 收货地址:\t".$address."\n"; //打开文件,(追加模式+二进制模式) @$fp=fopen("$DOCUMENT_ROOT/L02/files/orders.text",'ab'); flock($fp,LOCK_EX); if(!$fp){ echo "<p><strong>您的订单没有提交完成,请再试一次。</strong></p></body></html>"; exit; } //将数据写入到文件 fwrite($fp,$out_put_string,strlen($out_put_string)); flock($fp,LOCK_UN); //关闭文件流 fclose($fp); echo "<p>数据保存完成</p>"; ?> </body> </html>
Copyright statement: This article is an original article by the blogger and may not be reproduced without the blogger's permission.
The above introduces PHP writing files - saving the data submitted by users to files on the server, including aspects of the content. I hope it will be helpful to friends who are interested in PHP tutorials.