1. Trang chủ
  2. » Công Nghệ Thông Tin

15 code php hay dùng trong lập trình website

7 514 2
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề 15 Code PHP Hay Dùng Trong Lập Trình Website
Thể loại Tài liệu
Định dạng
Số trang 7
Dung lượng 24,23 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Send Mail using mail function in PHPCode: $to = "admin@user.vn"; $subject = "User.vn"; $body = "Body of your message here you can use HTML too... 14 # only files connecting with in the

Trang 1

1 Send Mail using mail function in PHP

Code:

$to = "admin@user.vn";

$subject = "User.vn";

$body = "Body of your message here you can use HTML too e.g <br> <b> Bold

</b>";

$headers = "From: Peter";

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

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

$headers = "X-Mailer:PHP5";

$headers = 'MIME-Version: 1.0";

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

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

2 Base64 Encode and Decode String in PHP

Code:

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

Code:

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 :

Code:

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'];

Trang 2

11 }

12 else

13 {

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

15 }

16 return $ip;

17 }

4 Seconds to String

Code:

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!#$%&amp;'*+-/=?^_`{|}~])@

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

Code:

01 //this is a sample xml string

02 $xml_string="<?xml version='1.0'?>

03 <moleculedb>

04 <molecule name='Benzine'>

05 <symbol>ben</symbol>

06 <code>A</code>

07 </molecule>

08 <molecule name='Water'>

09 <symbol>h2o</symbol>

Trang 3

10 <code>K</code>

11 </molecule>

12 </moleculedb>";

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, '<br />';

25 }

7 Database Connection in PHP

Code:

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 '<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">'."n"

20 '<html><head>'."n"

21 '<title>404 Not Found</title>'."n"

22 '</head><body>'."n"

23 '<h1>Not Found</h1>'."n"

24 '<p>The requested URL '

25

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

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

28 ' was not found on this server.</p>'."n"

29 '</body></html>'."n";

30 exit;

31 }

32

Trang 4

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

Code:

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"]} ‘;

Code:

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

Code:

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

Code:

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

Trang 5

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

Code:

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

Code:

01 function list_files($dir)

02 {

03 if(is_dir($dir))

04 {

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

06 {

Trang 6

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

08 {

09 /*pesky windows, images */

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

11 {

12 echo '<a target="_blank" href="'.$dir.$file.'">

13 '.$file.'</a><br>'."";

14 }

15 }

16 closedir($handle);

17 }

18 }

19 }

20 /*

21 To use:

22

23 <?php

24

25 list_files("images/");

26

27 ?>

28

29 */

14 Browser Detection script in PHP

Code:

1 $useragent = $_SERVER ['HTTP_USER_AGENT'];

2 echo "<b>Your User Agent is</b>: " $useragent;

15 Unzip a Zip File

Code:

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:

Code:

Trang 7

1 include 'functions.php';

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

3 echo 'Success!';

4 else

5 echo 'Error';

Ngày đăng: 04/07/2014, 22:46

TỪ KHÓA LIÊN QUAN

w