10 個實用的PHP代碼片段

openkk 12年前發布 | 17K 次閱讀 PHP

1. 獲取遠程客戶端IP地址

A quick and easy way to get the IP address of a client that is accessing your page:

function getRemoteIPAddress() {
    $ip = $_SERVER['REMOTE_ADDR'];
    return $ip;
}

Very simple but ineffective if your client is behind a proxy server. If you have reason to believe this or you just want to be more accurate, use this:

function getRealIPAddress() {
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) { // check ip from share internet
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { // to check ip is pass from proxy
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    } else {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}

2. 取得MySQL Timestamp

You often will want to fetch the timestamp of a particular row or set of rows. This quick query will return them.

$query = "select UNIX_TIMESTAMP(date_field) as mydate from mytable where 1=1";
$records = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($records)) {
    echo $row;
}

3. 校驗日期格式

Since we often use forms in PHP, you will want to validate that the date the user entered is in the correct YYYY-MM-DD format. This snippet will do just that!

function checkDateFormat($date) {
    // match the format of the date
    if (preg_match("/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/", $date, $parts)) {
        // check whether the date is valid of not
        if (checkdate($parts[2], $parts[3], $parts[1])) {
            return true;
        } else {
            return false;
        }
    } else {
        return false;
    }
}

You could also use the built-in checkdate() function that takes in a month, day and year as integers and checks if the date is valid as well as considers if each element is properly defined.

var_dump(checkdate(12, 31, 2000));
var_dump(checkdate(2, 29, 2001));

This function returns a boolean based on whether or not the date is valid, like this:

bool(true);
bool(false);

4. HTTP Redirection

Want to send your user to a different page they have landed on? Use this little snippet to add a redirection to the header of the request and send them to a different URL.

header('Location: http://www.yoursite.com/page.php');

5. 發送郵件

Being able to send email using our PHP scripts is a common function. The hardest part of this is setting up the different items needed and the headers to process the email correctly. Here is a snippet you can use as a template:

$to = "someone@domain.com";
$subject = "Your Subject here";
$body = "Body of your message here you can use HTML too. e.g. <br><b> Bold </b>";
$headers = "From: You\r\n";
$headers .= "Reply-To: info@yoursite.com\r\n";
$headers .= "Return-Path: info@yoursite.com\r\n";
$headers .= "X-Mailer: PHP\n";
$headers .= 'MIME-Version: 1.0' . "\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
mail($to, $subject, $body, $headers);

Once you have your email all set up, calling the mail function with all of the needed arguments will send your message.

6.Base64編碼和解碼

Base64 strings have all kinds of uses in PHP from saving image data to ensuring the binary data can be transported correctly. In this snippet we are encoding and decoding a Base64 URL.

function base64url_encode($plainText) {
    $base64 = base64encode($plainText);
    $base64url = strtr($base64, '+/=', '-,');
    return $base64url;
}

function base64urldecode($plainText) { $base64url = strtr($plainText, '-,', '+/='); $base64 = base64_decode($base64url); return $base64; }</pre>

You can check if a string is valid Base64 encoded by using the base64_decode function. For example:

if (base64_decode($mystring, true)) {
    // is valid
} else {
    // not valid
}

7. 創建和解析JSON Data

JSON, or JavaScript Object Notation is a data-interchange format. You may find yourself using JSON with PHP to send data as an object or as a serialization/deserialization solution. This snippet creates the JSON data format into an array.

$json_data = array ('id'=>1,'name'=>"John",'country'=>'Canada',"work"=>array("Google","Oracle"));
echo json_encode($json_data);

This snippet parses the JSON into a PHP array:

$json_string='{"id":1,"name":"John","country":"Canada","work":["Google","Oracle"]} ';
$obj=json_decode($json_string);

// print the parsed data echo $obj->name; //displays John echo $obj->work[0]; //displays Google</pre>

8. 探測用戶使用的瀏覽器類型

Since we often need to have different behaviors based on the user’s browser, or you just want this information for metric purposes, getting the user agent is simple:

$useragent = $_SERVER ['HTTP_USER_AGENT'];
echo "<b>Your User Agent is</b>: " . $useragent;

However, this will not work if the user is actively masking their agent with browser add-ons or other tools. There is no way to determine if the user agent is being spoofed.

9. 顯示網頁源代碼

This is a useful trick when browsing the source code of pages or helping co-workers with their web development projects. This snippet will display the source code of the given page, with line numbers:

$lines = file('http://google.com/');
foreach ($lines as $line_num => $line) {
    // loop thru each line and prepend line numbers
    echo "Line #<b>{$line_num}</b> : " . htmlspecialchars($line) . "<br>\n";
}

10. 調整服務器時間

When working in hosted or virtual environments we often have servers in different time-zones. This can be bad when displaying or using the current time, such as inserting a timestamp for a transaction. Here is how to adjust your server time to a different time zone:

$now = date('Y-m-d-G');
$now = strftime("%Y-%m-%d-%H", strtotime("$now -8 hours"));

Just add or subtract as needed to get the correct offset.

I hope you have enjoyed this list of PHP snippets and will find them useful as you progress on your journey through PHP. Remember to keep this list handy since many of these operations are performed regularly in your applications. I am sure you will also find many more you can add to this list.

 本文由用戶 openkk 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!