'팁&테크/PHP'에 해당되는 글 22건

  1. 2016.09.06 PHP로 Gmail SMTP 사용하기
  2. 2016.04.06 PHP 운영구성 관련 정리 #3
  3. 2016.04.05 PHP 운영구성 관련 정리 #2
  4. 2016.04.05 PHP 운영구성 관련 정리 #1
  5. 2016.02.22 [PhalconPHP] 팔콘PHP 프래임웍 관련 메모
  6. 2016.01.20 [PhalconPHP] 팔콘PHP Queue 기능 사용
  7. 2015.08.26 HTTP Redirect 시에 POST 값 넘기기
  8. 2015.01.09 mime_content_type 함수가 png mime type을 인식 못할 경우
  9. 2014.07.01 다국어 지원용 gettext 캐시 클리어 방법
  10. 2013.03.05 xor을 이용한 encrypt, decrypt
2016. 9. 6. 11:06

PHP로 Gmail SMTP 사용하기

composer 로 PHPMailer를 설치한다.

리눅스 서버에 OpenSSL 확장이 설치 되어있어야 한다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<?php
 
namespace google;
 
require __DIR__.'/../../_composer/vendor/autoload.php';
 
/**
 * Class GmailApi
 * TODO: OpenSSL Extension 이 있는 지 확인할 것.
 * @package google
 */
class GmailApi
{
    const FROM = '보내는이';
    const FROM_MAIL = 'Gmail주소';
    const FROM_PASSWORD = 'GMail비밀번호';
 
    /**
     * @param $toMail
     * @param $subject
     * @param $msg
     * @return bool
     * @throws \phpmailerException
     */
    public function send($toMail$subject$msg)
    {
        $mail = new \PHPMailer();
        $mail->isSMTP();
        $mail->SMTPAuth = true;
        $mail->SMTPSecure = 'tls';
        $mail->Host = 'smtp.gmail.com';
        $mail->Port = 587;
        $mail->Username = self::FROM_MAIL;
        $mail->Password = self::FROM_PASSWORD;
        $mail->setFrom(self::FROM_MAIL, self::FROM);
        $mail->addReplyTo(self::FROM_MAIL, self::FROM);
        $mail->CharSet = 'UTF-8';
        $mail->Subject = $subject;
        $mail->msgHTML($msg);
        $mail->addAddress($toMail);
        return $mail->send();
    }
}
 
cs


Gmail 에서 Imap 을 Enable 해야하고

구글계정 설정에서 보안 수준이 낮은 앱의 액세스를 허용해야 이용이 가능함


SMTPSecure = 'ssl', Port = 465 로도 접속 가능하다.


만약 설정에 이상이 없는데 아래 오류가 발생한다면 나와있는 링크를 방문에서 문제를 확인해보면 된다.

SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting


Gmail계정으로 IMAP을 처음 접속하게 되면 별도로 접속허용을 해줘야 이용이 가능한데.

$mail->SMTPDebug = 2; 로 설정하고 송수신되는 내용을 살펴보면

서버에서 https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsb.... 와같은 내용을 수신 받으면서 password faile 이 뜨는 경우가 난다.

서버에서 내려받은 주소를 웹브라우저에 연결해서 작업을 해줘야 하지만 소켓이라 안된다.

해결방법은 Troubleshooting 링크에도 나와있지만 웹브라우저로 사용하려는 gamil 계정에 로그인 한뒤에

https://www.google.com/accounts/DisplayUnlockCaptcha 링크를 방문해서 허용해주면 된다.

2016. 4. 6. 09:51

PHP 운영구성 관련 정리 #3

mod_fastcgi 설치

소스 다운로드
cd /opt/src
wget http://www.fastcgi.com/dist/mod_fastcgi-current.tar.gz
압축 및 컴파일
tar zxvf mod_fastcgi-current.tar.gz
cd mod_fastcgi-2.4.6/
cp Makefile.AP2 Makefile
make top_dir=/usr/lib64/httpd
make install top_dir=/usr/lib64/httpd
설치 이진 확인
ldd /usr/lib64/httpd/modules/mod_fastcgi.so
        linux-vdso.so.1 =>  (0x00007ffffeeea000)
        libpthread.so.0 => /lib64/libpthread.so.0 (0x00007f478e38c000)
        libc.so.6 => /lib64/libc.so.6 (0x00007f478dff8000)
        /lib64/ld-linux-x86-64.so.2 (0x0000003b69000000)

Apache2 / FastCGI 설정 (PHP-FPM)

성능 비교를 위해 확장자를 임시로 ".fphp"로 설정하고 있습니다. 실전 운용시에는 ".php"로 되돌립니다. Location 설정은 URL에 직접 액세스를 방지 내용입니다.Action 내부 리다이렉션 후 fcgi-bin URL을 사용할 수 있도록하기 위해 'env = REDIRECT_STATUS "을 설정합니다.

cat > "/etc/httpd/conf.d/php-fpm.conf" <<'EOF'
LoadModule fastcgi_module modules/mod_fastcgi.so
<FilesMatch "\.(fphp|html)$">
    SetHandler application/x-httpd-php
</FilesMatch>
Action application/x-httpd-php /fcgi-bin/php-fpm virtual
Alias /fcgi-bin/php-fpm /fcgi-bin-php-fpm
<Location /fcgi-bin/php-fpm>
    Order Deny,Allow
    Deny from All
    Allow from env=REDIRECT_STATUS
</Location>
FastCgiExternalServer /fcgi-bin-php-fpm -appConnTimeout 10 -idle-timeout 250 -socket /var/run/php-fpm.sock -pass-header Authorization
EOF

★ 중요 ★ 위 설정에서 "-appConnTimeout 10 -idle-timeout 250"은 반드시 설정해야합니다. idele-timeout은 기본적으로 30 초로되어 있지만, 경우에 따라서는 충분하지 않기 때문에 길게 설정해야합니다. "FastCGI : incomplete headers (0 bytes) received ...."오류가 토출 응답하지 않을 경우가 드물게 있습니다. 이 오류가 발생했을 때 "- idle-timeout"시간을 더 길게 설정하여 해결할 수 있습니다. 자세한 내용은 다음 사이트를 참조하십시오.

FastCGI 설치 설명서 :http://www.fastcgi.com/mod_fastcgi/docs/mod_fastcgi.html

PHP-FPM 서비스 확인 및 등록

서비스 동작 테스트
service php-fpm start
service php-fpm stop
서비스에 추가 테스트
chkconfig php-fpm on
서비스에서 제거 테스트
chkconfig php-fpm off
서비스 확인
chkconfig --list php-fpm
php-fpm 0 : off 1 : off 2 : off 3 : off 4 : off 5 : off 6 : off
서비스 등록
chkconfig php-fpm on

PHP-FPM 설정

글로벌과 수영장 설정으로 나눈다. 많은 옵션이 있지만, 아래와 같이 짧게 설정해도 문제는 없습니다. FastCGI 프로세스는 고정 (static)으로 설정을 권장합니다. 
Apache-1.3의 초기 버전에서 FastCGI를 사용해 보았습니다 만, 동적 (dynamic)에서의 설정은 다양한 문제가 발생 한 경험이 있습니다. FastCGI 프로세스는 기다리는 과정이기 때문에 메모리 누수를주의해야합니다. PHP-FPM에서 요청의 최대 수 (pm.max_requests)를 설정하고 있으면 자동으로 자식 프로세스를 재시작 해주는 기능이있어, 메모리 누수를 방지합니다. 메모리의 상황을 확인하면서 고정 (static)으로 시작上げる子프로세스 수를 결정합니다. 
설정시주의해야 할 것은, 기본적으로 생성 된 소켓 파일은 apache 또는 nginx 권한에 액세스 할 수 없기 때문에 listen.mode에서 권한을 0666으로해야합니다. 2G 메모리 머신에서 프로세스 수를 100으로해도 문제없이 동작 확인했습니다. 사이트에 따라 다르므로 HTOP를 설치하고 메모리 사용량을 보면서 조정합니다. 뿌뿌로세스 수 고정 (static)의 설정은 일단로드되면 고정 메모리를 확보합니다. 동적 (dynamic)의 설정은 메모리 사용량이 설정 범위 내에서 액세스 수에 따라 달라집니다.

php-fpm.conf 설정
mkdir /etc/fpm.d
rm -f /etc/php-fpm.conf
전역 설정
cat > "/etc/php-fpm.conf" <<EOF
[global]
pid = run/php-fpm.pid
error_log = log/php-fpm.log
log_level = notice
daemonize = yes
include=/etc/fpm.d/*.conf
EOF
풀 설정 (Apache 검증 권한)

Apache의 경우 아래의 설정으로 전환 확인합니다.

cat > "/etc/fpm.d/www.conf" <<'EOF'
[apache]
user = apache
group = apache
listen = /var/run/php-fpm.sock
listen.mode = 0666
pm = static
pm.max_children = 100
pm.max_requests = 1000
security.limit_extensions = .php .fphp .html .htm
EOF
풀 설정 (Nginx 검증 권한)

Nginx의 경우 아래의 설정으로 전환 확인합니다.

cat > "/etc/fpm.d/www.conf" <<'EOF'
[nginx]
user = nginx
group = nginx
listen = /var/run/php-fpm.sock
listen.mode = 0666
pm = static
pm.max_children = 100
pm.max_requests = 1000
security.limit_extensions = .php .fphp .html .htm
EOF
php 동작 테스트 파일 작성
cat > "/var/www/html/info_test.php" <<EOF
<?php
echo phpinfo();
?>
EOF

Nginx 컴파일 구축

nginx의 의존성에있는 라이브러리 설치
yum -y install GeoIP-devel.x86_64
yum -y install bxslt-devel.x86_64
yum -y install perl-ExtUtils-Embed.x86_64
yum -y install pcre-devel.x86_64
RPM-GPG-KEY 가져 오기
rpm --import http://mirror.centos.org/centos/6.5/os/x86_64/RPM-GPG-KEY-CentOS-6
Nginx의 최신 안정 버전 설치
rpm -i http://nginx.org/packages/centos/6/x86_64/RPMS/nginx-1.6.0-1.el6.ngx.x86_64.rpm
RPM 설치 디렉토리 확인
rpm -ql nginx
/etc/logrotate.d/nginx
/etc/nginx
/etc/nginx/conf.d
/etc/nginx/conf.d/default.conf
/etc/nginx/conf.d/example_ssl.conf
/etc/nginx/fastcgi_params
/etc/nginx/koi-utf
/etc/nginx/koi-win
/etc/nginx/mime.types
/etc/nginx/nginx.conf
/etc/nginx/scgi_params
/etc/nginx/uwsgi_params
/etc/nginx/win-utf
/etc/rc.d/init.d/nginx
/etc/sysconfig/nginx
/usr/sbin/nginx
/usr/share/nginx
/usr/share/nginx/html
/usr/share/nginx/html/50x.html
/usr/share/nginx/html/index.html
/var/cache/nginx
/var/log/nginx

RPM으로 설치 한 이유는 각종 설정 파일을 자동으로 배치하는 것입니다. 후 소스에서 다운로드하여 Google 개발 오픈 소스 "ngx_pagespeed"을 지원하도록 따로 컴파일한 실행파일을 바꿉니다. "/usr/sbin/nginx"

Nginx 및 소스 다운로드
cd /opt/src
wget -q http://nginx.org/download/nginx-1.6.0.tar.gz
tar zxvf nginx-1.6.0.tar.gz

wget -q https://github.com/pagespeed/ngx_pagespeed/archive/v1.8.31.4-beta.zip -O ngx_pagespeed-1.8.31.4-beta.zip
unzip ngx_pagespeed-1.8.31.4-beta.zip

cd ngx_pagespeed-1.8.31.4-beta/
wget -q https://dl.google.com/dl/page-speed/psol/1.8.31.4.tar.gz
tar -xzvf 1.8.31.4.tar.gz
컴파일 설정

컴파일 옵션 확인은 기존 RPM으로 설치되어있는 것과 동일한 구성하기 위해 "nginx -V"명령으로 확인 pgespeed 모듈을 마지막으로 추가해야합니다.

cd /opt/src/nginx-1.6.0
./configure --prefix=/etc/nginx \
    --sbin-path=/usr/sbin/nginx \
    --conf-path=/etc/nginx/nginx.conf \
    --error-log-path=/var/log/nginx/error.log \
    --http-log-path=/var/log/nginx/access.log \
    --pid-path=/var/run/nginx.pid \
    --lock-path=/var/run/nginx.lock \
    --http-client-body-temp-path=/var/cache/nginx/client_temp \
    --http-proxy-temp-path=/var/cache/nginx/proxy_temp \
    --http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp \
    --http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp \
    --http-scgi-temp-path=/var/cache/nginx/scgi_temp \
    --user=nginx --group=nginx \
    --with-http_ssl_module \
    --with-http_realip_module \
    --with-http_addition_module \
    --with-http_sub_module \
    --with-http_dav_module \
    --with-http_flv_module \
    --with-http_mp4_module \
    --with-http_gunzip_module \
    --with-http_gzip_static_module \
    --with-http_random_index_module \
    --with-http_secure_link_module \
    --with-http_stub_status_module \
    --with-http_auth_request_module \
    --with-http_xslt_module \
    --with-http_image_filter_module \
    --with-http_degradation_module \
    --with-mail \
    --with-mail_ssl_module \
    --with-file-aio \
    --with-ipv6 \
    --with-http_spdy_module \
    --with-cc-opt='-O2 -g -pipe -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic' \
    --with-ld-opt=' -Wl,-E' \
    --add-module=/opt/src/ngx_pagespeed-1.8.31.4-beta
컴파일
make -j10
기존 바이너리 교체
\cp objs/nginx /usr/sbin/nginx

Nginx 설정 (검증을위한 임시 설정)

Nginx 기본 설정

worker_processes CPU의 코어 수를 설정합니다.

기존 설정 백업
\cp /etc/nginx/nginx.conf /etc/nginx/nginx.conf_backup
설정 파일 덮어 쓰기
cat > "/etc/nginx/nginx.conf"<< 'EOF'
user  nginx;
worker_processes  3;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;


events {
    worker_connections  1024;
}

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    tcp_nopush      on;

    keepalive_requests 100;
    keepalive_timeout 10;

    gzip  on;
    gzip_static on;
    gzip_comp_level 2;
    gzip_buffers 64 8k;
    gzip_min_length 1100;
    gzip_types        text/plain 
                      text/xml 
                      text/css 
                      application/xml 
                      application/xhtml+xml 
                      application/rss+xml 
                      application/atom_xml 
                      application/javascript 
                      application/x-javascript 
                      application/x-httpd-php;
    gzip_disable      "MSIE [1-6]\.";
    gzip_disable      "Mozilla/4";
    gzip_vary  on;
    gzip_proxied      any;
    gzip_http_version 1.1;

    server_tokens off;

    include /etc/nginx/conf.d/*.conf;

}
EOF
Nginx 서버 설정

기존 Apache 벤치 마크 디렉토리를 그대로 설정하고 벤치마킹을 실시합니다.

\cp /etc/nginx/conf.d/default.conf /etc/nginx/conf.d/default.conf_backup

cat > "/etc/nginx/conf.d/default.conf" <<'EOF'
server {
    listen       80;
    server_name  localhost;

    location / {
        root   /var/www/html/;
        index  index.php;
        try_files $uri $uri/ /index.php?$uri&$args;
    }

    location ~ \.php$ {
        root           /var/www/html/;
        fastcgi_pass   unix:/var/run/php-fpm.sock;
        fastcgi_index  index.php;
        include        fastcgi_params;
        fastcgi_param  REMOTE_ADDR $remote_addr;
        fastcgi_param  REMOTE_PORT $remote_port;
        fastcgi_param  SERVER_ADDR $server_addr;
        fastcgi_param  SERVER_PORT $server_port;
        fastcgi_param  SERVER_NAME $server_name;
        fastcgi_param  CONTENT_TYPE $content_type;
        fastcgi_param  CONTENT_LENGTH $content_length;
        fastcgi_param  QUERY_STRING $query_string;
        fastcgi_param  PATH_INFO  $fastcgi_path_info;
        fastcgi_param  REQUEST_METHOD $request_method;
        fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param  SCRIPT_NAME $fastcgi_script_name;
        fastcgi_param  REQUEST_URI $request_uri;
        fastcgi_param  DOCUMENT_URI $document_uri;
        fastcgi_param  DOCUMENT_ROOT $document_root;
        fastcgi_param  SERVER_PROTOCOL $server_protocol;
        fastcgi_param  GATEWAY_INTERFACE CGI/1.1;
        fastcgi_param  SERVER_SOFTWARE nginx/$nginx_version;
        fastcgi_param  HTTPS $https;
        fastcgi_buffer_size 128k;
        fastcgi_buffers 256 16k; #4096k total
        fastcgi_busy_buffers_size 256k;
        fastcgi_temp_file_write_size 256k;
        fastcgi_max_temp_file_size 0; #disable buffering to disk
        client_max_body_size 0; #Allow large uploads
    }
}
EOF

Apache와 Nginx의 성능 검증 결과

nginx(woker) + php-fpm ⇒ 685.07 [#/sec]
apache(worker) + php-fpm ⇒ 594.79 [#/sec]
apache(prefork) + php-fpm ⇒ 560.84 [#/sec]
apache(prefork) + mod_php ⇒ 509.72 [#/sec]

위 결과는 환경이나 이용 상황에 따라 다를 수 있지만 대체로 "nginx (woker) + php-fpm"의 구성이 가장 좋은 성능이 나옵니다.

서버의 대역폭 검증 (TCP 처리량)

이 검사는 서버 2 대가 필요합니다. 로컬 또는 광역 네트워크에서도 확인할 수 있습니다. 서버 측의 방화벽을 해제해야합니다. 기본 포트는 5201입니다. 다음 도구를 모두 설치하고 확인합니다. 만일 서버의 IP를 "192.168.1.3/192.168.1.4"로 설정합니다. 이 검증은 AWS 또는 VPS 환경에서 DB 연결을 할 때 네트워크에 병목 현상이 없는지를 확인하기 위해서입니다. 또한 역방향 프록시 서버를 설정하여 운용 할 때 개별 서버에서 성능이 나오지도 네트워크에 병목 현상이 있고, 성능이 오르지 않는 경우가 있으므로 반드시 확인하여보십시오.

ym install -y iperf3
192.168.1.3:server

포트를 변경하는 경우에는 "- p 8080"과 같이 추가합니다.

iperf3 -s
192.168.1.4:client

서버 측의 포트가 기본 포트와 다른 경우는 "-p 8080"과 같이 추가합니다.

iperf3 -c 192.168.1.3


2016. 4. 5. 14:04

PHP 운영구성 관련 정리 #2

PHP 속도를 위해

OPcache + APCu 구성에서 고성능 PHP 환경을 구축합니다. OPcache은 기본 OP 코드의 캐시 기능을 지원하고 APCu는 사용자 데이터의 캐시 기능을 지원한다. 이전 APC는 두 기능이 하나가되어있었습니다 만, PHP5.5에서 네이티브 코드 캐시 Z​​end Opcache가 지원되게되었습니다.

PHP 빌드 설정

apache2 용 모듈 (prefork 용)도 함께 생성합니다. 이번에 구축하는 서버는 FastCGI에서 운영이기 때문에 C shared 옵션으로 컴파일 된 바이너리를 설치합니다. 스레드 안전 (Threads Safe)의 PHP는 아직 지원하지 않는 모듈 (PHP 확장)이 많이 있고, "Non Threads model"로 컴파일합니다. 스레드로부터 안전하게 보호하려면 "-enable-maintainer-zts"를 추가합니다. 스레드 안전에 컴파일하고 빌드하면 스레드 안전을 지원하지 않는 확장 (geos.c 등)을 나중에 추가하고 싶어도 컴파일 할 수 없기 때문에 매우 불편합니다. 불행히도 고기능 모듈을 컴파일 할 수없는 경우가 많아 곤란 때가 종종 있습니다.

미들웨어 빌드 정책에 대해

CentOS 에서는 개발 라이브러리 (xxx-devel.x86_64)는 yum으로 설치하도록합니다. 특히 "openssl"컴파일하고 빌드하면 최근 HeartBleed이라고 보안 취약점이 발견 된 경우에는 라이브러리를 포함하여 모든 다시 컴파일해야합니다. 버전이 맞지 않아 어쩔 수없이 라이브러리를 구축해야하는 케이스에는 예외로합니다. apache의 경우도 특별한 이유가 없으면 yum으로 설치하고 설정에서 보안 조치를 할 것을 권장합니다. 

PHP 빌드의 사전 준비

php 다운로드

빌드는 /opt/src 디렉토리에서 수행한다고 가정합니다. 
다음 작업은 모두 root로합니다.

su - cd /opt/src wget -q http://kr1.php.net/get/php-5.5.16.tar.gz/from/this/mirror -O php-5.5.16.tar.gz tar zxvf php-5.5.16.tar.gz

Shared Memory Allocation 컴파일 설치

세션을 공유 메모리에서 처리하면 성능이 향상됩니다. 이 라이브러리는 Threads Safe에 대응하지 않는 모듈입니다. Non Threads model에서 구축의 경우, 혹은 세션 처리가 전문 용도의 서버로 빌드 할 경우 고려할 가치가 있을지도 모릅니다. 이 확장의 설정은 여기서하지 않겠습니다.

wget ftp://ftp.ossp.org/pkg/lib/mm/mm-1.4.2.tar.gz
tar zxvf mm-1.4.2.tar.gz
cd mm-1.4.2
./configure --prefix=/usr --libdir='${prefix}/lib64'
make
make install
cd ../

세션은 아래와 같이 RAM 디스크에 마운트하고 설정하는 방법도 있습니다.

mkdir /tmp/ramdisk
chmod 777 /tmp/ramdisk
mount -t tmpfs -o size=512M tmpfs /tmp/ramdisk/
vi php.ini
session.save_path="/tmp/ramdisk"

Igbinary 모듈 설치

cd /opt/src/php-5.5.16/ext
wget -q https://github.com/phadej/igbinary/archive/master.zip -O igbinary.zip
unzip igbinary.zip
mv igbinary-master igbinary

Redis (remote dictionary server) 모듈 설치

Redis KVS 클라이언트 모듈

cd /opt/src/php-5.5.16/ext
wget -q https://github.com/nicolasff/phpredis/archive/master.zip -O phpredis.zip
unzip phpredis.zip
mv phpredis-master redis

APCu (APC User Cache) 모듈

cd /opt/src/php-5.5.16/ext
wget -q https://github.com/krakjoe/apcu/archive/master.zip -O apcu.zip
unzip apcu.zip
mv apcu-master apcu

PHP 컴파일 옵션 추가 설정

설치 한 모듈 (Extension)을 configure에 인식시킵니다.

cd /opt/src/php-5.5.16
./buildconf --force

옵션에 추가되어 있는지 확인합니다.

./configure --help | grep "redis\|igbinary\|apcu"
  --enable-igbinary          Enable igbinary support
  --enable-redis           Enable redis support
  --disable-redis-session      Disable session support
  --enable-redis-igbinary      Enable igbinary serializer support

igbinay/redis/apcu 소스 파일을 다운로드하여 phpize; ./configure;make; make install 명령으로도 설치가 가능합니다.

빌드 환경 구축

이미 설치되어 있으면 건너 뜁니다.

yum -y install autoconf
yum -y install automake
yum -y install libtool.x86_64
yum -y install flex.x86_64
yum -y install bison.x86_64
yum -y install gcc.x86_64
yum -y install gcc-c++.x86_64
yum -y install make.x86_64
yum -y install kernel-headers.x86_64
yum -y install kernel-devel.x86_64


PHP 빌드 환경 구축

이미 설치되어 있으면 건너 뜁니다. 
httpd-devel은 HTTPD 용 PHP 바이너리도 함께 생성 할 수 있습니다. 
라이브러리마다 일행하고있는 것은 쉽게 볼 수 있도록합니다.

yum install -y httpd-devel.x86_64
yum install -y libxml2-devel.x86_64
yum install -y bzip2-devel.x86_64
yum install -y libcurl-devel.x86_64
yum install -y libpng-devel.x86_64
yum install -y openjpeg-devel.x86_64
yum install -y freetype-devel.x86_64
yum install -y t1lib-devel.x86_64
yum install -y libXpm-devel.x86_64
yum install -y gd-devel.x86_64
yum install -y gmp-devel.x86_64
yum install -y libc-client-devel.x86_64
yum install -y libicu-devel.x86_64
yum install -y openldap-devel.x86_64
yum install -y libmcrypt-devel.x86_64
yum install -y mysql-devel.x86_64
yum install -y readline-devel.x86_64
yum install -y net-snmp-devel.x86_64
yum install -y libtidy-devel.x86_64
yum install -y libxslt-devel.x86_64
yum install -y libmcrypt-devel.x86_64
yum install -y libevent.x86_64
yum install -y libevent-devel.x86_64
yum install -y aspell-devel.x86_64
yum install -y enchant-devel.x86_64
yum install -y oniguruma-devel.x86_64
yum install -y unixODBC-devel.x86_64
yum install -y sqlite-devel.x86_64
yum install -y krb5-devel.x86_64

MySQL 서버 설치

yum install -y mysql-server.x86_64
서비스 등록
chkconfig mysqld on
서비스에서 삭제

사용하지 않는 경우는 서비스에서 제거해야합니다

chkconfig mysqld off
확인
chkconfig --list mysqld


MySQL 설정

cp /etc/my.cnf /etc/my.cnf.org

symbolic-links = 0 과 [mysqld_safe] 사이에 다음을 추가합니다.

vi /etc/my.cnf
character_set_server=utf8
default-storage-engine=InnoDB
innodb_file_per_table
[mysql]
default-character-set=utf8
[mysqldump]
default-character-set=utf8

서비스 시작 (root)

service mysqld start

명령도 실행 및 설정 단계 (초기 설정)

이 설정은 보안을 위해 반드시 실시합니다.

mysql_secure_installation

root 패스워드 → 그대로 Enter 
root 패스워드 설정 → Y Enter 
root 패스워드 입력 (2 회) → ******* Enter 
anonymous 사용자 삭제 → Y Enter 
원격 root 로그인 금지 → Y Enter 
test 데이터베이스 삭제 → Y Enter 
설정 반영 → Y Enter

로그인 확인

mysql -u root -p

암호 입력 Enter

mysql>\s

상기 설정 한 비밀번호로 로그인 할 수 있는지 확인 후 종료

mysql> exit

서비스를 중지합니다.

service mysqld stop

평소 사용하지 않는 때에는 자동시작 되지 않도록 서비스에서 off해둡니다.

chkconfig mysqld off

Redis 클라이언트와 서버 설치

현재에는 Memcached보다는 Redis 를 더 많이 사용하고 있습니다.

cd /opt/src

다운로드 및 설치

wget -q http://redis.googlecode.com/files/redis-2.6.14.tar.gz
tar xzf redis-2.6.14.tar.gz
cd redis-2.6.14
make -j10
make install

Redis 설정

rm -rf /etc/redis /var/lib/redis
mkdir /etc/redis /var/lib/redis
\cp src/redis-server src/redis-cli /usr/bin
\cp redis.conf /etc/redis
sed -e "s/^daemonize no$/daemonize yes/" -e "s/^# bind 127.0.0.1$/bind 127.0.0.1/" -e "s/^dir \.\//dir \/var\/lib\/redis\//" -e "s/^loglevel verbose$/loglevel notice/" -e "s/^logfile stdout$/logfile \/var\/log\/redis.log/" redis.conf > /etc/redis/redis.conf

Redis 서비스 스크립트 작성 및 설정

cat > "/etc/init.d/redis-server" <<'EOF'
#!/bin/sh
#
# redis-server        Startup script for the Redis Server
# 
# chkconfig:   - 85 15 
# description:  Redis is a persistent key-value database
# processname: redis-server
# config:      /etc/redis/redis.conf
# config:      /etc/sysconfig/redis
# pidfile:     /var/run/redis.pid

# Source function library.
. /etc/rc.d/init.d/functions

# Source networking configuration.
. /etc/sysconfig/network

# Check that networking is up.
[ "$NETWORKING" = "no" ] && exit 0

redis="/usr/bin/redis-server"
prog=$(basename $redis)

REDIS_CONF_FILE="/etc/redis/redis.conf"

[ -f /etc/sysconfig/redis ] && . /etc/sysconfig/redis

lockfile=/var/lock/subsys/redis

start() {
    [ -x $redis ] || exit 5
    [ -f $REDIS_CONF_FILE ] || exit 6
    echo -n $"Starting $prog: "
    daemon $redis $REDIS_CONF_FILE
    retval=$?
    echo
    [ $retval -eq 0 ] && touch $lockfile
    return $retval
}

stop() {
    echo -n $"Stopping $prog: "
    killproc $prog -QUIT
    retval=$?
    echo
    [ $retval -eq 0 ] && rm -f $lockfile
    return $retval
}

restart() {
    stop
    start
}

reload() {
    echo -n $"Reloading $prog: "
    killproc $redis -HUP
    RETVAL=$?
    echo
}

force_reload() {
    restart
}

rh_status() {
    status $prog
}

rh_status_q() {
    rh_status >/dev/null 2>&1
}

case "$1" in
    start)
        rh_status_q && exit 0
        $1
        ;;
    stop)
        rh_status_q || exit 0
        $1
        ;;
    restart|configtest)
        $1
        ;;
    reload)
        rh_status_q || exit 7
        $1
        ;;
    force-reload)
        force_reload
        ;;
    status)
        rh_status
        ;;
    condrestart|try-restart)
        rh_status_q || exit 0
        ;;
    *)
        echo $"Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload}"
        exit 2
esac
EOF
퍼미션 변경 
chmod 755 /etc/init.d/redis-server
서비스 등록
chkconfig --add redis-server
chkconfig --level 345 redis-server on

또는

chkconfig redis-server on

런레벨에 대해

0 : 종료 (시스템 종료)
1 : 단일 사용자 모드 (root 만)
2 : 네트워크없이 다중 사용자 모드
3 : 일반 다중 사용자 모드 (텍스트 로그인)
4 : 사용하지 않는
5 : 그래픽 로그인 다중 사용자 모드
6 : 시스템 재부팅

redis 서비스 시작

service redis-server start
cd /opt/src

PostgreSQL 설치

PostgreSQL-9.3.4 yum을 기본 저장소에 없기 때문에 컴파일 설치합니다.PostgreSQL는 root 권한으로 실행할 수 없기 때문에 다음 사용자를 추가해야합니다. make시 옵션 "-j10"옵션을 추가하고 시간 절약을 위해 병렬로 컴파일합니다.

중요 : PostgreSQL 백엔드와 기능의 대부분이 C ++ 언어로 작성되어 있기 때문에 안정적인 운용을 위해서는 std c++ 라이브러리를 사용해야 합니다. 지금까지 PostgreSQL은 한번도 다운 된 경험이 없습니다. 매우 신뢰할 수있는 데이터베이스입니다.

GIS 서버 포트 빌드 등의 자세한 내용은 다음 URL을 참조

http://nextdeveloper.hatenablog.com/entry/2014/05/20/164605

사용자 확인 및 추가

yum install -y finger
id postgres
finger postgres

이미 추가되어있는 경우는 생략합니다.

useradd postgres

다운로드 및 기본 DB의 설치 (PHP 용 라이브러리 구축)

http://nextdeveloper.hatenablog.com/entry/2014/05/20/164605

cd /opt/src
wget -q http://ftp.postgresql.org/pub/source/v9.3.4/postgresql-9.3.4.tar.gz
tar zxvf postgresql-9.3.4.tar.gz
cd postgresql-9.3.4
LDFLAGS=-lstdc++ ./configure --prefix=/usr --libdir='${prefix}/lib64'
make -j10 world
make install-world
cd ..

컴파일 전에 확인

일단 구성을하고 make 명령을 실행했을 때 반드시 make clean; ./buildconf --force 를 실행 한 후 ./configure -> make 단계에서 컴파일합니다. 그래도 구성에서 컴파일 옵션이 인식되지 않는 경우는 소스를 삭제하고 처음부터 다시 시작하십시오.

PHP 컴파일 구축 1 (C 공유 빌드 / FastCGI 용 / Apache 모듈)

옵션 설정에서 -dir 옵션은 /usr/local/mysql처럼 설치된 디렉토리 (prefix 디렉토리)를 지정합니다. . --with-xxx 옵션이 실패한 경우, 라이브러리의 디렉토리도 함께 설정합니다. 여기에서는, PHP 바이너리는 C shared 컴파일 바이너리를 기본으로합니다. 설치되는 모듈은 /etc/php.d/xxxx.ini 라는 파일명으로 모듈 파일 (.so)를 개별적으로 설정할 수 있습니다. 여기에서 PHP Apache 모듈 바이너리를 생성합니다. 필요없는 경우, 아래의 컴파일 옵션 --with-apxs2 \ 를 제거합니다.

PHP 런타임 모듈 중에서도 세션이 먼저 실행되고 있기 때문에 "session.so"이로드되지 않으면이 모듈에 의존하는 Extenshon에서 "Undefined symbol"오류가 발생합니다. 따라서 session 모듈은 PHP 본체에 통합 정적으로 컴파일하여이 문제를 해결합니다.

구성을 실행하기까지, phpredis/igbinary/apcu 이 ./configure 에서 아래와 같이 인식되고 있는지를 확인합니다.

./buildconf --force
./configure --help | grep "redis\|igbinary\|apcu"
  --enable-apcu           Enable APCu support
  --disable-apcu-rwlocks  Disable rwlocks in APCu
  --enable-apcu-debug     Enable APCu debugging
  --enable-apcu-clear-signal  Enable SIGUSR1 clearing handler
  --disable-apcu-mmap     Disable mmap, falls back on shm
  --enable-apcu-spinlocks        Use spinlocks before flocks
  --enable-igbinary          Enable igbinary support
  --enable-redis           Enable redis support
  --disable-redis-session      Disable session support
  --enable-redis-igbinary      Enable igbinary serializer support

--enable-cgi 는 FastCGI 옵션으로 컴파일됩니다. 지정하지 않아도 기본적으로 설정됩니다. CGI / FastCGI의 두 인터페이스를 지원합니다.

./configure \
    --prefix=/usr \
    --exec-prefix=/usr \
    --bindir=/usr/bin \
    --sbindir=/usr/sbin \
    --sysconfdir=/etc \
    --datadir=/usr/share \
    --includedir=/usr/include \
    --libdir=/usr/lib64 \
    --libexecdir=/usr/libexec \
    --localstatedir=/var \
    --sharedstatedir=/usr/com \
    --mandir=/usr/share/man \
    --infodir=/usr/share/info \
    --with-apxs2 \
    --with-config-file-path=/etc \
    --with-config-file-scan-dir=/etc/php.d \
    --with-libdir=lib64 \
    --with-layout=GNU \
    --with-fpm-user=www-data \
    --with-fpm-group=www-data \
    --enable-apcu=shared \
    --enable-bcmath=shared \
    --enable-calendar=shared \
    --enable-cgi \
    --enable-cli \
    --enable-ctype=shared \
    --enable-dba=shared \
    --enable-dom=shared \
    --enable-exif=shared \
    --enable-fileinfo=shared \
    --enable-filter=shared \
    --enable-fpm \
    --enable-ftp=shared \
    --enable-gd-jis-conv \
    --enable-gd-native-ttf \
    --enable-igbinary=shared \
    --enable-inline-optimization \
    --enable-intl=shared \
    --enable-json=shared \
    --enable-mbstring=shared \
    --enable-opcache=shared \
    --enable-pdo=shared \
    --enable-phar=shared \
    --enable-pcntl=shared \
    --enable-posix=shared \
    --enable-re2c-cgoto \
    --enable-redis=shared \
    --enable-redis-session \
    --enable-redis-igbinary \
    --enable-session=static \
    --enable-shmop=shared \
    --enable-sigchild=shared \
    --enable-simplexml=shared \
    --enable-soap=shared \
    --enable-sockets=shared \
    --enable-sysvsem=shared \
    --enable-sysvshm=shared \
    --enable-sysvmsg=shared \
    --enable-tokenizer=shared \
    --enable-xml=shared \
    --enable-xmlreader=shared \
    --enable-xmlwriter=shared \
    --enable-zend-signals \
    --enable-zip=shared \
    --enable-wddx=shared \
    --disable-rpath \
    --disable-ipv6 \
    --disable-debug \
    --with-freetype-dir=/usr \
    --with-icu-dir=/usr \
    --with-jpeg-dir=/usr \
    --with-libxml-dir=/usr \
    --with-png-dir=/usr \
    --with-openssl-dir=shared,/usr \
    --with-xpm-dir=/usr \
    --with-zlib-dir=shared,/usr \
    --with-bz2=shared \
    --with-curl=shared,/usr \
    --with-db4=shared \
    --with-enchant=shared \
    --with-gd=shared \
    --without-gdbm \
    --with-gettext=shared \
    --with-gmp=shared \
    --with-iconv=shared \
    --with-imap=shared \
    --with-imap-ssl \
    --with-kerberos \
    --with-ldap=shared \
    --with-ldap-sasl \
    --with-mcrypt=shared \
    --with-mhash=shared \
    --with-mm=/usr \
    --with-mysql=shared,/usr \
    --with-mysqli=shared,/usr/bin/mysql_config \
    --with-pdo-mysql=shared,/usr/bin/mysql_config \
    --with-openssl=shared \
    --with-pear \
    --with-pic=shared \
    --with-pgsql=shared,/usr \
    --with-pdo-pgsql=shared,/usr \
    --with-pdo-sqlite=shared,/usr \
    --with-pdo-odbc=shared,unixODBC,/usr \
    --with-pcre-regex \
    --with-pspell=shared \
    --with-readline=shared \
    --with-snmp=shared \
    --with-t1lib=shared \
    --with-tidy=shared,/usr \
    --with-unixODBC=shared,/usr \
    --with-xmlrpc=shared \
    --with-xsl=shared,/usr \
    --with-zlib=shared

컴파일

make -j10

php-fpm 사용자 추가

useradd www-data

설치

make install &&
install -v -m644 php.ini-production /etc/php.ini &&
install -v -m644 sapi/fpm/php-fpm.conf /etc/php-fpm.conf &&
install -v -m755 sapi/fpm/init.d.php-fpm /etc/init.d/php-fpm

php.ini 설정 변경

sed -i 's/expose_php = On/expose_php = Off/g;' /etc/php.ini sed -i 's/\;date.timezone =/date\.timezone = Asia\/Seoul/g;' /etc/php.ini


C 공유 PHP 설치 로그

make install
Installing PHP SAPI module:       apache2handler
/usr/lib64/httpd/build/instdso.sh SH_LIBTOOL='/usr/lib64/apr-1/build/libtool' libphp5.la /usr/lib64/httpd/modules
/usr/lib64/apr-1/build/libtool --mode=install cp libphp5.la /usr/lib64/httpd/modules/
libtool: install: cp .libs/libphp5.so /usr/lib64/httpd/modules/libphp5.so
libtool: install: cp .libs/libphp5.lai /usr/lib64/httpd/modules/libphp5.la
libtool: install: warning: remember to run `libtool --finish /opt/src/php-5.5.16/libs'
chmod 755 /usr/lib64/httpd/modules/libphp5.so
[activating module `php5' in /etc/httpd/conf/httpd.conf]
Installing shared extensions:     /usr/lib64/20121212/
Installing PHP CLI binary:        /usr/bin/
Installing PHP CLI man page:      /usr/share/man/man1/
Installing PHP FPM binary:        /usr/sbin/
Installing PHP FPM config:        /etc/
Installing PHP FPM man page:      /usr/share/man/man8/
Installing PHP FPM status page:      /usr/share/fpm/
Installing PHP CGI binary:        /usr/bin/
Installing PHP CGI man page:      /usr/share/man/man1/
Installing build environment:     /usr/lib64/build/
Installing header files:          /usr/include/php/
Installing helper programs:       /usr/bin/
  program: phpize
  program: php-config
Installing man pages:             /usr/share/man/man1/
  page: phpize.1
  page: php-config.1
Installing PEAR environment:      /usr/share/pear/
[PEAR] Archive_Tar    - already installed: 1.3.11
[PEAR] Console_Getopt - already installed: 1.3.1
[PEAR] PEAR           - already installed: 1.9.4
Wrote PEAR system config file at: /etc/pear.conf
You may want to add: /usr/share/pear to your php.ini include_path
[PEAR] Structures_Graph- already installed: 1.0.4
[PEAR] XML_Util       - already installed: 1.2.1
/opt/src/php-5.5.16/build/shtool install -c ext/phar/phar.phar /usr/bin
ln -s -f /usr/bin/phar.phar /usr/bin/phar
Installing PDO headers:          /usr/include/php/ext/pdo/

C 공유 PHP의 Extension 설정

쉘 스크립트에서 백지는 개별적으로 확인하기 쉽게하기 위해서입니다. 
내용을 확인 한 후 환경에 맞게 수정하십시오.

mkdir /etc/php.d
cat > "/etc/php.d/apcu.ini" <<EOF
extension=apcu.so
apc.enabled=1
apc.shm_size=128M
apc.enable_cli=1
apc.write_lock=1
apc.slam_defense=0
apc.gc_ttl=3600
apc.ttl=7200
apc.entries_hint=4096
apc.slam_defense=1
apc.mmap_file_mask=/tmp/apc.XXXXXX
apc.serializer=igbinary
EOF
echo -e extension=bcmath.so >/etc/php.d/bcmath.ini
echo -e extension=bz2.so >/etc/php.d/bz2.ini
echo -e extension=calendar.so >/etc/php.d/calendar.ini]
echo -e extension=ctype.so >/etc/php.d/ctype.ini
echo -e extension=curl.so >/etc/php.d/curl.ini
echo -e extension=dba.so >/etc/php.d/dba.ini
echo -e extension=dom.so >/etc/php.d/dom.ini
echo -e extension=enchant.so >/etc/php.d/enchant.ini
echo -e extension=exif.so >/etc/php.d/exif.ini
echo -e extension=fileinfo.so >/etc/php.d/fileinfo.ini
echo -e extension=ftp.so >/etc/php.d/ftp.ini
echo -e extension=gd.so >/etc/php.d/gd.ini
echo -e extension=gettext.so >/etc/php.d/gettext.ini
echo -e extension=gmp.so >/etc/php.d/gmp.ini
echo -e extension=iconv.so >/etc/php.d/iconv.ini
echo -e extension=igbinary.so >/etc/php.d/igbinary.ini
echo -e extension=imap.so >/etc/php.d/imap.ini
echo -e extension=intl.so >/etc/php.d/intl.ini
echo -e extension=json.so >/etc/php.d/json.ini
echo -e extension=ldap.so >/etc/php.d/ldap.ini
cat > "/etc/php.d/mbstring.ini" <<EOF
extension=mbstring.so
mbstring.language = Japanese
mbstring.internal_encoding = UTF-8
mbstring.http_input = UTF-8
mbstring.http_output = pass
mbstring.detect_order = UTF-8,SJIS,EUC-JP,JIS,ASCII
EOF
echo -e extension=mcrypt.so >/etc/php.d/mcrypt.ini
echo -e extension=mysql.so >/etc/php.d/mysql.ini
echo -e extension=mysqli.so >/etc/php.d/mysqli.ini
echo -e extension=odbc.so >/etc/php.d/odbc.ini

OPCache 프로덕션 설정

메모리를 어느 정도 포함하고있는 머신에서는 "opcache.memory_consumption"숫자를 늘립니다.

mkdir /var/lib/php
cat > "/etc/php.d/opcache.ini" <<EOF
zend_extension=opcache.so
[opcache]
opcache.enable=1
opcache.enable_cli=1
opcache.memory_consumption=128
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=4000
opcache.max_file_size=5M
opcache.blacklist_filename=/var/lib/php/opcache*.blacklist
opcache.revalidate_freq=0
opcache.revalidate_path=0
opcache.save_comments=0
opcache.load_comments=0
opcache.consistency_checks=1
opcache.fast_shutdown=1
EOF
echo -e extension=openssl.so >/etc/php.d/openssl.ini
echo -e extension=pcntl.so >/etc/php.d/pcntl.ini
echo -e extension=pdo.so >/etc/php.d/pdo.ini
echo -e extension=pdo_mysql.so >/etc/php.d/pdo_mysql.ini
echo -e extension=pdo_odbc.so >/etc/php.d/pdo_odbc.ini
echo -e extension=pdo_pgsql.so >/etc/php.d/pdo_pgsql.ini
echo -e extension=pdo_sqlite.so >/etc/php.d/pdo_sqlite.ini
echo -e extension=pgsql.so >/etc/php.d/pgsql.ini
echo -e extension=phar.so >/etc/php.d/phar.ini
echo -e extension=posix.so >/etc/php.d/posix.ini
echo -e extension=pspell.so >/etc/php.d/pspell.ini
echo -e extension=readline.so >/etc/php.d/readline.ini
echo -e "extension=redis.so\nredis.serializer=igbinary" >/etc/php.d/redis.ini
echo -e extension=shmop.so >/etc/php.d/shmop.ini
echo -e extension=simplexml.so >/etc/php.d/simplexml.ini
echo -e extension=snmp.so >/etc/php.d/snmp.ini
echo -e extension=soap.so >/etc/php.d/soap.ini
echo -e extension=sockets.so >/etc/php.d/sockets.ini
echo -e extension=sysvmsg.so >/etc/php.d/sysvmsg.ini
echo -e extension=sysvmsg.so >/etc/php.d/sysvmsg.ini
echo -e extension=sysvshm.so >/etc/php.d/sysvshm.ini
echo -e extension=tidy.so >/etc/php.d/tidy.ini
echo -e extension=tokenizer.so >/etc/php.d/tokenizer.ini
echo -e extension=wddx.so >/etc/php.d/wddx.ini
echo -e extension=xml.so >/etc/php.d/xml.ini
echo -e extension=xmlreader.so >/etc/php.d/xmlreader.ini
echo -e extension=xmlrpc.so >/etc/php.d/xmlrpc.ini
echo -e extension=xmlwriter.so >/etc/php.d/xmlwriter.ini
echo -e extension=xsl.so >/etc/php.d/xsl.ini
echo -e extension=zip.so >/etc/php.d/zip.ini
echo -e extension=zlib.so >/etc/php.d/zlib.ini

Pecl 명령에서 모듈 추가 설치 예

다음은 필요없는 경우는 생략합니다.

pecl install -f oauth-beta

PHP 모듈의 컴파일 설치

다음은 필요없는 경우는 생략합니다. geos 라이브러리는 컴파일시에주의가 필요합니다. GIS 기반의 라이브러리는 버전에 따라 의존성이 다르고 같은 라이브러리가 이미 설치되어있는 경우에는 라이브러리의 디렉토리를 변경하여 부딪치지 않도록해야합니다. 컴파일 할 때 가장 안정되어있는 3.3.9 버전을 선택합니다.

geos 확장을 설치하면 geoPHP이라는 편리한 클래스를 사용할 수 있습니다. 이 라이브러리를 설치하여 PHP에서 GIS의 다양한 데이터 포맷을 취급 할 수있게됩니다.지도보기를 더 고기능 할 때 매우 편리합니다.

geoPHP 모듈

https://github.com/phayes/geoPHP/

Goes 확장 설치

wget http://download.osgeo.org/geos/geos-3.3.9.tar.bz2
tar -xvjf geos-3.3.9.tar.bz2
cd geos-3.3.9
./autogen.sh
./configure --enable-php
make clean
make -j20
make install

설치된 확장의 대상이 소스 디렉토리되어 있기 때문에 수정해야합니다. 다음과 같이 기존 링크를 제거하고 ldconfig 에 설치된 먼저로드되도록합니다.

mv src/.libs/libgeos-3.3.9.so src/.libs/libgeos-3.3.9.so_orig
mv capi/.libs/libgeos_c.so.1 capi/.libs/libgeos_c.so.1_orig

sudo echo -e /usr/local/lib >/etc/ld.so.conf.d/geos-x86_64.conf
sudo echo -e extension=geos.so >/etc/php.d/geos.ini
/sbin/ldconfig

[root@dev geos-3.3.9]# ldd /usr/lib64/20121212/geos.so
        linux-vdso.so.1 =>  (0x00007fff549ff000)
        libgeos_c.so.1 => /usr/local/lib/libgeos_c.so.1 (0x00007f2609235000)
        libc.so.6 => /lib64/libc.so.6 (0x00007f2608e8f000)
        libgeos-3.3.9.so => /usr/local/lib/libgeos-3.3.9.so (0x00007f2608afb000)
        libstdc++.so.6 => /usr/lib64/libstdc++.so.6 (0x00007f26087f5000)
        libm.so.6 => /lib64/libm.so.6 (0x00007f2608570000)
        libgcc_s.so.1 => /lib64/libgcc_s.so.1 (0x00007f260835a000)
        /lib64/ld-linux-x86-64.so.2 (0x0000003424400000)

※주의 ※

기존 OS는 yum으로 설치되어있는 "geos-devel" 패키지 3.3.2이기 때문에 부딪치지 않도록주의합니다. 컴파일 설치 한 라이브러리의 디렉토리가 ldd명령으로 /usr /local/lib/ 되어 있는지 확인합니다.

이상 여기까지가 PHP를 C shared 빌드 방법입니다. 위에서 컴파일은 대부분의 확장이 추가 된 PHP 패키지입니다. 확장에 필요없는 경우는 코멘트에로드하지 않도록하고 구축합니다.

PHP 컴파일 구축 2 (정적 빌드 / Apache2의 PHP 모듈 용)

mod_php 용으로 빌드 할 때 static으로 컴파일하는 것이 다소 빠르기 때문에 정적 빌드 방법도 아래에 추가합니다.  staitc php-fpm 바이너리가 생성됩니다. 옵션 설정에서 -dir 옵션은 /usr/local/mysql 처럼 설치된 디렉토리 (prefix 디렉토리)를 지정합니다. . --with-xxx 옵션이 실패한 경우, 라이브러리의 디렉토리도 함께 설정합니다. 모듈 (extension)를 추가하려면 동적 라이브러리 (.so)에 추가하고 ". ini"파일에서 설정합니다. --with-apxs2 옵션도 추가하고 Apache의 PHP 모듈 (libphp5.so) 바이너리를 생성합니다. Opcache는 정적으로 컴파일해서 동적 라이브러리로 설치되므로주의합니다. C 공유 빌드 한 경우 또는 필요없는 경우는 생략합니다.

cd /opt/src/php-5.5.16

phpredis / igbinary / apcu가 configure에서 아래와 같이 인식되고 있는지를 확인합니다.

./buildconf --force
./configure --help | grep "redis\|igbinary\|apcu"
  --enable-apcu           Enable APCu support
  --disable-apcu-rwlocks  Disable rwlocks in APCu
  --enable-apcu-debug     Enable APCu debugging
  --enable-apcu-clear-signal  Enable SIGUSR1 clearing handler
  --disable-apcu-mmap     Disable mmap, falls back on shm
  --enable-apcu-spinlocks        Use spinlocks before flocks
  --enable-igbinary          Enable igbinary support
  --enable-redis           Enable redis support
  --disable-redis-session      Disable session support
  --enable-redis-igbinary      Enable igbinary serializer support


./configure \
    --prefix=/usr \
    --exec-prefix=/usr \
    --bindir=/usr/bin \
    --sbindir=/usr/sbin \
    --sysconfdir=/etc \
    --datadir=/usr/share \
    --includedir=/usr/include \
    --libdir=/usr/lib64 \
    --libexecdir=/usr/libexec \
    --localstatedir=/var \
    --sharedstatedir=/usr/com \
    --mandir=/usr/share/man \
    --infodir=/usr/share/info \
    --with-apxs2 \
    --with-config-file-path=/etc \
    --with-config-file-scan-dir=/etc/php.d \
    --with-libdir=lib64 \
    --with-layout=GNU \
    --with-fpm-user=www-data \
    --with-fpm-group=www-data \
    --enable-fpm \
    --enable-inline-optimization \
    --enable-apcu \
    --enable-bcmath \
    --enable-calendar \
    --enable-cgi \
    --enable-cli \
    --enable-ctype \
    --enable-dba \
    --enable-dom \
    --enable-exif \
    --enable-fileinfo \
    --enable-filter \
    --enable-ftp \
    --enable-gd-jis-conv \
    --enable-gd-native-ttf \
    --enable-intl \
    --enable-igbinary \
    --enable-json \
    --enable-mbstring \
    --enable-opcache \
    --enable-pdo \
    --enable-phar \
    --enable-pcntl \
    --enable-posix \
    --enable-re2c-cgoto \
    --enable-redis=static \
    --enable-redis-session \
    --enable-redis-igbinary \
    --enable-session \
    --enable-shmop \
    --enable-sigchild \
    --enable-simplexml \
    --enable-soap \
    --enable-sockets \
    --enable-sysvsem \
    --enable-sysvshm \
    --enable-sysvmsg \
    --enable-tokenizer \
    --enable-xml \
    --enable-xmlreader \
    --enable-xmlwriter \
    --enable-zip \
    --enable-wddx \
    --enable-zend-signals \
    --disable-rpath \
    --disable-debug \
    --with-freetype-dir=/usr \
    --with-icu-dir=/usr \
    --with-jpeg-dir=/usr \
    --with-libxml-dir=/usr \
    --with-png-dir=/usr \
    --with-openssl-dir=/usr \
    --with-xpm-dir=/usr \
    --with-zlib-dir=/usr \
    --with-bz2 \
    --with-curl=/usr \
    --with-db4 \
    --with-enchant \
    --with-gd \
    --without-gdbm \
    --with-gettext \
    --with-gmp \
    --with-iconv \
    --with-imap \
    --with-imap-ssl \
    --with-kerberos \
    --with-ldap \
    --with-ldap-sasl \
    --with-mcrypt \
    --with-mhash \
    --with-mm=/usr \
    --with-mysql=/usr \
    --with-mysqli=/usr/bin/mysql_config \
    --with-pdo-mysql=/usr/bin/mysql_config \
    --with-onig \
    --with-openssl \
    --with-pear \
    --with-pic \
    --with-pgsql=/usr \
    --with-pdo-pgsql=/usr \
    --with-pdo-sqlite=/usr \
    --with-pdo-odbc=unixODBC,/usr \
    --with-pcre-regex \
    --with-pspell \
    --with-readline \
    --with-snmp \
    --with-t1lib \
    --with-tidy \
    --with-unixODBC=/usr \
    --with-xmlrpc \
    --with-xsl=/usr \
    --with-zlib

정적 PHP를 컴파일 설치

컴파일
make -j10
php-fpm 사용자 추가
useradd www-data
설치
make install &&
install -v -m644 php.ini-production /etc/php.ini &&
install -v -m644 sapi/fpm/php-fpm.conf /etc/php-fpm.conf &&
install -v -m755 sapi/fpm/init.d.php-fpm /etc/init.d/php-fpm
php.ini 설정 변경
sed -i 's/expose_php = On/expose_php = Off/g;' /etc/php.ini
sed -i 's/\;date.timezone =/date\.timezone = Asia\/Seoul/g;' /etc/php.ini

정적 PHP 설치 로그

make install all
Installing PHP SAPI module:       apache2handler
/usr/lib64/httpd/build/instdso.sh SH_LIBTOOL='/usr/lib64/apr-1/build/libtool' libphp5.la /usr/lib64/httpd/modules
/usr/lib64/apr-1/build/libtool --mode=install cp libphp5.la /usr/lib64/httpd/modules/
libtool: install: cp .libs/libphp5.so /usr/lib64/httpd/modules/libphp5.so
libtool: install: cp .libs/libphp5.lai /usr/lib64/httpd/modules/libphp5.la
libtool: install: warning: remember to run `libtool --finish /opt/src/php-5.5.16/libs'
chmod 755 /usr/lib64/httpd/modules/libphp5.so
[activating module `php5' in /etc/httpd/conf/httpd.conf]
Installing shared extensions:     /usr/lib64/20121212/
Installing PHP CLI binary:        /usr/bin/
Installing PHP CLI man page:      /usr/share/man/man1/
Installing PHP FPM binary:        /usr/sbin/
Installing PHP FPM config:        /etc/
Installing PHP FPM man page:      /usr/share/man/man8/
Installing PHP FPM status page:      /usr/share/fpm/
Installing PHP CGI binary:        /usr/bin/
Installing PHP CGI man page:      /usr/share/man/man1/
Installing build environment:     /usr/lib64/build/
Installing header files:          /usr/include/php/
Installing helper programs:       /usr/bin/
  program: phpize
  program: php-config
Installing man pages:             /usr/share/man/man1/
  page: phpize.1
  page: php-config.1
Installing PEAR environment:      /usr/share/pear/
[PEAR] Archive_Tar    - already installed: 1.3.11
[PEAR] Console_Getopt - already installed: 1.3.1
[PEAR] PEAR           - already installed: 1.9.4
Wrote PEAR system config file at: /etc/pear.conf
You may want to add: /usr/share/pear to your php.ini include_path
[PEAR] Structures_Graph- already installed: 1.0.4
[PEAR] XML_Util       - already installed: 1.2.1
/opt/src/php-5.5.16/build/shtool install -c ext/phar/phar.phar /usr/bin
ln -s -f /usr/bin/phar.phar /usr/bin/phar
Installing PDO headers:          /usr/include/php/ext/pdo/

정적 PHP 설정 (Extension 설정)

정적 빌드에서도 opcache는 기본적으로 C 공유로 컴파일되므로 별도 설정해야합니다. 
extensions.ini 파일에 추가되는 모듈을 정리하고 설정하도록합니다

mkdir /var/lib/php
cat > "/etc/php.d/extensions.ini" <<'EOF'
;Opcache
zend_extension=opcache.so
[opcache]
[opcache]
opcache.enable=1
opcache.enable_cli=1
opcache.memory_consumption=128
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=4000
opcache.max_file_size=5M
opcache.blacklist_filename=/var/lib/php/opcache*.blacklist
opcache.revalidate_freq=0
opcache.revalidate_path=0
opcache.save_comments=0
opcache.load_comments=0
opcache.consistency_checks=1
opcache.fast_shutdown=1

;apcu
apc.enabled=1
apc.shm_size=128M
apc.enable_cli=1
apc.write_lock=1
apc.slam_defense=0
apc.gc_ttl=3600
apc.ttl=7200
apc.entries_hint=4096
apc.slam_defense=1
apc.mmap_file_mask=/tmp/apc.XXXXXX
apc.serializer=igbinary

;mbstring
mbstring.language = Japanese
mbstring.internal_encoding = UTF-8
mbstring.http_input = UTF-8
mbstring.http_output = pass
mbstring.detect_order = UTF-8,SJIS,EUC-JP,JIS,ASCII

EOF


2016. 4. 5. 13:13

PHP 운영구성 관련 정리 #1

PHP의 운영 구성

권장 PHP 구성

①PHP 언어 만 사용하는 환경

Nginx (Worker) + php-fpm
Apache-Worker + mod_fastcgi + php-fpm

②PHP / Ruby / Perl / Python 등 다국어 프로덕션

Nginx (Worker) + spawn-fcgi + php-cgi
Apache-Worker + spawn-fcgi + mod_fastcgi + php-cgi


여러 대의 운용 구성 예

  • varnish : SSL을 지원하지 않으므로 프런트 엔드에 pound (ssl wrapper)를 배치합니다.
  • 프런트 엔드에 nginx 보다 haproxy를 자주 사용합니다.
  • varnish와 백엔드 사이에 haproxy을 배치하는 구성도 있습니다.
  • HTTP의 POST, 세션, 쿠키 등을 올바르게 설정하고 구축해야합니다.
  • N : 다수
  • 1. pound <--> varnish <--> N * (apache + mod_php) 
    2. nginx <--> N * (apache + mod_php)
    3. pound <--> varnish <--> N * (apache + mod_fastcgi + php-cgi)
    4. nginx <--> N * (apache + mod_fastcgi + php-cgi)
    5. pound <--> varnish <--> N * (apache + mod_fastcgi+php-fpm)
    6. nginx <--> N * (apache + mod_fastcgi+php-fpm)
    7. pound <--> varnish <--> N * (nginx + php-fpm)
    9. nginx <--> N * (nginx + php-fpm)


부하 분산 시스템 구성의 정리

①pound-> varnish-> haproxy-> backend
②nginx-> backend
③haproxy-> backend


★ 정리 ★

고성능의 PHP 운영 환경 구축의 핵심은 컴파일 튜닝 커널 파라미터 튜닝, 캐싱,로드 밸런싱, PHP 운용의 기본 구성 내부 processing의 고속화, 내부 network의 고속화 등을 종합적으로 적절히 구성해야 됩니다.. 빠른 데이터 액세스 및 계산 능력이 필요한 경우는 그리드 컴퓨팅 (Globus Toolkit : 표준 미들웨어) 구축이라는 의미도 있지만, 자원을 낭비하지 않도록 개발 현장에서의 데이터베이스와 프로그래밍 최적화 화도 중요한 요소입니다.

결론은 PHP를 이용하는데있어서 가장 추천 할 수있는 기본 구성은 다음의 두 가지입니다.

Nginx 구성

 Nginx-Worker + php-fpm

Apache 구성

 Apache-Worker + mod_fastcgi + php-fpm

FastCGI 운용 관련 설정에 대해

 FastCGI는 요청을 기다리는 프로세스 수를 동적 (dynamic) 또는 정적 (static)으로 설정할 수 있습니다. 본인은 정적(static)설정을 선호합니다. php-fpm이 프로세스를 관리하는 데몬의 역할을하고 있습니다. "mod_fastcgi + php-cgi"라는 구성의 경우도 FastCGI 프로세스 수 설정은 동적 또는 정적으로 설정하지만, 정기적으로 유지 보수를 할 필요가있었습니다. 이러한 관리 기능을 php-fpm에서는 SAPI가 지원 중단없이 안전하게 FastCGI 프로세스의 자동 관리 할 수​​있게되었습니다.


Tuned에서의 튜닝

다음 도구를 설치하고 명령을 실행하면 자동으로 조정 해 준다고합니다. 내용을 모르는 경우 다음 명령을 실행하지 않고 그대로 넘어가십시오.

설치

yum install -y tuned

옵션 확인

tuned-adm list
Available profiles :
- default
- enterprise-storage
- desktop-powersave
- laptop-ac-powersave
- laptop-battery-powersave
- sap
- spindown-disk
- virtual-guest
- server-powersave
- throughput-performance
- virtual-host
- latency-performance

튜닝 실행 (latency-performance)

tuned-adm profile latency-performance


GRUB 구문 추가 설정에 의한 튜닝

다음 내용은 커널과 OS의 지식이있는 분에 한합니다. OS가 부팅되지 않을 위험이 있으므로 참고 정도로 해 주시면 감사하겠습니다. 100 만분의 1 초 단위를 경쟁 금융 기관의 빠른 거래 시스템 (Low latency Trading System)에 효과를 발휘하는 설정을 참고로 한 것입니다. 지금은 실시간 커널 등의 응용도 있으므로 Unix / Linux에서 새로운 기술에 대해 관심있는 분들은 Ubuntu의 lowlatency 커널을 참고로 해 주시면이라고 생각합니다. GRUB 구문의 끝에 다음 행을 추가하여 설정합니다. 다음 작업은 자신의 책임과 판단으로해야합니다. 불안이있는 것 같다면,이 설정은 생략합니다.

nosoftlockup nohz = off highres = off intel_idle.max_cstate = 0 processor.max_cstate = 0 cgroup_disable = memory nmi_watchdog = 0 divider = 4 nosoftlockup mce = ignore_ce


GRUB 구문의 예

주의 : 다음 "kernel"부분을 그대로 복사하여 바꾸면 OS가 시작되지 않습니다. 반드시 위의 행을 마지막에 추가하도록하십시오.

view /etc/
title CentOS (2.6.32-431.17.1.el6.x86_64)
        root (hd0,0)
        kernel /vmlinuz-2.6.32-431.17.1.el6.x86_64 ro root = UUID = 035d9a21-778d-40cf-9ecb-d244d7b95781 rd_NO_LUKS rd_NO_MD SYSFONT = latarcyrheb-sun16 KEYBOARDTYPE = pc KEYTABLE = jp106 LANG = ja_JP.UTF-8 rd_NO_LVM rd_NO_DM quiet nomodeset clocksource = kvm-clock console = tty0 console = ttyS0,115200n8r crashkernel = auto nosoftlockup nohz = off highres = off intel_idle.max_cstate = 0 processor.max_cstate = 0 cgroup_disable = memory nmi_watchdog = 0 divider = 4 nosoftlockup mce = ignore_ce
        initrd /initramfs-2.6.32-431.17.1.el6.x86_64.img

각 GRUB 설정 항목에 대한 설명은지면 상 생략합니다. 항목별로 검색하여 확인하시면 좋겠습니다합니다.


ulimit 설정 변경

서버 부하 테스트를 할 때 ulimit 설정 관련 오류를 확인할 수없는 경우가 많기 때문에 ulimit에 대한 기본값을 변경합니다.  명령으로 설정할 수 있지만 다시 시작하면 기본값으로 돌아갑니다. "/etc/security/limits.conf" 에 설정해 두거나 다음과 같이 추가합니다.

제한 확인

ulimit -n -u -s

권장 설정 반영

ulimit -n 65536 -u 16384 -s 32768

시작시 권장 사항 반영

echo "ulimit -n 65536 -u 16384 -s 32768">> /etc/sysconfig/init

커널 파라미터 튜닝

다음 내용은 자신의 책임과 판단으로해야합니다. 설정은 "Low latency Trading System"의 설정을 참고로하고 있습니다. 반드시 설정 내용을 확인하고 자신의 시스템에 맞게 각 항목의 내용을 이해 한 다음 변경하십시오. 다음 설정 반영 인한 중단 및 문제 등에 대해 책임을지지 않습니다. 다음 설정은 IPV6를 비활성화하고 IPV4 만 사용하는 환경 설정입니다.

세마포어 계산과 메모리 Latency 문제 관련 설정 적용

다음 cat 명령으로 작성된 쉘을 실행하고 출력되는 내용을 커널 매개 변수 세마포어로 설정합니다. 방화벽 설정에서 리버 프록시 서버로 사용하거나 큰 사이트의 경우, 메모리에 맞게 "netfilter"의 CONNTRACK_MAX 튜닝을 할 필요가 있습니다.

CONNTRACK_MAX 튜닝

참조 http://wiki.khnet.info/index.php/Conntrack_tuning

OS_BIT = 64
RAMSIZE =`grep MemTotal / proc / meminfo | sed -e 's / ^ [^ 0-9] * //'| cut -d ''-f1`
HASHSIZE =`echo "scale = 0; ($ RAMSIZE * 1024) / 131072 / ($ OS_BIT / 32)"| bc -l`
CONNTRACK_MAX =`echo "scale = 0; $ HASHSIZE * 8"| bc -l`

튜닝 값 계산과 일부 설정 반영

계산 된 값을 커널 파라미터 설정 내용을 확인하고 수정합니다.

cd / opt
cat> "kernel_optimize.sh"<< 'EOF'
#! / bin / sh
SHARED_BUFFER_RATIO = 0.25
OPTIMAL_SHMMNI = 8192
OS_BIT = 64
echo "kernel.shmmni = $ OPTIMAL_SHMMNI"
MAX_MEM =`grep MemTotal / proc / meminfo | sed -e 's / ^ [^ 0-9] * //'| cut -d ''-f1`
OS_PAGE_SIZE =`getconf PAGE_SIZE`
OPTIMAL_SHMMAX =`echo "scale = 0; (8192 + 208) * (($ MAX_MEM * 1024) / $ OS_PAGE_SIZE) * $ SHARED_BUFFER_RATIO"| bc -l | cut -d ''-f1`0
echo kernel.shmmax = $ OPTIMAL_SHMMAX
OPTIMAL_SHMALL =`echo "scale = 0; ($ OPTIMAL_SHMMAX / $ OS_PAGE_SIZE) * ($ OPTIMAL_SHMMNI / 16)"| bc -l | cut -d ''-f1`
echo kernel.shmall = $ OPTIMAL_SHMALL
if [$ MAX_MEM -gt 8192]; then #latency issues configuration
    echo 2> / proc / sys / vm / dirty_ratio
    echo 1> / proc / sys / vm / dirty_background_ratio
else
    echo 10> / proc / sys / vm / dirty_ratio
    echo 5> / proc / sys / vm / dirty_background_ratio
fi
#netfilter 설정
HASHSIZE =`echo "scale = 0; ($ MAX_MEM * 1024) / 131072 / ($ OS_BIT / 32)"| bc -l`
CONNTRACK_MAX =`echo "scale = 0; $ HASHSIZE * 8"| bc -l`
echo "net.netfilter.nf_conntrack_max = $ CONNTRACK_MAX"
echo "options nf_conntrack hashsize = $ HASHSIZE"> /etc/modprobe.d/nf_conntrack.conf
EOF


# 기존 커널 매개 변수 파일의 백업
cp /etc/sysctl.conf /etc/sysctl.conf_backup

# 위 설정을 반영
sh kernel_optimize.sh

# 커널 매개 변수 설정
# 아래의 내용은 각 항목의 내용을 확인 위에서 실행하여 계산 된 수치로 변경하고 cat 명령을 실행하십시오. 수정은 ★ 표시가있는 부분이 될 수 있습니다.

cat> "/etc/sysctl.conf"<< 'EOF'
### 커널 매개 변수 설정
# SysRq 설정
kernel.sysrq = 0

# 스케줄러 설정
kernel.sched_nr_migrate = 12

# 코어 덤프 파일 이름 설정
kernel.core_uses_pid = 1

###### 튜닝 설정 ######
# 커널 메시지 큐 최대 크기
kernel.msgmnb = 65536

# 커널 메시지 최대 크기
kernel.msgmax = 65536

# 세마포어 튜닝 계산
# SHARED_BUFFER_RATIO = 0.25
# OPTIMAL_SHMMNI = 8192
#echo "kernel.shmmni = $ OPTIMAL_SHMMNI"
# MAX_MEM =`grep MemTotal / proc / meminfo | sed -e 's / ^ [^ 0-9] * //'| cut -d ''-f1`
# OS_PAGE_SIZE =`getconf PAGE_SIZE`
# OPTIMAL_SHMMAX =`echo "scale = 0; (8192 + 208) * (($ MAX_MEM * 1024) / $ OS_PAGE_SIZE) * $ SHARED_BUFFER_RATIO"| bc -l | cut -d ''-f1`0
#echo kernel.shmmax = $ OPTIMAL_SHMMAX
# OPTIMAL_SHMALL =`echo "scale = 0; ($ OPTIMAL_SHMMAX / $ OS_PAGE_SIZE) * (OPTIMAL_SHMMNI / 16)"| bc -l | cut -d ''-f1`
#echo kernel.shmall = $ OPTIMAL_SHMALL

# 기본 설정 내용
# kernel.shmmni = 4092
# kernel.shmmax = 68719476736
# kernel.shmall = 4294967296

# 커널 헤더 소스의 내용
#define SHMMAX 0x2000000 / * max shared seg size (bytes) * /
#define SHMMIN 1 / * min shared seg size (bytes) * /
#define SHMMNI 4096 / * max num of segs system wide * /
#define SHMALL (SHMMAX / getpagesize () * (SHMMNI / 16))
#define SHMSEG SHMMNI / * max shared segs per process * /

## SHMMAX SHMMNI 68719476736 4096
## SHMALL = ----------- * ---------- = ------------- * ------ = 4294967296
## PAGE_SIZE 16 4096 16

# 다음 4G 메모리 설정의 예
# 세마포어 튜닝 계산의 내용을 아래에서 설정합니다.

# 1 프로세스 당 공유 메모리의 최소 크기 (byte)
kernel.shmmni = 8192

# 시스템 전체의 공유 메모리 페이지 최대
# ★ 아래는 세마포어 튜닝 계산의 내용에 맞게 수정합니다.
kernel.shmmax = 20593713000

# 공유​​ 메모리 세그먼트의 바이트 수 제한
# ★ 아래는 세마포어 튜닝 계산의 내용에 맞게 수정합니다.
kernel.shmall = 2574213632

# 매개 변수 순서의 내용
#semmsl semmns semopm semmni
# 세마포어 ID 별 세마포 시스템 전체의 세마포 한 번에 실시 할 수있는 세마포어 작업의 수 세마포어 ID의 최대 값
#OracleDB (semopm)는 100 이상 설정 필수
# 다음 설정은 메모리 데이터베이스 ALTIBASE 튜닝 참고.
kernel.sem = 2000 32000 512 5029

# 파일 오픈 IO 관련
# Oracle / MySQL 튜닝 참조
fs.aio-max-nr = 1048576
fs.file-max = 6815744

# 메모리 튜닝
vm.swappiness = 20
vm.overcommit_ratio = 99
vm.overcommit_memory = 2

# IPV6 비활성화
net.ipv6.conf.all.disable_ipv6 = 1
net.ipv6.conf.default.disable_ipv6 = 1

# 패킷 전송 해제
net.ipv4.conf.all.forwarding = 0
net.ipv4.conf.default.forwarding = 0

# listen 큐 제한 설정
net.core.somaxconn = 262144

# ICMP 에러 메시지를 무시
net.ipv4.icmp_ignore_bogus_error_responses = 1

# 위장 부정 패킷 : 리디렉션 기록
net.ipv4.conf.all.log_martians = 1
net.ipv4.conf.default.log_martians = 1

# 스푸핑 소스 IP 스푸핑 방지
net.ipv4.conf.all.rp_filter = 1

# L3 환경의 점보 프레임으로 통신하는 경우
# net.ipv4.tcp_mtu_probing = 1 

# 네트워크 자원 관련 설정
net.ipv4.tcp_fin_timeout = 15
net.ipv4.tcp_sack = 1
net.ipv4.tcp_fack = 1
net.ipv4.tcp_keepalive_time = 60
net.ipv4.tcp_keepalive_intvl = 3
net.ipv4.tcp_keepalive_probes = 3

# RFC1337을 준수 (Protect Against TCP Time-Wait)
net.ipv4.tcp_rfc1337 = 1

# 소켓의 고속 재활용 (DOS 공격 방지)
net.ipv4.tcp_max_tw_buckets = 1440000 
net.ipv4.tcp_tw_recycle = 1 
net.ipv4.tcp_tw_reuse = 1 

# TCP SYN Flood 공격 대책
net.ipv4.tcp_syncookies = 1

# RFC1323
# TCP 창 크기 조정 활성화 (64KByte 이상의 버퍼)
net.ipv4.tcp_timestamps = 0 
net.ipv4.tcp_window_scaling = 1

# 브로드 캐스트 주소로 ping에 응답 할 수없는
# ※ Smurf 공격 대책
net.ipv4.icmp_echo_ignore_broadcasts = 1

# ICMP Redirect 패킷을 거부
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.default.accept_redirects = 0

# Source Routed 패킷은 거부
net.ipv4.conf.all.accept_source_route = 0
net.ipv4.conf.default.accept_source_route = 0

# Kdump 사용 설정
net.ipv4.conf.all.force_igmp_version = 2
net.ipv4.conf.default.force_igmp_version = 2
kernel.unknown_nmi_panic = 1
kernel.panic_on_unrecovered_nmi = 1
kernel.panic_on_io_nmi = 1

# ARP 응답없이 설정
net.ipv4.conf.all.arp_ignore = 1
net.ipv4.conf.default.arp_ignore = 1

# 스푸핑 (소스 IP 스푸핑 방지)
net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.default.rp_filter = 1

# 클라이언트가 증가했을 때의 문제 해결 방법
net.ipv4.neigh.default.gc_thresh1 = 1024
net.ipv4.neigh.default.gc_thresh2 = 2048
net.ipv4.neigh.default.gc_thresh3 = 4096

# NIC 튜닝 설정
# 네트워크 버퍼 16M 충분
# 4MB까지 커널에서 자동 조정
net.core.rmem_max = 16777216
net.core.wmem_max = 16777216
net.core.rmem_default = 16777216
net.core.wmem_default = 16777216
net.core.optmem_max = 16777216
net.core.netdev_max_backlog = 250000
net.ipv4.tcp_mem = 4096 87380 16777216
net.ipv4.tcp_rmem = 4096 87380 16777216
net.ipv4.tcp_wmem = 4096 87380 16777216
net.ipv4.tcp_max_orphans = 16777216
net.ipv4.tcp_max_syn_backlog = 65535
net.ipv4.tcp_low_latency = 1
net.ipv4.tcp_no_metrics_save = 1
net.ipv4.tcp_congestion_control = htcp
net.ipv4.neigh.default.unres_qlen = 100
net.ipv4.neigh.lo.unres_qlen = 100
net.ipv4.neigh.eth0.unres_qlen = 100
net.ipv4.neigh.eth1.unres_qlen = 100
net.ipv4.route.flush = 1

# 고부하의 서버 / NAT / 프록시 서버에 대한 오류 방지 설정
# iptables를 다시 시작해야, iptables가 동작하지 않는 환경에서는 설정할 필요는 없습니다.

# net.netfilter.nf_conntrack_max 계산
# OS_BIT = 64
# RAMSIZE =`grep MemTotal / proc / meminfo | sed -e 's / ^ [^ 0-9] * //'| cut -d ''-f1`
# HASHSIZE =`echo "scale = 0; ($ RAMSIZE * 1024) / 131072 / ($ OS_BIT / 32)"| bc -l`
#CONNTRACK_MAX =`echo "scale = 0; $ HASHSIZE * 8"| bc -l`
#echo net.netfilter.nf_conntrack_max = $ CONNTRACK_MAX

# 4G 메모리 설정 예
# ★ 아래는 메모리에 맞게 수정합니다.
#iptables가 시작하지 않는 경우 반영시 오류가 발생합니다.
net.netfilter.nf_conntrack_max = 122576
net.netfilter.nf_conntrack_generic_timeout = 10
net.netfilter.nf_conntrack_tcp_timeout_established = 2160
net.netfilter.nf_conntrack_tcp_timeout_close = 8
net.netfilter.nf_conntrack_tcp_timeout_close_wait = 10
net.netfilter.nf_conntrack_tcp_timeout_time_wait = 10
net.netfilter.nf_conntrack_tcp_timeout_fin_wait = 10
net.netfilter.nf_conntrack_tcp_timeout_syn_sent = 10
net.netfilter.nf_conntrack_tcp_timeout_syn_recv = 10
net.netfilter.nf_conntrack_tcp_timeout_max_retrans = 30
net.netfilter.nf_conntrack_tcp_timeout_unacknowledged = 30
net.netfilter.nf_conntrack_tcp_loose = 1
net.netfilter.nf_conntrack_tcp_be_liberal = 0
net.netfilter.nf_conntrack_tcp_max_retrans = 3
net.netfilter.nf_conntrack_acct = 1
net.netfilter.nf_conntrack_checksum = 1
net.netfilter.nf_conntrack_log_invalid = 0
net.netfilter.nf_conntrack_expect_max = 256
EOF


2016. 2. 22. 19:14

[PhalconPHP] 팔콘PHP 프래임웍 관련 메모

1. 컨트롤러와는 별개의 뷰와 레이아웃을 적용할 경우(컨트롤러에서)


$this->view->pick('뷰명');

$this->view->setLayout('레이아웃명');


반드시 pick 를 먼저 실행하고 그 다음 setLayout을 사용할 것.

setLayout 을 먼저하고 pick을 할 경우 setLayout은 무시됨.


2. 실행 시 모듈이 로드되지 않는 경우

Starting php-fpm-5.6: Failed loading /usr/lib64/php/5.6/modules/phalcon.so:  /usr/lib64/php/5.6/modules/phalcon.so: undefined symbol: php_pdo_get_dbh_ce


이 경우는 PDO 보다 Phalcon 이 먼저 로드 되서 발생되는 문제로 주로 php.ini 에서 .so 파일을 로드 하지 않고 

별도로 php.d/10-opcache.ini 처럼 각각 따로 설정파일이 있는 경우에 발생한다.

php.ini 에 extension=phalcon.so 를 넣으면 가장 먼저 로드 되기 때문에 발생되는 오류이다.

php.d/에 50-phalcon.ini 파일을 만들고 그안에 extension=phalcon.so 를 넣고 실행하면 된다.


3. Phalcon Dev Tools로 작업 시 프로젝트 디렉토리가 아니라며 오류가 나는 경우

버전업이 되면서 프로젝트 디렉토리를 .phalcon 디렉토리가 존재하는지 확인하는 부분이 추가된듯 함

프로젝트 디렉토리에 .phalcon 디렉토리를 만들어주고 phalcon model 등의 명령을 사용할 것.


4. 모델 find 옵션

ParameterDescriptionExample
conditionsSearch conditions for the find operation. Is used to extract only those records that fulfill a specified criterion. By default Phalcon\Mvc\Modelassumes the first parameter are the conditions."conditions" => "name LIKE'steve%'"
columnsReturn specific columns instead of the full columns in the model. When using this option an incomplete object is returned"columns" => "id, name"
bindBind is used together with options, by replacing placeholders and escaping values thus increasing security"bind" => array("status" =>"A", "type" => "some-time")
bindTypesWhen binding parameters, you can use this parameter to define additional casting to the bound parameters increasing even more the security"bindTypes" =>array(Column::BIND_PARAM_STR,Column::BIND_PARAM_INT)
orderIs used to sort the resultset. Use one or more fields separated by commas."order" => "name DESC,status"
limitLimit the results of the query to results to certain range"limit" => 10
offsetOffset the results of the query by a certain amount"offset" => 5
groupAllows to collect data across multiple records and group the results by one or more columns"group" => "name, status"
for_updateWith this option, Phalcon\Mvc\Model reads the latest available data, setting exclusive locks on each row it reads"for_update" => true
shared_lockWith this option, Phalcon\Mvc\Model reads the latest available data, setting shared locks on each row it reads"shared_lock" => true
cacheCache the resultset, reducing the continuous access to the relational system"cache" => array("lifetime"=> 3600, "key" => "my-find-key")
hydrationSets the hydration strategy to represent each returned record in the result"hydration" =>Resultset::HYDRATE_OBJECTS


5. 모델에서 어트리뷰트(필드) 가져오고 null로 초기화

$metaData = new \Phalcon\Mvc\Model\MetaData\Memory();
$attr = (array)$metaData->getAttributes(new BaseModel\Abc());
$data = array_combine($attr, array_fill(0, count($attr), null));



2016. 1. 20. 11:52

[PhalconPHP] 팔콘PHP Queue 기능 사용

메뉴얼 : https://docs.phalconphp.com/en/latest/reference/queue.html

참고 : http://phalcontip.com/discussion/62/phalcon-with-beanstalkd


백그라운드로 작업하기 위해서는 Thread 를 사용해서 한파일에서 처리할 수도 있겠으나 팔콘에서는 기본적으로 Queue 기능을 지원한다. 자체적으로 기능을 지원하는건 아니고 외부 Beanstalkd 라는 메세지큐 서버를 사용해서 구현이 된다. 

물론 기본적으로 지원하는 Beanstalkd 말고 RabitMQ, Kafka, ZeroMQ 같은 걸 사용해도 될것이다.


간단하게 사용법을 정리하면 아래와 같다.

1. Beanstalkd 서버를 설치

  epel repo 가 설치되있다면 yum install beanstalkd 로 하면 설치가 끝

  없다면 https://github.com/kr/beanstalkd 여기서 다운받아 설치


  실행은 yum설치 시 service beanstalkd start하거나 개별로 beanstalkd -l 0.0.0.0 -p 11300 와 같이 아이피와 포트를 주고 실행하면 된다.(기본포트 11300)


2. 메세지 전달(Producer)

$queue = new \Phalcon\Queue\Beanstalk([ 'host' => 'localhost', 'port' => 11300 ]); $queue->put(array( '변수' => 1 ));


3. 메세지 처리(Consumer) - 메모리에 항상 상주해 있도록 한다.

$queue = new \Phalcon\Queue\Beanstalk([ 'host' => 'localhost', 'port' => 11300 ]); while(true) { while(($job = $queue->peekReady()) != false) { $message = $job->getBody(); print_r($message); $job->delete(); } sleep(5); } //이 부분은 하나가 아닌 동시에 여러개의 Consumer를 띄워 처리할때 메세지를 가져오는 방법이다. while (($job = $queue->reserve())) { $message = $job->getBody(); print_r($message); $job->delete(); }


2015. 8. 26. 09:34

HTTP Redirect 시에 POST 값 넘기기

307 temporary redirect, 308 permanant redirect

위의 두가지 헤더를 사용하면 받은 POST 값을 자동으로 redirect 되는 페이지로 넘겨줌.

출처 : http://www.phpschool.com/gnuboard4/bbs/board.php?bo_table=tipntech&wr_id=80109&page=1 PHP스쿨 송효진님


<?php

if(!isset($_POST['data'])) { ?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Redirect Test</title>
</head>
<body>
<form method="post" action="">
<input type="text" name="data" value="test data">
<input type="submit" value="submit">
</form>
<?php highlight_file(__FILE__); ?>
</body>
</html>
<?php
exit;
}

if(!isset(
$_GET['redirect'])) {
header('HTTP/1.1 307');
header('Location: /exams/redirecttest.php?redirect');
exit;
}

echo 
'<xmp>';
print_r($_POST);
print_r($_GET);
echo 
'</xmp>';
exit;


2015. 1. 9. 19:43

mime_content_type 함수가 png mime type을 인식 못할 경우

php 에서 mime_content_type 함수를 사용할때 png 파일의 mime type을 text/plain 으로 


읽어 들이는 경우가 있다


이 경우에는 아파치 서버의 환경 설정을 추가 하면 된다.


/usr/local/apache/conf/magic 파일을 열어서 아래 내용을 추가하고 재시작


#PNG Image Format

0 string \x89PNG image/png

2014. 7. 1. 10:41

다국어 지원용 gettext 캐시 클리어 방법

다국어 지원을 하기 위해서 시스템상의 번역파일(.po, .mo)을 이용하기 위해 

bindtextdomain 과 gettext 또는 _T() 를 사용하다 보면 .mo 파일이 업데이트된 이후에도 캐쉬에서 데이타를 읽어들여서 변경된 내용이 적용되지 않는다. 이 경우에는 php를 재시작 해줘야 하는데 재시작 없이 처리하는 방법을 알아보자.



방법 1. 번역파일이 존재하는 디렉토리에 소프트링크를 추가하여 bindtextdomain 으로 추가한다.

출처 : http://stackoverflow.com/questions/13625659/how-to-clear-phps-gettext-cache-without-restart-apache-nor-change-domain

cd locale
ln -s . nocache


bindtextdomain('domain', './locale/nocache');
bindtextdomain('domain', './locale');


- 주의 : 이 방법은 환경에 따라 원하는 동작이 되지 않는 경우도 있으므로 충분히 테스트를 하고 적용해야 한다.


방법 2. mo파일을 시간별로 미리 여러개를 만들어서 매번 다른걸 로드해서 캐싱되지 못하게 하는 방법.

출처 : http://www.php.net/manual/en/function.gettext.php#58310

<?php
function initialize_i18n($locale) {
    
putenv('LANG='.$locale);
    
setlocale(LC_ALL,"");
    
setlocale(LC_MESSAGES,$locale);
    
setlocale(LC_CTYPE,$locale);
    
$domains glob($locales_root.'/'.$locale.'/LC_MESSAGES/messages-*.mo');
    
$current basename($domains[0],'.mo');
    
$timestamp preg_replace('{messages-}i','',$current);
    
bindtextdomain($current,$locales_root);
    
textdomain($current);
    }
?>

msgfmt messages.po -o messages-`date +%s`.mo


- 주의 : 먼가 비효율적인 방법임


방법 3. 로드될때 마다 하나의 mo 파일을 다른 이름으로 복사해서 복사한 파일을 로드하는 방법

출처 : http://blog.ghost3k.net/articles/php/11/gettext-caching-in-php


// settings you may want to change
$locale = "en_US";  // the locale you want
$locales_root = "locales";  // locales directory
$domain = "default"; // the domain you're using, this is the .PO/.MO file name without the extension

// activate the locale setting
setlocale(LC_ALL, $locale);
setlocale(LC_TIME, $locale);
putenv("LANG=$locale");
// path to the .MO file that we should monitor
$filename = "$locales_root/$locale/LC_MESSAGES/$domain.mo";
$mtime = filemtime($filename); // check its modification time
// our new unique .MO file
$filename_new = "$locales_root/$locale/LC_MESSAGES/{$domain}_{$mtime}.mo"; 

if (!file_exists($filename_new)) {  // check if we have created it before
      // if not, create it now, by copying the original
      copy($filename,$filename_new);
}
// compute the new domain name
$domain_new = "{$domain}_{$mtime}";
// bind it
bindtextdomain($domain_new,$locales_root);
// then activate it
textdomain($domain_new);
// all done



2013. 3. 5. 14:55

xor을 이용한 encrypt, decrypt


/* 
Description : A function with a very simple but powerful xor method to encrypt 
              and/or decrypt a string with an unknown key. Implicitly the key is 
              defined by the string itself in a character by character way. 
              There are 4 items to compose the unknown key for the character 
              in the algorithm 
              1.- The ascii code of every character of the string itself 
              2.- The position in the string of the character to encrypt 
              3.- The length of the string that include the character 
              4.- Any special formula added by the programmer to the algorithm 
                  to calculate the key to use 
*/ 
FUNCTION ENCRYPT_DECRYPT($Str_Message) { 
//Function : encrypt/decrypt a string message v.1.0  without a known key 
//Author   : Aitor Solozabal Merino (spain) 
//Email    : aitor-3@euskalnet.net 
//Date     : 01-04-2005 
    $Len_Str_Message=STRLEN($Str_Message); 
    $Str_Encrypted_Message=""; 
    FOR ($Position = 0;$Position<$Len_Str_Message;$Position++){ 
        // long code of the function to explain the algoritm 
        //this function can be tailored by the programmer modifyng the formula 
        //to calculate the key to use for every character in the string. 
        $Key_To_Use = (($Len_Str_Message+$Position)+1); // (+5 or *3 or ^2) 
        //after that we need a module division because can´t be greater than 255 
        $Key_To_Use = (255+$Key_To_Use) % 255; 
        $Byte_To_Be_Encrypted = SUBSTR($Str_Message, $Position, 1); 
        $Ascii_Num_Byte_To_Encrypt = ORD($Byte_To_Be_Encrypted); 
        $Xored_Byte = $Ascii_Num_Byte_To_Encrypt ^ $Key_To_Use;  //xor operation 
        $Encrypted_Byte = CHR($Xored_Byte); 
        $Str_Encrypted_Message .= $Encrypted_Byte; 
        
        //short code of  the function once explained 
        //$str_encrypted_message .= chr((ord(substr($str_message, $position, 1))) ^ ((255+(($len_str_message+$position)+1)) % 255)); 
    } 
    RETURN $Str_Encrypted_Message; 
} //end function