Một số đoạn code thường được sử dụng trong PHP
Wednesday, 12. March 2008, 19:24:30
-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 . '">
'; 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);
?>









