Archive for the ‘php’ Category

Create daemons in PHP

» Create daemons in PHP

Everyone knows PHP can be used to create websites. But it can also be used to create desktop applications and commandline tools. And now with a class called System_Daemon, you can even create daemons using nothing but PHP. And did I mention it was easy?

What is a Daemon?

A daemon is a Linux program that run in the background, just like a ‘Service‘ on Windows. It can perform all sorts of tasks that do not require direct user input. Apache is a daemon, so is MySQL. All you ever hear from them is found in somewhere in /var/log, yet they silently power over 40% of the Internet.

You reading this page, would not have been possible without them. So clearly: a daemon is a powerful thing, and can be bend to do a lot of different tasks.

Why PHP?

Most daemons are written in C. It’s fast & robust. But if you are in a LAMP oriented company like me, and you need to create a lot of software in PHP anyway, it makes sense:

  • Reuse & connect existing code Think of database connections, classes that create customers from your CRM, etc.
  • Deliver new applications very fast PHP has a lot of build in functions that speed up development greatly.
  • Everyone knows PHP (right?) If you work in a small company: chances are there are more PHP programmers than there are C programmers. What if your C guy abandons ship? Admittedly it’s a very pragmatic reason, but it’s the same reason why Facebook is building HipHop.

Possible use cases

  • Website optimization If you’re running a (large) website, jobs that do heavy lifting should be taken away from the user interface and scheduled to run on the machine separately.
  • Log parser Continually scan logfiles and import critical messages in your database.
  • SMS daemon Read a database queue, and let your little daemon interface with your SMS provider. If it fails, it can easily try again later!
  • Video converter (think Youtube) Scan a queue/directory for incoming video uploads. Make some system calls to ffmpeg to finally store them as Flash video files. Surely you don’t want to convert video files right after the upload, blocking the user interface that long? No: the daemon will send the uploader a mail when the conversion is done, and proceed with the next scheduled upload

Deamons vs Cronjobs

Some people use cronjobs for the same Possible use cases. Crontab is fine but it only allows you to run a PHP file every minute or so.

  • What if the previous run hasn’t finished yet? Overlap can seriously damage your data & cause siginificant load on your machines.
  • What if you can’t afford to wait a minute for the cronjob to run? Maybe you need to trigger a process the moment a record is inserted?
  • What if you want to keep track of multiple ‘runs’ and store data in memory.
  • What if you need to keep your application listening (on a socket for example) Cronjobs are a bit rude for this, they may spin out of control and don’t provide a

framework for logging, etc. Creating a daemon would offer more elegance & possibilities. Let’s just say: there are very good reasons why a Linux OS isn’t composed entirely of Cronjobs :)

How it works internally

(Nerd alert!) When a daemon program is started, it fires up a second child process, detaches it, and then the parent process dies. This is called forking. Because the parent process dies, it will give the console back and it will look like nothing has happened. But wait: the child process is still running. Even if you close your terminal, the child continues to run in memory, until it either stops, crashes or is killed.

In PHP: forking can be achieved by using the Process Control Extensions. Getting a good grip on it, may take some studying though.

System_Daemon

Because the Process Control Extensions‘ documentation is a bit rough, I decided to figure it out once, and then wrap my knowledge and the required code inside a PEAR class called: System_Daemon. And so now you can just:

require_once “System/Daemon.php”;                 // Include the Class
 
System_Daemon::setOption(“appName”, “mydaemon”);  // Minimum configuration
System_Daemon::start();                           // Spawn Deamon!

And that’s all there is to it. The code after that, will run in your server’s background. So next, if you create a while(true) loop around that code, the code will run indefinitely. Remember to build in a sleep(5) to ease up on system resources.

Features & Characteristics

Here’s a grab of System_Daemon’s features:

  • Daemonize any PHP-CLI script
  • Simple syntax
  • Driver based Operating System detection
  • Unix only
  • Additional features for Debian / Ubuntu based systems like:
  • Automatically generate startup files (init.d)
  • Support for PEAR’s Log package
  • Can run with PEAR (more elegance & functionality) or without PEAR (for standalone packages)
  • Default signal handlers, but optionally reroute signals to your own handlers.
  • Set options like max RAM usage

Download

You could download the package from PEAR, or, if you have PEAR installed on your system: just run this from a console:

pear install -f System_Daemon

You can also update it using that last command.

Beta

Though I have quite some daemons set up this way, it’s officially still beta. So please report any bugs over at the PEAR page. Other comments may be posted here.

Complex Example

Ready to dig a little deeper? This example program is called ‘logparser’, it takes a look at a more complex use of System_Daemon. For instance, it introduces command line arguments like:

--no-daemon              # just run the program in the console this time
--write-initd            # writes a startup file

Read this source to get the picture. Don’t forget the comments!

#!/usr/bin/php -q
<?php
/**
 * System_Daemon turns PHP-CLI scripts into daemons.
 *
 * PHP version 5
 *
 * @category  System
 * @package   System_Daemon
 * @author    Kevin <kevin@vanzonneveld.net>
 * @copyright 2008 Kevin van Zonneveld
 * @license   http://www.opensource.org/licenses/bsd-license.php
 * @link      http://github.com/kvz/system_daemon
 */
 
/**
 * System_Daemon Example Code
 *
 * If you run this code successfully, a daemon will be spawned
 * but unless have already generated the init.d script, you have
 * no real way of killing it yet.
 *
 * In this case wait 3 runs, which is the maximum for this example.
 *
 *
 * In panic situations, you can always kill you daemon by typing
 *
 * killall -9 logparser.php
 * OR:
 * killall -9 php
 *
 */
 
// Allowed arguments & their defaults 
$runmode = array(
    ‘no-daemon’ => false,
    ‘help’ => false,
    ‘write-initd’ => false,
);
 
// Scan command line attributes for allowed arguments
foreach ($argv as $k=>$arg) {
    if (substr($arg, 0, 2) == ‘–’ && isset($runmode[substr($arg, 2)])) {
        $runmode[substr($arg, 2)] = true;
    }
}
 
// Help mode. Shows allowed argumentents and quit directly
if ($runmode['help'] == true) {
    echo ‘Usage: ‘.$argv[0].‘ [runmode]‘ . \n;
    echo ‘Available runmodes:’ . \n;
    foreach ($runmode as $runmod=>$val) {
        echo ‘ –’.$runmod . \n;
    }
    die();
}
 
// Make it possible to test in source directory
// This is for PEAR developers only
ini_set(‘include_path’, ini_get(‘include_path’).‘:..’);
 
// Include Class
error_reporting(E_ALL);
require_once ‘System/Daemon.php’;
 
// Setup
$options = array(
    ‘appName’ => ‘logparser’,
    ‘appDir’ => dirname(__FILE__),
    ‘appDescription’ => ‘Parses vsftpd logfiles and stores them in MySQL’,
    ‘authorName’ => ‘Kevin van Zonneveld’,
    ‘authorEmail’ => ‘kevin@vanzonneveld.net’,
    ’sysMaxExecutionTime’ => ‘0′,
    ’sysMaxInputTime’ => ‘0′,
    ’sysMemoryLimit’ => ‘1024M’,
    ‘appRunAsGID’ => 1000,
    ‘appRunAsUID’ => 1000,
);
 
System_Daemon::setOptions($options);
 
// This program can also be run in the forground with runmode –no-daemon
if (!$runmode['no-daemon']) {
    // Spawn Daemon 
    System_Daemon::start();
}
 
// With the runmode –write-initd, this program can automatically write a 
// system startup file called: ‘init.d’
// This will make sure your daemon will be started on reboot 
if (!$runmode['write-initd']) {
    System_Daemon::info(‘not writing an init.d script this time’);
} else {
    if (($initd_location = System_Daemon::writeAutoRun()) === false) {
        System_Daemon::notice(‘unable to write init.d script’);
    } else {
        System_Daemon::info(
            ’sucessfully written startup script: %s’,
            $initd_location
        );
    }
}
 
// Run your code
// Here comes your own actual code
 
// This variable gives your own code the ability to breakdown the daemon:
$runningOkay = true;
 
// This variable keeps track of how many ‘runs’ or ‘loops’ your daemon has
// done so far. For example purposes, we’re quitting on 3.
$cnt = 1;
 
// While checks on 3 things in this case:
// - That the Daemon Class hasn’t reported it’s dying
// - That your own code has been running Okay
// - That we’re not executing more than 3 runs 
while (!System_Daemon::isDying() && $runningOkay && $cnt <=3) {
    // What mode are we in?
    $mode = ‘”‘.(System_Daemon::isInBackground() ?  : ‘non-’ ).
        ‘daemon” mode’;

    // Log something using the Daemon class’s logging facility
    // Depending on runmode it will either end up:
    //  - In the /var/log/logparser.log
    //  - On screen (in case we’re not a daemon yet)  
    System_Daemon::info(‘{appName} running in %s %s/3′,
        $mode,
        $cnt
    );

    // In the actuall logparser program, You could replace ‘true’
    // With e.g. a  parseLog(’vsftpd’) function, and have it return
    // either true on success, or false on failure.
    $runningOkay = true;
    //$runningOkay = parseLog(’vsftpd’);

    // Should your parseLog(’vsftpd’) return false, then
    // the daemon is automatically shut down.
    // An extra log entry would be nice, we’re using level 3,
    // which is critical.
    // Level 4 would be fatal and shuts down the daemon immediately,
    // which in this case is handled by the while condition.
    if (!$runningOkay) {
        System_Daemon::err(‘parseLog() produced an error, ‘.
            ’so this will be my last run’);
    }

    // Relax the system by sleeping for a little bit
    // iterate also clears statcache
    System_Daemon::iterate(2);

    $cnt++;
}
 
// Shut down the daemon nicely
// This is ignored if the class is actually running in the foreground
System_Daemon::stop();

Console action: Controlling the Daemon

Now that we’ve created an example daemon, it’s time to fire it up! I’m going to assume the name of your daemon is logparser. This can be changed with the statement: System_Daemon::setOption('appName', 'logparser'). But the name of the daemon is very important because it is also used in filenames (like the logfile).

Execute

Just make your daemon script executable, and then execute it:

chmod a+x ./logparser.php ./logparser.php

Check

Your daemon has no way of communicating through your console, so check for messages in:

tail /var/log/logparser.log And see if it’s still running:

ps uf -C logparser.php

Kill

Without the start/stop files (see below for howto), you need to:

killall -9 logparser.php Autch.. Let’s work on those start / stop files, right?

Start / Stop files (Debian & Ubuntu only)

Real daemons have an init.d file. Remember you can restart Apache with the following statement?

/etc/init.d/apache2 restart That’s a lot better than killing. So you should be able to control your own daemon like this as well:

/etc/init.d/logparser stop /etc/init.d/logparser start Well with System_Daemon you can write autostartup files using the writeAutoRun() method, look:

$path = System_Daemon::writeAutoRun();On success, this will return the path to the autostartup file: /etc/init.d/logparser, and you’re good to go!

Run on boot

Surely you want your daemon to run at system boot.. So on Debian & Ubuntu you could type:

update-rc.d logparser defaults Done your daemon now starts every time your server boots. Cancel it with:

update-rc.d -f logparser remove

Logrotate

Igor Feghali shares with us a logrotate config file to keep your log files from growing too large. Just place a file in your /etc/logrotate.d/.

/var/log/mydaemon.log { rotate 15 compress missingok notifempty sharedscripts size 5M create 644 mydaemon_user mydaemon_group postrotate /bin/kill -HUP `cat /var/run/mydaemon/mydaemond.pid 2>/dev/null` 2> /dev/null || true endscript } Obviously, replace the mydaemon occurances with values corresponding to your environment. Thanks Igor!

Troubleshooting

Here are some issues you may encounter down the road.

  • Don’t use echo() **Echo writes to the STDOUT of your current session. If you logout, that will cause fatal errors and the daemon to die. Use System_Daemon::log() instead.
  • Connect to MySQL after you start() the daemon. Otherwise only the parent process will have a MySQL connection, and since that dies.. It’s lost and you will get a ‘MySQL has gone away’ error.
  • Error handling Good error handling is imperative. Daemons are often mission critical applications and you don’t want an uncatched error to bring it to it’s knees.
    • Reconnect to MySQL A connection may be interrupted. Think about network downtime or lock-ups when your database server makes backups. Whatever the cause: You don’t want your daemon to die for this, let it try again later.
    • PHP error handler As of 0.6.3, System_Daemon forwards all PHP errors to the log() method, so keep an eye on your logfile. This behavior can be controlled using the logPhpErrors (true||false) option.
  • Monit Monit is a standalone program that can kickstart any daemon, based on your parameters. Should your daemon fail, monit will mail you and try to restart it.
  • Watch that memory Some classes keep a history of executed commands, sent mails, queries, whatever. They were designed without knowing they would ever be used in a daemonized environment. Cause daemons run indefinitely this ‘history’ will expand indefinitely. Since unfortunately your server’s RAM is not infinite, you will run into problems at some point. This makes it’s very important to address these memory ‘leaks’ when building daemons.
  • Statcache will corrupt your data If you do a file_exists(), PHP remembers the results to ease on your disk until the process end. That’s ok but since the Daemon process does not end, PHP will not be able to give you up to date information. As of 0.8.0 you should call System_Daemon::iterate(2) instead of e.g. sleep(2), this will sleep & clear the cache and give you fresh & valid data.

I know I’m saying MySQL a lot, but you can obviously replace that with Oracle, MSSQL, PostgreSQL, etc.

  • Comments Off


<?php
require('GoogleMapAPI.class.php');
$map = new GoogleMapAPI('map1');
$map->setAPIKey('ABQIAAAAPOHd09dXhJtbKHeZpxlh6BTdM_BGb_HRDyhTa-dAuFdRUQ382BTsqAFfGu_x3jaT_hgEvzyEiREMIg');
$map->setMapType('map');
$map->enableInfoWindow();
$map->enableDirections();
$map->setInfoWindowTrigger('mouseover');
$map->setWidth('400px');
$map->setHeight('400px');
$map->setFT('13.786987220018625,100.60581922531128','13.780276823001238,100.60309410095215');

?>

    <html ">
    <head>
    <?php $map->printHeaderJS(); ?>
    <?php $map->printMapJS(); ?>
    <!-- necessary for google maps polyline drawing in IE -->
    <style type="text/css">
      v\:* {
        behavior:url(#default#VML);
      }
    </style>
    </head>
    <body onload="onLoad()">
    <table border=0>
    <tr><td>
    <?php $map->printMap(); ?>

    </td>
	<td>
    <?php $map->printSidebar(); ?>
	  <div id="route"></div>
    </td>
	</tr>
    </table>

    </body>
    </html>
  • Comments Off

PDF ไทย

ขั้นแรก ไป download fpdf จาก fpdf.org ก่อน

แตกไฟล์ออกมามันจะประกอบด้วย dir และ file ต่างๆ ดังนี้

เอาทั้งหมดนี้ไปวางไว้ใน dir ที่จำใช้ทำงาน เช่น ทำงานที่ workspace/ ก็เอาไปวางเป็น workspace/fpdf/ เป็นต้น(ปรับแก้ได้ตามใจนะไม่ได้บังคับใช้ในการอ้างอิงที่อยู่เท่านั้น)
อันนี้ code ลองทดสอบอันแรก เอามาจาก fpdf.org เลยเพื่อทดสอบว่า fpdf ทีเราเอามาใช้งานได้จริง
สมมติว่า save เป็นไฟล์ “firstpage.php” ไว้ที่ workspace/
เราก็จะเข้าไปทดสอบได้จาก http://hostname/…/workspace/firstpage.php
<?php
require(‘./fpdf/fpdf.php’);
$pdf=new FPDF();
$pdf->AddPage();
$pdf->SetFont(‘Arial’,‘B’,16);
$pdf->Cell(40,10,‘Hello World!’);
$pdf->Output();
?>
ถ้าได้ก็ไปต่อได้ถ้าไม่ได้ก็ลองใหม่(-_-)
ขั้นที่ 2 เตรียม font (ทำบน Windows Vista)
download ตัวทำ font http://www.fpdf.org/fr/dl.php?id=22
นำทั้งหมดมาที่ dir workspace/
copy font จาก dir font มาที่ dir ที่ทำงาน (เพื่อให้ง่าย)
ตัวอย่างเช่น เอา Font “Angsana New” จาก C:\Windows\Fonts มาใส่ไว้ที่ dir workspace/
โดยไฟล์ของ Font “Angsana New” ชื่อ angsa.ttf
ขั้นที่ 3

เปิด cmd ขึ้นมาแล้วย้ายตัวเองไปที่ dir workspace/

พิมพ์
ttf2pt1 -b -L cp874.map angsa.ttf angsa
จากขั้นตอนนี้จะได้ไฟล์มาสองตัวคือ angsa.afm กับ angsa.pfb copy ใส่ไว้ที่ workspace/fpdf/font/makefont/
ขั้นที่ 4
สร้างไฟล์ php 1 ไฟล์เพื่อสร้างfont ให้ใช้ได้กับ fpdf อีกที
สมมุติว่าชื่อ make_angsa.php อยู่ที่ workspace/fpdf/font/makefont/
<?
include(’makefont.php’);
MakeFont(’angsa,pfb’,'angsa.afm’,'cp874′)
?>
เปิด cmd แล้วมาที่ dir นี้พิมพ์
php make_angsa.php

จะได้ไฟล์ออกมาอีก 2 ไฟล์คือ angsa.php และ angsa.z

copy เอาทั้งสองตัวไปวางที่ workspace/fpdf/font/
น่าจะใช้ได้แล้วลองทดสอบโดย
<?php
require(‘./fpdf/fpdf.php’);
$str = “มอสสิล่า”;
$pdf=new FPDF();
$pdf->AddFont(’angsa’,”,’angsa.php’);
$pdf->AddPage();
$pdf->SetFont(angsa,,16);
$pdf->Cell(40,10,$str);
$pdf->Output();
?>

น่าจะได้แล้วนะ

ขั้นที่ พิเศษ
จาก ผมที่ผมได้ลองถ้าเปลี่ยน encoding เป็น utf8 แล้วมันจะใช้ไม่ได้แฮะ(จำเป็นต้องใช้เพราะดึงข้อมูล utf8 จาก db) ผมก็เลยงงๆ ถามๆ ไปเรื่อย แล้วก็ได้คำตอบจาก  @gookcompsci ว่าให้ลองใช้ iconv ดู โดยให้ดูก่อนว่า php มันเปิด function นี้ไว้หรือเปล่าถ้ามันเปิดอยู่ก็ง่ายขึ้นครับ
อันนี้ตัวอย่างการใช้ iconv
<?
$str = “string encoding เริ่มต้นสมมุติว่าเป็น utf8″;
//$str = iconv(’encoding เริ่มต้น’,'encoding ปลายทาง’,’string ที่จะเปลี่ยน’);
$str = iconv(’UTF-8′,’CP874′,$str); //ถูกแปลงเป็น CP874 ที่นี่
?>
ตัวอย่างการใช้งานกับ db
<?php
include(’config.php’);
include(’opendb.php’);
require(’./fpdf/fpdf.php’);
$sql = “SELECT * FROM user”;
$result = mysql_query($sql);
$str = ”;
while($row = mysql_fetch_array($result)){
$str .= $row['name'];
}
$str = iconv(’UTF-8′,’CP874′,$str);
$pdf=new FPDF();
$pdf->AddFont(’angsa’,”,’angsa.php’);
$pdf->AddPage();
$pdf->SetFont(’angsa’,”,16);
$pdf->Cell(40,10,$str);
$pdf->Output();
include(’closedb.php’);
?>
  • Comments Off

เมื่อใช้งาน fpdf ครั้งแรกจะไม่สามารถใช้ภาษาไทยได้ เนื่องจาก Class fpdf ไม่ได้เตรียม font ที่รองรับภาษาไทยไว้
ดังนั้นเราจะต้องทำการติดตั้ง font เพิ่มเติมเข้า ซึ่งสามารถโหลดได้จาก ที่นี่
1)  ให้ขยายไฟล์ fpdf_fontThai.zip ออกจะได้ไฟล์ที่มีนามสกุล .php และ .z

2) ทำการ Copy ไฟล์ทั้งหมดไปไว้ที่ Folder font

3)  font ที่เราเพิ่มเข้าไปมีชื่อเรียกและคุณสมบัติดังต่อไปนี้
N = Normal ตัวอักษรปกติ เวลาใช้ให้ใส่ค่าว่าง
ฺB = Bold ตัวอักษรหนา
I = Italic ตัวอักษรเอียง
IB = Italic Bold or Bold Italic ตัวอักษรหนาเอียง

  • AngsanaNew (N,B,I,IB)
  • CordiaNew (N,B,I,IB)
  • Tahoma (N,B)
  • BrowalliaNew (N,B,I,IB)
  • KoHmu (N)
  • KoHmu2 (N)
  • KoHmu3 (N)
  • MicrosoftSansSerif (N)
  • PLE_Cara (N)
  • PLE_Care (N,B)
  • PLE_Joy (N)
  • PLE_Tom (N,B)
  • PLE_TomOutline (N)
  • PLE_TomWide (N)
  • DilleniaUPC (N,B,I,IB)
  • EucrosiaUPC (N,B,I,IB)
  • FreesiaUPC (N,B,I,IB)
  • IrisUPC (N,B,I,IB)
  • JasmineUPC (N,B,I,IB)
  • KodchiangUPC (N,B,I,IB)
  • LilyUPC (N,B,I,IB)

4) ทดสอบผลการทำงานจาก font ที่เพิ่มเข้าไปโดยสร้างไฟล์ชื่อ exam_2.php และใส่ Code ดังต่อไปนี้

require(‘fpdf.php’);
$pdf=new FPDF();
$pdf->AddPage();
/*
เพิ่ม Font เข้ามาเท่าที่จะใช้เพราะจะทำ
ให้ไฟล์ pdf ของเรามีขนาดใหญ่
*/

$pdf->AddFont(‘AngsanaNew’,,‘angsa.php’);
$pdf->AddFont(‘AngsanaNew’,‘B’,‘angsab.php’);
$pdf->AddFont(‘AngsanaNew’,‘I’,‘angsai.php’);
//กำหนดแบบอักษร
$pdf->SetFont(‘AngsanaNew’,,18);
$pdf->Cell(0,10,‘ตัวอย่าง Font ภาษาไทย’);
$pdf->Ln(8);
$pdf->SetFont(‘AngsanaNew’,‘B’,20);
$pdf->Cell(0,10,‘Font ภาษาไทย AngsanaNew 20 ตัวหนา’);
$pdf->Ln(8);
$pdf->SetFont(‘AngsanaNew’,‘I’,25);
$pdf->Cell(0,10,‘Font ภาษาไทย AngsanaNew 25 ตัวเอียง’);$pdf->Output();

5) ผลการทดสอบ

  • Comments Off

php-agi originate


<?php
require('PHPAGI/phpagi-asmanager.php');

$callid = 'Somebody';

$asm = new AGI_AsteriskManager();
if($asm->connect())
{
$call = $asm->send_request('Originate',
array('Channel'=>"LOCAL/17165555555 at voicepulse",
'Context'=>'called_party_context',
'Exten'=>'899',
'Timeout' => '1000',
'Async'=>'1',
'MaxRetries' => '5',
'RetryTime' => '5',
'Priority'=>1,
'Callerid'=>$callid));
$asm->disconnect();
}

$channel = 'Local/[EMAIL PROTECTED]/1';
$exten = '';
$context = '';
$priority = '';
$application = 'Meetme';
$data = '500|qt|1234';
$timeout = '20000';
$callerid = '';
$variable = 'minutes=5';
$account = '';
$async = true;
$actionid = rand();

$asm->Originate($channel, $exten, $context, $priority, $application, $data,
$timeout, $callerid, $variable, $account, $async, $actionid);

?>

  • Comments Off

# aptitude update
# aptitude install apache2 apache2-doc apache2-mpm-prefork apache2-utils apache2.2-common
# aptitude install php5 php5-cgi php5-commonphp5-curlphp5-gd php5-mcrypt php5-mysql php5-odbc php5-pgsql php5-xmlrpc
# aptitude install libapache2-mod-php5

ช่วงนี้ aptitude ของ etch เป็นอะไรไม่รู้ ชอบติดตั้งไฟล์ไม่ครบ
(อาจเป็นที่ apt-proxy)
แก้ไขแพกเกจติดตั้งไฟล์ไม่ครบ โดยการแตกไฟล์โดยไม่ติดตั้ง ไปยัง /
# dpkg-deb -x /var/cache/apt/archives/apache2.2-common_2.2.3-3.1_i386.deb /

# aptitude install mysql-client-5.0 mysql-common mysql-server-5.0 phpmyadmin

บันทึกการเปิดโมดูลแบบน้อยสุด module-minimal
# a2enmod actions
# a2enmod alias
# a2enmod authz_host
# a2enmod cgi
# a2enmod dir
# a2enmod mime
# a2enmod php5
# a2enmod rewrite
# a2enmod status
# /etc/init.d/apache2 restart

บันทึกการเปิดใช้โมดูลแบบปกติ module-normal
# a2enmod alias
# a2enmod auth_basic
# a2enmod authn_file
# a2enmod authz_default
# a2enmod authz_groupfile
# a2enmod authz_host
# a2enmod authz_user
# a2enmod autoindex
# a2enmod cgi
# a2enmod dir
# a2enmod env
# a2enmod mime
# a2enmod mod_python
# a2enmod negotiation
# a2enmod php5
# a2enmod setenv
# a2enmod status
# /etc/init.d/apache2 restart

เอา php.ini จากตัวอย่างแบบ recommended มาใช้
# cp /usr/share/doc/php5/examples/php.ini-recommended /etc/php5/apache2/php.ini

แก้จะให้ใช้ได้กับ drupal
# vi /etc/php5/apache2/php.ini

...
; หน่วยความจำที่ยอมให้สคริปต์รันได้
; เก่าเป็น 8M drupal แนะนำ 12M เราใช้ 16M กันเหนียว
memory_limit = 16M ; Maximum amount of memory a script may consume (8MB)
...
; ตัวแปรเป็น global อัตโนมัติ
; อันนี้ก็กันเหนียว ตอนเขียนโค๊ดเรี่ยราดไว้หลายที่ เก่าเป็น Off เราแก้เป็น On
register_globals = On
...
; ขนาดไฟล์ใหญ่สุด ที่ post ได้
; อันนี้จำได้แม่น หน้าแตกเพราะเอา Bon Echo เข้าไม่ได้ เก่าเป็น 8M แก้เป็น 20M
post_max_size = 20M
...
; adodb ไม่ต้องก็ได้
include_path = ".:/usr/share/php5:/usr/share/php4:/usr/share/php/adodb"
...
; ค่าแนะนำของ drupal
session.save_handler = user
...
; ค่าแนะนำของ drupal
session.cache_limiter = none
...

ส่วนของไซต์ ถ้ามีหลายไซท์ ควรแยกไฟล์ออกมาวางไว้ที่ /etc/apache2/site-available
เวลาจะเปิดใช้งานก็ใช้คำสั่ง a2ensite
เช่นไซต์ example.com
# vi /etc/apache2/sites-available/example.com

<VirtualHost *:80>
  ServerAdmin webmaster@example.com
  ServerName www.example.com

  DocumentRoot /var/www/www.example.com/
  <Directory />
    Options FollowSymLinks
    AllowOverride All
  </Directory>
  <Directory /swww2/var/www/www.thaitux.info/>
    Options Indexes FollowSymLinks MultiViews
    DirectoryIndex index.html index.php
    AllowOverride All
    Order allow,deny
    allow from all
  </Directory>

  ErrorLog /var/log/apache2/error.log

  LogLevel warn

  CustomLog /var/log/apache2/access.log combined
  ServerSignature On
</VirtualHost>

เปิดใช้งานด้วยคำสั่ง
# a2ensite example.com
# /etc/init.d/apache2 restart

  • Comments Off

Time

Mp3

Msn status

  • manon2029@hotmail.com is

Chat with Meeh

Donate

    If you find an article useful, then please make a donation.

หมวดหมู่

UserOnline

Counter

  • Visitors today: 23
  • Visitors yesterday: 48
  • Visitors per day: 738
  • Max. visitors per day: 255
  • Total page views: 155,902
  • Page views of this page: 738
  • Currently online: 1
  • Max. online: 23
  • Total visitors: 33,987
  • counterStatistics