当前位置:Gxlcms > PHP教程 > 再来10个有用的PHP代码

再来10个有用的PHP代码

时间:2021-07-01 10:21:17 帮助过:6人阅读

http://www.learncomputer.com/10-useful-php-code-snippets/
  1. function getRemoteIPAddress() {
  2. $ip = $_SERVER['REMOTE_ADDR'];
  3. return $ip;
  4. }
  1. function getRealIPAddress() {
  2. if (!empty($_SERVER['HTTP_CLIENT_IP'])) { // check ip from share internet
  3. $ip = $_SERVER['HTTP_CLIENT_IP'];
  4. } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { // to check ip is pass from proxy
  5. $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
  6. } else {
  7. $ip = $_SERVER['REMOTE_ADDR'];
  8. }
  9. return $ip;
  10. }
  1. $query = "select UNIX_TIMESTAMP(date_field) as mydate from mytable where 1=1";
  2. $records = mysql_query($query) or die(mysql_error());
  3. while($row = mysql_fetch_array($records)) {
  4. echo $row;
  5. }
  1. function checkDateFormat($date) {
  2. // match the format of the date
  3. if (preg_match("/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/", $date, $parts)) {
  4. // check whether the date is valid of not
  5. if (checkdate($parts[2], $parts[3], $parts[1])) {
  6. return true;
  7. } else {
  8. return false;
  9. }
  10. } else {
  11. return false;
  12. }
  13. }
  1. header('Location: http://www.oschina.net/project/zh');
  1. $to = "someone@oschina.net";
  2. $subject = "Your Subject here";
  3. $body = "Body of your message here you can use HTML too. e.g.
    Bold ";
  4. $headers = "From: You\r\n";
  5. $headers .= "Reply-To: info@yoursite.com\r\n";
  6. $headers .= "Return-Path: info@yoursite.com\r\n";
  7. $headers .= "X-Mailer: PHP\n";
  8. $headers .= 'MIME-Version: 1.0' . "\n";
  9. $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
  10. mail($to, $subject, $body, $headers);
  1. function base64url_encode($plainText) {
  2. $base64 = base64_encode($plainText);
  3. $base64url = strtr($base64, '+/=', '-_,');
  4. return $base64url;
  5. }
  6. function base64url_decode($plainText) {
  7. $base64url = strtr($plainText, '-_,', '+/=');
  8. $base64 = base64_decode($base64url);
  9. return $base64;
  10. }
  1. $json_data = array ('id'=>1,'name'=>"John",'country'=>'Canada',"work"=>array("Google","Oracle"));
  2. echo json_encode($json_data);
  3. $json_string='{"id":1,"name":"John","country":"Canada","work":["Google","Oracle"]} ';
  4. $obj=json_decode($json_string);
  5. // print the parsed data
  6. echo $obj->name; //displays John
  7. echo $obj->work[0]; //displays Google
  1. $useragent = $_SERVER ['HTTP_USER_AGENT'];
  2. echo "Your User Agent is: " . $useragent;
  1. $lines = file('http://www.oschina.net/home/about');
  2. foreach ($lines as $line_num => $line) {
  3. // loop thru each line and prepend line numbers
  4. echo "Line #{$line_num} : " . htmlspecialchars($line) . "
    \n";
  5. }
  1. $now = date('Y-m-d-G');
  2. $now = strftime("%Y-%m-%d-%H", strtotime("$now -8 hours"));

人气教程排行