十段特别有用的PHP代码

2013 年 8 月 5 日4740

  1、使用PHP Mail函数发送Email

  $to = "viralpatel.net@gmail.com";

  $subject = "VIRALPATEL.net";

  $body = "Body of your message here you can use HTML too. e.g.﹤br﹥﹤b﹥ Bold ﹤/b﹥";

  $headers = "From: Peter\r\n";

  $headers .= "Reply-To: info@yoursite.com\r\n";

  $headers .= "Return-Path: info@yoursite.com\r\n";

  $headers .= "X-Mailer: PHP5\n";

  $headers .= "MIME-Version: 1.0" . "\n";

  $headers .= "Content-type: text/html; charset=iso-8859-1"."\r\n";

  mail($to,$subject,$body,$headers);

  ?﹥

  2、PHP中的64位编码和解码

  n base64url_encode($plainText)

  $base64 = base64_encode($plainText);

  $base64url = strtr($base64, "+/=", "-_,");

  return $base64url;

  n base64url_decode($plainText)

  $base64url = strtr($plainText, "-_,", "+/=");

  $base64 = base64_decode($base64url);

  return $base64;

  3、获取远程IP地址

  n getRealIPAddr()

  if (!empty($_SERVER["HTTP_CLIENT_IP"])) //check ip fromshareinternet

  $ip=$_SERVER["HTTP_CLIENT_IP"];

  elseif (!empty($_SERVER["HTTP_X_FORWARDED_FOR"])) //to check ipispass from proxy

  $ip=$_SERVER["HTTP_X_FORWARDED_FOR"];

  else

  $ip=$_SERVER["REMOTE_ADDR"];

  return $ip;

  4、 日期格式化

  n checkDateFormat($date)

  //match the format of the date

  if (preg_match ("/^([0-9]4)-([0-9]2)-([0-9]2)$/",$date,$parts))

  //check weather the date is valid of not

  return true;

  else

  return false;

  else

  return false;

  5、验证Email

  $email = $_POST["email"];

  echo "This is a valid email.";

  else

  echo "This is an invalid email.";

  6、在PHP中轻松解析XML

  //this is a sample xml string

  $xml_string="﹤?xml version="1.0"?﹥

  ﹤moleculedb﹥

  ﹤molecule﹥

  ﹤symbol﹥ben﹤/symbol﹥

  ﹤code﹥A﹤/code﹥

  ﹤/molecule﹥

  ﹤molecule﹥

  ﹤symbol﹥h2o﹤/symbol﹥

  ﹤code﹥K﹤/code﹥

  ﹤/molecule﹥

  ﹤/moleculedb﹥";

  //load the xml string using simplexml n

  $xml = simplexml_load_string($xml_string);

  //loop through the each node of molecule

  foreach ($xml-﹥molecule as $record)

  //attribute are accessted by

  echo $record["name"], " ";

  //node are accessted by -﹥ operator

  echo $record-﹥symbol, " ";

  echo $record-﹥code, "﹤br /﹥";

【来源:51cto】

(责任编辑:和讯网站)

0 0