Vua Tên Miền chuyên cung cấp tên miền đẹp, giá rẻ! Hãy liên hệ kỹ thuật: 0914205579 - Kinh doanh: 0912191357 để được tư vấn, hướng dẫn miễn phí, Cảm ơn quý khách đã ủng hộ trong thời gian qua!
kinh doanh, bán hàng, tư vấn, bảo hiểm Những cá nhân, tổ chức, đại lý,muốn bán, hợp đồng bảo hiểm
Sunday, January 2, 2011

Giới thiệu tới các bạn các đoạn code hay dùng nhất trong lập trình php.nên tham khảo bổ sung kiến thức webbsite cho bạn.

1. Send Mail using mail function in PHP



Trích:
01 $to = "admin@user.vn";

02 $subject = "User.vn";

03 $body = "Body of your message here you can use HTML too. e.g.
Bold ";

04 $headers = "From: Peter";

05 $headers .= "Reply-To: info@yoursite.com";

06 $headers .= "Return-Path: mailto:info@yoursite.com";

07 $headers .= "X-Mailer:PHP5";

08 $headers .= 'MIME-Version: 1.0";

09 $headers .= 'Content-type: text/html; charset=iso-8859-1";

10 mail($to,$subject,$body,$headers);
2. Base64 Encode and Decode String in PHP



Trích:
01 function base64url_encode($plainText) {

02 $base64 = base64_encode($plainText);

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

04 return $base64url;

05 }

06

07 function base64url_decode($plainText) {

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

09 $base64 = base64_decode($base64url);

10 return $base64;

11 }
3. Get Remote IP Address in PHP



Trích:
1 function getRemoteIPAddress() {

2 $ip = $_SERVER['REMOTE_ADDR'];

3 return $ip;

4 }


Nếu người truy cập web cố tình dấu địa chỉ ip này bằng proxy thì sử dụng code sau :



Trích:
01 function getRealIPAddr()

02 {

03 if (!empty($_SERVER['HTTP_CLIENT_IP'])) //check ip from

04 {

05 $ip=$_SERVER['HTTP_CLIENT_IP'];

06 }

07 elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))

08 //to check ip is pass from proxy

09 {

10 $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];

11 }

12 else

13 {

14 $ip=$_SERVER['REMOTE_ADDR'];

15 }

16 return $ip;

17 }


4. Seconds to String





Trích:
01 function secsToStr($secs) {

02 if($secs>=86400){$days=floor($secs/86400);$secs=$secs%86400;

03 $r=$days.' day';

04 if($days<>1){$r.='s';}if($secs>0){$r.=', ';}}

05 if($secs>=3600){$hours=floor($secs/3600);$secs=$secs%3600;

06 $r.=$hours.' hour';

07 if($hours<>1){$r.='s';}if($secs>0){$r.=', ';}}

08 if($secs>=60){$minutes=floor($secs/60);$secs=$secs%60;

09 $r.=$minutes.' minute';

10 if($minutes<>1){$r.='s';}if($secs>0){$r.=', ';}}

11 $r.=$secs.' second';if($secs<>1){$r.='s';}

12 return $r;

13 }


5. Email validation snippet in PHP



Trích:
1 $email = $_POST['email'];

2 if(preg_match("~([a-zA-Z0-9!#$%&'*+-/=?^_`{|}~])@

3 ([a-zA-Z0-9-]).([a-zA-Z0-9]{2,4})~",$email)) {

4 echo 'This is a valid email.';

5 } else{

6 echo 'This is an invalid email.';

7 }


6. Parsing XML in easy way using PHP





Trích:
01 //this is a sample xml string

02 $xml_string="

03

04

05 ben

06 A

07


08

09 h2o

10 K

11


12
";

13

14 //load the xml string using simplexml function

15 $xml = simplexml_load_string($xml_string);

16

17 //loop through the each node of molecule

18 foreach ($xml->molecule as $record)

19 {

20 //attribute are accessted by

21 echo $record['name'], ' ';

22 //node are accessted by -> operator

23 echo $record->symbol, ' ';

24 echo $record->code, '
';

25 }


7. Database Connection in PHP





Trích:
01 if(basename(__FILE__) == basename($_SERVER['PHP_SELF'])) send_404();

02 $dbHost = "localhost"; //Location Of Database usually its localhost

03 $dbUser = "xxxx"; //Database User Name

04 $dbPass = "xxxx"; //Database Password

05 $dbDatabase = "xxxx"; //Database Name

06

07 $db = mysql_connect("$dbHost", "$dbUser", "$dbPass")

08 or die ("Error connecting to database.");

09 mysql_select_db("$dbDatabase", $db)

10 or die ("Couldn't select the database.");

11

12 # This function will send an imitation 404 page if the user

13 # types in this files filename into the address bar.

14 # only files connecting with in the same directory as this

15 # file will be able to use it as well.

16 function send_404()

17 {

18 header('HTTP/1.x 404 Not Found');

19 print ''."n".

20 ''."n".

21 '404 Not Found'."n".

22 ''."n".

23 '

Not Found

'."n".

24 '

The requested URL '.

25

26 str_replace(strstr($_SERVER['REQUEST_URI'], '?'),

27 '', $_SERVER['REQUEST_URI']).

28 ' was not found on this server.

'."n".

29 ''."n";

30 exit;

31 }

32

33 # In any file you want to connect to the database,

34 # and in this case we will name this file db.php

35 # just add this line of php code (without the pound sign):

36 # include"db.php";


8. Creating and Parsing JSON data in PHP





Trích:
1 $json_data = array ('id'=>1,'name'=>"rolf",'country'=>'russia',

2 "office"=>array("google","oracle"));

3 echo json_encode($json_data);


Sử dụng mảng $json_string=’{“id”:1,”name”:”rolf”, ”country”:”rus sia”,”office”:

["google","oracle"]} ‘;



Trích:
1 $obj=json_decode($json_string);

2 //print the parsed data

3 echo $obj->name; //displays rolf

4 echo $obj->office[0]; //displays google


9. Process MySQL Timestamp in PHP







Trích:
1 $query = "select UNIX_TIMESTAMP(date_field) as mydate

2 from mytable where 1=1";

3 $records = mysql_query($query) or die(mysql_error());

4 while($row = mysql_fetch_array($records))

5 {

6 echo $row;

7 }


10. Generate An Authentication Code in PHP







Trích:
01 # This particular code will generate a random string

02

03 # that is 25 charicters long 25 comes from the number

04

05 # that is in the for loop

06

07 $string = "abcdefghijklmnopqrstuvwxyz0123456789";

08

09 for($i=0;$i<25;$i++){

10

11 $pos = rand(0,36);

12

13 $str .= $string{$pos};

14

15 }

16

17 echo $str;

18

19 # If you have a database you can save the string in

20

21 # there, and send the user an email with the code in

22

23 # it they then can click a link or copy the code

24

25 # and you can then verify that that is the correct email

26

27 # or verify what ever you want to verify


11. Date format validation in PHP







Trích:
01 function checkDateFormat($date)

02 {

03 //match the format of the date

04 if (preg_match ("/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/",

05 $date, $parts))

06 {

07 //check weather the date is valid of not

08 if(checkdate($parts[2],$parts[3],$parts[1]))

09 return true;

10 else

11 return false;

12 }

13 else

14 return false;

15 }


12. HTTP Redirection in PHP







Trích:
1 header('Location: 'http://you_stuff/url.php');


13. Directory Listing in PHP







Trích:
01 function list_files($dir)

02 {

03 if(is_dir($dir))

04 {

05 if($handle = opendir($dir))

06 {

07 while(($file = readdir($handle)) !== false)

08 {

09 /*pesky windows, images..*/

10 if($file != "." && $file != ".." && $file != "Thumbs.db")

11 {

12 echo '

13 '.$file.'

'."";

14 }

15 }

16 closedir($handle);

17 }

18 }

19 }

20 /*

21 To use:

22

23
24

25 list_files("images/");

26

27 ?>

28

29 */


14. Browser Detection script in PHP







Trích:
1 $useragent = $_SERVER ['HTTP_USER_AGENT'];

2 echo "Your User Agent is: " . $useragent;


15. Unzip a Zip File







Trích:
01 function unzip($location,$newLocation){

02 if(exec("unzip $location",$arr)){

03 mkdir($newLocation);

04 for($i = 1;$i< count($arr);$i++){

05 $file = trim(preg_replace("~inflating: ~","",$arr[$i]));

06 copy($location.'/'.$file,$newLocation.'/'.$file);

07 unlink($location.'/'.$file);

08 }

09 return TRUE;

10 }else{

11 return FALSE;

12 }

13 }


Use the code as following:







Trích:
1 include 'functions.php';

2 if(unzip('zipedfiles/test.zip','unziped/myNewZip'))

3 echo 'Success!';

4 else

5 echo 'Error';
Soạn bởi: http://dangkyoffice.com | http://cenrea.com
tcaviet@gmail.com

0 comments:

Post a Comment

domain, domain name, premium domain name for sales

Bài hay: