2009年10月29日 星期四

樹狀menu

  



2009年10月14日 星期三

FreeBSD SSH配置

文章出處:FreeBSD SSH配置詳解

首先vi編輯/etc/inetd.conf,去掉ssh前的#,保存退出
編輯/etc/rc.conf
最後加入:sshd_enable="yes"即可
激活sshd服務:
#/etc/rc.d/sshd start
用下面命令檢查服務是否啟動,在22端口應該有監聽。
#netstat -an //檢視有無 *.22 LISTEN
最後
vi /etc/ssh/sshd_config,

下面是我的配置文件:(/etc/ssh/sshd_config)
####################################################

# $OpenBSD: sshd_config,v 1.72 2005/07/25 11:59:40 markus Exp $
# $FreeBSD: src/crypto/openssh/sshd_config,v 1.42.2.1 2005/09/11 16:50:35 des Exp $

# This is the sshd server system-wide configuration file. See
# sshd_config(5) for more information.

# This sshd was compiled with PATH=/usr/bin:/bin:/usr/sbin:/sbin

# The strategy used for options in the default sshd_config shipped with
# OpenSSH is to specify options with their default value where
# possible, but leave them commented. Uncommented options change a
# default value.

# Note that some of FreeBSD's defaults differ from OpenBSD's, and
# FreeBSD has a few additional options.

#VersionAddendum FreeBSD-20050903

#Port 22
#Protocol 2
#AddressFamily any
#ListenAddress 10.1.10.196
#ListenAddress ::

# HostKey for protocol version 1
#HostKey /etc/ssh/ssh_host_key
# HostKeys for protocol version 2
#HostKey /etc/ssh/ssh_host_dsa_key

# Lifetime and size of ephemeral version 1 server key
#KeyRegenerationInterval 1h
#ServerKeyBits 768

# Logging
# obsoletes QuietMode and FascistLogging
#SyslogFacility AUTH
#LogLevel INFO

# Authentication:

#LoginGraceTime 2m
#PermitRootLogin no
#StrictModes yes
#MaxAuthTries 6

#RSAAuthentication yes
#PubkeyAuthentication yes
#AuthorizedKey .ssh/authorized_keys
# For this to work you will also need host keys in /etc/ssh/ssh_known_hosts
#RhostsRSAAuthentication no
# similar for protocol version 2
#HostbasedAuthentication no
# Change to yes if you don't trust ~/.ssh/known_hosts for
# RhostsRSAAuthentication and HostbasedAuthentication
#IgnoreUserKnownHosts no
# Don't read the user's ~/.rhosts and ~/.shosts files
#IgnoreRhosts yes

# Change to yes to enable built-in password authentication.
PasswordAuthentication yes
#PermitEmptyPasswords no

# Change to no to disable PAM authentication
#ChallengeResponseAuthentication yes

# Kerberos options
#KerberosAuthentication no
#KerberosOrLocalPasswd yes
#KerberosTicketCleanup yes
#KerberosGetAFSToken no

# GSSAPI options
#GSSAPIAuthentication no
#GSSAPICleanupCredentials yes

# Set this to 'no' to disable PAM authentication, account processing,
# and session processing. If this is enabled, PAM authentication will
# be allowed through the ChallengeResponseAuthentication mechanism.
# Depending on your PAM configuration, this may bypass the setting of
# PasswordAuthentication, PermitEmptyPasswords, and
# "PermitRootLogin without-password". If you just want the PAM account and
# session checks to run without PAM authentication, then enable this but set
# ChallengeResponseAuthentication=no
#UsePAM yes

#AllowTcpForwarding yes
#GatewayPorts no
#X11Forwarding yes
#X11DisplayOffset 10
#X11UseLocalhost yes
#PrintMotd yes
#PrintLastLog yes
#TCPKeepAlive yes
#UseLogin no
#UsePrivilegeSeparation yes
#PermitUserEnvironment no
#Compression delayed
#ClientAliveInterval 0
#ClientAliveCountMax 3
#UseDNS no
#PidFile /var/run/sshd.pid
#MaxStartups 10

# no default banner path
#Banner /some/path

# override default of no subsystems
Subsystem sftp /usr/libexec/sftp-server

IgnoreRhosts yes
IgnoreUserKnownHosts yes
PrintMotd yes
StrictModes no
RSAAuthentication yes
PermitRootLogin yes #允許root登錄
PermitEmptyPasswords no #不允許空密碼登錄
PasswordAuthentication yes # 設置是否使用口令驗證。

##############################################

記得修改完配置文件後,重新啟動sshd服務器(/etc/rc.d/sshd restart)即可。

2009年9月15日 星期二

清空apache的log檔案

清除方式:
cp /dev/null /var/log/httpd-access.log
cp /dev/null /var/log/httpd-error.log

使用別名清除(bash):
編輯/etc/profile
ee /etc/profile
aslias clrlog="cp /dev/null /var/log/httpd-access.log;cp /dev/null /var/log/httpd-error.log"

2009年8月26日 星期三

2009年7月9日 星期四

MySQL資料庫中一堆mysql-bin.00000X的東東

MySQL資料庫中,一堆mysql-bin.000001、mysql-bin.000002…的東東,有些都爆大的,網路搜尋找到官網有人提出類似問題:
http://forums.mysql.com/read.php?26,127650,127650
基本上可刪除它,它只是一般的log檔案。
==MS系統使用方式,從1開始==
1. 開始→執行→cmd

2. cd C:\AppServ\MySQL\data(進入存放這些log檔案的資料夾中)
==Freebsd系統使用方式,從3開始==
3. mysql -u root -p

4. 輸入MySQL密碼

5. mysql> reset master;(最後面的分號別忘了加上)

6. my.ini中可以註解掉
#log-bin=mysql-bin
#binlog_format=mixed

以後就不會再生出來這麼多的mysql-bin.00000X,目前預設都沒開啟,想要開啟的可以自己加入。

7. 也可直接刪除mysql-bin.00000X的東東。

突發狀況記錄

關於出現sh/sell錯誤指令,而無法正常開機
解決如下
fsck -y
mount -a
reboot

2009年4月26日 星期日

修改FreeBSD 系統時間 (freebsd 時間為:UTC)

首先要瞭解這兩個時間定義
UTC----全球標準時間指的是由世界時間標準設定的時間。原先也被稱為格林威治標準時間或者 GMT
CST----CMOS時間,即本機的時間!

因為剛安裝系統是使用UTC時間,所以安裝系統後,需要設置回台灣時區!

#date YYMMHHMM //(年月時分)設定當地時間
#cp /usr/share/zoneinfo/Asia/Taipei /etc/localtime //指定時區
#adjkerntz -a //調整COMS時間
#date

重啟完後! 看時間沒有改變!!
PS:
adjkerntz 命令 adjkerntz = adjust kernal timezone
調整改變CMOS時間來反映出時區的改變及讓kernel維持著當前的時區
-a 當時區改變時,這個形態被用來更新 CMOS 當地時間

2009年4月23日 星期四

chmod 權限

-rw-------(600)--只有屬主有讀寫權限。

-rw-r--r--(644)--只有屬主有讀寫權限;而屬組用戶和其他用戶只有讀權限。

-rwx------(700)--只有屬主有讀、寫、執行權限。

-rwxr-xr-x(755)--屬主有讀、寫、執行權限;而屬組用戶和其他用戶只有讀、執行權限。

-rwx--x--x(711)--屬主有讀、寫、執行權限;而屬組用戶和其他用戶只有執行權限。

-rw-rw-rw-(666)--所有用戶都有文件讀、寫權限。這種做法不可取。

-rwxrwxrwx(777)--所有用戶都有讀、寫、執行權限。更不可取的做法。

以下是對目錄的兩個普通設定:

drwx------(700)-只有屬主可在目錄中讀、寫。

drwxr-xr-x(755)-所有用戶可讀該目錄,但只有屬主才能改變目錄中的內容。

2009年4月20日 星期一

FreeBSD 一些 /etc/ 下檔案的說明

原作者 chinaunix.net keigopan

---- 以下是內容 ----

FreeBSD中/etc下的文件可以說是紛繁復雜,對熟悉它的人來講不算什麼,但對于一個新手來說就。。。太亂了,下面是一些經常用到的配置文件的作用和配置方法,但願能給你一點幫助。

1. aliases
2. crontab
3. csh.cshrc
4. csh.login
5. csh.logout
6. daily
7. defaultdomain
8. exports
9. fbtab
10.fstab
11.ftpusers
12.group
13.host.conf
14.hosts
15.inetd.conf
16.localtime
17.login.conf
18.make.conf
19.monthly
20.motd
21.netstart----新版已改名為/etc/rc.network
22.passwd
23.printcap
24.profile
25.rc
26.rc.conf----代替原來的/etc/sysconfig
27.rc.conf.local----代替原來的/etc/rc.local
28.rc.i386
29.rc.local----新版改名為/etc/rc.conf.local
30.rc.network----代替原來的/etc/netstart
31.resolv.conf
32.services
33.shells
34.sysconfig----新版已改名為/etc/rc.conf
35.syslog.conf
36.termcap
37.ttys
38.weekly

1. aliases

這個檔案主要是告訴 sendmail 要將信轉寄給哪些使用者, 或是交由哪個程式處理.

如. root: user1,name2,user3
usenet: "|/usr/local/bin/mail-post.pl"

如上範例, sendmail 會將原先寄給的 root 的信分送給 user1 和 name2 和 user3, 而把寄給 usenet 的信交由 mail-post.pl 處理.

在你修改完之後, 要記得執行 "newaliases" 來更新 /etc/aliases.db

關於 aliases 之詳細說明, 請 man aliases 查詢.

2. crontab

這是給 root 用的 crontab file, 你也可以殺掉這個檔案以 "crontab -e" 來替代.
格式如下...

#分 小時 天 月 禮拜几 用誰的身份 命令
*/5 * * * * root /usr/libexec/atrun

minute: 分鐘/小時, 范圍自 0 至 59
hour: 小時/天, 范圍自 0 至 23
mday: 天/月, 范圍自 0 至 31
month: 月/年, 范圍自 0 至 12
wday: 天/周, 范圍自 0 至 7 (0, 7 表示星期天)
who: 表是以誰的身份執行這個 command
(這只對 /etc/crontab 有用, crontab -e 無此欄位)
command: 命令或是 shell script

*/N: 表示每 N 一算, 像小時而言, */3 指的是 0,3,6,9,12

請 man 5 crontab 去看詳細說明.

3. csh.cshrc

# 系統內定給 csh shell 用的 .cshrc 檔

## 确定 HOME 目錄
setenv HOME $HOME
set home=$HOME
cd $HOME

## 檔案權限設定
umask 022

## 就是 Aliases 嘛
alias pftp '/usr/local/bin/pftp'
alias free 'pstat -s|grep -v not'
alias talk ytalk
alias ruptime '/usr/bin/ruptime|grep -v down'
alias ftp ncftp
alias rwho '/usr/bin/rwho -a|grep -v LOGIN'
alias more less
alias zmore zless
alias m less
alias pss 'ps auxw|sort -k 2|grep $USER'
alias psm 'ps auxw|sort -k 1,2|more'
alias psl psm
alias psv 'ps auxw|grep -v $USER|sort -k 2|more'
alias d '/usr/local/bin/colorls -G -alFgk \!* | more'
alias dir '/usr/local/bin/colorls -G -alFgk \!*'
alias rd rmdir
alias md mkdir
alias cls clear
alias cd.. 'cd ..'
alias del '/bin/rm -i'
alias xdel '/bin/rm -rf'
alias mv 'mv -i'
alias dir/w '/bin/ls -aFgk'
alias dw '/bin/ls -aFgk'
#alias x '(startx &)>&/dev/console;sleep 300;lo'
#alias lpr 'lpr -m'
alias cp 'cp -i'
alias rm 'rm -i'
alias lo 'clear;exit'
alias bye 'clear;exit'
#alias vi cvi
alias unlo 'unset autologout;unsetenv autologout'
alias q joe
alias .. 'cd ..'
alias ... 'cd ../..'
#alias ku 'ku -W'
alias tin rtin
#alias s 'exec screen'

## 環境設定
set path = (/sbin /usr/sbin /bin /usr/bin /usr/local/sbin /usr/local/bin)
set path = ($path /etc /usr/etc /usr/local/etc)
set path = ($path /usr/X11R6/bin /usr/games)
set path = ($path ~ ~/bin .)
set mail = (10 /var/mail/$USER)
set recexact
set autolist
set matchbeep = ambiguous
set autoexpand
set autocorrect
set ignoreeof
set noclobber
set notify
set correct = all
if ( ! $?WINDOW ) then
# set prompt = "%B%m [%/] [%?] -%n- "
set prompt = "%B%m [%/] -%n- "
else
set prompt = "%B%m [%/] -%n- [W$WINDOW] "
endif
set prompt2 = "(%t %m)%~ #%% "
set prompt3 = "%SDo you mean [%R] (y/n/e) ? "
set history = 500
set savehist = 500
set time=100
#set watch=(1 any any)
set symlinks = ignore
set listlinks
set listjobs
set rmstar
set showdots
#set tperiod = 30
# set autologout = (60 2)
#setenv MANPATH /usr/man:/usr/local/man:/usr/man/preformat:/usr/X11/man:/usr/openwin/man
setenv EDITOR /usr/local/bin/joe
setenv VISUAL /usr/local/bin/joe
setenv EXINIT 'set ai'
setenv LESS "-EsPm-LESS-"
setenv LESSCHARDEF "8bcccbcc18b95.."
setenv PAGER "less -Em"
#setenv PAGER more
setenv LC_CTYPE lt_LN.ISO_8859-1
setenv LANG C
setenv BLOCKSIZE 1k
setenv MACHINE_ARCH i386
setenv MACHINE i386
setenv ORGANIZATION "交大資工 ADONIS"

## X 相關設定
setenv XWINHOME '/usr/X11R6'
setenv X11HOME '/usr/X11R6'
setenv OPENWINHOME '/usr/X11R6'
setenv XKEYSYMDB /usr/X11R6/lib/X11/XKeysymDB
setenv XNLSPATH /usr/X11R6/lib/X11/nls
#setenv LD_LIBRARY_PATH /usr/lib:/usr/X11R6/lib:/usr/local/lib
stty erase '^?'

if ( $?TERM ) then
if ($TERM == "xterm" || $TERM == "xterms") then
stty erase '^H'
endif
endif

## 雜七雜八設定
#set term = vt100
#set TERM = vt100
#setenv term vt100
#setenv TERM vt100
#stty extb
stty 38400
stty crt
stty -tabs
stty -istrip
stty pass8
unlo
#bindkey "[HOME]" beginning-of-line
#bindkey "[ESC]" keyboard-quit
limit coredumpsize 0

# 給 FSP Client 用
setenv FSP_PORT 21
setenv FSP_HOST nctuccca.edu.tw
setenv FSP_DIR /
setenv FSP_TRACE
setenv FSP_DELAY 3000

# Aii.. 就是 fsp aliases
alias fcat '(set noglob; exec fcatcmd \!*)'
alias fcd 'setenv FSP_DIR `(set noglob; exec fcdcmd \!*)`;fpwd'
alias fdu \(set noglob\; exec fducmd \!\*\)
alias ffind \(set noglob\; exec ffindcmd \!\*\)
alias fget '(set noglob; exec fgetcmd \!*)'
alias fgrab '(set noglob; exec fgrabcmd \!*)'
alias fls '(set noglob; exec flscmd -F \!*)'
alias fll '(set noglob; exec flscmd -l \!*)'
alias fdir '(set noglob; exec flscmd -l \!*)'
alias fmore \(set noglob\; exec fcatcmd \!\* \| more\)
alias fpro '(set noglob; exec fprocmd \!*)'
alias fpwd 'echo "$FSP_HOST ($FSP_PORT): $FSP_DIR"'
alias frm '(set noglob; exec frmcmd \!*)'
alias frmdir '(set noglob; exec frmdircmd \!*)'
alias fhost 'setenv FSP_HOST \!*;setenv FSP_DIR /'

4. csh.login

# 系統內定的 .login 檔.

#stty extb
stty 38400
#stty crt
#stty -tabs
stty -istrip
stty pass8

# Mesg y if not console
mesg y
if ( `tty | cut -c 6-` == console ) then
mesg n
endif

msgs -fp

5. csh.logout

# 系統內定的 .logout
clear
.

6. daily

cron 會依照 /etc/crontab 去做每日例行的工作. 注意一下有些 commands 對你的硬盤造成很大的負荷, 像是最後一行的 "sh /etc/security", 他會從你的根目錄開始查詢. 你可以加些每天你想要執行的commands, 像是 "quotacheck -a", "bin/rm/-f /tmp*junk*.

7. defaultdomain

這個檔案記載你的 domainname, 你有跑 yp (nis) 時才有用. 當然閑閑填一填也沒差啦.

8. exports

這個檔案定義哪些目錄可經由 NFS 給別人使用.
例如 /cdrom -ro host1,host2
/home -maproot=root host3

Notice: 若你沒加 "-ro" 表示可以寫入, 所以你應當小心點.

做完修正後, "kill -1 $mountd_pid", 然後用 "showmount -e" 去看看 NFS 是否做的正确. 如果有錯, 用 "tail /var/log/messages" 來看錯誤訊息.

你應該要將 /etc/rc.conf 中的 nfs_client_enable, nfs_server_enable 設為 YES.

詳細說明請 man 5 exports.

9. fbtab

/dev/ttyv0 0600 /dev/console
/dev/ttyv1 0600 /dev/console
/dev/ttyv2 0600 /dev/console
/dev/ttyv3 0600 /dev/console
#/dev/ttyv0 0600 /dev/pcaudio:/dev/pcaudioctl

10.fstab

這個檔案定義當你開机時, 你想 mount 哪些 partition.
例如.

/dev/sd0a / ufs rw 1 1
/dev/sd0e /dos msdos ro,-gmsdos,-m750 1 1
/dev/sd0g /usr/local ufs rw,userquota 1 1
/dev/sd0h /home ufs rw,userquota,groupquota 1 1
/dev/sd0b none swap sw 0 0
proc /proc procfs rw 0 0
kern /kern kernfs rw 0 0

詳情請 man fstab.

如果你的 /usr 沒有跟 / 放在一起,要特別注意,/usr 不可以放在使用 LKM 載入的 filesystem 後面。例如,你的 MSDOSFS 是利用 LKM 載入的(也就是說,你沒有把 MSDOSFS 編譯在 kernel 中),你的 /dos
一定要放在 /usr 後面,不然開机會失敗,例如:

modload:exec(/usr/bin/ld):NO such file or directiory
msdos:vfsload(msdos):Operation not permitted
Filessystem mount failed,startup aborted
Enter pathname of shell or RETURN for sh

11.ftpusers

這個檔注明的 users 將無法 ftp 這台机器. 只要寫 username 即可. 算是禁止 ftp 進來的黑名單吧.

12.group

這個檔案主要記載著 group 名稱, group id 以及隸屬於該 group 的使用者.

要記得在 FreeBSD 中, 只有屬於 wheel group 的使用者才能 su 成 root.

在升級時特別注意 /usr/src/etc/group 中是否有新增系統 group, 如 network 這個 group 就是最近新增的 group.

其他詳細請用 man group.

13.host.conf

這個檔案決定 DNS-name-lookup 的先後順序. 你最好先 "hosts", 其次 "bind", 最後用 "nis".

hosts: 自 /etc/hosts 查詢.
bind: 自 nameserver (參考 /etc/resolv.conf 設定) 查詢.
nis: 自 nis server 查詢.

14.hosts

這個檔案記載了你所需要的 ip 和 hostname, 最少要包括 localhost 和你自己的 hostname, 通常是提供優先於 nameserver 的查詢, 或是沒有 nameserver 時的查詢.

格式如下:
IP-addr full-hostname alias
如. 123.456.789.123 heaven.net.com heaven

請 man hosts 去看詳細說明.

15.inetd.conf

這個檔案定義由 inetd 所提供的服務, 應該要和 /etc/services 保持一致性.

當你修改這個檔案的時候, 記得要 kill -1 $inetd_pid 去知會 inetd 要重新更新資料.

你可以安裝 tcp-wrapper (tcpd) 以增加安全性.

16.localtime

這個檔記載你所在的時區資料, 你可以從 /usr/share/zoneinfo 中選一個適合的來用.

就台灣而言, 你應該用 /usr/share/zoneinfo/Asia/Taipei, 正常來說, 在 install 時會自動將此檔案 copy 到 /etc/localtime.

17.login.conf

此檔案可控制系統資源與帳號各方面的限制,亦可設定內定之環境變數。

"man login.conf" for detail.

18.make.conf

當你用 make 時, 這個定義檔將被參考.

如果不是以 BSD 格式撰寫的 Makefiles, 你應該安裝 gmake (GNU)

19.monthly

每月例行的 jobs.

20.motd

Message Of Today, 顧名思義, 就是當你 login 時所出現的畫面.

假如你要有自己的 motd, 你必須把 /etc/rc.local 前面几行在開机時會更改 motd 的命令拿掉, 否則你每次開机 motd 會被亂改.

21.netstart----新版已改名為/etc/rc.network

目前此檔已由 /etc/rc.network 取代 目前此檔只作為 root 在 single user mode 要手動啟動網路服務
時使用。 這個檔案不要做更動, 應該去修改 /etc/rc.conf

22.passwd

/etc/passwd /etc/master.passwd /etc/spwd.db /etc/pwd.db 都是 由 vipw 所產生的. 關於怎樣去建一個帳號, 請參考 HOW-TO-adduser.

你可以 man passwd, vipw, chpass, chfn 查詢詳細說明.

23.printcap

這個檔案定義印表机的設定, 在修改後, 試著用 lpr 去列印一些東西, 假如你覺得很慢, 試著用 lptcontrol -p 去改變 /dev/lpt0 到 poll 模式, 當然, 你可以將 lptcontrol -p 加到 /etc/rc.local 里 以使每次開机都有效.

man lptcontrol 查詢詳細說明.

24.profile

這是 /bin/sh 的 default 設定.

25.rc

當系統開机時, kernel 會先去載入 /sbin/init, 然後 /sbin/init 會去執行 /etc/rc, 所以 /etc/rc 相對於 DOS 而言就好像 AUTOEXEC.BAT. 這個檔案不要去更改, 假如你不希望每次開机時 /tmp 會被清乾凈, 那你可以將跟 /tmp 相關的几行給砍掉. (個人偏好)

26.rc.conf----代替原來的/etc/sysconfig

這主要用來做系統開机時的環境設定. /etc/rc, /etc/rc.i386, /etc/rc.conf.local, /etc/rc.network, /etc/[bla bla] 都會參考這個檔案. 所以這個檔案可以說非常重要.

大多都有注解, 以下列舉一些你該注意的地方...
1) hostname : 你的完整 hostname (FQDN: 像是 freebsd.csie.nctu.edu.tw)
2) network_interfaces : 網路卡的 device name, 像是 "ed0 lnc0".
3) ifconfig_xxx : 定義網路卡及其 ip address.
像是 ifconfig_ed0="inet 140.113.145.1 netmask 0xffffff00"
ifconfig_ed1="inet 140.113.190.1 netmask 0xffffff00"
方法如下...
ifconfig_$device-name="inet $IP netmask $netmask",
netmask 0xffffff00 就是 255.255.255.0 表 Class C 網路.
4) defaultrouter: 內定的 router IP.(比如: 140.113.122.254)
5) routdflags : 通常 NO. 但是假如你想要跑 routed, 則用 "-s" 或 "-q".
詳細說明請 man routed.
6) rwhod : YES 執行 rwho daemon. rwho 跟 ruptime 須此 daemon.
7) sendmail_flags : 執行 sendmail daemon, 通常設為 "-db -q30m"
nfs_* : 執行 nfs client 或 server
9) check_quotas : enable 檔案系統 quotas
10) accountint : enable command accounting, "lastcomm" 須要.
11) firewall_enable : enable firewall 的功能
firewall_type : 指定 firewall 的形態

你應該設定完後再重新開机以測試是否每個改變都合乎你的要求.

27.rc.conf.local----代替原來的/etc/rc.local

在這個檔案加入你個人的設定, 你可以將開机時想要執行的動作放在這里. 像 gopherd, lptcontrol, swap-on-file 等.

28.rc.i386

這個檔案不要更動.

29.rc.local----新版改名為/etc/rc.conf.local

新版已由/etc/rc.conf.local所取代。

30.rc.network----代替原來的/etc/netstart

有關網路方面各項設定請由 /etc/rc.conf 設定,原則上此檔不需更動

31.resolv.conf

這定義 DNS 查詢 nameserver 的先後順序.

1. domain : 將你的 domainname 放這兒.
2. nameserver : 將你的 nameservers 放這兒, 最前面的會被當成主要的nameserver.
3. search : 將 domainnames 放這兒, 當你沒有輸入完整的 hostname 時, 他會將 domainnames 附加上去. 例如: search csie.NCTU.edu.tw NCTU.edu.tw edu.tw tw

詳情請 man resolver.

32.services

定義 service 名字以及 port. 不需要更動。

33.shells

所有的 shell 都應該放在這個檔案里, 像是 /bin/sh, /bin/tcsh, /home/bbs/bin/bbsrf 等等.

假如說有某個使用者的 shell 沒有列在這個檔案中, 有些程式如 ftpd 會拒絕該使用者 ftp, 如 adduser 將會拒絕執行.

man shells 查詢詳細說明.

34.sysconfig----新版已改名為/etc/rc.conf

參考 rc.conf。

35.syslog.conf

這個檔案指出系統的 log 應該儲存在哪兒.

36.termcap

這個應該 link 到 /usr/share/misc/termcap.

37.ttys

定義 tty 的形式及某些 tty 允不允許 root login. 假如某些 ttys 後面加有 "secure", 表示 root 可以 login. 你應當多加些, 如 /dev/tty[pqrs][0-9a-v]

詳情請 man ttys。

38.weekly

每周例行的工作。

2009年4月14日 星期二

FreeBSD 7.01 release 安裝記錄7(網頁伺服器:加速PHP5-APC)

==============================
安裝Pecl-APC
==============================
參考[FreeBSD] 安裝 PHP APC 加速網頁速度

# cd /usr/ports/www/pecl-APC
# make config install clean
勾選
[X] MMAP Enable mmap memory support (default: IPC shm)
[X] SEMAPHORES Enable sysv IPC semaphores (default: fcntl())
[X] FILEHITS Enable per request cache info

1.打開 /usr/local/etc/php/extensions.ini

# vi /usr/local/etc/php/extensions.ini
# 檢查最後一行是否如下,若沒有,請加入此行:
extension=apc.so

2.打開 /usr/local/etc/php.ini

# vi /usr/local/etc/php.ini
# 最後加入:
#
#[APC]
apc.enabled=1
apc.shm_segments=1
# 要讓 apc 使用多少記憶體
apc.shm_size=128
# ttl 設定成 300 second,這樣快取命中率比較高,增加自己網站速度,看自己網站調整喔
apc.ttl=300
apc.user_ttl=300
apc.num_files_hint=1024
# 這行請勿修改,後面的 XXXXXX 系統會自己建立喔
apc.mmap_file_mask=/tmp/apc.XXXXXX
apc.enable_cli=1

2009年4月12日 星期日

安裝apache22無法啟動問題集

==============================
解決mod_unique_id: unable to find IPv4 address of問題
==============================
引用怪異的apache
就在裝完apache之後,發現怎麼啟動它就是不會run,httpd.conf的設定都是OK的,啟動過程,scripts也沒有show錯誤,查

vi /var/log/httpd-error.log

才發現有個神奇的alert--hostname nor servname provided, or not known: mod_unique_id: unable to find IPv4 address of "diablo",原來是apache有的mod_unique_id的模組,會去檢查機器的ip跟hostname。
因為機器都是架在NAT底下,所以這個模組就不會給過了,之前在學校都不會遇到這種問題,大概用的都是public ip的關係吧,每台都有自己的public ip跟DNS,那要怎麼解決這個問題,找出在httpd.conf中的LoadModule unique_id_module libexec/apache22/mod_unique_id.so,把它mark起來就可以了。

2009年4月9日 星期四

(網頁伺服器)小技巧,各主機應都適用

引用此篇Apache+PHP 學習小技巧底下修改方式適用FreeBSD主機,其它主機只要找到相關文件(httpd.conf;php.ini),照其修改即可

Description :

進來架了很多 CMS 及 Blog 的網站,突然發現有編碼的問題,ISO-8855、big-5、uft-8、、、等編碼問題,我的Virtual Host同時存在使用 big5 和 uft-8 兩種不同編碼情況下,時而造成亂碼,時而看不見網頁需由 client 端瀏覽器更改檢視才能看見,實在不方便。所以我更改了一些 Server 上的設定,果然問題解決所以將心得技巧寫下來。

Setps : 將其註解,不使用

#vi /usr/local/etc/apache2/httpd.conf
AddDefaultCharset big5 -> #AddDefaultCharset big5
#vi /usr/local/etc/php.ini
default_charset = "utf-8" -> ;default_charset = "uft-8"

[FreeBSD] 安裝 memcache for php 多重伺服器共享 Session

[FreeBSD] 安裝 memcache for php 多重伺服器共享 Session

2009年4月8日 星期三

FreeBSD 7.01 release 安裝記錄6(網頁伺服器:第三步PHP5+phpMyAdmin)

==============================
安裝php5 配合第二步請安裝時加裝cgi fastcgi
==============================
記得勾選APACHE Build Apache module不然Apache不認得PHP

# cd /usr/ports/lang/php5
# make config install clean

==============================
php.ini檔
==============================
複製 php.ini-dist 到 php.ini

# cp /usr/local/etc/php.ini-dist /usr/local/etc/php.ini

修改php.ini

output_buffering = 8192
; Maximum size of POST data that PHP will accept.
post_max_size = 64M
; Temporary directory for HTTP uploaded files (will use system default if not
; specified).
upload_tmp_dir = /tmp
; Maximum allowed size for uploaded files.用於上傳資料庫資料時可設定
upload_max_filesize = 128M
[Date]
; Defines the default timezone used by the date functions
date.timezone = Asia/Taipei ;加入Asia/Taipei時區
; where MODE is the octal representation of the mode. Note that this
; does not overwrite the process's umask.
session.save_path = "/tmp"

再安裝php5-extensions
勾選(上網所收集的..搞不太懂,又找不到什麼資料可看,英文能力太差,看不懂)反正別人用就跟著用吧= ="
CTYPE、EXIF、GD、ICONV、IMAP、MBSTRING、MYSQL、MYSQLI、PCRE、SESSION、XML、ZIP、ZLIB

# cd /usr/ports/lang/php5-extensions
# make config install clean

以上模組建議都以內定值安裝,如果懂得用就自行設定吧^^
==============================
安裝php5-extensions(mysqli時出現無法安裝解決方式)
==============================
錯誤訊息如下:

/usr/ports/databases/php5-mysqli/work/php-5.2.12/ext/mysqli/mysqli.c: In function 'zm_startup_mysqli':
/usr/ports/databases/php5-mysqli/work/php-5.2.12/ext/mysqli/mysqli.c:637: error: 'MYSQL_RPL_MASTER' undeclared (first use in this function)
/usr/ports/databases/php5-mysqli/work/php-5.2.12/ext/mysqli/mysqli.c:637: error: (Each undeclared identifier is reported only once
/usr/ports/databases/php5-mysqli/work/php-5.2.12/ext/mysqli/mysqli.c:637: error: for each function it appears in.)
/usr/ports/databases/php5-mysqli/work/php-5.2.12/ext/mysqli/mysqli.c:638: error: 'MYSQL_RPL_SLAVE' undeclared (first use in this function)
/usr/ports/databases/php5-mysqli/work/php-5.2.12/ext/mysqli/mysqli.c:639: error: 'MYSQL_RPL_ADMIN' undeclared (first use in this function)

解決方式:

# ee /usr/local/include/mysql/mysql.h

編輯內容
找到這段
/*原文 start
enum mysql_protocol_type
{
MYSQL_PROTOCOL_DEFAULT, MYSQL_PROTOCOL_TCP, MYSQL_PROTOCOL_SOCKET,
MYSQL_PROTOCOL_PIPE, MYSQL_PROTOCOL_MEMORY
};
原文 end*/
/*
There are three types of queries - the ones that have to go to
the master, the ones that go to a slave, and the adminstrative
type which must happen on the pivot connectioin
*/
新增

enum mysql_rpl_type
{
MYSQL_RPL_MASTER, MYSQL_RPL_SLAVE, MYSQL_RPL_ADMIN
};

/*原文 start
typedef struct character_set
{
unsigned int number; /* character set number */
unsigned int state; /* character set state */
const char *csname; /* collation name */
const char *name; /* character set name */
原文 end */

==============================
extensions.ini檔
==============================
/usr/local/etc/php/extensions.ini
==============================
移除 php5-extensions 要用
==============================

# pkg_deinstall -r php5-extensions

這樣子才會把 php5-extensions 下面那些散落在各個目錄的 extensions 移除。php5-extensions 只是個用 dependency 導到各個目錄去裝 extension 的 meta port 而已。
==============================
安裝phpMyAdmin
==============================

# cd /usr/ports/databases/phpmyadmin # 安裝 phpMyAdmin
# make install clean

複製config檔修改

# cd /usr/local/www/phpMyAdmin # 切換目錄
# cp config.sample.php config.inc.php
# vi config.inc.php
//找到$cfg['Servers'][$i]['auth_type']修改線上認證方式 http 認證
$cfg['Servers'][$i]['auth_type'] = 'http';
//增加此行,遮蔽information_schema資料庫,雖不能修改但使用者皆會看到此資料庫,不顯示它
$cfg['Servers'][$i]['hide_db'] = 'information_schema';
# chmod 644 config.inc.php //儲存config.inc.php後 變更權限644


# vi /usr/local/etc/apache22/httpd.conf # 編輯 Apache 的設定檔加入下列幾行
Alias /phpmyadmin/ "/usr/local/www/phpMyAdmin/"
<Directory "/usr/local/www/phpMyAdmin/">
Options none
AllowOverride Limit
Order Deny,Allow
Deny from all
Allow from 127.0.0.1 192.168.1.0/24
</Directory>

FreeBSD 7.01 release 安裝記錄5(網頁伺服器:第二步Apache22)

==============================
安裝apache22 + mpm_worker + mod_fastcgi
==============================
Apache + mpm_worker + mod_fastcgi + php-cgi
[FreeBSD]安裝 apache2 (worker) + PHP5.2.6 + mod_fastcgi + php5-fcgi
修正 Apache Worker MPM 與 APC 設定
安裝時請記得勾選MYSQL CGID

# cd /usr/ports/www/apache22
# make config WITH_MPM=worker install clean
# pkg_info | grep apache
;
; 成功會出現
;
# apache-worker-2.2.9_5 Version 2.2.x of Apache web server with worker MPM.

編輯 /usr/local/etc/apache22/httpd.conf

#內定值:網站目錄設定,可自行修改目錄位置
DocumentRoot "/usr/local/www/apache22/data"
#設定Apache的讓網站的檔案結構不讓別人看到,以內定值為例
<Directory "/usr/local/www/apache22/data">
# 原碼:
Options Indexes FollowSymLinks
# 修改:
#Options Indexes FollowSymLinks ; 註解此行
# 或修改成:
Options -Indexes FollowSymLinks
</Directory>
#約216行原碼:
#DirectoryIndex index.html;加上 index.php 或直接改成index.php
DirectoryIndex index.php
#再加上這兩行
AddType application/x-httpd-php .php
AddType application/x-httpd-php-source .phps


裝apache22時 /etc/rc.conf 加上

apache22_enable="YES"
apache22_http_accept_enable="YES"

這樣就會在跑起來的時候幫你 load accf_http 這個需要的 kernel module 了。
==============================
apache相關指令
==============================

# apachectl start //start啟動服務,restart重啟,stop停止
# apachectl configtest //測試配置文件 是否正確

==============================
Worker MPM 配置
==============================
修改 /usr/local/etc/apache22/httpd.conf

# 約420行,若之前有修改以上的設置,則在422行 原碼:
# Server-pool management (MPM specific)
#Include etc/apache22/extra/httpd-mpm.conf 將#去掉
Include etc/apache22/extra/httpd-mpm.conf

修改httpd-mpm.conf
 
# vi /usr/local/etc/apache22/extra/httpd-mpm.conf ; httpd-mpm.conf內找到
<IfModule mpm_worker_module>
StartServers 1
ServerLimit 3
MaxClients 100
MinSpareThreads 25
MaxSpareThreads 50
ThreadLimit 50
ThreadsPerChild 50
MaxRequestsPerChild 10000
</IfModule>

引用:
設計只跑起一隻 httpd,負責所有的連線。
「StartServers」就是剛啟動時要先生出來的 httpd 程序數量
「ServerLimit」定義了最大程序數量,每個程序裡面會包含「ThreadsPerChild」個 Thread(每個 Thread都可以應對一個 Request,不需要傳統那樣一個 Request 就需要一個程序。而當不夠的時候,他會自動增加 Thread 或 Child 來處理)
「MinSpareThreads」和「MaxSpareThreads」定義了最少和最多的空閒 Thread 數量。接著,這邊用「ThreadLimit」來限制了每個 Child 的最大 Thread 數量。
「ThreadPerChild」和「ServerLimit」的乘績決定了「MaxClients」的上限,也就是能夠承受的最大 Request 數量。
「MaxRequestsPerChild」,決定了 Child 接受了幾個 Request 之後就要關閉,等待如果需要才重新產生一個程序。預設是零,也就是不結束。設定重新產生,可以避免安全問題,更重要的是不需要那麼多程序時不會佔用著資源。

調整的時候,可以搭配 ab 壓力測試:

ab -c 同時連線數量 -n 每個連線的Request數量

ex:
ab -c 50 -n500
ab -c 100 -n 1000


==============================
安裝mod_fastcgi ; 若php5尚未安裝請先跳過,等php5安裝(CGI FASTCGI要勾選)完後再安裝
==============================
1.安裝mod_fastcgi 並新建 fastcgi目錄

# cd /usr/ports/www/mod_fastcgi
# make install clean
# mkdir /usr/local/www/fastcgi

確認PHP5支援fastcgi

# cd /usr/ports/lang/php5
# make showconfig | grep -i FASTCGI
支援出現底下訊息:
# FASTCGI=on "Enable fastcgi support (CGI only)"
或此指令
# /usr/local/bin/php-cgi -v
支援出現底下訊息:
PHP 5.2.5 with Suhosin-Patch 0.9.6.2 (cgi-fcgi) (built: Mar 6 2008 09:15:41)
Copyright (c) 1997-2007 The PHP Group
Zend Engine v2.2.0, Copyright (c) 1998-2007 Zend Technologies
其中出現 cgi-fcgi 即有支援

2.然後寫個 script 給 fastcgi 來跑 php:

#!/bin/sh
PHPRC="/usr/local/etc"
export PHPRC
PHP_FCGI_CHILDREN=128
export PHP_FCGI_CHILDREN
exec /usr/local/bin/php-cgi

3.存成 /usr/local/www/fastcgi/php.fcgi,記得要

# chmod 755 /usr/local/www/fastcgi/php.fcgi

4.編輯 /usr/local/etc/apache22/httpd.conf 大概在105行

原式:
LoadModule php5_module libexec/apache22/libphp5.so
#LoadModule fastcgi_module libexec/apache22/mod_fastcgi.so
修改後:
#LoadModule php5_module libexec/apache22/libphp5.so ; 會衝突,所以必順把它註解
LoadModule fastcgi_module libexec/apache22/mod_fastcgi.so

然後寫個 mod_fastcgi.conf 放在 /usr/local/etc/apache22/Includes/ 底下:

<IfModule fastcgi_module>
FastCgiConfig -maxClassProcesses 1
FastCgiConfig -idle-timeout 60 //若使用大量資料上傳,如上傳資料庫檔案,則設大一點
ScriptAlias /fastcgi/ "/usr/local/www/fastcgi/"
AddHandler fastcgi-script .fcgi
AddHandler php-fastcgi .php
Action php-fastcgi /fastcgi/php.fcgi
</IfModule>
<Directory /usr/local/www/fastcgi>
SetHandler fastcgi-script
AllowOverride All
Order allow,deny
Allow from all
</Directory>

讓httpd 只能生出一隻 fastcgi,再加上前面限制只有一隻 httpd,可以確保整個 apache 只會透過這個 fastcgi socket 跑 php。
原本 php 該要 AddType 的部分還是要加,改好以後 apache restart 就可以用了。
==============================
備註:
==============================
從PHP5.2.10版本開始(現在有PHP5.2.10和5.3兩個版本),有None-Thread Safe與Thread Safe兩種版本的可供選擇,這兩種版本有何不同,作為使用者來說又應該如何選擇呢?下面聚友將為您講述。

先從字面意思上理解,None-Thread Safe就是非線程安全,在執行時不進行線程(thread)安全檢查;Thread Safe就是線程安全,執行時會進行線程(thread)安全檢查,以防止有新要求就啟動新線程的 CGI 執行方式耗盡系統資源。

再來看PHP的兩種執行方式:ISAPI和FastCGI。FastCGI執行方式是以單一線程來執行操作,所以不需要進行線程的安全檢查,除去線程安全檢查的防護反而可以提高執行效率,所以,如果是以 FastCGI(無論搭配 IIS 6 或 IIS 7)執行 PHP ,都建議下載、執行 non-thread safe 的 PHP (PHP 的二進位檔有兩種包裝方式:msi 、zip ,請下載 zip 套件)。而線程安全檢查正是為ISAPI方式的PHP準備的,因為有許多php模塊都不是線程安全的,所以需要使用Thread Safe的PHP。

[保留不使用它]
portupgrade -fr 重編 lang/php5 和 lang/php5-extensions 重新編過就會是 Thread Safe
==============================
語系支援與虛擬伺服器設定
==============================

# 修改httpd.conf
# vi /usr/local/etc/apache22/httpd.conf
# 語系支援
# Language settings
#Include etc/apache22/extra/httpd-languages.conf ; 把註解拿掉
Include etc/apache22/extra/httpd-languages.conf
# 虛擬伺服器設定
# Virtual hosts
#Include etc/apache22/extra/httpd-vhosts.conf ; 把註解拿掉
Include etc/apache22/extra/httpd-vhosts.conf

# 設定虛擬主機
# vi /usr/local/etc/apache22/extra/httpd-vhosts.conf
# 自行修改成所需設定
NameVirtualHost 192.168.1.10 ; 請設定成主機IP,可虛擬/實體IP,虛擬IP請自行設定IP分享器
<VirtualHost 192.168.1.10>
ServerAdmin admin@Domain
DocumentRoot /usr/local/www/apache22/data/freebsd.ntut.idv.tw/www ; 主機內網站目錄
ServerName freebsd.ntut.idv.tw ; 網站網址
ErrorLog /var/log/httpd-error.log
CustomLog /var/log/httpd-access.log common
</VirtualHost>

2009年4月7日 星期二

FreeBSD 7.01 release 安裝記錄4(網頁伺服器:第一步安裝MYSQL)

參考文件
MySQL51 + Apache22 + PHP5 + phpMyAdmin
建議安裝順序 mysql51-server -> apache22 -> php5
安裝前請記得ports tree已經更新完成
==============================
安裝mysql51-server 編碼為unicode(UTF8)
==============================
# cd /usr/ports/databases/mysql51-server
# make WITH_CHARSET=utf8 WITH_XCHARSET=all WITH_COLLATION=utf8_unicode_ci BUILD_OPTIMIZED=yes install clean

複製MySQL的系統設定檔, my.cnf 來修改
# cp/usr/local/share/mysql/my-xxxx.cnf /etc/my.cnf

目前 MySQL 有提供四個範例檔,皆位於 /usr/local/share/mysql/ 目錄中,四個檔案的開頭皆為 my-*。關於其中的差別,可觀看其中的頭幾行說明,然後將範例本身或修改過後,置於特定目錄中即可。
my-huge.cnf,記憶體 1G-2G。
my-large.cnf,記憶體 512M。
my-medium.cnf,記憶體 32-64M。
my-small.cnf,記憶體 <= 64M。
my-innodb-heavy-4G.cnf,使用 INNODB,且記憶體 4G。

雖然編譯有加上預設的編碼了,以防萬一一下。
找到 [mysqld] 和 [client] 加上:
[mysqld]
default-character-set=utf8
[client]
default-character-set=utf8

編輯 /etc/rc.conf 加上
mysql_enable="YES"

若MYSQL只想本機使用,可設置
# 原碼:
#skip-networking ; 把註解拿掉
# 修改:
skip-networking

==============================
控制MySQL資料庫指令
==============================
start 啟動
stop 停止
restart 重啟
# /usr/local/etc/rc.d/mysql-server start ; stop ; restart

==============================
設定MySQL Root密碼
==============================
# mysqladmin -u root -p password 輸入新密碼 # 輸入(新密碼) 修改 root 密碼
Enter password:      # 輸入(舊密碼) 直接 Enter 剛裝完時 root 預設是空密碼

忘記root密碼處理
# /usr/local/etc/rc.d/mysql-server stop //先停止mysql
# cd /usr/local/bin //進入此目錄
# mysqld_safe --skip-grant-tables --skip-networking & //照打
# mysql //登入mysql
>use mysql;
>update user set password=PASSWORD("new-password") where user="root";
>flush privileges; 

==============================
變更MYSQL 資料庫目錄,內定 /var/db/mysql,並記得修改權限
==============================
修改 /etc/rc.conf 例:/home/data/mysql
# ee /etc/rc.conf
mysql_dbdir="/home/data/mysql" //加入此行
# mkdir -p /home/data/mysql (上述資料庫目錄,就是你的資料庫文件想放的地方。後文中的路徑別忘了一起更改)
# chown mysql:mysql /home/data/mysql
# cp /usr/local/share/mysql/my-large.cnf /etc/my.cnf

FreeBSD 7.01 release 安裝記錄3(安裝samba網芳)

安裝參考Samba@FreeBSD 架設程序
twbsd.org-第二十章 SAMBA 網路芳鄰
由 ports 安裝 Samba:

# cd /usr/ports/net/samba3
# make install

安裝選項:

Options for samba 3.0.24,1
[X] LDAP With LDAP support
[X] ADS With Active Directory support
[ ] CUPS With CUPS printing support
[ ] WINBIND With WinBIND support
[X] ACL_SUPPORT With ACL support
[ ] FAM_SUPPORT With File Alteration Monitor
[X] SYSLOG With Syslog support
[ ] QUOTAS With Disk quota support
[X] UTMP With UTMP accounting support
[ ] MSDFS With MSDFS support
[ ] PAM_SMBPASS With PAM authentication vs passdb backends
[ ] CLUSTER With experimental cluster support
[ ] EXP_MODULES With experimental modules
[X] POPT With system-wide POPT library
[ ] MAX_DEBUG With maximum debuging

編輯 Samba CONF 檔案:

# vi /usr/local/etc/smb.conf
# cp /usr/local/etc/smb.conf.sample /usr/local/etc/smb.conf //若無smb.conf 則複製

全域設定 (Global Settings):
smb.conf內參數: 'workgroup'
範例:

workgroup = WORKGROUP

smb.conf內參數: 'server string'
範例:

server string = %h Samba Server
'%h' 代表主機名稱變數。

smb.conf內參數: 'security'
要使用哪一種安全模式。如果設定為 share,就是任何人都可以存取,無需使用帳號密碼;
而設為 user 則是要輸入使用者名稱及密碼。如果我們設為 user,必須要再設定使用者
使用者及密碼。
範例:

security = user // share

smb.conf內參數: 'log file'
範例:

log file = /var/log/samba/%m.log

smb.conf內參數: 'dos charset'
Windows 用戶端的編碼,繁體中文 Windows 使用的是 big5 編碼,這個編碼在 Samba 內的格式被稱為『 cp950 』喔!
範例:

dos charset = cp950

smb.conf內參數: 'create mask' 'directory mask'
設定新建檔案時的權限為何。Samba 的權限除了看資料夾的權限設定外,還會看 UNIX 的
權限。我們將新建檔案的權限設為 0666,新建目錄設為 0777,以讓不同使用者所建立的
可以讓有權存取該共享資料夾的使用者存取。
範例:

create mask = 0666
directory mask = 0777

smb.conf內參數: 'sendfile'
在下載檔案時,我們使用 FreeBSD 的系統呼叫 sendfile() 以提高下載速度。使用
sendfile() 可以提高效能近一倍喔!

use sendfile = yes

使用者權限 (Share Definitions):
設定使用者家目錄,原始設定為:

[homes]
comment = Homes Directories
browseable = no
writable = yes

更改為:

[homes]
comment = Home directory for %u on %h
browseable = no
writable = yes
path = /usr/home/%u/
valid users = %S

設定共享資料夾,所有使用者都可以讀寫檔案:

# A publicly accessible directory, read/write to all users.
[public]
comment = %h Shared Public Directory
path = /usr/home/samba/public
force directory mode = 0777
force create mode = 0777
force group = nobody
force user = nobody
public = yes
writeable = yes
read only = no

測試 Samba CONF 檔案有無語法錯誤:

# /usr/local/bin/testparm | more

建立共享資料夾:

# cd /usr; mkdir home ; cd home ; mkdir samba ; cd samba ; mkdir public
# chmod 777 public

使用者帳號設定:
使用者必須同時設定兩種帳號: OS database (FreeBSD 的使用者帳號)、Samba user database (Samba 的使用者帳號) 才能正常登入 Samba 伺服器。

建立 OS database (FreeBSD 的使用者帳號):(假設帳號名稱為 winuser)

# adduser

adduser 用法,請參閱 FreeBSD Man Pages、 FreeBSD 使用者管理。
建立 Samba user database (Samba 的使用者帳號):

# smbpasswd -a winuser

顯示:
New SMB password:
鍵入 Windows 密碼,顯示:
Retype new SMB password:
再鍵入 Windows 寫碼確認。

啟動 Samba:
設定開機時,自動啟動 Samba,在 /etc/rc.conf 加入這一行設定:

samba_enable="YES"

有了 /usr/local/etc/rc.d/samba 我們只要在後面再加上 start 或 stop 就可以啟動或停止 samba 的服務
啟動samba

# /usr/local/etc/rc.d/samba start

==============================
我的設定檔,留著備用
==============================

[global]
workgroup = WORKGROUP
security = share
encrypt passwords = no
hosts allow = 192.168.1.
load printers = no
printing = bsd
dos charset = cp950
#[Customize]
use sendfile=yes
create mask=0666
directory mask=0777
smb ports=139
#============================ Share Definitions ==============================
[homes]
comment = Home Directories for %u on %h
path = /
browseable = yes
writable = yes
read only = no
public = no
force directory mode = 0777
force create mode = 0777
force group = nobody
force user = nobody
底下目錄全註解

==============================
解決Samba Server Unable to connect to CUPS server localhost:631 - 連線被拒絕問題
==============================
修改/usr/local/etc/smb.conf

# vi /usr/local/etc/smb.conf
load printers = no
printing = bsd
printcap name = /dev/null
disable spoolss = yes
# /usr/local/etc/rc.d/samba restart //smb.conf儲存後重啟samba

==============================
解決smbd[xxxx]: getpeername failed;lib/util_sock.c:get_peer_addr 錯誤==============================
修改/usr/local/etc/smb.conf

# vi /usr/local/etc/smb.conf
smb ports=139 //只監聽port 139 適用XP系統
# iptables -I INPUT 1 -p tcp --dport 445 -j DROP //阻擋445port的連線
# /usr/local/etc/rc.d/samba restart //smb.conf儲存後重啟samba

2009年4月6日 星期一

FreeBSD 7.01 release 安裝記錄2(變更shell為bash)

由於FreeBSD預設shell為csh將它變更為bash
安裝bash

# cd /usr/ports/shells/bash
# make install clean

修改預設目錄

# pw usermod 使用者id -s /usr/local/bin/bash

註:使用者id ex:root 或自設使用者id

用bash設定提示符bash的相關設定檔 /etc/profile
應該不會有使用者不想要顯示中文吧...所以設定在系統性的檔案

# vi /etc/profile 或 # ee /etc/profile
#中文顯示設定如下
LC_CTYPE=en_US.ISO8859-1
export LC_CTYPE
LC_ALL=zh_TW.Big5
export LC_ALL
LANG=zh_TW.Big5
export LANG
#預設編輯器
EDITOR=/usr/local/bin/joe
export EDITOR
VISUAL=/usr/local/bin/joe
export VISUAL
#提示符設定如下
PS1="[\u@\h \w]\\$ "
#使用別名 可設置同DOS指令
alias dir="ls -alh"
alias cls="clear"
alias rd="rmdir"
alias md="mkdir"
alias cd..="cd .."
alias del="rm"
alias deltree="rm -r"
alias copy="cp"
alias move="mv"
alias ren="mv"
alias ipconfig="ifconfig"
alias clrlog="cp /dev/null /var/log/httpd-access.log;cp /dev/null /var/log/httpd-error.log"

註:=號兩旁最好皆勿用空格區開,以免錯誤
===節自鳥哥的 Linux 私房菜===
PS1:(提示字元的設定)
這是 PS1 (數字的 1 不是英文字母),這個東西就是我們的『命令提示字元』喔! 當我們每次按下 [Enter] 按鍵去執行某個指令後,最後要再次出現提示字元時, 就會主動去讀取這個變數值了。上頭 PS1 內顯示的是一些特殊符號,這些特殊符號可以顯示不同的資訊, 每個 distributions 的 bash 預設的 PS1 變數內容可能有些許的差異,不要緊,『習慣你自己的習慣』就好了。 你可以用 man bash 去查詢一下 PS1 的相關說明,以理解底下的一些符號意義。

\d :可顯示出『星期 月 日』的日期格式,如:"Mon Feb 2"
\H :完整的主機名稱。舉例來說,鳥哥的練習機為『www.vbird.tsai』
\h :僅取主機名稱在第一個小數點之前的名字,如鳥哥主機則為『www』後面省略
\t :顯示時間,為 24 小時格式的『HH:MM:SS』
\T :顯示時間,為 12 小時格式的『HH:MM:SS』
\A :顯示時間,為 24 小時格式的『HH:MM』
\@ :顯示時間,為 12 小時格式的『am/pm』樣式
\u :目前使用者的帳號名稱,如『root』;
\v :BASH 的版本資訊,如鳥哥的測試主機板本為 3.2.25(1),僅取『3.2』顯示
\w :完整的工作目錄名稱,由根目錄寫起的目錄名稱。但家目錄會以 ~ 取代;
\W :利用 basename 函數取得工作目錄名稱,所以僅會列出最後一個目錄名。
\# :下達的第幾個指令。
\$ :提示字元,如果是 root 時,提示字元為 # ,否則就是 $ 囉~

FreeBSD 7.01 release 安裝記錄1(csup更新)

安裝完FreeBSD 7.01 release 後馬上使用csup更新ports tree
FreeBSD 在 6.2 版之後已經內建 /usr/bin/csup 的 ports tree 更新工具,舊版本是 cvsup 必須自行安裝。

請在 /etc/make.conf 裡加入以下內容(不更新X11,速度快)

SUPHOST=cvsup.tw.freebsd.org
SUP_UPDATE="YES"
SUP=/usr/bin/csup
SUPFLAGS=-g -L 2

SUPFILE=/usr/share/examples/cvsup/stable-supfile
PORTSSUPFILE=/usr/share/examples/cvsup/ports-supfile
MASTER_SITE_BACKUP?=\
ftp://cvsup.tw.freebsd.org/pub/FreeBSD/distfiles/${DIST_SUBDIR}/\
ftp://cvsup2.tw.freebsd.org/pub/FreeBSD/distfiles/${DIST_SUBDIR}/\
ftp://cvsup3.tw.freebsd.org/pub/FreeBSD/distfiles/${DIST_SUBDIR}/\
ftp://ftp.freebsd.org/pub/FreeBSD/distfiles/${DIST_SUBDIR}/
MASTER_SITE_OVERRIDE?=${MASTER_SITE_BACKUP}
WITHOUT_X11=yes

更新 ports tree

# cd /usr/ports
# make update

更新 src

# cd /usr/src
# make update

參考文件1

2009年3月26日 星期四

onclick使用thickbox

原文出處jQuery thickbox’s onclick event


Click me

So, you create a javascript function called dotb(title, url) and reference jquery library to open the overlay.

function dotb(title, url)
{
$(document).ready(function(){ tb_show(title, url, null); });
}

2009年3月20日 星期五

phpRTF 文件相關教學

建立RTF文件

$rtf = new Rtf();

設定A4紙張

$sect = &$rtf->addSection();
$sect->setPaperWidth(21); //設定版面寛21CM
$sect->setPaperHeight(29.7);//設定版面高29.7CM

建立文件欄

$sect = &$rtf->addSection();
$sect->setColumns(array(4, 4, 10));//建立3段文件欄,第一段4cm,第二段4cm,第三段10cm







第一段文字第二段文字第三段文字

2009年3月19日 星期四

UTF8 互轉 BIG5

big5 轉 utf-8
PHP 程式碼:
$str=iconv("big5","UTF-8",$str);

utf-8 轉 big5
PHP 程式碼:
$str=iconv("UTF-8","big5",$str);

2009年3月17日 星期二

網頁相關

網頁列印A4解析度
CSS 文字像素大小與百分比對應

PHP 線上產生可列印文件方案總匯

PHP 線上產生可列印文件方案總匯
列印html特定區塊

PHP轉WORD方式

首先確定你的系統為windows平台並且安裝了OFFICE

$msword = new com("word.application");
$msdocument = $msword->documents->Open("c:\a.doc" ,False, True);
$msdocument->saveas("c:\aa.htm",8);

2009年3月3日 星期二

thickbox IE7 錯位問題

將thickbox 3.1內thickbox.js 284行

if ( !(jQuery.browser.msie && jQuery.browser.version < 7)) { // take away IE6
$("#TB_window").css({marginTop: '-' + parseInt((TB_HEIGHT / 2),10) + 'px'});
}

修改成

if ( !(jQuery.browser.msie6)) { // take away IE6
$("#TB_window").css({marginTop: '-' + parseInt((TB_HEIGHT / 2),10) + 'px'});
}

即可

2009年2月9日 星期一

PHP SQL 注入攻擊的技術實現以及預防辦法

  最近在折騰 PHP + MYSQL 的編程。瞭解了一些 PHP SQL 注入攻擊的知識,於是寫了這篇文章 http://www.xiaohui.com/weekly/20070314.htm,總結一下經驗。在我看來,引發 SQL 注入攻擊的主要原因,是因為以下兩點原因:



  1. php 配置文件 php.ini 中的 magic_quotes_gpc 選項沒有打開,被置為 off


  2. 開發者沒有對數據類型進行檢查和轉義




  不過事實上,第二點最為重要。我認為, 對用戶輸入的數據類型進行檢查,向 MYSQL 提交正確的數據類型,這應該是一個 web 程序員最最基本的素質。但現實中,常常有許多小白式的 Web 開發者忘了這點, 從而導致後門大開。



  為什麼說第二點最為重要?因為如果沒有第二點的保證,magic_quotes_gpc 選項,不論為 on,還是為 off,都有可能引發 SQL 注入攻擊。下面來看一下技術實現:



 一. magic_quotes_gpc = Off 時的注入攻擊


  magic_quotes_gpc = Off 是 php 中一種非常不安全的選項。新版本的 php 已經將默認的值改為了 On。但仍有相當多的服務器的選項為 off。畢竟,再古董的服務器也是有人用的。



  當magic_quotes_gpc = On 時,它會將提交的變量中所有的 '(單引號)、"(雙號號)、\(反斜線)、空白字符,都為在前面自動加上 \。即 ' 變成 ', "變成 ".下面是 php 的官方說明:



magic_quotes_gpc boolean


Sets the magic_quotes state for GPC (Get/Post/Cookie) operations. When magic_quotes are on, all ' (single-quote), " (double quote), \ (backslash) and NUL's are escaped with a backslash automatically



  如果沒有轉義,即 off 情況下,就會讓攻擊者有機可乘。以下列測試腳本為例:



http://www.xiaohui.com/weekly/20070314.htm

<?
if ( isset($_POST["f_login"] ) )
{
// 連接數據庫...
// ...代碼略...

// 檢查用戶是否存在
$t_strUname = $_POST["f_uname"];
$t_strPwd = $_POST["f_pwd"];
$t_strSQL = "SELECT * FROM tbl_users WHERE username='$t_strUname' AND password = '$t_strPwd' LIMIT 0,1";

if ( $t_hRes = mysql_query($t_strSQL) )
{
// 成功查詢之後的處理. 略...
}
}
?>
<html><head><title>sample test</title></head>
<body>
<form method=post action="">
Username: <input type="text" name="f_uname" size=30><br>
Password: <input type=text name="f_pwd" size=30><br>
<input type="submit" name="f_login" value="登錄">
</form>
</body>



  在這個腳本中,當用戶輸入正常的用戶名和密碼,假設值分別為 zhang3、abc123,則提交的 SQL 語句如下:


SELECT * FROM tbl_users
WHERE username='zhang3' AND password = 'abc123' LIMIT 0,1


  如果攻擊者在 username 字段中輸入:zhang3' OR 1=1 #,在 password 輸入abc123,則提交的 SQL 語句變成如下:


SELECT * FROM tbl_users
WHERE username='zhang3' OR 1=1 #' AND password = 'abc123' LIMIT 0,1


  由於 # 是 mysql中的註釋符, #之後的語句不被執行,實現上這行語句就成了:


SELECT * FROM tbl_users
WHERE username='zhang3' OR 1=1


  這樣攻擊者就可以繞過認證了。如果攻擊者知道數據庫結構,那麼它構建一個 UNION SELECT,那就更危險了:


  假設在 username 中輸入:zhang3 ' OR 1 =1 UNION select cola, colb,cold FROM tbl_b #


  在password 輸入: abc123,


  則提交的 SQL 語句變成:


SELECT * FROM tbl_users
WHERE username='zhang3 '
OR 1 =1 UNION select cola, colb,cold FROM tbl_b #' AND password = 'abc123' LIMIT 0,1


  這樣就相當危險了。如果magic_quotes_gpc選項為 on,引號被轉義,則上面攻擊者構建的攻擊語句就會變成這樣,從而無法達到其目的:



SELECT * FROM tbl_users
WHERE username='zhang3' OR 1=1 #'
AND password = 'abc123'
LIMIT 0,1

SELECT * FROM tbl_users
WHERE username=''zhang3 ' OR 1 =1 UNION select cola, colb,cold FROM tbl_b #' '
AND password = 'abc123' LIMIT 0,1


 二. magic_quotes_gpc = On 時的注入攻擊



  當 magic_quotes_gpc = On 時,攻擊者無法對字符型的字段進行 SQL 注入。這並不代表這就安全了。這時,可以通過數值型的字段進行SQL注入。



  在最新版的 MYSQL 5.x 中,已經嚴格了數據類型的輸入,已默認關閉自動類型轉換。數值型的字段,不能是引號標記的字符型。也就是說,假設 uid 是數值型的,在以前的 mysql 版本中,這樣的語句是合法的:



INSERT INTO tbl_user SET uid="1";
SELECT * FROM tbl_user WHERE uid="1";



  在最新的 MYSQL 5.x 中,上面的語句不是合法的,必須寫成這樣:



INSERT INTO tbl_user SET uid=1;
SELECT * FROM tbl_user WHERE uid=1;


  這樣我認為是正確的。因為作為開發者,向數據庫提交正確的符合規則的數據類型,這是最基本的要求。



  那麼攻擊者在 magic_quotes_gpc = On 時,他們怎麼攻擊呢?很簡單,就是對數值型的字段進行 SQL 注入。以下列的 php 腳本為例:


<?
if ( isset($_POST["f_login"] ) )
{
// 連接數據庫...
// ...代碼略...

// 檢查用戶是否存在
$t_strUid = $_POST["f_uid"];
$t_strPwd = $_POST["f_pwd"];
$t_strSQL = "SELECT * FROM tbl_users WHERE uid=$t_strUid AND password = '$t_strPwd' LIMIT 0,1";
if ( $t_hRes = mysql_query($t_strSQL) )
{
// 成功查詢之後的處理. 略...
}

}
?>
<html><head><title>sample test</title></head>
<body>
<form method=post action="">
User ID: <input type="text" name="f_uid" size=30><br>
Password: <input type=text name="f_pwd" size=30><br>
<input type="submit" name="f_login" value="登錄">
</form>
</body>



  上面這段腳本要求用戶輸入 userid 和 password 登入。一個正常的語句,用戶輸入 1001和abc123,提交的 sql 語句如下:


SELECT * FROM tbl_users WHERE username=1001 AND password = 'abc123' LIMIT 0,1



  如果攻擊者在 userid 處,輸入:1001 OR 1 =1 #,則注入的sql語句如下:


SELECT * FROM tbl_users WHERE username=1001 OR 1 =1 # AND password = 'abc123' LIMIT 0,1

  攻擊者達到了目的。



 三. 如何防止 PHP SQL 注入攻擊


  如何防止 php sql 注入攻擊?我認為最重要的一點,就是要對數據類型進行檢查和轉義。總結的幾點規則如下:



  1. php.ini 中的 display_errors 選項,應該設為 display_errors = off。這樣 php 腳本出錯之後,不會在 web 頁面輸出錯誤,以免讓攻擊者分析出有作的信息。
  2. 調用 mysql_query 等 mysql 函數時,前面應該加上 @,即 @mysql_query(...),這樣 mysql 錯誤不會被輸出。同理以免讓攻擊者分析出有用的信息。另外,有些程序員在做開發時,當 mysql_query出錯時,習慣輸出錯誤以及 sql 語句,例如:
    $t_strSQL = "SELECT a from b....";
    if ( mysql_query($t_strSQL) )
    {
    // 正確的處理
    }
    else
    {
    echo "錯誤! SQL 語句:$t_strSQL \r\n錯誤信息".mysql_query();
    exit;
    }

      這種做法是相當危險和愚蠢的。如果一定要這麼做,最好在網站的配置文件中,設一個全局變量或定義一個宏,設一下 debug 標誌:


    全局配置文件中:
    define("DEBUG_MODE",0); // 1: DEBUG MODE; 0: RELEASE MODE

    //調用腳本中:
    $t_strSQL = "SELECT a from b....";
    if ( mysql_query($t_strSQL) )
    {
    // 正確的處理
    }
    else
    {
    if (DEBUG_MODE)
    echo "錯誤! SQL 語句:$t_strSQL \r\n錯誤信息".mysql_query();
    exit;
    }

  3. 對提交的 sql 語句,進行轉義和類型檢查



 四. 我寫的一個安全參數獲取函數


  為了防止用戶的錯誤數據和 php + mysql 注入 ,我寫了一個函數 PAPI_GetSafeParam(),用來獲取安全的參數值:


define("XH_PARAM_INT",0);
define("XH_PARAM_TXT",1);
function PAPI_GetSafeParam($pi_strName, $pi_Def = "", $pi_iType = XH_PARAM_TXT)
{
if ( isset($_GET[$pi_strName]) )
$t_Val = trim($_GET[$pi_strName]);
else if ( isset($_POST[$pi_strName]))
$t_Val = trim($_POST[$pi_strName]);
else
return $pi_Def;

// INT
if ( XH_PARAM_INT == $pi_iType)
{
if (is_numeric($t_Val))
return $t_Val;
else
return $pi_Def;
}

// String
$t_Val = str_replace("&", "&amp;",$t_Val); // 註:實際程序中,應該為 小寫的 &.
$t_Val = str_replace("<", "&lt;",$t_Val); $t_Val = str_replace(">", "&gt;",$t_Val);
if ( get_magic_quotes_gpc() )
{
$t_Val = str_replace("\"", "&quot;",$t_Val);
$t_Val = str_replace("'", "&#039;",$t_Val);
}
else
{
$t_Val = str_replace(""", "&quot;",$t_Val);
$t_Val = str_replace("'", "&#039;",$t_Val);
}
return $t_Val;
}


  在這個函數中,有三個參數:


$pi_strName: 變量名
$pi_Def: 默認值
$pi_iType: 數據類型。取值為 XH_PARAM_INT, XH_PARAM_TXT, 分別表示數值型和文本型。

  如果請求是數值型,那麼調用 is_numeric() 判斷是否為數值。如果不是,則返回程序指定的默認值。

  簡單起見,對於文本串,我將用戶輸入的所有危險字符(包括HTML代碼),全部轉義。由於 php 函數 addslashes()存在漏洞,我用 str_replace()直接替換。get_magic_quotes_gpc() 函數是 php 的函數,用來判斷 magic_quotes_gpc 選項是否打開。


  剛才第二節的示例,代碼可以這樣調用:

<?
if ( isset($_POST["f_login"] ) )
{
// 連接數據庫...
// ...代碼略...

// 檢查用戶是否存在
$t_strUid = PAPI_GetSafeParam("f_uid", 0, XH_PARAM_INT);
$t_strPwd = PAPI_GetSafeParam("f_pwd", "", XH_PARAM_TXT);
$t_strSQL = "SELECT * FROM tbl_users WHERE uid=$t_strUid AND password = '$t_strPwd' LIMIT 0,1";
if ( $t_hRes = mysql_query($t_strSQL) )
{
// 成功查詢之後的處理. 略...
}
}
?>


  這樣的話,就已經相當安全了。PAPI_GetSafeParam的代碼有點長,但犧牲這點效率,對保證安全,是值得的。希望大家多批評指正。:)


原文:http://www.xiaohui.com/weekly/20070314.htm

2009年1月13日 星期二

新建目錄與下載檔案寫法


//新建目錄
function create_dir($path) {
if (!file_exists($path)) {//如果文件夾不存在
create_dir(dirname($path)); //取得最後一個文件夾的全路徑返回開始的地方
mkdir($path, 0777);
return true;
}
}



//下載檔案
function download_file($file){

//First, see if the file exists
if (!is_file($file)) { die("404 File not found!"); }

//Gather relevent info about file
$len = filesize($file);
$filename = basename($file);
$file_extension = strtolower(substr(strrchr($filename,"."),1));

//This will set the Content-Type to the appropriate setting for the file
switch( $file_extension ) {
case "pdf": $ctype="application/pdf"; break;
case "exe": $ctype="application/octet-stream"; break;
case "zip": $ctype="application/zip"; break;
case "doc": $ctype="application/msword"; break;
case "xls": $ctype="application/vnd.ms-excel"; break;
case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
case "gif": $ctype="image/gif"; break;
case "png": $ctype="image/png"; break;
case "jpeg":
case "jpg": $ctype="image/jpg"; break;
case "mp3": $ctype="audio/mpeg"; break;
case "wav": $ctype="audio/x-wav"; break;
case "mpeg":
case "mpg":
case "mpe": $ctype="video/mpeg"; break;
case "mov": $ctype="video/quicktime"; break;
case "avi": $ctype="video/x-msvideo"; break;

//The following are for extensions that shouldn't be downloaded (sensitive stuff, like php files)
case "php":
case "htm":
case "html":
case "txt": die("Cannot be used for ". $file_extension ." files!"); break;

default: $ctype="application/force-download";
}

//Begin writing headers
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
header("Content-Description: File Transfer");

//Use the switch-generated Content-Type
header("Content-Type: $ctype");

//Force the download
$header="Content-Disposition: attachment; filename=".$filename.";";
header($header );
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".$len);
@readfile($file);
exit;
}

2009年1月12日 星期一

PHP 發送夾帶附件mail

郵件相關的東西。下面是一個帶附件(一個HTML文件)電子郵件的例子。
Return-Path: Date: Mon, 22 May 2000 19:17:29 +0000 From: Someone To: Person Message-id: <83729KI93LI9214@example.com> Content-type: multipart/mixed; boundary="396d983d6b89a" Subject: Here's the subject --396d983d6b89a Content-type: text/plain; charset=iso-8859-1 Content-transfer-encoding: 8bit
This is the body of the email.
--396d983d6b89a Content-type: text/html; name=attachment.html Content-disposition: inline; filename=attachment.html Content-transfer-encoding: 8bit

This is the attached HTML file

--396d983d6b89a--
  前面的7行是郵件的頭,其中值得注意的是Content-type頭部分。這個頭告訴郵件程序電子郵件是由一個以上的部分組成的。不含附件的郵件只有一個部分:消息本身。帶附件的電子通常至少由兩部分組成:消息和附件。這樣,帶兩個附件的郵件由三部分組成:消息,第一個附件和第二個附件。
  帶附件的電子郵件的不同部分之間用分界線來分隔。分界線在Content--type頭中定義。郵件的每個新部分以兩個連字號(--)和分界線開始。 最後一個分界線後也有兩個連字號,表示這個郵件中沒有其它的部分了。
  在每個分界線後有一些行,用來告訴郵件程序這個部分的內容的類型。 比如,看看上面例子中第一個分界線後面的兩行--以Content-type: text/plain開頭的行。這些行說明後面的部分是ISO-8859-1字符集的純文本。跟在第二個分界線後的行告訴郵件程序現在的部分是一個HTML文件,它的名字是"attachment.html"。
  Content-disposition這持告訴郵件程序如果可能就以內嵌的方式顯示附件。現在新的郵件程序會在消息後顯示HTML的內容。如果Content- disposition被設為attachment,那麼郵件程序就不會顯示HTML文件的內容,而是顯示一個連接到文件的圖標(或其它的類似的東西)。收件人要看附件的內容,必須點擊這個圖標。一般情況下,如果附件是一些文本(包含HTML),Content-disposition會被設為inline,這是因為現在大部分郵件程序能夠不借助其它瀏覽器而直接顯示附件(文本)的內容。如果附件不是文本(比如圖片或其它類似的內容),Content-disposition 就設為attachment。 我們仿照上面的例子,自己寫一個php程序,可以對提交的 收信人,發送人,信件內容,附件進行處理。
首先建立一個靜態頁面,代碼如下:























發送者:
接受者:
下載提示:
源數據文件:
 



要注意的是 : 表單裡 ENCTYPE="multipart/form-data" 一定要有。
再來看一下 發送郵件的php程序:

//文本內容
$text = $_POST['text'];
//標題
$subject = $_POST['subject'];
//發送者
$from = $_POST['from'];
//接受者
$to = $_POST['to'];
//附件
$file = $_FILES['upload_file']['tmp_name'];
// 定義分界線
$boundary = uniqid( "");
$headers = "Content-type: multipart/mixed; boundary= $boundary\r\n";
$headers .= "From:$from\r\n";
//確定上傳文件的MIME類型
if($_FILES['upload_file']['type'])
$mimeType = $_FILES['upload_file']['type'];
else
$mimeType ="application/unknown";
//文件名
$fileName = $_FILES['upload_file']['name'];

// 打開文件
$fp = fopen($file, "r");
// 把整個文件讀入一個變量
$read = fread($fp, filesize($file));
//我們用base64方法把它編碼
$read = base64_encode($read);
//把這個長字符串切成由每行76個字符組成的小塊
$read = chunk_split($read);
//現在我們可以建立郵件的主體
$body = "--$boundary
Content-type: text/plain; charset=iso-8859-1
Content-transfer-encoding: 8bit
$text
--$boundary
Content-type: $mimeType; name=$fileName
Content-disposition: attachment; filename=$fileName
Content-transfer-encoding: base64
$read
--$boundary--";
//發送郵件
if(mail($to, $subject,$body,$headers))
print "OK! the mail $from --- $to has been send
";
else
print "fail to send mail
";
?>

看不明白沒關係,我來說明一下:
  1,郵件頭的構造 :一般包括 內容類型(Content-type)要發送附件,設置為 multipart/mixed 意思是多個部分 (郵件本身+附件)。 boundary ,就是上面提到的分界線,他的值用php自帶的 uniqid();函數取得 接受方,抄送等,在後面加上 From: Cc:。與上面的 Content-type boundary 之間用 \r\n 分割 。
  2 郵件體 如果是純文本的郵件內容 它的格式如下: Content-type: text/plain; charset=iso-8859-1 Content-transfer-encoding: 8bit 後面再緊接著加上 郵件的文本內容。 如果是附件: Content-type: $mimeType; name=$fileName Content-disposition: attachment; filename=$fileName Content-transfer-encoding: base64 後面再緊接著加上 附件內容。 $mimeType 是附件的 MIME類型。 可以用 $_FILES['upload_file']['type'] 得到。 $fileName 就是附件的名字了 郵件文本內容和附件之間用 boundary 分割。 有人會問,附件內容是什麼?附件內容就是用read函數讀入所上傳的附件,然後再把它經過base64編碼之後再用chunk_split 大卸N塊,每塊大小是默認的76字符。 好了,現在再去看那段程序,應該沒什麼問題了吧?把相應的變量帶入mail函數里面就ok了。
以上程序在 PHP Version 4.3.8 freeBSD 下測試通過。