萬盛學電腦網

 萬盛學電腦網 >> 網絡編程 >> php編程 >> php $_POST[]獲取表單數據方法

php $_POST[]獲取表單數據方法

在php教程獲取表單數據有專用的命令, $_POST[]就是這個函數了,下面我們一個簡單的實例

<?php
echo 'Hello, ' . $_POST['first_name'] . '!';
?>
 
輸出是來自表單的first_name的值。

再復雜一點點的實例,

$_POST['name'] = trim($_POST['name']);

if (strlen($_POST['name']) == 0) {
    $errors[] = "Your name is required.";
}

好了,下面做一個關於$_POST的完整實例

<?php
  $user =  $_POST['user'];
  $color = $_POST['color'];
  $self =  $_SERVER['PHP_SELF'];

  if( ( $user != null ) and ( $color != null ) )
  {
    setcookie( "firstname", $user , time() + 36000 );
    setcookie( "fontcolor", $color, time() + 36000 );
    header( "Location:getcookie.php" );
    exit();
  }
?>

 

<html>

 <head>
  <title>Set Cookie Data</title>
 </head>

 <body>

  <form action ="<?php echo( $self ); ?>" method = "post">

  Please enter your first name:
  <input type = "text" name = "user"><br><br>

  Please choose your favorite font color:<br>
  <input type = "radio" name = "color" value = "#FF0000">Red
  <input type = "radio" name = "color" value = "#00FF00">Green
  <input type = "radio" name = "color" value = "#0000FF">Blue
  <br><br>
  <input type = "submit" value = "submit">
  </form>

 </body>

</html>


 
總結:上面的實例沒做安全處理,只是簡單的獲取了表單提交的數據,我們可以做一些安全處理,如isset() addslashes 等處理。

copyright © 萬盛學電腦網 all rights reserved