Danh mục : PHP - PHP5- PHP7

Thủ thuật php

Thủ thuật php

Thủ thuật php


Sử dụng PHP để chuyển đến 1 URL khác

PHP

Code:

header("Location: http://yoursite.com/")

?>



Trong HTML bạn có thể sử dụng đoạn mã sau:
 

Code:

 

   

   

   

   

   

 

   

   

 

Hiển thị thông tin trình duyệt đang sử dụng.


Bạn sử dụng đoạn PHP sau trong đoạn mà bạn muốn hiển thị:

PHP

Code:

$browser = "$HTTP_USER_AGENT"; 

print("Bạn đang sử dụng: $browser")

?>


hoặc 

PHP

Code:

 

print(" Bạn đang sử dụng: $browser ")

 

Tạo 1 cái Shoutbox đơn giản

Bạn làm theo các bước sau đây.

B1: Tạo 1 DB như sau:

PHP Code:

CREATE TABLE `tagboard` ( 
`idint(7NOT NULL auto_increment
`namevarchar(250NOT NULL default ''
`commentstext NOT NULL
`datetimestamp(14NOT NULL
PRIMARY KEY (`id`), 
TYPE=MyISAM AUTO_INCREMENT=419 ;  

 


B2:Viết 1 file config.php có nội dung như sau:

PHP Code:


$dbuser=""//Database Username 
$dbname=""//Database Name 
$dbpass=""// Database Password 
?>


B3:Tạo 1 file tag.php có nôi dung như sau:

PHP Code:

<iframe src="view.php" name="tag" width="179" height="130" frameborder=0 marginwidth="0" marginheight="0">iframe><form method="POST" ACTION="todo.php"
<input type="text" NAME="name" Value=">"
<textarea NAME="post" cols="27" rows="3">textarea
<br
<input TYPE="submit" value="Submit">  

 


B4:Tiếp theo là file todo.php

PHP Code:


if ($name == '' || $post == ''") 

die ("Please fill all fieldsClick <a HREF=tag.php>hereato return."); 

include('config.php'); 

$post = preg_replace("/","&lt;",$post); 
$post = preg_replace("/>/","&gt;",$post); 
$post = nl2br($post); 
$comments = "$post"; 


$c=mysql_connect("localhost","$dbuser","$dbpass"); 
mysql_select_db($dbname); 
$todo="INSERT INTO tagboard (id,name,comments,dateVALUES('','$name','$comments',now())"; 
$solution = mysql_query($todo) or die (mysql_error()); 
if ($solution) 

?> 
refresh" content="0;url=tag.php" > 

} ?>


B5:Cuối cùng là file view.php

PHP Code:


include('config.php'); 
//Kết nối DB 
$c=mysql_connect("localhost","$dbuser","$dbpass"); 
//Lựa chọn DB 
mysql_select_db($dbname); 
//Lựa chọn tên DB 
$todo='SELECT * FROM `tagboard` order by id desc LIMIT 50'
$solution=mysql_query($todo); 
while ($place mysql_fetch_array($solution)) 

$id=$place["id"]; 
$comments=$place["comments"]; 
//là nơi hiển thị trên trang web 
?> 
»echo "$place[name]"?>
echo ": $comments
?> 

}?>


Chúc bạn thành công !

 

Ngày 1: Những câu lệnh cơ bản xử lí chuỗi

Code:

 

//Hàm kiem tra mot chuoi có phai là mot hyperlink:

 

function checkLink($link){

 * *if (!stristr($link, "http://")) return "http://".$link;

 * *else return $link;

 *}

 

//Hàm cat bo khong trong trong chuoi:

 

function stripSpaces($text, $replace=NULL) {

 * *if (is_string($replace)) return str_replace(" ", substr($replace, 0, 1), $text);

 * *else return str_replace(" ", "", $text);

 *}

 

//Hàm kiem tra mot chuoi có phai là các ky tu alphabet hoac ky tu so tu 0-9

 

 function alphaNum($stripper) {

 * *return preg_replace("/[^a-zA-Z0-9]/", "", $stripper);

 *}

 

//Hàm kiem tra chuoi có chua duu ' hoac dau ":

 

function checkUnslashed($text){

 * *if (preg_match("/[\s\w]+[\"']/", $text))

 * * *return TRUE;

 * *else

 * * *return FALSE;

 *}

 

//Hàm cat bo dau ' hoac dau " trong chuoi:

 

 function stripQuotes($text) {

 * *$text = str_replace("'", "", $text);

 * *$text = str_replace("\"", "", $text);

 * *return $text;

 *}

 

//Hàm thêm vào dau \ tryuoc dau ' hoac dau ":

 

function addslashes($text) {

 * *if (get_magic_quotes_gpc()) return $text;

 * *else return addslashes($text);

 *}

 

//Hàm ma hóa ky tu sang utf-8, rat hay dó các ban:

 

 function utfEncode($text){

 * *$text = $this->stripSlashQuotes($text);

 

 * *$search = array("//");

 * *$replace = array('<', '>');

 

 * *return preg_replace($search, $replace, $text);

 *}

 

//Hàm *kiem tra bay loi các dang chuoi nhap vào (form nhap) *nhu email,number,file,...

 

function isValidInput($userEntry, $type=NULL) {

 * *if (empty($userEntry) || !is_string($userEntry)) return FALSE;

 

 * *switch ($type) {

 * *case "chars_space":

 *if (eregi("^[a-z_0-9 ]+$",$userEntry)) return TRUE;

 *else return FALSE;

 *break;

 

 * *case "number":

 *if (ereg("^[0-9]+$",$userEntry)) return TRUE;

 *else return FALSE;

 *break;

 

 * *case "url":

 *if (eregi("^(http:\/\/)[_a-z0-9-]+(\.[_a-z0-9-]+|\/)", $userEntry)) return TRUE;

 *else return FALSE;

 *break;

 

 * *case "email":

 *if (eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)+$", $userEntry)) return TRUE;

 *else return FALSE;

 *break;

 

 * *case "file":

 *if (eregi("^[a-z_0-9\.]+$",$userEntry)) return TRUE;

 *else return FALSE;

 *break;

 

 * *default:

 *if (eregi("^[a-z_0-9]+$",$userEntry)) return TRUE;

 *else return FALSE;

 *break;

 * *}

 *}// END FUNC validForm()

?>

Tiêu đề "Mỗi ngày một source" không đúng với topic này!

 

Tạo 1 mini chat đơn giản.

B1. Tạo 1 file HTML có nội dung như sau:

PHP Code:

<html
<head
<title>Mini chat &#273;ơn giản 
head
<body
  <form method="post"><br
  Login:<input type="text" name="login" size="6"><br
  Message:<input type="text" name="message" size="10"><br
  <input type="submit" value="Send"><br
  form
body
html>  

 


B2. Tạo 1 file php có nội dung như sau

PHP Code:


/* 
CREATE TABLE MINICHAT ( 
  LOGIN varchar(20) NOT NULL default '', 
  MESSAGE varchar(255) NOT NULL default '', 
  ITSTIME varchar(10) NOT NULL default '' 
); 
*/ 

// Thêm thông điệp vào mini chat 
function addMessage$login$message ) { 

   $login mysql_escape_stringstrip_tags$login ) ); 
   $message mysql_escape_stringstrip_tags$message'') ); 
   mysql_query"INSERT INTO MINICHAT ( ITSTIME, LOGIN, MESSAGE ) VALUES ( "'".time()."''".$login."','".$message."' )"); 


// Gửi thông điệp 
if ( isset( $_POST['msg'] )) { 
   addMessage( $_POST['login'], $_POST['msg'] ); 

?>


Chú ý: Bạn nên tách rời đoạn tạo DB va lưu nó thành 1 file config.php, bạn tham khảo thử bài trên.

Chúc bạn thành công ! 
Description: http://www.updatesofts.com/forums/images/smilies/1.gif

 

Viết 1 trang Upload = PHP.

B1. Bạn viết 1 trang HTML có nội dung như sau:

PHP Code:

<html>  
<head>  
<title>Uploadtitle>  
head>  
<body>  
<h1>Uploadh1>  
<form enctype="multipart/form-data" action="upload.php" method="post">  
<input type="hidden" name="MAX_FILE_SIZE" value="1000000"File:  
<input name="userfile" type="file">  
<input type="submit" value="Upload">  
form>  
body>  
html>  

 



B2. Bạn viết 1 trang upload.php:

PHP Code:


// $userfile is where file went on webserver  
$userfile $HTTP_POST_FILES['userfile']['tmp_name'];  
// $userfile_name is original file name  
$userfile_name $HTTP_POST_FILES['userfile']['name']; 
// $userfile_size is size in bytes  
$userfile_size $HTTP_POST_FILES['userfile']['size'];  
// $userfile_type is mime type e.g. image/gif  
$userfile_type $HTTP_POST_FILES['userfile']['type'];  
// $userfile_error is any error encountered  
$userfile_error $HTTP_POST_FILES['userfile']['error'];  

// userfile_error was introduced at PHP 4.2.0  
// use this code with newer versions  

if ($userfile_error 0) {  
echo 'Problem: ';  
switch ($userfile_error)  
{ case 1:  
echo 'File exceeded upload_max_filesize';  
break;  
case 2:  
echo 'File exceeded max_file_size';  
break;  
case 3:  
echo 'File only partially uploaded';  
break; 
case 4:  
echo 'No file uploaded';  
break;  
}  
exit;  
}  

// put the file where we'd like it  
$upfile '/uploads/'.$userfile_name;  

// is_uploaded_file and move_uploaded_file  
if (is_uploaded_file($userfile))  
{  
if (!move_uploaded_file($userfile$upfile))  
{  
echo 'Problem: Could not move file to destination directory';  
exit;  
}  
} else {  
echo 'Problem: Possible file upload attack. Filename: '.$userfile_name;  
exit;  
}  
echo 'File uploaded successfully

'
;  

// show what was uploaded  
echo 'Preview of uploaded file contents:

 


';  
echo $contents
echo '


';  
?>


Chú ý ở trên: dòng $upfile = '/uploads/'.$userfile_name; là thư mục các file upload được lưu vào, bạn có thể thay đổi nó tùy theo ý mình.

Chúc bạn thành công ! 
Description: http://www.updatesofts.com/forums/images/smilies/1.gif

 

Hiển thị thông tin trình duyệt đang sử dụng.

Bạn sử dụng đoạn PHP sau trong đoạn mà bạn muốn hiển thị:

PHP Code:


$browser "$HTTP_USER_AGENT";  
print("Bạn đang sử dụng: $browser"
?>


Để đẹp hơn bạn có thể sửa thành:

PHP Code:

print(" Bạn đang sử dụng: $browser ")  
 


Chúc bạn thành công ! Description: http://www.updatesofts.com/forums/images/smilies/1.gif



Tạo cho mình 1 mục tìm kiếm ngay trên site của bạn

Quote:

Tạo cho mình 1 mục tìm kiếm ngay trên site của bạn (sử dụng google)

Trước hết bạn tạo 1 form để nhập từ khóa tìm kiếm:

PHP Code:

<form action="search.php" method="post">  
    <input type="text" name="search">  
<br
    <input type="submit" value="Search"> <input type="reset" value="Reset">  
form>  

 



Còn đây là nội dung file search.php:

PHP Code:


$website "www.yoursite.com";  

$search $_POST['search'];  
$search str_replace(" ","+",$search);  
$search stripslashes($search);  

header("Location: http://www.google.com/search?q=site%3A$website+%22$search%22&btnG=Google+Search");  
?>


Chú ý thay đổi www.yoursite.com thành địa chỉ website của bạn. 
Chúc bạn thành công ! Description: http://www.updatesofts.com/forums/images/smilies/1.gif

 

Hiển thị hình ảnh Random ở chữ ký.

Bạn tạo 1 thư mục images chứa các hình ảnh cần hiển thị và 1 file random.php có nội dung như sau:

PHP Code:


$folder 'images/'//tên thư mục mà bạn lưu chứa hình ảnh. 
                    
$exts 'jpg jpeg png gif'

$files = array(); $i = -1
if ('' == $folder$folder './'
$handle opendir($folder); 
$exts explode(' '$exts); 
while (false !== ($file readdir($handle))) { 
    foreach($exts as $ext) {  
        if (preg_match('/\.'.$ext.'$/i'$file$test)) {  
            $files[] = $file
            ++$i
            } 
        } 
    } 
closedir($handle);  
mt_srand((double)microtime()*1000000);  
$rand mt_rand(0$i);  

header('Location: '.$folder.$files[$rand]); 
?>


Để hiển thị những hình ảnh đó bạn chỉ cần chèn dòng sau vào chữ ký của bạn:

PHP Code:

[img*]http://www.yoursite.com/random.php[*/img]  
 


Chú ý: Bỏ * trong đoạn mã trên
Chúc bạn thành công ! 
Description: http://www.updatesofts.com/forums/images/smilies/1.gif

 

Tạo cho mình 1 form mail liên hệ trên web.

Bắt đầu với đoạn mã sau:

PHP Code:


print(

 

 

 


 


 


  
 
 
"); 
// Đây là phần hiển thị để khách hàng điền thông tin. 
?>


Viết 1 file form.php có nội dung như sau:

PHP Code:


$_GET['action'] = (isset($_GET['action'])) ? $_GET['action'] : 
''
if ($_GET['action'] == 'send') { 
if (empty($_POST['name']) || empty($_POST['sender']) || empty($_POST['subject']) || empty($_POST['text'])) 
// Kiểm tra các thông tin trong field 

echo '

Xin vui lòng điền đầy đủ thông tin!

'
} else { 
extract($_POST); 
$ip $_SERVER['REMOTE_ADDR']; 
$email "[email protected]"
// Thay đổi thành email của bạn 
$mailmsg "Name: $name\n"
$mailmsg .= "Email: $sender\n"
$mailmsg .= "Subject: $subject\n"
$mailmsg .= "IP: $ip\n\n"
$mailmsg .= "Message: $text"
if (mail($email$subject$mailmsg"From: $sender\n")); 

print("

Thông tin của bạn đã được chuyển đi!

"); 



?>

 


Chúc bạn thành công ! Description: http://www.updatesofts.com/forums/images/smilies/1.gif

Tạo 1 đồng hồ trên site của bạn.

PHP Code:


$time_offset ="0";  
$adj = ($time_offset 120);  
$time date(" h:i:s",time() + $adj);  

echo "$time"
?>


Chúc bạn thành công ! Description: http://www.updatesofts.com/forums/images/smilies/1.gif

 

Lưu lại thông tin User vào website.

Bạn tạo 1 file logger.txt và cho nó vào thư mục admin.
Sau đó bạn viết 1 file PHP có nội dung như sau:

PHP Code:


$Date date("F jS Y, h:iA");  
$user_ip $REMOTE_ADDR;  
$host gethostbyaddr($user_ip);  
$user_browser $HTTP_USER_AGENT;  
$file "admin/logger.txt";  
$fp fopen($file"a+");  
fputs ($fp"
Date: $Date 
 IP: $user_ip 
 Host(ISP) $host 
 Trình duyệt: $user_browser
------------------------------------
"
);  
fclose($fp);  
?>


CHúc bạn thành công ! Description: http://www.updatesofts.com/forums/images/smilies/1.gif

 

Phongle(UDS)

 


Tags