Skip navigation.

xem phim mien phi coi phim truc tuyen mien phi

Nghe nhac xem phim doc truyen. nghe nhac nghe music. download nhac. coi phim truc tuyen. xem phim mien phi.

Một số đoạn code thường được sử dụng trong PHP

Hàm chuyển chuỗi tiếng việt có dấu thành tiếng việt không dấu:
-Yêu cầu: Bạn phải lưu file php theo charset là UTF-8. Có thể dùng Notepad hoặc Editplus version mới nhất...

Hàm chuyển chuỗi tiếng việt có dấu thành tiếng việt không dấu: -Yêu cầu: Bạn phải lưu file php theo charset là UTF-8. Có thể dùng Notepad hoặc Editplus version mới nhất Code: function khongdau($str) { $str = preg_replace("/(à|á|ạ|ả|ã|â|ầ|ấ|ậ|ẩ|ẫ|ă|ằ|ắ|ặ|ẳ|ẵ)/", 'a', $str); $str = preg_replace("/(è|é|ẹ|ẻ|ẽ|ê|ề|ế|ệ|ể|ễ)/", 'e', $str); $str = preg_replace("/(ì|í|ị|ỉ|ĩ)/", 'i', $str); $str = preg_replace("/(ò|ó|ọ|ỏ|õ|ô|ồ|ố|ộ|ổ|ỗ|ơ|ờ|ớ|ợ|ở|ỡ)/", 'o', $str); $str = preg_replace("/(ù|ú|ụ|ủ|ũ|ư|ừ|ứ|ự|ử|ữ)/", 'u', $str); $str = preg_replace("/(ỳ|ý|ỵ|ỷ|ỹ)/", 'y', $str); $str = preg_replace("/(đ)/", 'd', $str); $str = preg_replace("/(À|Á|Ạ|Ả|Ã|Â|Ầ|Ấ|Ậ|Ẩ|Ẫ|Ă|Ằ|Ắ|Ặ|Ẳ|Ẵ)/", 'A', $str); $str = preg_replace("/(È|É|Ẹ|Ẻ|Ẽ|Ê|Ề|Ế|Ệ|Ể|Ễ)/", 'E', $str); $str = preg_replace("/(Ì|Í|Ị|Ỉ|Ĩ)/", 'I', $str); $str = preg_replace("/(Ò|Ó|Ọ|Ỏ|Õ|Ô|Ồ|Ố|Ộ|Ổ|Ỗ|Ơ|Ờ|Ớ|Ợ|Ở|Ỡ)/", 'O', $str); $str = preg_replace("/(Ù|Ú|Ụ|Ủ|Ũ|Ư|Ừ|Ứ|Ự|Ử|Ữ)/", 'U', $str); $str = preg_replace("/(Ỳ|Ý|Ỵ|Ỷ|Ỹ)/", 'Y', $str); $str = preg_replace("/(Đ)/", 'D', $str); //$str = str_replace(" ", "-", str_replace("&*#39;","",$str)); return $str; } -Cách sử dụng: Code: <?php $string = "Cộng hòa xã hội chủ nghĩa Việt Nam"; $xstring = khongdau($string); echo $xstring; //Kết quả: //Output: Cong hoa xa hoi chu nghia Viet Nam ?> Hàm cắt bớt chuỗi Unicode: -Mô tả: Hàm này giúp cho ai có nhu cầu cần cắt bớt tiêu đề hoặc đoạn text nào đó có định dạng là tiếng Việt Unicode. Code: function cstr($text, $start=0, $limit=12) { if (function_exists('mb_substr')) { $more = (mb_strlen($text) > $limit) ? TRUE : FALSE; $text = mb_substr($text, 0, $limit, 'UTF-8'); return array($text, $more); } elseif (function_exists('iconv_substr')) { $more = (iconv_strlen($text) > $limit) ? TRUE : FALSE; $text = iconv_substr($text, 0, $limit, 'UTF-8'); return array($text, $more); } else { preg_match_all("/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/", $text, $ar); if(func_num_args() >= 3) { if (count($ar[0])>$limit) { $more = TRUE; $text = join("",array_slice($ar[0],0,$limit))."..."; } $more = TRUE; $text = join("",array_slice($ar[0],0,$limit)); } else { $more = FALSE; $text = join("",array_slice($ar[0],0)); } return array($text, $more); } } function cut_title($text, $limit=25) { $val = cstr($text, 0, $limit); return $val[1] ? $val[0]."..." : $val[0]; } -Cách sử dụng: Code: $str = "Cộng hòa xã hội chủ nghĩa Việt Nam"; echo cut_title($str); Hàm chống SQL Injection Code: function anti_sql($sql) { $sql = preg_replace(sql_regcase("/(from|select|insert|delete|where|drop table|show tables|#|\*|--|\\\\)/"),"",$sql); return trim(strip_tags(addslashes($sql))); #strtolower() } Hàm lấy IP chính xác, hiện tại chưa thể phát hiện sock Code: function getip() { if (isset($_SERVER)) { if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { $realip = $_SERVER['HTTP_X_FORWARDED_FOR']; } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) { $realip = $_SERVER['HTTP_CLIENT_IP']; } else { $realip = $_SERVER['REMOTE_ADDR']; } } else { if (getenv("HTTP_X_FORWARDED_FOR")) { $realip = getenv( "HTTP_X_FORWARDED_FOR"); } elseif (getenv("HTTP_CLIENT_IP")) { $realip = getenv("HTTP_CLIENT_IP"); } else { $realip = getenv("REMOTE_ADDR"); } } return $realip; } đoạn code tính thời khoảng (duration), tính ra số ngày. Code: function duration_vip($duration) { $time = $duration; $day = floor($time/(3600*24)); $hour = floor(($time%(3600*24))/(3600)); $minute = floor(($time%(3600))/(60)); if($minute!=0) { $time = $minute.'\''; } else { $time=''; } if($hour!=0) { $time = $hour.'h'.$time; } if($day!=0) { $time = $day.' ngày '.$time; } return $time; } cách dùng $date_num = duration_vip(($time_expired - $time_created)); Trong đó $time_expired và $time_created là các biến có dạng Datetime trong MySQL. Hàm lấy random str: Code: function RandomStr($Length) { $Chars = array("a","A","b","B","c","C","d","D","e","E","f","F","g", "G","h","H","i","I","j","J","k", "K","l","L","m","M","n","N","o","O","p","P","q","Q", "r","R","s","S","t","T","u","U","v", "V","w","W","x","X","y","Y","z","Z","1","2","3","4", "5","6","7","8","9"); $RandCode = ""; for ($i=0; $i<$Length; $i++) { $RandCode .= $Chars[rand(0, count($Chars)-1)]; } return $RandCode; } Upload file từ 1 direct URL: Code: function UploadFromUrl($Url) { define("URL_1",$Url); $UploadDir = "upload/files/"; $FileName = explode("/", $Url); $FileName = $FileName[count($FileName)-1]; define("URL_2",$UploadDir.$FileName); $f1 = @fopen ( URL_1, "rb"); $f2 = @fopen ( URL_2, "w"); while ( $Buff = @fread( $f1, 1024 ) ) { @fwrite($f2, $Buff); } @fclose($f1); @fclose($f2); } Redirect trong PHP: function redirect($url) { if (@preg_match('/Microsoft|WebSTAR|Xitami/', getenv('SERVER_SOFTWARE'))) { header('Refresh: 0; URL=' . $url); echo '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"><meta http-equiv="refresh" content="0; url=' . $url . '">Redirect</head><body>
If your browser does not support meta redirection please click HERE to be redirected
</body></html>'; exit; } header('Location: ' . $url); exit; } Refresh page: function page_refresh($strpage) { print "<script>window.location='".$strpage."';</script>"; } Chống sql inject: function id_replace($id) { $id = str_replace("+","",$id); $id = str_replace("'","''",$id); $id = str_replace("union","",$id); $id = str_replace("select","",$id); $id = str_replace("\*","",$id); $id = str_replace("\%","",$id); $id = str_replace("%","",$id); $id = str_replace("2b","",$id); if (strlen($id) > 10) { $id=""; } return $id; } function string_replace($string) { $string = str_replace(""","\"",$string); $string = str_replace("+","",$string); $string = str_replace("'","''",$string); $string = str_replace("<","[",$string); $string = str_replace(">","]",$string); $string = str_replace(">","]",$string); $string = str_replace("<","[",$string); $string = str_replace("union","",$string); $string = str_replace("select","",$string); $string = str_replace("\*","",$string); $string = str_replace("\%","",$string); $string = str_replace("%","",$string); $string = str_replace("2b","",$string); if (strlen($string) > 15) { $string=""; } return $string; } Kiểm tra số: function isNumeric($object) { if (!isset($object)) return false; $match = '^[+-]?\d+(?:\.\d+)?(?:[Ee][+-]?\d+)?$'; return (preg_match('|' . $match . '|', $object)); } Đọc nội dung file: function read_file ($fname) { if (!file_exists($fname)) return null; $fd = fopen ($fname, "r"); $contents = @fread ($fd, filesize ($fname)); fclose ($fd); return $contents; } Kiểm tra url: function checkURL($entry){ // clear http:// for all case $entry = preg_replace ("/^http:\/\//i","",$entry); // clear all part after / for all case $entry = preg_replace ("/\/.*/i","",$entry); return (!preg_match ("/^([a-z0-9\-_]+)((?:\.[a-z0-9_\-]+)+)$/i", $entry,$fg))?true:false; } Định dạng ngày tháng năm: function FormatDateTime($datetime) { return date('d/m/Y H:i:s', strtotime($datetime)); } Chuyển ngày tháng dạng: dd-mm-yyyy -> định dạng ngày tháng để insert vào csdl rồi ta có thể đọc ra từ hàm date(d-m-Y, $row['date']) function parseDay($day) { $myDay = explode('-',$day); $dateParse = mktime(0,0,0,$myDay[1],$myDay[0],$myDay[2]); return $dateParse; } Một class nữa có đầy đủ hết các thao tác về file class FileSystem { /** * Method Download File Content * @param File Content, File Name, File Type, Extension */ public function DownloadFile($FileString, $FileName, $FileType, $Ext) { header('Content-Type: ' . $FileType); header('Expires: ' . gmdate('D, d M Y H:i:s') . ' GMT'); header('Content-Disposition: attachment; filename="' . $FileName . "." . $Ext . '"'); header('Content-Length: ' . strlen($FileString)); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Pragma: public'); echo $FileString; exit; } /** * Method Get File Content * @param str * @return str */ public function GetContent($File) { return file_get_contents($File); } /** * Method Write File Content * @param File path, Write Type, Content */ public function WriteFile($File, $Type, $Content) { $Handle = @fopen($File,$Type); fwrite($Handle, $Content); @fclose($Handle); } /** * Method Read and Show Folder Item * @param Folder path * @return array */ public function ShowDir($Folder) { $ItemArray = array(); if (is_dir($Folder)) { if ($Handle = @opendir($Folder)) { while (($Item = readdir($Handle)) !== false) { $ItemArray[] = $Item; } @closedir($Handle); } } return $ItemArray; } /** * Method Delete File * @param File path */ public function DelFile($File) { @unlink($File); } /** * Method Creat Folder * @param Folder path */ public function CreatFolder($Folder,$chmod=0775) { @mkdir($Folder,$chmod); } /** * Method Remove Dir * @param Folder path */ public function RemoveDir($Dir) { $ItemArray = $this->ShowDir($Dir); for ($i=0; $i<sizeof($ItemArray); $i++) { if ($ItemArray[$i] != "." && $ItemArray[$i] != "..") { if (is_dir($Dir."/".$ItemArray[$i])) { $this->RemoveDir($Dir."/".$ItemArray[$i]); } else { $this->DelFile($Dir."/".$ItemArray[$i]); } } } @rmdir($Dir); } } Hàm sinh 1 pass ngẫu nhiên <?php /***************************** # ALL TYPE OF RANDOM PASSWORD # Author: phund # Email:nducphu@gmail.com # admin@coder.com.vn # Website: http://coder.com.vn *****************************/ class oRandomPass{ public $str_allow = array ( "0123456789", "abcdefghijklmnopqrstuvxyz", "ABCDEFGHIJKLMNOPQRSTUVXYZ", "_@.-=+" ); var $pass_length = 12; /* length of password */ var $pass_type = "0,1,2"; /* //Type of password: - 0: Include number - 1: Include lowercase character - 2: Include UPPERCASE character - 3: Include special character - ...and more //You can set your custom allow password string by add more value into $str_allow */ /*---------------------------------------- //Function Name: mProcessRandom() //Desc: Make string to random password //Premission: private //Input: rand_type - Output: string -----------------------------------------*/ public function mProcessRandom(){ $str = $this->mStringMaker(); $length = strlen($str); @mt_rand($this->makeSeed()); for($i=0; $i<=$this->pass_length-1; $i++){ $output .= $str{mt_rand(0,$length-1)}; } return $output; } /*---------------------------------------- //Function Name: mStringMaker() //Desc: Make string to random password //Premission: private //Input: rand_type - Output: string -----------------------------------------*/ private function mStringMaker(){ $allow = explode(",",$this->pass_type); foreach($allow as $k){ if(array_key_exists($k,$this->str_allow)) $output .= $this->str_allow[$k]; } return $output; } /*---------------------------------------- //Function Name: makeSeed() //Author: php.net -----------------------------------------*/ private function makeSeed(){ list($usec, $sec) = explode(' ', microtime()); return (float) $sec + ((float) $usec * 100000); } } /* EXAMPLE USAGE */ $test = new oRandomPass; /* //SET INPUT VARIABLE IF YOU WANT $test->pass_length = 16; $test->pass_type = "0,1,3"; */ echo $test->mProcessRandom(); /* Example output: zqo8nd9mSJAa */ ?> Hàm này lấy một instance của một đối tượng (đảm bảo chỉ có một instance của đối tượng đó được khởi tạo, giống như mẫu Singleton) function &getInstance($className){ static $instance; if(!class_exists($className)){ return false; } if(!isset($instance[$className])){ $instance[$className] = new $className(); } return $instance[$className]; } Sử dụng $newInstance = &getInstance('<class name>'); Hàm kiểm tra một chuỗi có đúng định dạng e-mail không - copy từ sách /** * Kiem tra dinh dang dia chi email co hop le khong * Dinh dang hop le: * - name@domain.com * - name@domain.com.vn * - first.last@domain.info * - first_last@sub.domain.vn * - firstlast123@sub.domain.com.vn * - first-last@sub1.sub2....domain.com * * @param string $string can kiem tra * @return bool */ function isValidEmail($string) { if (preg_match("/^\w(\.?[\w-])*@\w(\.?[-\w])*\.[a-z]{2,4}$/i", $string)) { return true; } else { return false; } } Hàm lấy địa chỉ IP người dùng (copy từ Google) function getUserIP() { if (isset($_SERVER)) { if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])) { return $_SERVER["HTTP_X_FORWARDED_FOR"]; } if (isset($_SERVER["HTTP_CLIENT_IP"])) { return $_SERVER["HTTP_CLIENT_IP"]; } return $_SERVER["REMOTE_ADDR"]; } if (getenv('HTTP_X_FORWARDED_FOR')) { return getenv('HTTP_X_FORWARDED_FOR'); } if (getenv('HTTP_CLIENT_IP')) { return getenv('HTTP_CLIENT_IP'); } return getenv('REMOTE_ADDR'); } Hàm loại bỏ toàn bộ khoảng trắng function removeSpaces($str) { $str = trim($str); $str = str_replace("\r\n", " ", $str); $str = str_replace("\n", " ", $str); $str = str_replace("\t", " ", $str); while (strstr($str, " ")) { $str = str_replace(" ", " ", $str); } return $str; } Loại bỏ các tag HTML /** * Loai bo tat ca cac the HTML * * @param string $str * @return string */ function removeHTML($str) { return preg_replace('/<([\/\w]+)[^>]*>/si', '', $str); Lấy thời gian hiện tại dựa trên giờ GMT /** * Lay thoi gian hien tai theo GMT * * @param int $offsetHours * @return int */ function getCurrentTime($offsetHours = 0) { $time = mktime(gmdate('H'), gmdate('i'), gmdate('s'), gmdate('m'), gmdate('d'), gmdate('Y')) + ($offsetHours * 60 * 60); return $time; } Hiển thị ngày tháng và giờ theo vùng GMT +7 putenv("TZ=Asia/Jakarta"); echo 'Hôm nay: '.date('D d - m - Y h:i A').'.
'; echo 'Giờ được tính theo giờ (GMT'.date('O').')
'; Upload file đơn giản: <form method="post" enctype="multipart/form-data"> File name: <input type="file" name="userfile"> <input type="submit" value="Upload"> </form> <?php if (isset($_FILES['userfile'])){ if (is_uploaded_file($_FILES['userfile']['tmp_name'])) { move_uploaded_file($_FILES['userfile']['tmp_name'], "./" . $_FILES['userfile']['name']); echo "File is valid, and was successfully uploaded"; } } ?> Upload đồng thời nhiều file (bao nhiêu tùy thích): <form method="post" enctype="multipart/form-data"> File name: <input type="file" name="userfile[]">
File name: <input type="file" name="userfile[]">
File name: <input type="file" name="userfile[]">
File name: <input type="file" name="userfile[]">
File name: <input type="file" name="userfile[]">
<input type="submit" value="Upload"> </form> <?php if (isset($_FILES['userfile'])){ //print_r($_FILES); foreach ($_FILES['userfile']['name'] as $k=>$v){ if (is_uploaded_file($_FILES['userfile']['tmp_name'][$k])) { move_uploaded_file($_FILES['userfile']['tmp_name'][$k], "./" . $_FILES['userfile']['name'][$k]); echo "File '" . $_FILES['userfile']['name'][$k] . "' is valid, and was successfully uploaded
"; } } } ?> Chức năng tạo ảnh thumbnail: Upload các file ảnh JPG, thay đổi kích thước thực sự (resize) và ghi thành file mới. FORM upload <form action="resizeimage1.php" method="post" enctype="multipart/form-data"> <input name="image1" type="file">
<input name="image2" type="file">
<input name="image3" type="file">
<input name="" type="submit"> </form> File xử lý <?php $image1 = basename($_FILES['image1']['name']); $image2 = basename($_FILES['image2']['name']); $image3 = basename($_FILES['image3']['name']); $uploaddir = 'D:\\Webs\\Demo\\Img\\'; $uploadfile1 = $uploaddir . basename($_FILES['image1']['name']); $uploadfile2 = $uploaddir . basename($_FILES['image2']['name']); $uploadfile3 = $uploaddir . basename($_FILES['image3']['name']); // echo '
';
if (move_uploaded_file($_FILES['image1']['tmp_name'], $uploadfile1)) {
   echo "Image1 is valid, and was successfully uploaded.\n";
} else {
   echo "Possible file upload attack!\n";
   echo "
"; } // echo '
';
if (move_uploaded_file($_FILES['image2']['tmp_name'], $uploadfile2)) {
   echo "Image2 is valid, and was successfully uploaded.\n";
} else {
   echo "Possible file upload attack!\n";
   echo "
"; } // echo '
';
if (move_uploaded_file($_FILES['image3']['tmp_name'], $uploadfile3)) {
   echo "Image3 is valid, and was successfully uploaded.\n";
} else {
   echo "Possible file upload attack!\n";
   echo "
"; } echo "Car inserted into database"; // Now Resize Images /* resizeToFile resizes a picture and writes it to the harddisk * * $sourcefile = the filename of the picture that is going to be resized * $dest_x = X-Size of the target picture in pixels * $dest_y = Y-Size of the target picture in pixels * $targetfile = The name under which the resized picture will be stored * $jpegqual = The Compression-Rate that is to be used */ function resizeToFile ($sourcefile, $dest_x, $dest_y, $targetfile, $jpegqual) { /* Get the dimensions of the source picture */ $picsize=getimagesize("$sourcefile"); $source_x = $picsize[0]; $source_y = $picsize[1]; $source_id = imageCreateFromJPEG("$sourcefile"); /* Create a new image object (not neccessarily true colour) */ $target_id=imagecreatetruecolor($dest_x, $dest_y); /* Resize the original picture and copy it into the just created image object. Because of the lack of space I had to wrap the parameters to several lines. I recommend putting them in one line in order keep your code clean and readable */ $target_pic=imagecopyresampled($target_id,$source_id, 0,0,0,0, $dest_x,$dest_y, $source_x,$source_y); /* Create a jpeg with the quality of "$jpegqual" out of the image object "$target_pic". This will be saved as $targetfile */ imagejpeg ($target_id,"$targetfile",$jpegqual); return true; } //Set Quality to Max $jpegqual = '100'; //Resize Main Image $sourcefile = $uploadfile1; $targetfile = $uploaddir . 'main_' . basename($_FILES['image1']['name']); $dest_x = '570'; $dest_y = '428'; resizeToFile ($sourcefile, $dest_x, $dest_y, $targetfile, $jpegqual); $sourcefile = $uploadfile2; $targetfile = $uploaddir . 'main_' . basename($_FILES['image2']['name']); $dest_x = '570'; $dest_y = '428'; resizeToFile ($sourcefile, $dest_x, $dest_y, $targetfile, $jpegqual); $sourcefile = $uploadfile3; $targetfile = $uploaddir . 'main_' . basename($_FILES['image3']['name']); $dest_x = '570'; $dest_y = '428'; resizeToFile ($sourcefile, $dest_x, $dest_y, $targetfile, $jpegqual); //Create Thumbnails $sourcefile = $uploadfile1; $targetfile = $uploaddir . 'thumb_' . basename($_FILES['image1']['name']); $dest_x = '120'; $dest_y = '90'; resizeToFile ($sourcefile, $dest_x, $dest_y, $targetfile, $jpegqual); $sourcefile = $uploadfile2; $targetfile = $uploaddir . 'thumb_' . basename($_FILES['image2']['name']); $dest_x = '120'; $dest_y = '90'; resizeToFile ($sourcefile, $dest_x, $dest_y, $targetfile, $jpegqual); $sourcefile = $uploadfile3; $targetfile = $uploaddir . 'thumb_' . basename($_FILES['image3']['name']); $dest_x = '120'; $dest_y = '90'; resizeToFile ($sourcefile, $dest_x, $dest_y, $targetfile, $jpegqual); //Delete Uploaded Source Files as no longer required if(file_exists($uploadfile1)) unlink($uploadfile1); if(file_exists($uploadfile2)) unlink($uploadfile2); if(file_exists($uploadfile3)) unlink($uploadfile3); ?>

Hướng dẫn dùng dnsparking (www.everydns.net)Chuyển phần mềm cài đặt từ chỗ này sang chỗ khác

Write a comment

You must be logged in to write a comment. If you're not a registered member, please sign up.

December 2009
S M T W T F S
November 2009January 2010
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31