这个问题很basic,不过还是困扰了我一段时间.(这里主要讨论的是命令行模式下)
我本来觉得应该使用命令 rmdir
但是发现它无法删除非空的目录.
后来发现了原来应该使用命令 rm -rf 目录名
其中参数-f表示force.使用了这个参数就不会提示你是否要删除了.
Linux下如何删除非空目录
mrtg for linux 安装
本文中使用的系统为RH9.0,本机IP地址为192.168.1.6
一、MRTG需要以SNMP服务为基础,所以请确保你的系统已经启用了此服务
1.请确保你的系统安装了以下软件包
net-snmp-5.0.6-17
net-snmp-devel-5.0.6-17
net-snmp-utils-5.0.6-17
2.修改/etc/snmp/snmpd.conf
去掉如下一行的注释
view mib2 included .iso.org.dod.internet.mgmt.mib-2 fc
在大约55行处添加如下一行
view systemview included .1.3.6.1.2.1.2
把如下行
access notConfigGroup “” any noauth exact systemview none none
改作:
access notConfigGroup “” any noauth exact mib2 none none
3.启用snmpd服务
#service snmpd start
#chkconfig –levle 2345 snmpd on
4.查看端口的开启状况
# netstat -tunlp |grep snmp
tcp 0 0 0.0.0.0:199 0.0.0.0:* LISTEN 4973/snmpd
udp 0 0 0.0.0.0:161 0.0.0.0:* 4973/snmpd
二、MRTG生成供浏览图像需要httpd服务的支持,同时也需要gd、libpng和zlib三个软件包的支持,而gd的正常运行也需要其它的几个软件,下面一并安装它们
1.安装zlib-1.2.3
#tar zxvf zlib-1.2.3.tar.gz
#cd zlib-1.2.3
#./configure –prefix=/usr/local/zlib
#make
#make install
2.安装httpd-2.2.4
#tar zxvf httpd-2.2.4.tar.gz
#cd httpd-2.2.4
#./configure –prefix=/usr/local/apache –sysconfdir=/etc/httpd –enable-so –enable-track-vars –enable-rewrite –with-z-dir=/usr/local/zlib
#make
#make install
启动httpd
/usr/local/apache/bin/apachectl -k start
3.安装libpng-1.2.14
#tar zxvf libpng-1.2.14.tar.gz
# cd libpng-1.2.14
# cp scripts/makefile.linux makefile
# make (若是提示找不到zlib库文件或者头文件,多半是makefile文件里zlib的默认路径有误。可编辑makefile文件,找到zlib项并重新指 定路径到/usr/local/zlib/lib和/usr/local/zlib/include)。
# make install
4.安装freetype-2.1.10
# tar -zvxf freetype-2.1.10.tar.gz
# cd freetype-2.1.10
# mkdir -p /usr/local/freetype
# ./configure –prefix=/usr/local/freetype
# make;make install
5.安装jpegsrc.v6b
jpeg默认不会自建目录,因此需手动建立目录:
# mkdir -pv /usr/local/jpeg6/{,bin,lib,include,man/{,man1},man1}
安装
#tar zxvf jpegsrc.v6b.tar.gz
# ./configure –prefix=/usr/local/jpeg6/ –enable-shared –enable-static
# make
# make install
# make install-lib
6.安装libxml2-2.6.19
# tar -zxf libxml2-2.6.19.tar.gz
# cd libxml2-2.6.19
# mkdir -p /usr/local/libxml2
# ./configure –prefix=/usr/local/libxml2
# make; make install
#cp xml2-config /usr/bin
7.安装GD-2.0.33库
# tar -zvxf gd-2.0.33.tar.gz
# mkdir -p /usr/local/gd2
# cd gd-2.0.33
# ./configure –prefix=/usr/local/gd2 –with-jpeg=/usr/local/jpeg6/ –with-png=/usr/local/lib/ –with-zlib=/usr/local/zlib/ –with-freetype=/usr/local/freetype/
# make
# make install
三、安装配置MRTG
1.下载mrtg,目前最新版本为mrtg-2.15.1
http://oss.oetiker.ch/mrtg/pub/mrtg-2.15.1.tar.gz
2.安装mrtg-2.15.1
#tar zxvf mrtg-2.15.1.tar.gz
# cd mrtg-2.15.1
# ./configure –prefix=/usr/local/mrtg –sysconfdir=/etc/mrtg –with-gd=/usr/local/gd2/include –with-gd-lib=/usr/local/gd2/lib –with-gd-inc=/usr/local/gd2/include –with-png=/usr/local/include –with-png-lib=/usr/local/lib –with-png-inc=/usr/local/include –with-zlib=/usr/local/zlib/include –with-zlib-lib=/usr/local/zlib/include –with-zlib-inc=/usr/local/zlib/include
# make
# make install
3.基本配置
生成主配置文件
#/usr/local/mrtg/cfgmaker public@localhost > /etc/mrtg/mrtg.cfg
编辑/etc/mrtg/mrtg.cfg
将
#WorkDir:/home/http/mrtg
去掉注释并改为
WorkDir: /usr/local/apache/htdocs/mrtg (此处是你的httpd默认的主目录)
去掉如下行的注释
# Options[_]: growright, bits
添加如下行,实现网页中的中文字符显示
Language:gb2312
生成MRTG网页主页面文件
#/usr/local/mrtg/bin/indexmaker /etc/mrtg/mrtg.cfg –output=/usr/local/apache/htdocs/mrtg/index.html –title=”My MRTG”
4.启动MRTG
#env LANG=C /usr/local/mrtg/bin/mrtg /etc/mrtg/mrtg.cfg
这个命令会输出一些错误信息,一般可以安全忽略,连续执行三次此命令即可。
5.MRTG生成的web页面是静态的,为了能让其不断的刷新,需要将以上命令添加进crontab
#crontab -e
添加如下一行
*/3 * * * * env LANG=C /usr/local/mrtg/bin/mrtg /etc/mrtg/mrtg.cfg
注:此行表示每三分钟刷新一次,你可以根据自己的需要修改刷新时间间隔。
6.安装完毕,可以去查看结果了,在浏览器输入形如以下地址
http://192.168.1.6/mrtg (IP地址为你的机器IP)
四、一个示例:内存使用监视
1.新建一个存放脚本的文件夹
#mkdir -pv /usr/local/apache/htdocs/mrtgsh
2.建立脚本文件
#vi /usr/local/apache/htdocs/mrtgsh/mrtg.memory
添加如下脚本:
#!/bin/bash
# run this script to check the mem usage.
totalmem=`/usr/bin/free |grep Mem |awk ‘{print $2}’`
usedmem=`/usr/bin/free |grep Mem |awk ‘{print $3}’`
UPtime=`/usr/bin/uptime | awk ‘{print $3″”$4″”$5}’`
echo $totalmem
echo $usedmem
echo $UPtime
让其具有运行权限
#chmod 755 /usr/local/apache/htdocs/mrtgsh/mrtg.memory
3.编辑/etc/mrtg/mrtg.cfg
添加如下内容
Target[memory]: `/usr/local/apache/htdocs/mrtgsh/mrtg.memory`
MaxBytes[memory]: 4096000
Title[memory]:Memory Usages
ShortLegend[memory]: &
kmg[memory]:kB,MB
kilo[memory]:1024
YLegend[memory]: Memory Usage :
Legend1[memory]: Total Memory :
Legend2[memory]: Used Memory :
LegendI[memory]: Total Memory :
LegendO[memory]: Used Memory :
Options[memory]: growright,gauge,nopercent
PageTop[memory]:
Memory Usages
4.重新生成主页面文件
#/usr/local/mrtg/bin/indexmaker /etc/mrtg/mrtg.cfg –output=/usr/local/apache/htdocs/mrtg/index.html –title=”My MRTG”
5.可根据情况重新启动MRTG,然后就可以查看效果了。
华为交换机SNMP配置命令
(1) snmp-agent sys-info contact
设置管理员的标识及联系方法,请把替换为你要设置成的值,下同。这个值初始是HuaWei BeiJing China,用指令display current-configuration可以在当前执行的配置的靠末尾看到该项。
(2) snmp-agent sys-info location
设置交换机的位置信息,这项初始没有设置。
(3) snmp-agent community read public
设置一个SNMP Community,使用该Community连接交换机时,只可以读取其SNMP信息。你可以把指令中的public换成你想要的字符串。
(4) snmp-agent community write private
设置一个SNMP Community,使用该Community连接交换机时,不仅可以读取其SNMP信息,还可以将值写入SNMP的MIB对象,实现对设备进行配置。你可以把指令中的private换成你想要的字符串。
(5) snmp-agent sys-info version all
设置交换机支持的SNMP协议,有v1,v2c,v3这3个版本,如果你不确定,最好设为all,将会同时支持这3个协议。在S3050C-0025上初始是只支持v3版本的,如果你没有正确设定它,mibbrower等一些读取软件可能会无法读取信息。
一般只需设置第(3)和第(5)个指令就可以读取到交换机的SNMP信息了。在旧的vrp系统上设置可能不同,我测试的交换机使用的是vrp3.10版本。
我使用的是PHP-SNMP的函数来读取交换机的SNMP信息的。
CentOS 6.0 设置IP地址网关DNS
切忌:
在做任何操作之前先备份原文件,我们约定备份文件的名称为:源文件名称+bak+日期,例如原文件名称为:centos.txt
那么备份文件名称为:centos.txtbak
=======================================================================
引言:linux的网卡IP地址是存放在文件中的,这个配置文件在/etc/sysconfig/network-scripts下,
名称分别为ifcfg-eth0,ifcfg-eth1等
如果你只有一块网卡,就只有ifcfg-eth0一个文件,
如果你有两块或者两块以上的网卡,就会有ifcfg-eth1、ifcfg-eth2等文件的出现。
=======================================================================
先查看电脑有几块网卡:
终端命令下面输入:
cd /etc/sysconfig/network-scripts #进入/etc/sysconfig/network-scripts文件夹中
ls -1 #查看/etc/sysconfig/network-scripts文件夹中所有的文件,发现只有一个ifcfg-eth0,说明电脑只有一块网卡
cd #返回
cp /etc/sysconfig/network-scripts/ifcfg-eth0 /etc/sysconfig/network-scripts/ifcfg-eth0bak110816 #备份件
vi /etc/sysconfig/network-scripts/ifcfg-eth0 #进入网卡ifcfg-eth0配置文件
NM_CONTROLLED=yes #network mamager的参数,实时生效,不需要重启
ONBOOT=yes #设置为yes,开机自动启用网络连接
IPADDR=192.168.21.129 #IP地址
BOOTPROTO=none #设置为none禁止DHCP,设置为static启用静态IP地址,设置dhcp开启DHCP服务
NETMASK=255.255.255.0 #子网掩码
DNS2=8.8.4.4 #第二个dns服务器
TYPE=Ethernet #网络类型为:Ethernet
GATEWAY=192.168.21.2 #设置网关
DNS1=8.8.8.8 #第一个dns服务器
IPV6INIT=no #禁止IPV6
USERCTL=no #是否允许非root用户控制该设备,设置为no,只能用root用户更改
HWADDR=00:0C:29:2C:E1:0F #网卡的Mac地址
PREFIX=24
DEFROUTE=yes
IPV4_FAILURE_FATAL=yes
NAME="System eth0" #定义设备名称
保存退出
cp /etc/resolv.conf /etc/resolv.confbak #备份文件
vi /etc/resolv.conf #设置DNS服务器
nameserver 8.8.8.8
nameserver 8.8.4.4
重启网络服务:
service network restart
/etc/init.d/network restart
如果不行,就重启一下服务器:shutdown -r now 或者reboot
到此,网络配置完成!
如何在cisco3550交换机上实现端口限速
PC1接在Cisco3550 F0/1上,速率为1M;
PC1接在Cisco3550 F0/2上,速率为2M;
Cisco3550的G0/1为出口。
二、详细配置过程
注:每个接口每个方向只支持一个策略;一个策略可以用于多个接口。因此所有PC的下载速率的限制都应该定义在同一个策略(在本例子当中
为policy
-map user-down),而PC不同速率的区分是在Class-map分别定义。
1、在交换机上启动QOS
Switch(config)#mls qos //在交换机上启动QOS
2、分别定义PC1(10.10.1.1)和PC2(10.10.2.1)访问控制列表
Switch(config)#Access-list 10 permit 10.10.1.0 0.0.0.255 //控制pc1上行流量
Switch(config)#access-list 100 permit any 10.10.1.0 0.0.0.255 //控制pc1下行流量
Switch(config)#access-list 11 permit 10.10.2.0 0.0.0.255 //控制pc2上行流量
Switch(config)#access-list 111 permit any 10.10.2.0 0.0.0.255 //控制pc2下行流量
3、定义类,并和上面定义的访问控制列表绑定
Switch(config)# class-map user1-up //定义PC1上行的类,并绑定访问列表10
Switch(config-cmap)# match access-group 10
Switch(config-cmap)# exit
Switch(config)# class-map user2-up
Switch(config-cmap)# match access-group 11 //定义PC2上行的类,并绑定访问列表10
Switch(config-cmap)# exit
Switch(config)# class-map user1-down
Switch(config-cmap)# match access-group 100 //定义PC1下行的类,并绑定访问列表100
Switch(config-cmap)# exit
Switch(config)# class-map user2-down
Switch(config-cmap)# match access-group 111 //定义PC2下行的类,并绑定访问列表111
Switch(config-cmap)# exit
4、定义策略,把上面定义的类绑定到该策略
Switch(config)# policy-map user1-up //定义PC1上行的速率为1M
Switch(config-pmap)# class user1-up
Switch(config-pmap-c)# trust dscp
Switch(config-pmap-c)# police 1024000 1024000 exceed-action drop
Switch(config)# policy-map user2-up //定义PC2上行的速率为2M
Switch(config-pmap)# class user2-up
Switch(config-pmap-c)# trust dscp
Switch(config-pmap-c)# police 2048000 1024000 exceed-action drop
Switch(config)# policy-map user-down
Switch(config-pmap)# class user1-down
Switch(config-pmap-c)# trust dscp
Switch(config-pmap-c)# police 1024000 1024000 exceed-action drop
Switch(config-pmap-c)# exit
Switch(config-pmap)# class user2-down
Switch(config-pmap-c)# trust dscp
Switch(config-pmap-c)# police 2048000 1024000 exceed-action drop
Switch(config-pmap-c)# exit
5、在接口上运用策略
Switch(config)# interface f0/1
Switch(config-if)# service-policy input user1-up
Switch(config)# interface f0/2
Switch(config-if)# service-policy input user2-up
Switch(config)# interface g0/1
Switch(config-if)# service-policy input user-down
javascript:window.open 打开最大化窗口设置及详解
目的主要是使用javascript:window.open()对浏览器 iE6.0,7.0,8.0,chorme,safari,firefox适用
刚开始的时候对最大化使用
Open
对IE6.0,它的效果是全屏,但是没有了关闭等等按钮,必须打开任务管理器了才能关掉,对用户很不方便。
而对safari,根本就不起作用,还是原来的窗体大小打开。
正确的使用方法是
Open
对这些浏览器是 OK的
随便添加些window.open()的介绍
1.基本语法 window.open(pageURL,name,parameters)
2.各项参数
其中yes/no也可使用1/0;pixel value为具体的数值,单位象素。
参数 | 取值范围 | 说明
alwaysLowered | yes/no | 指定窗口隐藏在所有窗口之后
alwaysRaised | yes/no | 指定窗口悬浮在所有窗口之上
depended | yes/no | 是否和父窗口同时关闭
directories | yes/no | Nav2和3的目录栏是否可见
height | pixel value | 窗口高度
hotkeys | yes/no | 在没菜单栏的窗口中设安全退出热键
innerHeight | pixel value | 窗口中文档的像素高度
innerWidth | pixel value | 窗口中文档的像素宽度
location | yes/no | 位置栏是否可见
menubar | yes/no | 菜单栏是否可见
outerHeight | pixel value | 设定窗口(包括装饰边框)的像素高度
outerWidth | pixel value | 设定窗口(包括装饰边框)的像素宽度
resizable | yes/no | 窗口大小是否可调整
screenX | pixel value | 窗口距屏幕左边界的像素长度
screenY | pixel value | 窗口距屏幕上边界的像素长度
scrollbars | yes/no | 窗口是否可有滚动栏
titlebar | yes/no | 窗口题目栏是否可见
toolbar | yes/no | 窗口工具栏是否可见
Width | pixel value | 窗口的像素宽度
z-look | yes/no | 窗口被激活后是否浮在其它窗口之上
3.一个例子介绍
弹出的窗口的外观,尺寸大小,弹出的位置以适应该页面的具体情况。
- <SCRIPT LANGUAGE="javascript">
- <!--
- window.open ('page.html', 'newwindow', 'height=100, width=400, top=0,left=0, toolbar=no, menubar=no, scrollbars=no, resizable=no,location=no, status=no')
- //写成一行
- -->
- </SCRIPT>
参数解释:
window.open 弹出新窗口的命令;
'page.html' 弹出窗口的文件名;
'newwindow' 弹出窗口的名字(不是文件名),非必须,可用空''代替;
height=100 窗口高度;
width=400 窗口宽度;
top=0 窗口距离屏幕上方的象素值;
left=0 窗口距离屏幕左侧的象素值;
toolbar=no 是否显示工具栏,yes为显示;
menubar,scrollbars 表示菜单栏和滚动栏。
Resizable=no 是否允许改变窗口大小,yes为允许;
location=no 是否显示地址栏,yes为允许;
status=no 是否显示状态栏内的信息(通常是文件已经打开),yes为允许;
</SCRIPT>
js脚本结束
PHP读取Excel文件
PHP-ExcelReader是一个读取Excel文件内容的一个PHP类。它能将Excel工作表的数据库读入到PHP的数组中,方便PHP调用。
压缩包:phpExcelReader.zip,包含两个必需文件:oleread.inc、reader.php。
使用方法:
- require_once "reader.php";
- $xl_reader= new Spreadsheet_Excel_Reader ( );
- $data->setOutputEncoding('CP936'); //注意编码:中文编码CP936或GBK。
- $xl_reader->read("filename.xls"); //读取文件
- //数据调用示例
- $numRows = $data->sheets[0]['numRows'];
- $numCols = $data->sheets[0]['numCols'];
- for ($i = 1; $i <= $numRows; $i++) {
- for ($j = 1; $j <= $numCols; $j++) {
- echo """.$data->sheets[0]['cells'][$i][$j]."",";
- }
- echo "n";
- }
VBS脚本Ghost后自动修改计算机名及IP
Ghost后自动修改计算机名及IP 脚本
VBS代码如下: [复制以下代码到文档 另存为 IP.vbs ]
===============================================
- '相关IP参数请自行修改!源码开放 版权所无 欢迎转载!http://hi.baidu.com/lin123
- Dim Name
- Name="A" '机器名前缀
- Dim Num
- Num=Inputbox ("代码收集:Linowen QQ:64929924"+chr(10)&chr(13)+"IP:192.168.0.* 子网:255.255.255.0 网关:192.168.0.254 DNS:61.144.56.101"+chr(10)&chr(13)+"请输入本机编号:"+chr(10)&chr(13)+"必须是001-244之间的三位'半角'数字!","易游 广州创誉网络_Linowen")
- Dim Ipnum
- Ipnum=0+Num 'IP为机器号+0
- Dim SubnetMask
- SubnetMask="255.255.255.0" '子网掩码
- Dim Gateway
- Gateway="192.168.0." '网关前3位
- Dim gatewayip
- gatewayip="254" '网关最后1位
- dim Dns1
- Dns1="61.144.56.101" '主DNS
- dim Dns2
- Dns2="192.168.0.254" '次DNS
- Set Sh = CreateObject("WScript.Shell")
- Sh.RegWrite "HKEY_LOCAL_MACHINESystemCurrentControlSetControlComputerNameComputerNameComputerName",Name&Num,"REG_SZ"
- Sh.RegWrite "HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServicesTcpipParametersNV Hostname",Name&Num,"REG_SZ"
- Sh.RegWrite "HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServicesTcpipParametersHostname",Name&Num,"REG_SZ"
- Set sh = Nothing
- Set oShell = Nothing
- strComputer = "."
- Set objWMIService = GetObject("winmgmts:\" & strComputer & "rootcimv2")
- Set colNetAdapters = objWMIService.ExecQuery _
- ("Select * from Win32_NetworkAdapterConfiguration where IPEnabled=TRUE")
- strIPAddress = Array(Gateway&Ipnum)
- strSubnetMask = Array(SubnetMask)
- strGateway = Array(gateway&gatewayip)
- strGatewayMetric = Array(1)
- arrDNSServers = Array(Dns1,Dns2)
- For Each objNetAdapter in colNetAdapters
- errEnable = objNetAdapter.EnableStatic(strIPAddress, strSubnetMask)
- errGateways = objNetAdapter.SetGateways(strGateway, strGatewaymetric)
- errDNS=objNetAdapter.SetDNSServerSearchOrder(arrDNSServers)
- Next
- Set objWMIService = GetObject("winmgmts:" _
- & "{impersonationLevel=impersonate}!\" & strComputer & "rootcimv2")
- Set colComputers = objWMIService.ExecQuery _
- ("Select * from Win32_ComputerSystem")
- For Each objComputer in colComputers
- 'ObjComputer.Rename(Name&Num)
- Next
- Set objNetworkSettings = objWMIService.Get("Win32_NetworkAdapterConfiguration")
- objNetworkSettings.SetIPXVirtualNetworkNumber(Num)
- Set Delfso = CreateObject("Scripting.FileSystemObject")
- Delfso.DeleteFile(WScript.ScriptName)
无限联动select,从数据库中读取
文件1.htm:
//无限联动菜单,从数据库中读取
function xmlGet(url){
if(window.XMLHttpRequest){
http_request=new XMLHttpRequest();
}else if(window.ActiveXObject){
http_request=new ActiveXObject("Microsoft.XMLHTTP");
}
var linkurl=url;
http_request.open("GET",linkurl,false);
http_request.send(null);
return http_request.responseText;
}
function buildSel(fid,selid){
if(fid>=0){
sel=document.getElementById('sel'+selid);
sel.options.length=0;
str=xmlGet('2.php?fid='+fid);
if(str!=''){
array1=str.split('@|@');
sel.options.add(new Option('请选择','-1'));
for(var i=0;i<array1.length;i++){
array2=array1.split('@_@');
sel.options.add(new Option(array2[0],array2[1]));
}
sel.options[0].selected=true;
for(var k=selid+2;k<=3;k++){//更改下下级以下菜单为空
subsel=document.getElementById('sel'+k);
subsel.length=1;
subsel.options[0].selected=true;
}
}
}
}
</script>
<select name="sel1" id="sel1" onchange="buildSel(this.value,2)"></select>
<select name="sel2" id="sel2" onchange="buildSel(this.value,3)"></select>
<select name="sel3" id="sel3"></select>
<script language="JavaScript">buildSel(0,1);</script>
_____________________________________________________________________
文件2.php
$rs=mysql_query("select * from photosort where fid=".$_GET["fid"]." order by id");
$rows=mysql_num_rows($rs);
$str='';
if($rows>0){
for($i=0;$i<$rows;$i++){
$str.=mysql_result($rs,$i,'title')."@_@".mysql_result($rs,$i,'id')."@|@";
}
}
if(strlen($str)>0){
$str=substr($str,0,strlen($str)-3);
}
echo $str;
mysql_close($db);?>
_____________________________________________________________________
数据库:
`id` int(10) unsigned NOT NULL auto_increment,
`fid` int(10) unsigned NOT NULL default '0',
`title` varchar(100) NOT NULL default '',
PRIMARY KEY (`id`),
KEY `fid` (`fid`),
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
优化PHP程序的方法
1. If a method c++an be static, declare it static. Speed improvement is by a factor of 4. 如果一个方法可静态化,就对它做静态声明。速率可提升至4倍。
2. echo is faster than print. echo 比 print 快。
3. Use echo’s multiple parameters instead of string concatenation. 使用echo的多重参数(译注:指用逗号而不是句点)代替字符串连接。
4. Set the maxvalue for your for-loops before and not in the loop. 在执行for循环之前确定最大循环数,不要每循环一次都计算最大值。
5. Unset your variables to free memory, especially large arrays. 注销那些不用的变量尤其是大数组,以便释放内存。
6. Avoid magic like __get, __set, __autoload 尽量避免使用__get,__set,__autoload.
7. require_once() is expensive require_once()代价昂贵。
8. Use full paths in includes and requires, less time spent on resolving the OS paths. 在包含文件时使用完整路径,解析操作系统路径所需的时间会更少。
9. If you need to find out the time when the script started executing, $_SERVER['REQUEST_TIME'] is preferred to time() 如果你想知道脚本开始执行(译注:即服务器端收到客户端请求)的时刻,使用$_SERVER['REQUEST_TIME']要好于time()。
10. See if you can use strncasecmp, strpbrk and stripos instead of regex. 检查是否能用strncasecmp,strpbrk,stripos函数代替正则表达式完成相同功能。
11. str_replace is faster than preg_replace, but strtr is faster than str_replace by a factor of 4. str_replace函数比preg_replace函数快,但strtr函数的效率是str_replace函数的四倍。
12. If the function, such as string replacement function, accepts both arrays and single characters as arguments, and if your argument list is not too long, consider writing a few redundant replacement statements, passing one character at a time, instead of one line of code that accepts arrays as search and replace arguments. 如果一个字符串替换函数,可接受数组或字符作为参数,并且参数长度不太长,那么可以考虑额外写一段替换代码,使得每次传递参数是一个字符,而不是只写一行代码接受数组作为查询和替换的参数。
13. It’s better to use select statements than multi if, else if, statements. 使用选择分支语句(译注:即switch case)好于使用多个if,else if语句。
14. Error suppression with @ is very slow. 用@屏蔽错误消息的做法非常低效。
15. Turn on apache’s mod_deflate 打开apache的mod_deflate模块。
16. Close your database connections when you’re done with them. 数据库连接当使用完毕时应关掉。
17. $row['id'] is 7 times faster than $row[id]. $row['id']的效率是$row[id]的7倍。
18. Error messages are expensive. 错误消息代价昂贵。
19. Do not use functions inside of for loop, such as for ($x=0; $x < count($array); $x) The count() function gets called each time. 尽量不要在for循环中使用函数,比如for ($x=0; $x < count($array); $x)每循环一次都会调用count()函数。
20. Incrementing a local variable in a method is the fastest. Nearly the same as calling a local variable in a function. 在方法中递增局部变量,速度是最快的。几乎与在函数中调用局部变量的速度相当。
21. Incrementing a global variable is 2 times slow than a local var. 递增一个全局变量要比递增一个局部变量慢2倍。
22. Incrementing an object property (eg. $this->prop++) is 3 times slower than a local variable. 递增一个对象属性(如:$this->prop++)要比递增一个局部变量慢3倍。
23. Incrementing an undefined local variable is 9-10 times slower than a pre-initialized one. 递增一个未预定义的局部变量要比递增一个预定义的局部变量慢9至10倍。
24. Just declaring a global variable without using it in a function also slows things down (by about the same amount as incrementing a local var)。 PHP probably does a check to see if the global exists. 仅定义一个局部变量而没在函数中调用它,同样会减慢速度(其程度相当于递增一个局部变量)。PHP大概会检查看是否存在全局变量。
25. Method invocation appears to be independent of the number of methods defined in the class because I added 10 more methods to the test class (before and after the test method) with no change in performance. 方法调用看来与类中定义的方法的数量无关,因为我(在测试方法之前和之后都)添加了10个方法,但性能上没有变化。
26. Methods in derived classes run faster than ones defined in the base class. 派生类中的方法运行起来要快于在基类中定义的同样的方法。
27. A function call with one parameter and an empty function body takes about the same time as doing 7-8 $localvar++ operations. A similar method call is of course about 15 $localvar++ operations. 调用带有一个参数的空函数,其花费的时间相当于执行7至8次的局部变量递增操作。类似的方法调用所花费的时间接近于15次的局部变量递增操作。
28. Surrounding your string by ‘ instead of ” will make things interpret a little faster since php looks for variables inside “…” but not inside ‘…’. Of course you can only do this when you don’t need to have variables in the string. 用单引号代替双引号来包含字符串,这样做会更快一些。因为PHP会在双引号包围的字符串中搜寻变量,单引号则不会。当然,只有当你不需要在字符串中包含变量时才可以这么做。
29. When echoing strings it’s faster to separate them by comma instead of dot. Note: This only works with echo, which is a function that can take several strings as arguments. 输出多个字符串时,用逗号代替句点来分隔字符串,速度更快。注意:只有echo能这么做,它是一种可以把多个字符串当作参数的”函数”(译注:PHP手册中说echo是语言结构,不是真正的函数,故把函数加上了双引号)。
30. A PHP script will be served at least 2-10 times slower than a static HTML page by Apache. Try to use more static HTML pages and fewer scripts. Apache解析一个PHP脚本的时间要比解析一个静态HTML页面慢2至10倍。尽量多用静态HTML页面,少用脚本。
31. Your PHP scripts are recompiled every time unless the scripts are cached. Install a PHP caching product to typically increase performance by 25-100% by removing compile times. 除非脚本可以缓存,否则每次调用时都会重新编译一次。引入一套PHP缓存机制通常可以提升25%至100%的性能,以免除编译开销。
32. Cache as much as possible. Use memcached – memcached is a high-performance memory object caching system intended to speed up dynamic web applications by alleviating database load. OP code caches are useful so that your script does not have to be compiled on every request. 尽量做缓存,可使用memcached.memcached是一款高性能的内存对象缓存系统,可用来加速动态Web应用程序,减轻数据库负载。对运算码(OP code)的缓存很有用,使得脚本不必为每个请求做重新编译。
33. When working with strings and you need to check that the string is either of a certain length you’d understandably would want to use the strlen() function. This function is pretty quick since it’s operation does not perform any calculation but merely return the already known length of a string available in the zval structure (internal C struct used to store variables in PHP)。 However because strlen() is a function it is still somewhat slow because the function call requires several operations such as lowercase & hashtable lookup followed by the execution of said function. In some instance you can improve the speed of your code by using an isset() trick. 当操作字符串并需要检验其长度是否满足某种要求时,你想当然地会使用strlen()函数。此函数执行起来相当快,因为它不做任何计算,只返回在zval结构(C的内置数据结构,用于存储PHP变量)中存储的已知字符串长度。但是,由于strlen()是函数,多多少少会有些慢,因为函数调用会经过诸多步骤,如字母小写化(译注:指函数名小写化,PHP不区分函数名大小写)、哈希查找,会跟随被调用的函数一起执行。在某些情况下,你可以使用isset()技巧加速执行你的代码。
Ex.(举例如下)
if (strlen($foo) < 5) { echo “Foo is too short”; }
vs.(与下面的技巧做比较)
if (!isset($foo{5})) { echo “Foo is too short”; }
Calling isset() happens to be faster then strlen() because unlike strlen(), isset() is a language construct and not a function meaning that it’s execution does not require function lookups and lowercase. This means you have virtually no overhead on top of the actual code that determines the string’s length. 调用isset()恰巧比strlen()快,因为与后者不同的是,isset()作为一种语言结构,意味着它的执行不需要函数查找和字母小写化。也就是说,实际上在检验字符串长度的顶层代码中你没有花太多开销。
34. When incrementing or decrementing the value of the variable $i++ happens to be a tad slower then ++$i. This is something PHP specific and does not apply to other languages, so don’t go modifying your C or Java code thinking it’ll suddenly become faster, it won’t. ++$i happens to be faster in PHP because instead of 4 opcodes used for $i++ you only need 3. Post incrementation actually causes in the creation of a temporary var that is then incremented. While pre-incrementation increases the original value directly. This is one of the optimization that opcode optimized like Zend’s PHP optimizer. It is still a good idea to keep in mind since not all opcode optimizers perform this optimization and there are plenty of ISPs and servers running without an opcode optimizer. 当执行变量$i的递增或递减时,$i++会比++$i慢一些。这种差异是PHP特有的,并不适用于其他语言,所以请不要修改你的C或Java代码并指望它们能立即变快,没用的。++$i更快是因为它只需要3条指令(opcodes),$i++则需要4条指令。后置递增实际上会产生一个临时变量,这个临时变量随后被递增。而前置递增直接在原值上递增。这是最优化处理的一种,正如Zend的PHP优化器所作的那样。牢记这个优化处理不失为一个好主意,因为并不是所有的指令优化器都会做同样的优化处理,并且存在大量没有装配指令优化器的互联网服务提供商(ISPs)和服务器。
35. Not everything has to be OOP, often it is too much overhead, each method and object call consumes a lot of memory. 并不是事必面向对象(OOP),面向对象往往开销很大,每个方法和对象调用都会消耗很多内存。
36. Do not implement every data structure as a class, arrays are useful, too. 并非要用类实现所有的数据结构,数组也很有用。
37. Don’t split methods too much, think, which code you will really re-use. 不要把方法细分得过多,仔细想想你真正打算重用的是哪些代码?
38. You can always split the code of a method later, when needed. 当你需要时,你总能把代码分解成方法。
39. Make use of the countless predefined functions. 尽量采用大量的PHP内置函数。
40. If you have very time consuming functions in your code, consider writing them as C extensions. 如果在代码中存在大量耗时的函数,你可以考虑用C扩展的方式实现它们。
41. Profile your code. A profiler shows you, which parts of your code consumes how many time. The Xdebug debugger already contains a profiler. Profiling shows you the bottlenecks in overview. 评估检验(profile)你的代码。检验器会告诉你,代码的哪些部分消耗了多少时间。Xdebug调试器包含了检验程序,评估检验总体上可以显示出代码的瓶颈。
42. mod_gzip which is available as an Apache module compresses your data on the fly and can reduce the data to transfer up to 80%. mod_zip可作为Apache模块,用来即时压缩你的数据,并可让数据传输量降低80%.
近期评论