php-protocolbuffers

protocol buffer on php

First, install protobuf from source
$ git clone https://github.com/google/protobuf.git
$ cd protobuf
$ ./autogen.sh
$ ./configure
$ make
$ make check
$ sudo make install
$ sudo ldconfig # refresh shared library cache.

Second, install php-protocolbuffers
$ git clone https://github.com/chobie/php-protocolbuffers.git
$ cd php-protocolbuffers
$ phpize
$ ./configure
$ make
$ sudo make install

# please add following line to your php.ini
$ sudo vi /etc/php/fpm-php5.6/ext/protocolbuffers.ini
extension=protocolbuffers.so
$ sudo vi /etc/php/cli-php5.6/ext/protocolbuffers.ini
extension=protocolbuffers.so
$ sudo ln -s /etc/php/fpm-php5.6/ext/protocolbuffers.ini /etc/php/fpm-php5.6/ext-active/protocolbuffers.ini
$ sudo ln -s /etc/php/cli-php5.6/ext/protocolbuffers.ini /etc/php/cli-php5.6/ext-active/protocolbuffers.ini

Third, install composer.phar
$ curl -s http://getcomposer.org/installer | php
$ sudo mv composer.phar /usr/local/bin

Fourth, install protoc-gen-php
$ git clone https://github.com/chobie/protoc-gen-php.git
$ cd https://github.com/chobie/protoc-gen-php.git

# add protocolbuffers/protoc-gen-php entry to your global composer.json ($HOME/.composer/composer.json)
{
"require": {
"protocolbuffers/protoc-gen-php": "dev-master"
}
}

# install with composer
$ composer.phar global install
# set PATH (add this line to your .bashrc or .zshrc.)
$ export PATH=$HOME/.composer/vendor/bin/:$PATH

Fifth, just make a demo
demo .proto file definition
package openviewmobile;
message Person
{
required int32 user_id = 1;
optional string name = 2;
}

okay, let’s generate php classes with protoc

$ protoc --php_out . person.proto

when you want to use openviewmobile\Person class, you just do require person.proto.php.

setUserId(1234);
$person->setName("chobie");
$raw = $person->serializeToString();
echo $raw
?>

Google Protocol Buffers Official Doc
php-protocolbuffers wiki
Protocol Buffers – Google’s data interchange format

multiple git sites using different ssh keys

First, you must use ssh-keygen to generate ssh key for your different accessing git sites. Like github, gitlab, or gitcafe etc.

$ ssh-keygen -t rsa -b 4096 -C "your_email@example.com"

Finally, edit ~/.ssh/config to add configuration to specific git site
$ vi ~/.ssh/config

Host gitlab.com
    RSAAuthentication yes
    IdentityFile ~/my-ssh-key-directory/my-gitlab-private-key-filename
    User git
Host git.assembla.com
    RSAAuthentication yes
    IdentityFile ~/.ssh/id_rsa_assembla
    User git
openwrt

How To Build openwrt for WR841N on linux from source codes

First, setup build environment, different linux distribution use different method.
ignore…
Next, fetch the openwrt surce code
# git clone git://git.openwrt.org/openwrt.git
Next, install extra packages
# ./scripts/feeds update -a
# ./scripts/feeds install -a
Next, config the source codes
# make menuconfig

Target System---AR71xx/AR7240/AR913x/AR934x
Target Profile---TP-LINK WR841N/ND
LuCI—>Collections—– <*> luci

Next, build
# make V=99

outputs are under ./bin

authpuppy

How To Install authpuppy on Nginx

As we know the authpuppy official wiki website only supply the installation guide on apache web server, but as a good result as I practiced, it can be successfully installed on the nginx web server.

Go on details, my linux server using Gentoo Linux, but i think it works on any linux popular distribution, Redhat, centos, debian, ubuntu, arch etc.

Step by step go on,

First, setup your NGINX web server, and I show you my nginx configuration

server {

listen   [your server ip]:80;

index index.php index.html index.htm;

server_name www.[your server name] [your server name] *.[your server name];

access_log /var/log/nginx/[your server name].access_log main;

error_log /var/log/nginx/[your server name].error_log info;

set $domain [your server name];

set $subdomain "";

if ( $host ~* (\b(?!www\b)\w+)\.\w+\.[a-zA-Z]+$ ) {

set $subdomain /$1;

}

client_max_body_size 200M;

root /var/www/$domain$subdomain;

location / {

#if ($domain !~* ^www$) {

#rewrite ^/(.*)    /$domain/$1 break;

#}

try_files $uri $uri/ /index.php?q=$uri&$args;

}

error_page 404 /404.html;

error_page 500 502 503 504 /50x.html;

 

location = /50x.html {

root /usr/share/nginx/www;

}

# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000

location ~ \.php$ {

# With php5-fpm:

fastcgi_pass unix:/var/run/php5-fpm.sock;

fastcgi_index index.php;

fastcgi_param  SCRIPT_FILENAME    $document_root$fastcgi_script_name;

#fastcgi_param SCRIPT_FILENAME /var/www/$domain$subdomain$fastcgi_script_name;

include fastcgi_params;

}

}

check nginx is OK.

Next, download the authpuppy source codes from authpuppy official website

# wget -c authpuppy-1.0.0-stable.tgz

# tar xf authpuppy-1.0.0-stable.tgz

# chown -R www. authpuppy

# cd authpuppy

# ln -s /[your home]/authpuppy/lib/vendor/symfony/data/web/sf sf

# chown -h www. sf

Next, goto your web server virtual hosts folder

# ln -s /[your home]/authpuppy/web authpuppy

# chown -h www. authpuppy

Nest setup database

# mysqladmin -uroot -p create authpuppy

# mysql -uroot -p

Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 45
Server version: 5.0.51a-3ubuntu5.5 (Ubuntu)
   
Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
   
mysql> create user 'authpuppy'@'localhost' identified by 'authpuppydev';
Query OK, 0 rows affected (0.21 sec)
   
mysql> grant all privileges on authpuppy.* to 'authpuppy'@'localhost' with grant option;
Query OK, 0 rows affected (0.02 sec)

You may now navigate to http://<your authpuppy server>/

If the database is not configured yet, the file will be created. A check of requirements will also automatically be made. Make sure all required requirements are met.

Follow the instructions on the screen through the installation process. If it is a first install, you’ll be invited to create a first admin user for the application

Congratulations! You’re now ready to go! Just click on the “Administrative Login” link to get the login prompt for the admin section and access more interesting stuff.

Build squashfs tools for Mac OS X

To squash/unsquash a Linux squashfs filesystem on a Mac, you can build the squashfs tools.

A few modifications of the source are required for OS X:

  • The FNM_EXTMATCH flag doesn’t exist in the fnmatch library on OS X. This just means that you can’t use glob patterns with mksquashfs.
  • The constants to figure out how many CPUs the machine has are in the sysctl header instead of the sysinfo header.
  • The C99 compiler has different semantics for the inline keyword, so inline functions should also be static.
  • Instead of llistxattr(), lgetxattr(), lsetxattr(), Apple uses a XATTR_NOFOLLOW flag on the non-link equivalent functions.

Here’s a complete download-and-build recipe:

curl -OL http://iweb.dl.sourceforge.net/project/squashfs/squashfs/squashfs4.2/squashfs4.2.tar.gz
tar xzvf squashfs4.2.tar.gz
cd squashfs4.2/squashfs-tools

sed -i.orig 's/FNM_EXTMATCH/0/; s/sysinfo.h/sysctl.h/; s/^inline/static inline/' mksquashfs.c unsquashfs.c

cat <<END >> xattr.h
#define llistxattr(path, list, size) \
  (listxattr(path, list, size, XATTR_NOFOLLOW))
#define lgetxattr(path, name, value, size) \
  (getxattr(path, name, value, size, 0, XATTR_NOFOLLOW))
#define lsetxattr(path, name, value, size, flags) \
  (setxattr(path, name, value, size, 0, flags | XATTR_NOFOLLOW))
END

make
sudo cp mksquashfs unsquashfs /usr/local/bin

Usage notes:

The filesystem you’re unsquashing probably has root-owned files in it, so you’ll have to use sudo to run unsquashfs as root.

The limit of open files is somewhat low on a Mac, so you’ll get a bunch of errors if you try to unsquash a whole filesystem:

write_file: failed to create file squashfs-root/path/to/file, because Too many open files

Just change the limit in the shell before running unsquashfs:

ulimit -n 2000
sudo unsquashfs filesystem.squashfs

There seems to be a bug when drawing the progress bar that causes Floating point exception, which you can workaround by using the -n flag.

18 commands to monitor network bandwidth on Linux server

Network monitoring on Linux

This post mentions some linux command line tools that can be used to monitor the network usage. These tools monitor the traffic flowing through network interfaces and measure the speed at which data is currently being transferred. Incoming and outgoing traffic is shown separately.

Some of the commands, show the bandwidth used by individual processes. This makes it easy to detect a process that is overusing network bandwidth.

The tools have different mechanisms of generating the traffic report. Some of the tools like nload read the “/proc/net/dev” file to get traffic stats, whereas some tools use the pcap library to capture all packets and then calculate the total size to estimate the traffic load.

Here is a list of the commands, sorted by their features.

1. Overall bandwidth - nload, bmon, slurm, bwm-ng, cbm, speedometer, netload  2. Overall bandwidth (batch style output) - vnstat, ifstat, dstat, collectl  2. Bandwidth per socket connection - iftop, iptraf, tcptrack, pktstat, netwatch, trafshow  3. Bandwidth per process - nethogs

1. Nload

Nload is a commandline tool that allows users to monitor the incoming and outgoing traffic separately. It also draws out a graph to indicate the same, the scale of which can be adjusted. Easy and simple to use, and does not support many options.

So if you just need to take a quick look at the total bandwidth usage without details of individual processes, then nload will be handy.

$ nload

nload command linux

Installing Nload – Fedora and Ubuntu have got it in the default repos. CentOS users need to get nload from Epel repositories.

# fedora or centos
$ yum install nload -y

# ubuntu/debian
$ sudo apt-get install nload

2. iftop

Iftop measures the data flowing through individual socket connections, and it works in a manner that is different from Nload. Iftop uses the pcap library to capture the packets moving in and out of the network adapter, and then sums up the size and count to find the total bandwidth under use.

Although iftop reports the bandwidth used by individual connections, it cannot report the process name/id involved in the particular socket connection. But being based on the pcap library, iftop is able to filter the traffic and report bandwidth usage over selected host connections as specified by the filter.

$ sudo iftop -n

The n option prevents iftop from resolving ip addresses to hostname, which causes additional network traffic of its own.

iftop command linux

Install iftop – Ubuntu/Debian/Fedora users get it from default repos. CentOS users get it from Epel.

# fedora or centos
yum install iftop -y

# ubuntu or debian
$ sudo apt-get install iftop

3. iptraf

Iptraf is an interactive and colorful IP Lan monitor. It shows individual connections and the amount of data flowing between the hosts. Here is a screenshot

$ sudo iptraf

iptraf linux command

Install iptraf

# Centos (base repo)
$ yum install iptraf

# fedora or centos (with epel)
$ yum install iptraf-ng -y

# ubuntu or debian
$ sudo apt-get install iptraf iptraf-ng

4. nethogs

Nethogs is a small ‘net top’ tool that shows the bandwidth used by individual processes and sorts the list putting the most intensive processes on top. In the event of a sudden bandwidth spike, quickly open nethogs and find the process responsible. Nethogs reports the PID, user and the path of the program.

$ sudo nethogs

nethogs command linux

Install Nethogs – Ubuntu, Debian, Fedora users get from default repos. CentOS users need Epel

# ubuntu or debian (default repos)
$ sudo apt-get install nethogs

# fedora or centos (from epel)
$ sudo yum install nethogs -y

5. bmon

Bmon (Bandwidth Monitor) is a tool similar to nload that shows the traffic load over all the network interfaces on the system. The output also consists of a graph and a section with packet level details.

bmon linux network monitor

Install Bmon – Ubuntu, Debian and Fedora users can install from default repos. CentOS users need to setup repoforge, since its not available in Epel.

# ubuntu or debian
$ sudo apt-get install bmon

# fedora or centos (from repoforge)
$ sudo yum install bmon

Bmon supports many options and is capable of producing reports in html format. Check the man page for more information

6. slurm

Slurm is ‘yet’ another network load monitor that shows device statistics along with an ascii graph. It supports 3 different styles of graphs each of which can be activated using the c, s and l keys. Simple in features, slurm does not display any further details about the network load.

$ slurm -s -i eth0

slurm command linux

Install slurm

# debian or ubuntu
$ sudo apt-get install slurm

# fedora or centos
$ sudo yum install slurm -y

7. tcptrack

Tcptrack is similar to iftop, and uses the pcap library to capture packets and calculate various statistics like the bandwidth used in each connection. It also supports the standard pcap filters that can be used to monitor specific connections.

tcptrack command linux

Install tcptrack – Ubuntu, Debian and Fedora have it in default repos. CentOS users need to get it from RepoForge as it is not available in Epel either.

# ubuntu, debian
$ sudo apt-get install tcptrack

# fedora, centos (from repoforge repository)
$ sudo yum install tcptrack

8. Vnstat

Vnstat is bit different from most of the other tools. It actually runs a background service/daemon and keeps recording the size of data transfer all the time. Next it can be used to generate a report of the history of network usage.

$ service vnstat status
 * vnStat daemon is running

Running vnstat without any options would simply show the total amount of data transfer that took place since the date the daemon is running.

$ vnstat
Database updated: Mon Mar 17 15:26:59 2014

   eth0 since 06/12/13

          rx:  135.14 GiB      tx:  35.76 GiB      total:  170.90 GiB

   monthly
                     rx      |     tx      |    total    |   avg. rate
     ------------------------+-------------+-------------+---------------
       Feb '14      8.19 GiB |    2.08 GiB |   10.27 GiB |   35.60 kbit/s
       Mar '14      4.98 GiB |    1.52 GiB |    6.50 GiB |   37.93 kbit/s
     ------------------------+-------------+-------------+---------------
     estimated      9.28 GiB |    2.83 GiB |   12.11 GiB |

   daily
                     rx      |     tx      |    total    |   avg. rate
     ------------------------+-------------+-------------+---------------
     yesterday    236.11 MiB |   98.61 MiB |  334.72 MiB |   31.74 kbit/s
         today    128.55 MiB |   41.00 MiB |  169.56 MiB |   24.97 kbit/s
     ------------------------+-------------+-------------+---------------
     estimated       199 MiB |      63 MiB |     262 MiB |

To monitor the bandwidth usage in realtime, use the ‘-l’ option (live mode). It would then show the total bandwidth used by incoming and outgoing data, but in a very precise manner without any internal details about host connections or processes.

$ vnstat -l -i eth0
Monitoring eth0...    (press CTRL-C to stop)

   rx:       12 kbit/s    10 p/s          tx:       12 kbit/s    11 p/s

Vnstat is more like a tool to get historic reports of how much bandwidth is used everyday or over the past month. It is not strictly a tool for monitoring the network in real time.

Vnstat supports many options, details about which can be found in the man page.

Install vnstat

# ubuntu or debian
$ sudo apt-get install vnstat

# fedora or centos (from epel)
$ sudo yum install vnstat

9. bwm-ng

Bwm-ng (Bandwidth Monitor Next Generation) is another very simple real time network load monitor that reports a summary of the speed at which data is being transferred in and out of all available network interfaces on the system.

$ bwm-ng
bwm-ng v0.6 (probing every 0.500s), press 'h' for help
  input: /proc/net/dev type: rate
  /         iface                   Rx                   Tx                T
ot==========================================================================
==           eth0:           0.53 KB/s            1.31 KB/s            1.84
KB             lo:           0.00 KB/s            0.00 KB/s            0.00
KB--------------------------------------------------------------------------
--          total:           0.53 KB/s            1.31 KB/s            1.84
KB/s

If the console size is sufficiently large, bwm-ng can also draw bar graphs for the traffic using the curses2 output mode.

$ bwm-ng -o curses2

Install Bwm-NG – On CentOS bwm-ng can be installed from Epel.

# ubuntu or debian
$ sudo apt-get install bwm-ng

# fedora or centos (from epel)
$ sudo apt-get install bwm-ng

10. cbm – Color Bandwidth Meter

A tiny little simple bandwidth monitor that displays the traffic volume through network interfaces. No further options, just the traffic stats are display and updated in realtime.

cbm linux network monitor

$ sudo apt-get install cbm

11. speedometer

Another small and simple tool that just draws out good looking graphs of incoming and outgoing traffic through a given interface.

$ speedometer -r eth0 -t eth0

speedometer linux network monitor

Install speedometer

# ubuntu or debian users
$ sudo apt-get install speedometer

12. Pktstat

Pktstat displays all the active connections in real time, and the speed at which data is being transferred through them. It also displays the type of the connection, i.e. tcp or udp and also details about http requests if involved.

$ sudo pktstat -i eth0 -nt

pktstat linux network monitor

$ sudo apt-get install pktstat

13. Netwatch

Netwatch is part of the netdiag collection of tools, and it too displays the connections between local host and other remote hosts, and the speed at which data is transferring on each connection.

$ sudo netwatch -e eth0 -nt

netwatch linux network monitor

$ sudo apt-get install netdiag

14. Trafshow

Like netwatch and pktstat, trafshow reports the current active connections, their protocol and the data transfer speed on each connection. It can filter out connections using pcap type filters.

Monitor only tcp connections

$ sudo trafshow -i eth0 tcp

trafshow linux network monitor

$ sudo apt-get install netdiag

15. Netload

The netload command just displays a small report on the current traffic load, and the total number of bytes transferred since the program start. No more features are there. Its part of the netdiag.

$ netload eth0

netload linux network monitor

$ sudo apt-get install netdiag

16. ifstat

The ifstat reports the network bandwidth in a batch style mode. The output is in a format that is easy to log and parse using other programs or utilities.

$ ifstat -t -i eth0 0.5
  Time           eth0       
HH:MM:SS   KB/s in  KB/s out
09:59:21      2.62      2.80
09:59:22      2.10      1.78
09:59:22      2.67      1.84
09:59:23      2.06      1.98
09:59:23      1.73      1.79

Install ifstat – Ubuntu, Debian and Fedora users have it in the default repos. CentOS users need to get it from Repoforge, since its not there in Epel.

# ubuntu, debian
$ sudo apt-get install ifstat

# fedora, centos (Repoforge)
$ sudo yum install ifstat

17. dstat

Dstat is a versatile tool (written in python) that can monitor different system statistics and report them in a batch style mode or log the data to a csv or similar file. This example shows how to use dstat to report network bandwidth

$ dstat -nt
-net/total- ----system----
 recv  send|     time     
   0     0 |23-03 10:27:13
1738B 1810B|23-03 10:27:14
2937B 2610B|23-03 10:27:15
2319B 2232B|23-03 10:27:16
2738B 2508B|23-03 10:27:17

Install dstat

$ sudo apt-get install dstat

18. collectl

Collectl reports system statistics in a style that is similar to dstat, and like dstat it is gathers statistics about various different system resources like cpu, memory, network etc. Over here is a simple example of how to use it to report network usage/bandwidth.

$ collectl -sn -oT -i0.5
waiting for 0.5 second sample...
#         <----------Network---------->
#Time       KBIn  PktIn  KBOut  PktOut 
10:32:01      40     58     43      66 
10:32:01      27     58      3      32 
10:32:02       3     28      9      44 
10:32:02       5     42     96      96 
10:32:03       5     48      3      28

Install Collectl

# Ubuntu/Debian users
$ sudo apt-get install collectl

#Fedora
$ sudo yum install collectl

Summary

Those were a few handy commands to quickly check the network bandwidth on your linux server. However these need the user to login to the remote server over ssh. Alternatively web based monitoring tools can also be used for the same task.

Ntop and Darkstat are some of the basic web based network monitoring tools available for Linux. Beyond these lie the enterprise level monitoring tools like Nagios that provide a host of features to not just monitor a server but entire infrastructure.

How to install latest PHP 5.4.x on Ubuntu 12.04 LTS

1. Add this package-repository to your system. If Ubuntu says that you need to download a key first, then follow the instructions given in the notice.

sudo add-apt-repository ppa:ondrej/php5-oldstable

If you get an error message now, then please do an update first and install the python-software-properties, that need to be necessary to add a package repository:

sudo apt-get update
sudo apt-get install python-software-properties

2. Update

sudo apt-get update

Check the available version of PHP (the result is self-explaining, the version on the top is the one that will be installed):

apt-cache policy php5

3. Install PHP 5.4.x

sudo apt-get install php5

Check the installed version of PHP (if this does not show 5.4.x please restart your apache)

php5 -v

Please note: The ondrej/php5-oldstable repository (which is used here) provides the very latest version of the PHP 5.4-branch. Usually a version-update is available a few days after it was been officially released. This is really cool and a big step forward as Ubuntu, Debian, CentOS etc. provide only very old versions by default.

How To Install and Use Memcache on Ubuntu 12.04

About Memcache

Memcache is a system that works to speed up virtual private servers by caching server information. The program allows you to allocate a specific amount of the server ram toward caching recently queried data for a certain amount of time. Once the data is requested again, memcache speeds up the process of retrieving it by displaying the cached information instead of generating the result from the database.

Setup

The steps in this tutorial require the user to have root privileges. You can see how to set that up in the Basic Users Tutorial. Before starting off, it’s a good idea to update apt-get to make sure that all of the packages we download to the VPS are up to date.

sudo apt-get update

Additionally, you should have MySQL and PHP installed on the virtual server.

sudo apt-get install mysql-server php5-mysql php5 php5-memcache

Install Memcache

Installing memcache takes several steps.

To start, install memcached via apt-get.

sudo apt-get install memcached

The next step is to install php-pear, the repository that stores memcache.

sudo apt-get install php-pear

If you do not have a compiler on your server, you can download build-essential in order to install memcache:

sudo apt-get install build-essential

Finally use PECL (PHP Extension Community Library) to install memcache:

sudo pecl install memcache

Say yes by pressing enter during the installation when you are asked if you would like to “Enable memcache session handler support? [yes] :”

Once you have completed the installation of memcache with PECL on the VPS, add memcached to memcache.ini:

echo "extension=memcache.so" | sudo tee /etc/php5/conf.d/memcache.ini

Now you are ready to start using Memcache.

Confirm Memcache and See Stats

After Memcache is downloaded, you can check that it has been installed by searching for it:

ps aux | grep memcache

Additionally, you can see the memcache stats by typing:

echo "stats settings" | nc localhost 11211

Step Three—How Memcache Works

Memcache works by redirecting code to first attempt to retrieve data from the cache before querying the server’s database. The cache populates by saving recently retrieved server data for a certain amount of time. By caching recently requested information, future queries do not have to go through the longer process of retrieving the information from a database and can, instead, access it through the cache.

The memcache page shows this abbreviated code on its homepage to summarize the memcache process:

function get_foo(foo_id)
    foo = memcached_get("foo:" . foo_id)
    return foo if defined foo

    foo = fetch_foo_from_database(foo_id)
    memcached_set("foo:" . foo_id, foo)
    return foo
end

A Simple Memcache Example

This section will set up a simple php script to use memcache for retrieving a single value originally found in a mysql table.

The following steps set up a mysql user who can access the appropriate database, create a table to query, and insert the one value that we will test in the new mysql table.

Log into mysql: mysql -u root -p and execute the following commands:

use test;

grant all on test.* to test@localhost identified by 'testing123';

create table example (id int, name varchar(30));

insert into example values (1, "new_data");

exit;

Once you have exited MySQL, create the memcache script file:

nano memtest.php

We are now going to build up the php script step by step (the entire script will be at the end of the section):

  • Start off by creating a new persistent connection with memcache, which runs on memcache’s default port, 11211.
    <?php
    $meminstance = new Memcache();
    $meminstance->pconnect('localhost', 11211);
  • The next step is to connect to the new mysql database with the user that we created earlier:
    mysql_connect("localhost", "test", "testing123") or die(mysql_error());
    mysql_select_db("test") or die(mysql_error());
  • After that, go ahead and create the query that we will pose to the server, as well as provide a key to identify that specific action:
    $query = "select id from example where name = 'new_data'";
    $querykey = "KEY" . md5($query);
  • The script first searches the cache for the answer to the query. If the result does not exist, the script reroutes the question to the original database. Once the query has been answered by the original database, the script stores the result in memcache, using the “set” command– which both saves it and allows the user to designate the number of seconds that it should remain in the cache (600 would save it in the cache for 10 minutes).
    When we run the script for the first time, it will inform us that the data was collected from the mysql database. However, as it does so, it stores the information in the cache, so that a second run of the script retrieves it from the cache and lets the user know. In 10 minutes the cache is emptied once more and running the script will make it access the database once again.

    $result = $meminstance->get($querykey);
    
    if (!$result) {
           $result = mysql_fetch_array(mysql_query("select id from example where name = 'new_data'")) or die('mysql error');
           $meminstance->set($querykey, $result, 0, 600);
    print "got result from mysql\n";
    return 0;
    }
    
    print "got result from memcached\n";
    return 0;
    
    ?>

Altogether the script looks like this:

<?php
$meminstance = new Memcache();
$meminstance->pconnect('localhost', 11211);

mysql_connect("localhost", "test", "testing123") or die(mysql_error());
mysql_select_db("test") or die(mysql_error());

$query = "select id from example where name = 'new_data'";
$querykey = "KEY" . md5($query);

$result = $meminstance->get($querykey);

if (!$result) {
       $result = mysql_fetch_array(mysql_query("select id from example where name = 'new_data'")) or die('mysql error');
       $meminstance->set($querykey, $result, 0, 600);
print "got result from mysql\n";
return 0;
}

print "got result from memcached\n";
return 0;

?>

Running the script on the command line produces the following results:

# php memtest.php 
got result from mysql

# php memtest.php 
got result from memcached

# php memtest.php 
got result from memcached

Conclusion

This tutorial covers speeding up the retrieval of data from a database by connecting it to memcache. However, do keep in mind that memcache’s strengh originates from the fact that is a cache—it is not a datastore. When using memcache, do not expect it to replace a database. Because memcache only holds values for a set length of time for a given key, you may not always find the information you need cached, and in cases like these, having the original server database is imperative.

Nevertheless, memcache is a very useful program and can do a lot to increase the server efficiency.

If you have any other questions about Memcache, feel free to ask about specifics on our forum.

在Linux中为非SSH用户配置SFTP环境

某些环境中,系统管理员想要允许极少数用户在可以传输文件到Linux机器中,但是不允许使用 SSH。要实现这一目的,我们可以使用SFTP,并为其构建chroot环境。

SFTP & chroot背景:

SFTP是指SSH文件传输协议(SSH File Transfer protocol)或安全文件传输协议(Secure File Transfer Protocol),它提供了可信数据流下的文件访问、文件传输以及文件管理功能。当我们为SFTP配置chroot环境后,只有被许可的用户可以访问,并被限制到他们的主目录中,换言之:被许可的用户将处于牢笼环境中,在此环境中它们甚至不能切换它们的目录。

在本文中,我们将配置Ubuntu 12.04.5 LTS中的SFTP Chroot环境。我们开启一个用户帐号‘Guest’,该用户将被允许在Linux机器上传输文件,但没有ssh访问权限。

步骤:1 创建组

$ sudo groupadd  sftp_users

步骤:2 分配附属组(sftp_users)给用户

如果用户在系统上不存在,使用以下命令创建( 这里给用户指定了一个不能登录的 shell,以防止通过 ssh 登录):

$ sudo useradd  -G sftp_users  -s /bin/false  guest

$ sudo passwd guest

对于已经存在的用户,使用以下usermod命令进行修改:

$ sudo usermod –G sftp_users  -s /bin/false  guest

注意:如果你想要修改用户的默认主目录,那么可以在useradd和usermod命令中使用‘-d’选项,并设置合适的权限

步骤:3 现在编辑配置文件 “/etc/ssh/sshd_config”

$ sudo vi /etc/ssh/sshd_config

 #comment out the below line and add a line like below
 #Subsystem sftp /usr/libexec/openssh/sftp-server  
 Subsystem sftp internal-sftp
 
 # add Below lines  at the end of file 
 Match Group sftp_users  
 X11Forwarding no  
 AllowTcpForwarding no 
 ChrootDirectory %h     
 ForceCommand internal-sftp 

此处:

  • Match Group sftp_users – 该参数指定以下的行将仅仅匹配sftp_users组中的用户
  • ChrootDirectory %h – 该参数指定用户验证后用于chroot环境的路径(默认的用户主目录)。对于用户 Guest,该路径就是/home/guest。
  • ForceCommand internal-sftp – 该参数强制执行内部sftp,并忽略任何~/.ssh/rc文件中的命令。

重启ssh服务

$ sudo service ssh restart

步骤:4 设置权限:

$ sudo chmod 755 /home/guest

$ sudo chown root /home/guest

$ sudo chgrp -R sftp_users /home/guest

如果你想要允许guest用户上传文件,那么创建一个上传文件夹,设置权限如下:

$ sudo mkdir /home/guest/upload

$ sudo chown guest. /home/guest/upload/

步骤:5 现在尝试访问系统并进行测试

via: http://www.linuxtechi.com/configure-chroot-sftp-in-linux/

https://linux.cn/article-3692-1.html

国内外各种建站免费面板和一键包汇总

面板类:

国外:

VestaCP:http://vestacp.com/ (目前最为推荐的面板,自带中文)
Kloxo-MR:https://github.com/mustafaramadhan/kloxo/ (7.0真的很强大,很好看,很实用,有中文包)

Webmin/Virtualmin:http://www.webmin.com/virtualmin.html (很稳定,很安全,自带中文)
Ispconfig:https://github.com/dclardy64/ISPConfig-3-Debian-Installer (官网安装我都没看懂,这个网址是一键安装的)

Webuzo:http://www.webuzo.com/downloads (个人用还是不错的)
centos webpanel:http://centos-webpanel.com/ (据说比较有发展前途)

Froxlor:http://www.froxlor.org/ (很轻量的,适应各种环境)
Ajenti:http://ajenti.org/ (自带中文)

i-MSCP:http://i-mscp.net/  (简单易用)
zPanel(sentora):http://www.zpanelcp.com/  (支持win)
AlternC:https://alternc.org/ (简单)

国内:

http://amh.sh/ (4.2版免费)
http://www.wdlinux.cn/bbs/ (简单易用,近来爆出不少严重安全漏洞)

http://www.kanglesoft.com/ (全能空间)
http://www.zijidelu.org/ (支持freeBSD)

一键包:

国外:

http://centminmod.com/ (据说很适合wordpress)

http://tuxlite.com/

https://github.com/Xeoncross/lowendscript  (lowendscript演变来的)

https://github.com/maxexcloo/Minimal

https://github.com/KnightSwarm/Minstall

https://github.com/mikegioia/Debian-Server

国内:

http://lnmp.org/ (用的人很多,适应性很强)
http://teddysun.com/lamp (很好用的LAMP一键包)

http://teddysun.com/lamp-yum (适合小内存≥64M的LAMP)
http://bbs.aliyun.com/read/151729.html (阿里云论坛看到的)
https://github.com/wangyan/lanmp (针对512M内存的VPS进行了优化)

http://www.hhvmc.com/thread-17-1-1.html (hhvm的一键包)
http://blog.7qy.com/installation/hot-lcmp (cherokee的一键包)
https://www.lxconfig.com/thread-69-1-1.html (有openresty哦)
http://shuang.ca/llnmp/ (LiteSpeed的一键包)

http://llsmp.cn/

http://blog.linuxeye.com/31.html

http://www.phpstudy.net/