10 个实用的PHP代码片段
openkk 12年前
<h2>1. 获取远程客户端IP地址<br /> </h2> <p>A quick and easy way to get the IP address of a client that is accessing your page:</p> <pre class="brush: php">function getRemoteIPAddress() { $ip = $_SERVER['REMOTE_ADDR']; return $ip; }</pre> <p>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:</p> <pre class="brush: php">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; }</pre> <h2>2. 取得MySQL Timestamp</h2> <p>You often will want to fetch the timestamp of a particular row or set of rows. This quick query will return them.</p> <pre class="brush: php">$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; }</pre> <h2>3. 校验日期格式</h2> <p>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!</p> <pre class="brush: php">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; } }</pre> <p>You could also use the built-in <code>checkdate()</code> 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.</p> <pre class="brush: php">var_dump(checkdate(12, 31, 2000)); var_dump(checkdate(2, 29, 2001));</pre> <p>This function returns a boolean based on whether or not the date is valid, like this:</p> <pre class="brush: php">bool(true); bool(false);</pre> <h2>4. HTTP Redirection</h2> <p>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.</p> <pre class="brush: php">header('Location: http://www.yoursite.com/page.php');</pre> <h2>5. 发送邮件</h2> <p>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:</p> <pre class="brush: php">$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);</pre> <p>Once you have your email all set up, calling the mail function with all of the needed arguments will send your message.</p> <h2>6.Base64编码和解码</h2> <p>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.</p> <pre class="brush: php">function base64url_encode($plainText) { $base64 = base64_encode($plainText); $base64url = strtr($base64, '+/=', '-_,'); return $base64url; } function base64url_decode($plainText) { $base64url = strtr($plainText, '-_,', '+/='); $base64 = base64_decode($base64url); return $base64; }</pre> <p>You can check if a string is valid Base64 encoded by using the <code>base64_decode</code> function. For example:</p> <pre class="brush: php">if (base64_decode($mystring, true)) { // is valid } else { // not valid }</pre> <h2>7. 创建和解析JSON Data</h2> <p><code>JSON</code>, or JavaScript Object Notation is a data-interchange format. You may find yourself using <code>JSON </code>with PHP to send data as an object or as a serialization/deserialization solution. This snippet creates the JSON data format into an array.</p> <pre class="brush: php">$json_data = array ('id'=>1,'name'=>"John",'country'=>'Canada',"work"=>array("Google","Oracle")); echo json_encode($json_data);</pre> <p>This snippet parses the <code>JSON </code>into a PHP array:</p> <pre class="brush: php">$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> <h2>8. 探测用户使用的浏览器类型</h2> <p>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:</p> <pre class="brush: php">$useragent = $_SERVER ['HTTP_USER_AGENT']; echo "<b>Your User Agent is</b>: " . $useragent;</pre> <p>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.</p> <h2>9. 显示网页源代码</h2> <p>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:</p> <pre class="brush: php">$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"; }</pre> <h2>10. 调整服务器时间</h2> <p>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:</p> <pre class="brush: php">$now = date('Y-m-d-G'); $now = strftime("%Y-%m-%d-%H", strtotime("$now -8 hours"));</pre> <p>Just add or subtract as needed to get the correct offset.</p> <p>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.</p> <div class="wp-socializer 32px"></div>