杂乱手札 - LINUX, Apache, Mysql, PHP, HTML-JS-CSS, Redis 2014 to 2016


很乱,很乱,very乱......

一分耕耘一分收获。













====================== Begin ===========================

SSH

基本ssh登录

ssh username@IP   // ssh rudon@***.***.***.*** 


无密码SSH登录

约定: 电脑A上的Ua用户,想要免密码ssh登录到远程的服务器B上的Ub用户

概括: 本地电脑A生成密码对,包含密钥(/home/Ua/.ssh/id_rsa)和公钥(/home/Ua/.ssh/id_rsa.pub),然后把公钥id_rsa.pub的内容追加到在服务器B的"已验证用户记录文件"上(/home/Ub/.ssh/authorized_keys),并设置此文件的权限为600,即可。

流程:

/* In 电脑A */
cd
ssh-keygen -t rsa -C "你的电子邮箱"
cd ~/.ssh/
cat id_rsa.pub              (复制内容)

/* In 服务器B */
ssh Ub@***.***.***.***         (然后输入密码)
cd ~/.ssh/                  (若不存在,请以Ub身份创建)
echo '刚才在电脑A上复制的公钥内容' >> authorized_keys           (若不行,使用sudo进行文件创建和修改)
chmod 600 authorized_keys   (若不行,请使用sudo)
exit

/* 回到了电脑A */
cd
ssh Ub@***.***.***.***







Advanced Case

grep -Rl '((w++' */*html | cut -d/ -f1 | sort -u


[编辑]System Setting

Multi-Kernel Start Menu

Set up Virtual Host

Notice of install of wrong version

alias: Remember variables

delete_strange_file: Delete weird(strange) name files and directories


[编辑]System Corporation

ls -l |grep "^-"|wc -l        /* 统计当前文件夹下文件的个数,文件数量 */
ls -l |grep "^d"|wc -l        /* 统计当前文件夹下目录的个数,文件夹数量 */
ls -lR|grep "^-"|wc -l        /* 统计当前文件夹下文件的个数,包括子文件夹里的  */
ls -lR|grep "^d"|wc -l        /* 统计文件夹下目录的个数,包括子文件夹里的  */
find . -type f -name "*.zip"        /*  */
find . -type d -name "config"        /*  */
find . -type f -size +100M        /* 大于100m的文件 */
du -sh /path/to/dir        /* 文件夹大小 */
du -h .        /* 查看当前文件夹大小,和遍历下面的所有文件大小 */


/* 保持文件结构,排除某些文件夹,备份其他所有文件 */
sudo ls
cd 
cd /path-to-backup/
rsync -av --progress /var/www/cms/ /path-to-backup/ --exclude any-dir-name-in-source-dir/ --exclude 2nd-dir-name/
ls


/* 保持文件结构,依据文件格式,备份部分文件 */
sudo ls
cd
cd SystemBackup
mkdir 2015xxxx-xxxx
cd 2015xxxx-xxxx
mkdir filesFromCMS
cd /var/www/
tar -cvf - $(find ./cms/templates/ -name "*.html" -o -name "*.htm" -o -name "*.php" -o -name "*.txt" -o -name "*.json") | (cd /home/rudon/SystemBackup/2015xxxx-xxxx/filesFromCMS/; tar -xvf -)
cd /home/rudon/SystemBackup/2015xxxx-xxxx/filesFromCMS/
ls


/* 根据名称,删除部分文件夹 */
cd /path-to-target-dir/
find . -type d -name "templates_c"
find . -type d -name "templates_c" | xargs rm -rf
find . -type d -name "templates_c"


cURL in terminal 


search IP and Host-name in LAN


view_a_big_text_file:tail -n100 filename (click for more)

nano

Terminal_Command:cp, rm, chown, chmod, scp, rename, uname, svn command,

smtp_terminal

vi

SSH:link to other ubuntu with terminal, 无密码SSH登录

scp: Copy file to other host

Fn_KEY: show desktop(ctrl+win+d),switch windows(Alt+Tab,or ~ key)

SHELL Script

Find a file:find /var/www -name %partname%


Hide_a_folder: Just rename, add '.' before the folder name, and save.It's also for files.

see the size of file: du -h xxx.tar.gz >>> will be 86M

____________________ du xxx.tar.gz >>> will be 87568

Make a zip : tar cvzf xxx.tar.gz xxx/

                  tar -xvf infoform.tar.gz

delete folder : rm -r foldername/


make a zip and keep constrution for folder 

保持文件夹结构,打包散乱的文件
cd /var/www/
zip -r target.zip cms/xx/xx.php cms/yy/yy.php

[编辑]System Error

GPU HANG

broken package

Restart window manager : sudo service lightdm restart

showing "Permission denied" when using nano? Here 


中文乱码 (Mass with un-english)

播放器(media player, Rhythmbox)

  1. sudo apt-get install python-mutagen
  2. cd ~/Music/
  3. mid3iconv -e GBK *.mp3
  4. OK!





[编辑]Office Software

install software

Chinese input Method

Keepass




[编辑]Media Software

Photivo




[编辑]Cron jobs

Good examples

Example of our cron jobs






Set up Virtual Host

Dependence


.....


Config in apache


  1. /etc/php5/apache2/php.ini
  2. /etc/apache2/apache2.conf
  3. /etc/apache2/ports.conf
  4. /etc/apache2/sites-available/xxx
  5. /etc/apache2/sites-enabled/xxx
  6. /etc/hosts

目录

 [隐藏
apache2.conf

(Have a look)

#       /etc/apache2/
#       |-- apache2.conf
#       |       `--  ports.conf
#       |-- mods-enabled
#       |       |-- *.load
#       |       `-- *.conf
#       |-- conf.d
#       |       `-- *
#       `-- sites-enabled
#               `-- *


ports.conf
NameVirtualHost *:80
Listen 80


hosts
127.0.0.1       localhost
192.168.1.104   secure.xxx.com
sites-available/xxx
    <VirtualHost *:80>
            ServerName xn--tjVz7pJ.com           #中文域名的punycode编码
            ServerAlias www.xn--tjVz7pJ.com      #中文域名的punycode编码
            DocumentRoot /usr/local/www/website/huojiu
            SuexecUserGroup huojiu huojiu
            ErrorLog "/usr/local/www/website/huojiu/error_log"
            CustomLog "/usr/local/www/website/huojiu/access_log" common
    </VirtualHost>


sites-enabled/xxx

make a link from sites-available,like:
sudo ln -s ../sites-available/xxx xxx



CURL



Example

commandreturn
cURL http://www.baidu.com/
<!DOCTYPE html>
<html><head><title>百度一下,你就知道</title><meta http-equiv="content-type" 
content="text/html;charset=utf-8"><title>百度一下,你就知道</title>
............
</html>
            
cURL curl -X GET http://babycms.com/admin/ajax.php?action=check_is_runing&sid=100
true
            
cURL curl -X POSThttp://production.shippingapis.com/ShippingAPITest.dll&API=RateV4&xml='<RateV4Request USERID="181SHENAS219">......</RateV4Request>'
[1] 22124
[2] 22125
            



Javascript



目录

 [隐藏

AngularJS



More kind

1.JQuery for more ------------------ not using now
2.AngularJS for more ----------------- not using now
3.Bootstrap


More skill


[编辑]more skill

  1. sorting in tag table (tablesorter)
  2. Charts


[编辑][js] convert from json_string to js object

 var obj = eval('(' + data + ')');
 if(obj.success == 'true'){
    alert(obj.filefullname);
  }


[编辑][js] get_selected_option_html

       var obj = document.getElementById(id);
       for (i = 0; i < obj.length; i++) {
           if (obj[i].selected == true) {
               return obj[i].innerHTML;
           }
       }


[编辑][js] trim, remove space for str

   function trim(str) {
       return str.replace(/(^\s*)|(\s*$)/g, "");
   }
   function ltrim(str) {
       return str.replace(/(^\s*)/g, "");
   }
   function rtrim(str) {
       return str.replace(/(\s*$)/g, "");
   }

[编辑][js] assoc array

{}

        var myhash = {};
        myhash["key1"] = "54";
        myhash["key2"] = "654";
        var s = JSON.stringify(myhash);
        alert(s); // {"key1":"54","key2":"654"}

If you want to use number as key: using []

        var myhash = [];
        myhash[2] = "2222222";
        myhash["key1"] = "54";
        myhash["key2"] = "654";
        myhash[3] = "3333333";

        var s = JSON.stringify(myhash);
        alert(s); // [null,null,"2222222","3333333"]

[编辑]more js

stringObject.split(a,b)

字符串 转数组: stringObject.split(a,b) //a is ',' and b is limit how many will cut(not required) 
四种JS遍历数组方法 
Js操作Select大全


[编辑]Get ids who is checked

   function get_selected_ids(classname) {
       var new_order = [];
       $("."+classname).each(function() {
           if( this.checked ){
               new_order.push(this.value);
           }
       });
       var newid = new_order.join(',');
       return newid;
   }
   _________html____________
   <input type="checkbox" name="select[]" class="select_class_input" value="<?php echo $cat['id']; ?>"/>
   _________to use____________
       var ids = get_selected_ids('select_class_input');
       alert(ids);



[编辑]foucs on tail of element.input

       function tail_focus(obj){
           var t=$("#"+obj).val();
           $("#"+obj).val("").focus().val(t); // That is copy content at first, then make it empty, then focus, and paste again.
       }



[编辑]Select all or none

Example

      $(function () {
      // Select all or none
      $("#AllorNone").click(function(){
          var wantall = document.getElementById('AllorNone').checked;
          var newTask = document.getElementsByName('select[]');
          for(var i=0;i<newTask.length;i++){
           var e=newTask[i];
            if(wantall){
             e.checked=true;
             
            }else{
             e.checked=false;
             
            }
          } 
      });
  });
  _________html____________
  <input type="checkbox" id="AllorNone"/>
  <input type="checkbox" name='select[]'/>......


[编辑]Ajax Example

	$.ajax({
	    url: "http://url/",
	    type: "POST",
	    dataType: "json",
	    data: {
		"name": "Boy"
	    },
	    success: function(json) {
		if (json.success) {
		    // ...
		} else {
		    // ...
		}
	    },
	    complete: function() {
		// ...
	    },
	    error: function() {
		// ...
	    }
	});

[编辑]append element

Tags: append, cover layer, black layer, div append

    function show_focus_pic (){
        var win_height = $(window).height() - 40;
        var ele1 = $("<img src='.....' style='.......'/>").text(name);
        var ele2 = $("<div id='...' style='z-index:2;position: fixed;left:0;top:20px;text-align:center; width:100%;height:"+win_height+"px;'></div>");
            ele2.append(ele1);
        
        //$("#sys_cover_lay").append(ele2);
        $(document.body).append(ele2);
    }



[编辑]Scroll window

Tags: scroll, scrollTop, window height New function:

            jQuery(document).ready(function ($) {

                $body = (window.opera) ? (document.compatMode == "CSS1Compat" ? $('html') : $('body')) : $('html,body');

                $('#btn_to_top').click(function () {
                    $body.animate({scrollTop: 1}, 100);
                    return false;
                });
                $('#btn_to_bottom').click(function () {
                    $body.animate({scrollTop: $(document).height()}, 100);
                    return false;
                });

            });

Old function:

    function scroll (){
        var win_height = $(window).height();
        var input_height = document.getElementById('b_zipcode').offsetTop;

        //$('#id').animate({scrollTop: 1000+'px'}, 1000);
        $('html,body').animate({scrollTop: input_height+'px'}, 1000);
    }

[编辑]Simple Example

http://XXX.com/admin/index.php?module=listings&action=showlistings&section_id=699 [Drag and Drop]


html:

<link rel="stylesheet" href="./assets/css/jquery-ui.css" />

<script src="./assets/js/jquery-ui.js"></script>

$(function() {

       var $sortable   =  $('#sortable');
       var $old_order  =  $('#old_order');
       var new_order   = [];
       var old_order   = [];
       
       // Find the url
       var url= window.location.href;
       var superurl= url.split('?')[0];
       superurl = superurl+'?module=listings&action=change_order';
       
       
       $( "#sortable" ).sortable({ 
           axis: 'y',
           distance: 50,
           //revert: true,
           cursor: 'move',
           opacity: 0.6, 
           placeholder: 'placeholder_empty',
           start: function(event, ui) {
               old_order   = [];
               new_order   = [];
               $sortable.children(".ui-state-default").each(function() { 
                   old_order.push(this.id); 
                });
               $old_order.val(old_order);
           },
           
           update: function(event, ui) {
               old_order   = [];
               new_order   = [];
                $sortable.children(".ui-state-default").each(function() {
                   
                   new_order.push(this.id); 
                });
                var newid = new_order.join(','); 
                var oldid = $old_order.val();
                $.ajax({ 
                   type: "post", 
                   url: superurl,
                   data: { neworder: newid, oldorder: oldid },
                   //beforeSend: function() { 
                        //$show.html("<img src='load.gif' /> "); 
                   //},
                   success: function(msg) { 
                        //alert(msg); 
                        //$show.html(""); 
                   } 
                }); 
           }
       });
       $( "#sortable" ).disableSelection();
   });


And then,in html:

<tbody id="sortable">

<tr class="order_ico_tr ui-state-default" id='{$listings[item].id}'>



php:receive ajax and echo back;


Selector find option with angularJS

keywords:select, selector, find option

-------------------------------------------------
jQuery获取Select选择的Text和Value:
语法解释:
1. $("#select_id").change(function(){//code...});    //为Select添加事件,当选择其中一项时触发
2. var checkText=$("#select_id").find("option:selected").text();   //获取Select选择的Text
3. var checkValue=$("#select_id").val();   //获取Select选择的Value
4. var checkIndex=$("#select_id ").get(0).selectedIndex;   //获取Select选择的索引值

5. var maxIndex=$("#select_id option:last").attr("index");   //获取Select最大的索引值
jQuery设置Select选择的Text和Value:
语法解释:
1. $("#select_id ").get(0).selectedIndex=1;   //设置Select索引值为1的项选中
2. $("#select_id ").val(4);    //设置Select的Value值为4的项选中
3. $("#select_id option[text='jQuery']").attr("selected", true);    //设置Select的Text值为jQuery的项选中

jQuery添加/删除Select的Option项:
语法解释:
1. $("#select_id").append("<option value='Value'>Text</option>");   //为Select追加一个Option(下拉项)
2. $("#select_id").prepend("<option value='0'>请选择</option>");   //为Select插入一个Option(第一个位置)
3. $("#select_id option:last").remove();   //删除Select中索引值最大Option(最后一个)
4. $("#select_id option[index='0']").remove();   //删除Select中索引值为0的Option(第一个)
5. $("#select_id option[value='3']").remove();   //删除Select中Value='3'的Option
5. $("#select_id option[text='4']").remove();   //删除Select中Text='4'的Option
-------------------------------------------------

	// Find worldwide
	angular.forEach($scope.shipping_addr_options , function($one_row){
	    if($one_row.name == 'WorldWide'){
		$scope.shipping_addr = $one_row;
		$("#shipping_country option:contains('WorldWide')").attr("selected", "selected");
		ifindit = true;
		found_worldwide = true;
		return;
	    }
	});



Foreach Array

keywords:遍历数组,for in,foreach array,loop array

	var arr = [11, 22, 33];
	for(var v in arr){
	    alert(v); // 0,1,2
	}
	var o = { a:1, b:2};
	for(var v in o){
	   alert(v); //a,b
	} 


Pass string-json-arr from PHP to JS, with QUOTE

keywords:单引号,双引号,数组传送,特殊符号,quote, double quote, js string ,input, array json string, html

============ PHP's data =============
    $arr = array(
        0 => array(
            'names' => "Peter's Hat",
            'price' => "100.22"
        ),
        1 => array(
            'names' => '14.1" notepad',
            'price' => "1500"
        )
    );

    /* Get names_in_html_tag_attribute, like:  title="{$names_str}" */
    $names_arr = array();
    foreach ($arr as $one){
        $names_arr[] = htmlspecialchars($one['name'],ENT_QUOTES);
    }
    $names_str = implode(',', $names_arr);

    
    /* Get names_in_html_js_as_arr, like:  var arr = {$names_arr_str}; */
    $names_arr_str = '';
    foreach ($arr as $one){
        $name = addslashes($one['name']);
        $h = ($names_arr_str == '')?'':',';
        $names_arr_str .= $h."'{$name}'";
    }
    $names_arr_str = '['.$names_arr_str.']';
	
	
============ HTML's data =============
    <a title="{$names_str}">xx</a>
    
    <script>
        var arr = {$names_arr_str};
        alert(JSON.stringify(arr));
    </script>
	
	


Print Array

keywords:打印数组,弹出,查看,alert array,print array, JSON.stringify, alert json

Best
    var arr=[{"id":0,"row_id":5,"pid":69,"quantity":1,"color":"Black"},{"id":1,"row_id":6,"pid":69,"quantity":1,"color":"Orange"}];
    var b=JSON.stringify(arr);
    alert(b);


Just so so
    function scan_array(arr) {
        for(var key in arr) {
            if(typeof(arr[key]) == 'array' || typeof(arr[key]) == 'object') {
                scan_array(arr[key]);
            } else {
                document.write(key + ' = ' + arr[key] + '<br>');
            }
        }
        document.write('<hr>');
    }




Jquery .each

keywords:遍历元素, 遍历数组 , foreach arr, foreach elements

    $('.Class_name').each(function(i,ele){
        // i is the key 0,1,2,3,4,5,....
        if(ele.checked){
            $(ele).parent().parent().remove();
        }
    });




Insert into text , in Foucs-position

keywords:append , focus , insert text, 插入,光标点,点击

    /**
     * Insert into text , in Foucs-position
     * 
     * @param {type} obj_id
     * @param {type} str
     * @returns {undefined}
     * 
     * @link http://www.cnblogs.com/yoyiorlee/archive/2011/04/04/2005213.html
     */
    function insertText(obj_id, str) {
        var obj = document.getElementById(obj_id);
        if (document.selection) {
            var sel = document.selection.createRange();
            sel.text = str
        } else if (typeof obj.selectionStart === 'number' && typeof obj.selectionEnd === 'number') {
            var startPos = obj.selectionStart,
                    endPos = obj.selectionEnd,
                    cursorPos = startPos,
                    tmpStr = obj.value;
            obj.value = tmpStr.substring(0, startPos) + str + tmpStr.substring(endPos, tmpStr.length);
            cursorPos += str.length;
            obj.selectionStart = obj.selectionEnd = cursorPos
        } else {
            obj.value += str
        }
    }
    function moveEnd(obj_id) {
        var obj = document.getElementById(obj_id);
        obj.focus();
        var len = obj.value.length;
        if (document.selection) {
            var sel = obj.createTextRange();
            sel.moveStart('character', len);
            sel.collapse();
            sel.select()
        } else if (typeof obj.selectionStart == 'number' && typeof obj.selectionEnd == 'number') {
            obj.selectionStart = obj.selectionEnd = len
        }
    }



Tablesorter


[编辑]Example

sites_and_paypal_mails


[编辑]code

   <script src="assets/js/jquery.tablesorter.min.js"></script>
   <script>
       {literal}
       $(document).ready(function() 
           { 
               $("#sorttingtable_new").tablesorter(); 
           }
       );
       {/literal}
   </script>
   ....
   <table class="table table-bordered table-striped" id='sorttingtable_new'>
   ....



[编辑]No sort line

if you didn't want to sort first and 5th <th>, just change

  $("#sorttingtable_new").tablesorter(); 

to

  $("#sorttingtable_new").tablesorter({headers:{0:{sorter:false},4:{sorter:false}}});




MySQL


目录

 [隐藏

[编辑]connect

  1. mysql_connect('localhost','username','password');
  2. mysql_query('SET NAMES UTF8');
  3. mysql_select_db('name_of_database');



[编辑]Stop / Start Mysql server

  1. [start] sudo start mysql
  2. [stop] sudo stop mysql

http://wiki.ubuntu.com.cn/MySQL

[编辑]Mysql Change Permissions For User

  1. (to check) show grants for lprsadm;
  2. (new user) grant select,insert,update,delete on [DB-name].* to [User-name]@localhost Identified by "[Password]";
  3. (to change) grant all privileges on DB-name to User-name
  4. (new password) mysql> SET PASSWORD FOR 'root'@'localhost' = PASSWORD('NEW_PWD');


[编辑]repair all databases

root@web1:/var/log/mysql# mysqlcheck --repair --all-databases -p

and type the MySQL root password



[编辑]search

Query with id order 
1.SQL: select * from table where id IN (8,3,6,9,1,2,5,7);

result will be order by 1,2,3,5,6,7,8,9

2.SQL: select * from table where id IN (8,3,6,9,1,2,5,7) order by field(id,3,6,9,1,2,5,8,7);

result will be order by 3,6,9,1,2,5,8,7





Copy table

Tags: copy id column,copy table,copy columns, Insert into new Table with id from other table

Same construction

INSERT INTO `table1` SELECT * FROM `table2`;

Different construction

INSERT INTO `table1` (col_name1, col_name2) SELECT old_column1,old_column2 FROM `table2`;



Search columns in one database

Tags: Look for columns by keyword, match columns

DEMO

SELECT DISTINCT TABLE_NAME, COLUMN_NAME 
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME LIKE '%keyword%'
    AND TABLE_SCHEMA='--name-of-database--';

[编辑]Do with it

drop database `XXX`; source ~/work/dump.sql


Add index

   ALTER TABLE `XXX`.`t_info` ADD INDEX `INDEX` (`t_id` ASC) ;
   ALTER TABLE `XXX`.`t` ADD INDEX `INDEX` (`t_id` ASC) ;
   ALTER TABLE `XXX`.`t_pro` ADD INDEX `INDEX` (`sid` ASC) ;


[编辑]Fatal Error

Database divert


[编辑]Character encoding problems

convert character encoding

To change:

admin.init.php

function update

big bullshit ==> if($this->useencoding) $fields[]="`".$v1."`='".addslashes(iconv('utf-8','windows-1251' , $data[$v1]))."'";


Show encodings

1. Schema

SELECT default_character_set_name FROM information_schema.SCHEMATA S WHERE schema_name='dbname';

2. Table

SELECT CCSA.character_set_name FROM information_schema.`TABLES` T,
       information_schema.`COLLATION_CHARACTER_SET_APPLICABILITY` CCSA
WHERE CCSA.collation_name = T.table_collation
  AND T.table_schema = "dbname"
  AND T.table_name = "pages";

3. Column

SELECT character_set_name FROM information_schema.`COLUMNS` C
WHERE table_schema = "dbname"
  AND table_name = "pages"
  AND column_name = "name";

4. References:

http://kunststube.net/frontback/

[编辑]dump and restore data

dump and restore one row


Dump data with "where"

    mysqldump -t -uroot -pxxxxxxxxxx db_name table_name -w "id > 200"  > path-to-file.sql

[编辑]output as a sql file

mysqldump -uxxx -pxxx database_name(or table name) > file_name

ex:(get out of mysql command)root@ns2:~# mysqldump -u xxx-pasdasdasd db_name > ~/dump.sql







[编辑]Some useful example

Get who is on Birthday today?

col:birthday datetime 
value format:1998-05-07
SQL: .... where DATE_FORMAT(`birthday`,'%m')=DATE_FORMAT(NOW(),'%m') AND DATE_FORMAT(`birthday`,'%d')=DATE_FORMAT(NOW(),'%d');






Redis



目录

 [隐藏

Installation

For more: http://blog.csdn.net/liguohui/article/details/7686560 
For more: http://www.cnblogs.com/viaivi/archive/2011/12/08/2281319.html

  1. Install Redis
  2. mkdir Programs
  3. cd Programs/
  4. sudo apt-get install php5-dev
  5. <Go to download lastest version for Redis (tar.gz file) to current folder, URL is http://redis.io/download>
  6. tar xzvf [your-file-name].tar.gz
  7. cd [new-folder-name-with-unziped-files]
  8. make
  9. sudo make install
  10. Install PHP-Redis
  11. cd ../  (back to folder 'Programs')
  12. wget --no-check-certificate http://github.com/nicolasff/phpredis/tarball/master -O phpredis.tar.gz
  13. tar xzvf phpredis.tar.gz
  14. cd nicolasff-phpredis-f1231c9
  15. phpize
  16. ./configure
  17. make
  18. sudo make install
  19. sudo nano /etc/php5/apache2/php.ini
  20. <add "extension=redis.so" in the bottom, save>
  21. sudo nano /etc/php5/cli/php.ini
  22. <add "extension=redis.so" in the bottom, save>
  23. sudo apache2ctl restart
  24. <Start server for Redis: >~/Programs/redis-2.8.7/src/redis-server
  25. OK! check redis is good or not by phpinfo()
  26. Autorun Redis when system start
  27. mkdir tmp
  28. cd tmp
  29. wget https://github.com/ijonas/dotfiles/raw/master/etc/init.d/redis-server
  30. wget https://github.com/ijonas/dotfiles/raw/master/etc/redis.conf
  31. sudo mv redis-server /etc/init.d/redis-server
  32. sudo chmod +x /etc/init.d/redis-server
  33. sudo mv redis.conf /etc/redis.conf
  34. sudo useradd redis
  35. sudo mkdir -p /var/lib/redis
  36. sudo mkdir -p /var/log/redis
  37. sudo chown redis.redis /var/lib/redis
  38. sudo chown redis.redis /var/log/redis
  39. sudo update-rc.d redis-server defaults
  40. sudo /etc/init.d/redis-server start
  41. OK, restart PC and check




Import & Export

backup, save, restore, rdb, copy redis data

Main Flows: 
1. dump data into dump.rdb (A) in origin server 
2. copy rdb file(A) to new server 
3. Stop Redis service in new server 
4. replace old rdb file(B) in new server to be our new dump.rdb(A) 
5. Start Redis service in new server, and redis will load our target data from this rdb file (A)



Details:

  1. Prepare for settings in source server:
    1. Path of redis's scripts: run "root@server-name:/# find . -type f -name 'redis*'", you will get these on Linux: 
      ./usr/bin/redis-check-dump 
      ./usr/bin/redis-check-aof 
      ./usr/bin/redis-server 
      ./usr/bin/redis-cli 
      ./etc/redis/redis.conf 
    2. Path of redis's rdb files: run "root@server-name:/# find . -type f -name '*.rdb'", you will get these on Linux: 
      ./dump.rdb 
      ./var/lib/redis/dump.rdb
  2. In origin server, backup data from Redis into one dump.rdb file: 
    /usr/bin/redis-cli
    save
  3. cd /
  4. scp ./dump.rdb username@ip-of-new-server:~/any/path/for/source/rdb/file/
  5. In new target server, /usr/bin/redis-cli shutdown
  6. sudo cp ~/any/path/for/source/rdb/file/dump.rdb /dump.rdb
  7. sudo chmod 0644 /dump.rdb
  8. /usr/bin/redis-server, and redis will load our data
  9. Done, more in http://stackoverflow.com/questions/6004915/how-do-i-move-a-redis-database-from-one-server-to-another


Usage

<?php
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$redis->set('key', 'hello world');
echo $redis->get('key');
?>



PHP-CI-redis

For more: https://github.com/joelcox/codeigniter-redis

        /* String */
        $this->redis->set('str_key','str_value');
        //echo $this->redis->get('str_key');// will be "str_value"
        
        /* List */
        $this->redis->del('list_key');
        $this->redis->lpush('list_key',array('lpush_1','lpush_2'));
        $this->redis->rpush('list_key',array('rpush_1','rpush_2'));
        //print_r( $this->redis->lrange('list_key',0, -1) );die;
        //Array ( [0] => lpush_2 [1] => lpush_1 [2] => rpush_1 [3] => rpush_2 ) 
        
        /* Hash */
        $this->redis->hset('hash_ci','name','rudon');
        $this->redis->hmset('hash_ci',array('name','rudon_new','id',100));
        //echo $this->redis->hget('hash_ci','name'); // rudon_new
        //print_r($this->redis->hmget('hash_ci',array('name','id'))); //Array ( [0] => rudon_new [1] => 100 )
        //print_r( $this->redis->hgetall('hash_ci') );//Array ( [0] => name [1] => rudon_new [2] => id [3] => 100 )
        //print_r( $this->redis->hkeys('hash_ci'));//Array ( [0] => name [1] => id )
        //print_r( $this->redis->hvals('hash_ci'));//Array ( [0] => rudon_new [1] => 100 ) 
        
        
        /* Sets */
        $this->redis->del('sets_key');
        $this->redis->del('sets_key_2');
        $this->redis->sadd('sets_key','val1','val2');
        $this->redis->sadd('sets_key_2','val1','new1','new2');
        //print_r($this->redis->SMEMBERS('sets_key'));//Array ( [0] => val1 [1] => val2 [2] => id_1 ) 
        //print_r($this->redis->scard('sets_key'));//2
        //print_r($this->redis->sdiff('sets_key','sets_key_2'));//Array ( [0] => val2 ) 
        //print_r($this->redis->sinter('sets_key','sets_key_2'));//Array ( [0] => val1 ) 
        //print_r($this->redis->sismember('sets_key','val3'));//0 or 1
        //print_r($this->redis->smove('sets_key','sets_key_2','val2'));//move "val2" from "sets_key" to "sets_key_2"
        //print_r($this->redis->spop('sets_key'));// Random del and show one item in "sets_key"
        //print_r($this->redis->srandmember('sets_key'));// Random show one item in "sets_key"
        //$this->redis->srem('sets_key','val2'); // Remove "val2" from "sets_key"
        //print_r($this->redis->sunion('sets_key','sets_key_2'));// --No-repeat-- Array ( [0] => new1 [1] => val1 [2] => val2 [3] => new2 ) 
        
        
        
        /**
         * SortedSet
         * 
         * [More]
         * zrem key member [member ...] ---- del memeber
         * zremrangebyrank key 0 1      ---- del member(s) by their rank ,from 0
         * zremrangebyscore key 12 20   ---- del member(s) by their score
         * zrevrange key 1 -1           ---- show members by key in list,reverse showing
         * zrevrangebyscore (reverse of zrangebyscore)
         * zrevrank (reverse of zrank)
         * 
         */
        $this->redis->del('SortedSet');
        $this->redis->zadd('SortedSet',8,'val1',7,'val2');
        //print_r($this->redis->zrange('SortedSet',0,-1));//Array ( [0] => val2 [1] => val1 ) 
        //print_r($this->redis->zrange('SortedSet',0,-1,'WITHSCORES'));//Array ( [0] => val2 [1] => 7 [2] => val1 [3] => 8 )
        //print_r($this->redis->zcard('SortedSet'));//2
        $this->redis->del('z_join_test');
        $this->redis->zadd('z_join_test',100,'John');
        $this->redis->zadd('z_join_test',100,'Tom');
        //print_r($this->redis->zscore('z_join_test','Tom'));//100
        //print_r($this->redis->zincrby('z_join_test',-5,'Tom'));//95 (Will save and show score)
        //print_r($this->redis->zrange('z_join_test',0,-1,'WITHSCORES'));//Array ( [0] => John [1] => 100 [2] => Tom [3] => 100 ) 
        //print_r($this->redis->zcount('z_join_test',99,101));//Will show 2, (min99 max101)
        $this->redis->zadd('z_join_test',60,'Peter');
        //print_r($this->redis->zrangebyscore('z_join_test',0,90,'WITHSCORES'));//Array ( [0] => Peter [1] => 60 ) 
        //print_r($this->redis->zrangebyscore('z_join_test','-inf','+inf'));//Array ( [0] => Peter [1] => John [2] => Tom ) 
        //print_r($this->redis->zrank('z_join_test','Tom'));// 2,key-number-type, because order for them is 60、100、100, and letter "T" make Tom at last





SVN


目录

 [隐藏

[编辑]Command line

  1. svn propset svn:ignore 'templates' . -->remember the '.' at the last. It's for ingore the folder, who is not under version of svn
  2. svn update
  3. svn commit -m "this is the second version~"
  4. svn log -r100:150
  5. svn log -r1:HEAD (Show log ASC, new sort order)
  6. svn diff
  1. svn svn status---------------------------------------show all the list of file who is changed, from svn libraby
  2. svn svn status | grep 'M'----------------------------show modify files



  1. svn commit -m "...." file1.php xx/file2.php   =>Multy-files-commit
  2. svn diff -r532:543 --summarize   =>show list of name of modified files, between 2 version.
  3. svn export svn://192.168.1.105/comname/trunk/secure new_folder/   =>export files without SVN-setting-files to folder.
  4. svn checkout svn://192.168.1.105/comname/trunk/secure new_folder/   =>get svn files with svn-setting-files.



[编辑]Error

What is doing:svn diff --summarize 376:379 svn://192.168.1.105/comname/branches/xxxxxx_newbackend/secure/ 
Error:Cannot mix repository and working copy targets 
Reason:different svn version ,using different Command 
Right:svn diff --summarize -r 376:379 svn://192.168.1.105/comname/branches/xxxxxx_newbackend/secure/ 
Mine:svn version 1.7.5 (r1336830)

more in here

【Conflict】

Resolve #1 Rebuild
  1. cd /var/www/cms/
  2. cd ../
  3. rm -Rf cms/
  4. svn up cms/




[编辑]commands

1. Remove a folder

svn delete http://www.yourrepository.com/svn/folder --message "Deleting"

2. Tag

svn copy http://svn.example.com/project/trunk http://svn.example.com/project/tags/1.0 -m "Release 1.0"





[编辑]Not finished

Edit message after commited, for revision xx

rudon@rudon-Lenovo:~/NetBeansProjects/comname/trunk/cms$ svn propedit -r 633 --revprop svn:log

But it will say error :

svn: E165006: Repository has not been enabled to accept revision propchanges;
ask the administrator to create a pre-revprop-change hook

How to do? Not finished, with some helpful link :

  1. http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-repository-hooks.html
  2. http://home.introweb.nl/d/dodger/svnauthor.html
  3. http://www.microhowto.info/howto/mirror_a_subversion_repository.html
  4. http://www.360doc.com/content/13/0801/14/7811581_304026238.shtml




Git

什么是Git?

百科 

Git是一种版本控制系统。跟svn、cvs是同级的概念。
1.Github是一个网站,给用户提供git服务。这样你就不用自己部署git系统,直接用注册个账号,用他们提供的git服务就可以。 
2.BitBucket是仅次于github的第二大git服务商。



BitBucket使用方法, 本地

(适用于Linux-Ubuntu)

BitBucket 

(在Bitbucket.org上注册帐号)
(创建一个私人仓库,命名为CMS)

/* 添加你电脑的SSH-public-key到BitBucket后台去, 按以下方法,或者参考http://blog.aboutc.net/linux/37/github-bitbucket-connect-via-ssh-keys */
cd ~/.ssh
( 如果返回 "No such file or directory", 说明你目前还没有一个密匙对, 创建方法:ssh-keygen -t rsa -C "your_email@example.com" )
sudo apt-get install xclip
xclip -sel clip < ~/.ssh/id_rsa.pub
( 在BitBucket后台: )
1. 点击右上角"用户头像"
2. 点击下拉菜单中的 "Manage account"
3. 点击左侧 "SSH keys"
4. 点击 "Add key"
5. 粘贴你的密匙到 "Key" 文本区
6. 点击 "Add key"


/* 安装GIT */
sudo apt-get install git

/* 添加Git支持到NetBeans IDE  */
(Tools => Plugins => Click on second tab "Available Plugins" => Search "bitbucket" => select first 2 plugins with "bitbucket" => Install)

/* 开始本地化 */
cd /var/www/
mkdir cms
cd cms
git init
git remote add origin git@@bitbucket.org:comname/cms.git     (注意! path "comname/cms.git" should depends on your repository)
git status

/* 创建文件并提交到本地Git数据库,并Push到公共的BitBucket的仓库中 */
mkdir any-folder
mkdir includes
cd includes
echo 'anycode' >> sys_config.php
cd ../
git status
git commit -m "CMS, init with files."
git push -u origin master

/* 忽略指定文件和目录 */
cd /var/www/cms
echo "any-folder" >> .gitignore
echo "/includes/sys_config.php" >> .gitignore

cp -p includes/sys_config.php includes/DIST-sys_config.php
git rm --cached includes/sys_config.php
rm includes/sys_config.php
git status
git commit -m "CMS, ignore config file."
git push -u origin master

/* 忽略后重新在本地建立这个文件,到时同一个开发组的人都要各自创建 */
cp -p includes/DIST-sys_config.php includes/sys_config.php
nano includes/sys_config.php

( 在Netbeans中导入这个目录,并重新在git中提交和push (因为Netbeans会在根目录创建.netbeans隐形文件夹) )
Done!






BitBucket使用方法, 服务器

(适用于Linux-Ubuntu)

/* Clone */
[--Backup target server first--]
sudo -i
cd /var/www
ll             					   ====> to see the owner for target folder
mv babycms babycms_svn
mkdir babycms
cd babycms
git clone git@bitbucket.org:comname/cms.git .       ====> Look out for "." at the end

/* Update */
cd /var/www
chown -R babycms:babycms babycms/
cp -p babycms_svn/includes/sys_config.php babycms/includes/sys_config.php
cp -p babycms_svn/includes/config.redis.php babycms/includes/config.redis.php
cp -Rp babycms_svn/templates/ babycms/
[-- And other ignored files --]

/* Pull from Remote Git */
cd /var/www/babycms/
git pull 








Bootstrap

目录

 [隐藏

Version

v2.3.2

more

v3.0.3

more


Function

Hover navbar menu Version:3.x

Html

<ul class="nav nav-pills">
    <!-- v1 -->
    <li class="active">
        <a href="http://local_dev.com/multi/category/Home">
            <!---->
            Home
        </a>
    </li>
    <!-- v1 -->
    <li>
        <a href="http://local_dev.com/multi/category/product">
            <!---->
            product
        </a>
    </li>
    <!-- v1 -->
    <li class="dropdown">
        <a class="dropdown-toggle" data-toggle="dropdown">
            <!---->
            Case
        </a>
        <!-- v2 -->
        <ul class="dropdown-menu sub-menu">
            <li class="dropdown">
                <a class="dropdown-toggle" data-toggle="dropdown">
                    <!-- href="http://local_dev.com/multi/category/case-lv2"-->
                    case_lv2
                </a>
                <!-- v3 -->
                <ul class="dropdown-menu sub-menu">
                    <li>
                        <a href="http://local_dev.com/multi/category/case-lv3-1">
                            case_lv3_1
                        </a>
                    </li>
                    <li>
                        <a href="http://local_dev.com/multi/category/case-lv3-3">
                            case_lv3_3
                        </a>
                    </li>
                </ul>
            </li>
        </ul>
    </li>
</ul>


Bootstrap v3 has removed class "sub-menu", they think sub-menu will go out of screen in Mobile.
More css to show the good position for sub-menu (cat level 3 or higher):

.dropdown-menu .sub-menu {
    left: 100%;
    position: absolute;
    top: 0;
    /*visibility: hidden;*/
    margin-top: -1px;
}

Bootstrap v3 had cancel the "hover-and-show-sub-menu" effect,because in Mobile no "hover"
More js to show cat when mouse over menu, (hover)

        $('ul.nav li.dropdown').hover(function() {
          $(this).find('.dropdown-menu:first').stop(true, true).delay(20).fadeIn(20);
        }, function() {
          $(this).find('.dropdown-menu').stop(true, true).delay(20).fadeOut(20);
        });




Hover navbar menu Version:2.x

Html

<ul class="nav nav-pills">
    <li><a href="index.html">Home</a></li>
    <li><a href="#">Acessories</a></li>
    <li class="dropdown">
      <a href="#" data-toggle="dropdown" class="dropdown-toggle">Boy <b class="caret"></b></a>
      <ul class="dropdown-menu" id="menu1">
        <li>
            <a href="#">Shirts <i class="icon-chevron-right pull-right"></i></a>
            <ul class="dropdown-menu sub-menu">
                <li><a href="#">Shirts</a></li>
                <li><a href="#">T-shirts</a></li>
                <li><a href="#">Polo Shirts</a></li>
                <li><a href="#">Tanktop</a></li>
            </ul>
        </li>
        <li><a href="#">Jacket</a></li>
        <li><a href="#">Pants</a></li>
        <li><a href="#">Boxer</a></li>
        <li class="divider"></li>
        <li><a href="#">SweatShirts</a></li>
      </ul>
    </li>
    <li class="dropdown">
      <a href="#" data-toggle="dropdown" class="dropdown-toggle">Girl <b class="caret"></b></a>
      <ul class="dropdown-menu" id="menu1">
        <li><a href="#">Shirts</a></li>
        <li><a href="#">Pants</a></li>
        <li><a href="#">Skirts</a></li>
      </ul>
    </li>
    <li><a href="#">Edition</a></li>
    <li><a href="#">Authorized Dealer</a></li>
    <li><a href="about.html">About</a></li>
    <li class="active"><a href="contact.html">Contact</a></li>
</ul>





Plugin

bootstrap-tagsinput Version:2.x

Download and demo

http://timschlechter.github.io/bootstrap-tagsinput/examples/

Issue: can not Sort the result when using typeahead

bootstrap-tagsinput didn't support method "sorter" in typehead

Try without bootstrap-tagsinput, only typeahead
<script src="jquery.js"></script>
<link rel="stylesheet" href="bootstrap.css" /> 
<script src="bootstrap.js"></script>
<link rel="stylesheet" href="bootstrap-tagsinput.css" /> 
<script src="bootstrap-tagsinput.min.js"></script> 

<div class="well">
    <input id="search" autocomplete="off" placeholder=" Try 'man'"/>
</div>
<script type="text/javascript">
    var colors = ["red", "blue", "Makk","green","manmm","manih", "yellow", "brown man", "black man", "an man", "Zoo man","man","Kman"];
 
    $('#search').typeahead({
        source: colors,
        highlighter: function (item) {
            var regex = new RegExp( '(' + this.query + ')', 'gi' );
            return item.replace( regex, "<u>$1</u>" );
        },
        sorter: function (items){
            //console.write('sss');
            //return items.sort();
            //return items.reverse();
            
            var beginswith = [], caseSensitive = [], caseInsensitive = [], item, aItem;
            while (aItem = items.shift()) {
                //alert(aItem);
                //var item = JSON.parse(aItem);
                var item = aItem;
                if (!item.toLowerCase().indexOf(this.query.toLowerCase())) beginswith.push(item);
                else if (~item.indexOf(this.query)) caseSensitive.push(item);
                else caseInsensitive.push(item);
            }

            return beginswith.concat(caseSensitive, caseInsensitive)
            
            
        }
    });
</script>
Deal with cannot support sorter in tagsinput

<a href="http://datapsyche.wordpress.com/2014/05/28/bootstrap-3-tagsinput-typeahead-problems/">http://datapsyche.wordpress.com/2014/05/28/bootstrap-3-tagsinput-typeahead-problems/</a> 
<a href="http://tatiyants.com/how-to-use-json-objects-with-twitter-bootstrap-typeahead/">http://tatiyants.com/how-to-use-json-objects-with-twitter-bootstrap-typeahead/</a>







PHP


目录

 [隐藏

[编辑]Setting

  1. php.ini
  2. conf.d
  3. apache2.conf
  4. ports.conf
  5. sites-available
  6. sites-enabled
  7. hosts





[编辑]Install From Zero in Ubuntu 12.04

Keywords: install, config php 
[More] http://blog.sina.com.cn/s/blog_4d8502030101bv4h.html

apache2 mysql php

  1. sudo apt-get update
  2. sudo apt-get install apache2
  3. apt-get install mysql-server mysql-client
  4. sudo apt-get install php5 libapache2-mod-php5
  5. sudo apt-get install php5-mysql

cURL GD

  1. sudo apt-get update
  2. sudo apt-get install php5-curl
  3. apt-get install php5-gd

to set utf-8 for mysql

  1. sudo nano /etc/mysql/my.cnf
  2. search "[client]", add "default-character-set=utf8"
  3. search "[mysqld]", add these test:
    default-storage-engine=INNODB
    character-set-server=utf8
    collation-server=utf8_general_ci

Make apache running as different user

  1. sudo apt-get install apache2-mpm-itk
  2. sudo a2enmod mpm_itk
  3. In site setting,like "/etc/apache2/sites-available/local_dev.com", add "AssignUserID USERNAME GROUPNAME" 
    more is in http://www.gaggl.com/2013/11/ubuntu-apache2-run-vhost-as-different-user/


Phing

  1. sudo apt-get update
  2. sudo apt-get install php-pear
  3. sudo pear upgrade-all
  4. sudo pear channel-discover pear.phing.info
  5. sudo pear install --alldeps phing/phing
  6. apt-get install libssh2-1-dev libssh2-php

When got error: 
1.check system variable "$PATH" existing by command "env" or "echo $PATH" 
2.if not,run command "PATH=$PATH:." for one time 
3.or write "export PATH=$PATH:." on bottom of "~/.bashrc" for auto-run. 
4. You also can test like "svn diff --summarize -r 998:999 svn://diskstation/comname/trunk/secure/"


Some tool

  1. sudo apt-get update
  2. sudo apt-get install openssh-server (For SSH)

netbeans

  1. Download netbeans8 from https://netbeans.org/downloads/index.html
  2. Download JDK7 from http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-1880260.html
  3. Install JDK, like http://www.myexception.cn/linux-unix/1465484.html
    if with error about "can not find jdk", use this:
    rudon@rudon-Lenovo:~/Downloads/software$ sudo sh netbeans-8.0-php-linux.sh --javahome /home/rudon/Programs/jdk1.7.0_51/
  4. Look for Install-file named "netbeans-8.0-php-linux.sh", install it like "sudo sh file-name.sh"
  5. Config_the_NetBeans

workbench

  1. Download workbench from http://dev.mysql.com/downloads/tools/workbench/
  2. sudo dpkg -i file-name.deb








[编辑]MOST shit

  1. $xx = new DateInterval('P2Y'); ___OK
  2. $xx = new DateInterval('P2M'); ___OK
  3. $xx = new DateInterval('P2D'); ___OK
  4. $xx = new DateInterval('P2H'); ___Wrong
  5. $xx = new DateInterval('PT2H'); ___OK



[编辑]FEATURE

Set up Virtual Host

Punycode ___Change "domain.com" to "xn--somecharshere.com"

PHPmailer

config the NetBeans

ci Framework

Bootstarp

Tablesorter

Run .sh as ROOT -- to kill process in linux More

PEAR

Phing

htaccess

json_encode does't work when string contents Russian like "domain"

SiteScreenShot_PHP

Tags: page screenshot,site screenshot

readdir_PHP order

Tags: readdir, filesystem, file order

Convert Picture in command line with PHP

Tags: exec(), image magick, terminal, resize

Picture Mime in PHP

Tags: mime, image, image/gif, image/jpeg

Cut string for Wide Characters in PHP

Tags: strlen, mb_strlen, cut with length, utf-8, russia, chinese

Draw thumbnail in PHP

Tags: thumbnail, thumb, image resize, imagecopyresampled()

[编辑]HTML

HTML character entity -- &nbsp; &emsp;   HTML字符实体 More_Chinese More_english


Beautiful 404 pages 
https://maps.googleapis.com/maps/api/geocode/output?parameters


Gray page 

html {
    -webkit-filter: grayscale(100%);
    -moz-filter: grayscale(100%);
    -ms-filter: grayscale(100%);
    -o-filter: grayscale(100%);
    filter: grayscale(100%);
    filter: progid:DXImageTransform.Microsoft.BasicImage(grayscale=1);    
}

[编辑]Codeigniter

Keywords: ci, config , smarty 
[More] http://www.cnmiss.cn/?p=261

using smarty

application is "news"

  1. Download zip file from http://www.smarty.net/download
  2. copy folder "libs" to /ci/news/libraries/ with new name "Smarty"
  3. Create "Cismarty.php" in /ci/news/libraries/, with content (see content in url http://www.cnmiss.cn/?p=261
    Remember to add "parent::__construct();" under "public function __construct(){"
  4. Create "smarty.php" in /ci/news/config/, with content (see content in url http://www.cnmiss.cn/?p=261)
  5. add "Cismarty" into array $autoload['libraries'], in /ci/news/config/autoload.php
  6. Create "MY_Controller.php" in /ci/news/core/, with content (see content in url http://www.cnmiss.cn/?p=261)
  7. Create new controller test.php with code "class Test extends MY_Controller {}"
  8. OK, enjoy it in Controllers 
    $this->assign('test',$data);
    $this->assign('tmp','hello');
    $this->display('test.html');

[编辑]Component

gd2
Intall php5-curl




[编辑]Important experience

Intall php5-curl there're lots of error, finally we need this article, and download one deb file and install it. where's this article?

Date span For example:

Flot -- draw a pic with JQuery

preg --with \n or \n\r

Array Sortting :array_multisort, usort, sort

Javascript#Pass_string-json-arr_from_PHP_to_JS.2C_with_QUOTE 单引号,双引号,数组传送,特殊符号,quote, double quote, js string ,input, array json string, html






[编辑]Useful function

1.Delete folder with contant (recursive)

   public function dirDel($path) {
       $path = rtrim($path, '/');
       $hand = opendir($path);
       while (($file = readdir($hand)) !== false) {
           if ($file == "." || $file == "..")
               continue;
           if (is_dir($path . "/" . $file)) {
               $this->dirDel($path . "/" . $file);
           } else {
               @unlink($path . "/" . $file);
           }
       }
       closedir($hand);
       @rmdir($path);
   }



2.object to array (recursive, in class file)

   function object_to_array($object){
       if( !is_object( $object ) && !is_array( $object ) ){
           return $object;
       }
       if( is_object( $object ) ){
           $object = get_object_vars( $object );
       }
       return array_map( array('______Class name_______','object_to_array'), $object );
   }

object to array (recursive, not in class file)

   function object_to_array($object){
       if( !is_object( $object ) && !is_array( $object ) ){
           return $object;
       }
       if( is_object( $object ) ){
           $object = get_object_vars( $object );
       }
       return array_map( 'object_to_array', $object );
   }


3. xslt

(format xml content with new format)

Content is long, please click "xslt" to jump.


4. rudon-helper

(an useful function)

Keywords: function a(), debug, var_dump() 


5. break and continue in Foreach

you can use break and continue in foreach.

    $array = array(1,2,3,4,5,6,7,8,9);
    foreach ($array as $value)
    {
        if($value == 3){continue;}
        echo $value;
        if ($value == 5){break;}
    }

[编辑]Mistake

1.header

wrong:header("www.baiodu.com"); 
right:header("location:www.baiodu.com");


2.json_NON-ENGLISH

["js_site_array"]=> string(20819) ""2":"yiendovape.com","704":"中文.com""


Echo中文文件名 乱码

其他中文都正常 

<?php
header('Content-Type: text/html; charset=utf-8');
$path_target_dir = 'any-path-for-dir';
$link_target_dir = 'http://yousite.com/any-dir/';
$files = array();
$dh = opendir($path_target_dir);
while ($file = readdir($dh)) {
    $p = $path_target_dir . $file;
    if ($file != '.' && $file != '..' && is_file($p)) {
        $files[] = array(
            'file' => iconv('GBK','UTF-8',$file),
            'ext' => pathinfo($file, PATHINFO_EXTENSION),
            'link' => $link_target_dir . iconv('GBK','UTF-8',$file),
        );
    }
}
?>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<ul>
    <?php foreach ($files as $one): ?>
        <li>
            <a href="<?php echo $one['link']; ?>">
                <?php echo $one['file']; ?>
            </a>
        </li>
    <?php endforeach; ?>
</ul>

[编辑]Problem

can't not write into file and mkdir?

Beacause own of www folder is not the user now apache2 using.

1. so we use set "/etc/apache2/site-a..ble/cms" that

  1. php_value session.save_path /var/www/dev_domainevd/tmp
  2. AssignUserId comnamecms comnamecms

2.but fail when restart apache2?

we need to install module for "AssignUserId",it's to install the package "apache2-mpm-itk".

then we need change the session_path for this module ,restart,okit's me,Rudon. (talk) 11:59, 10 May 2013 (CEST)



[编辑]Problem

1.install magento ,but asked 'PHP extension "mcrypt" must be loaded.' 2.(nomarly)http://www.techytalk.info/install-magento-ubuntu-fix-php-extensions-0-must-be-loaded-error-php-5-4/

 sudo apt-get install php5-mcrypt php5-curl php5-gd
 fail

The following packages have unmet dependencies:

php5-curl : Depends: phpapi-20100525
            Depends: php5-common (= 5.4.6-1ubuntu1.2) but 5.3.10-1ubuntu3 is to be installed
php5-gd : Depends: phpapi-20100525
          Depends: php5-common (= 5.4.6-1ubuntu1.2) but 5.3.10-1ubuntu3 is to be installed
php5-mcrypt : Depends: phpapi-20100525

E: Unable to correct problems, you have held broken packages.


 so, sudo apt-get install php5-common=5.4.6-1ubuntu1.2
 done
 now we can "sudo apt-get install php5-mcrypt php5-curl php5-gd"

3.done

4.Disaster!!!

 php can't not work!
 "__Whoops, it looks like you have an invalid PHP version.__", and the other old vitrul host also die~

5.Why?

 beacause "sudo apt-get install php5-common=5.4.6-1ubuntu1.2" ,wrong version of ubuntu!!!!

6.how to fix? sudo apt-get remove php5-common=5.4.6-1ubuntu1.2 sudo apt-get install apache2-mpm-itk sudo apt-get install libapache2-mod-php5 sudo apt-get install php5 sudo apt-get install php5-common sudo apt-get install php5-mysql


ok ! but magento also die~

7........waitting for Fix it!!






Config the NetBeans



[编辑]Speed up

  1. http://wiki.netbeans.org/FaqNetbeansConf
  2. http://hi.baidu.com/beiqf/item/7a2e1f8833375ac599255fd5
  3. http://tieba.baidu.com/p/1722225498


[编辑]Support "Short tag" for PHP

  1. Right click your project title ,in "Files" tag
  2. click property
  3. Check out "Support short tag"


[编辑]Missing "Refresh Folder" on right click

  1. Tools
  2. Options
  3. Miscellaneous
  4. Files
  5. Disable “Enable auto-scanning of sources”




Set up Virtual Host





Dependence


.....


Config in apache


  1. /etc/php5/apache2/php.ini
  2. /etc/apache2/apache2.conf
  3. /etc/apache2/ports.conf
  4. /etc/apache2/sites-available/xxx
  5. /etc/apache2/sites-enabled/xxx
  6. /etc/hosts

目录

 [隐藏
apache2.conf

(Have a look)

#       /etc/apache2/
#       |-- apache2.conf
#       |       `--  ports.conf
#       |-- mods-enabled
#       |       |-- *.load
#       |       `-- *.conf
#       |-- conf.d
#       |       `-- *
#       `-- sites-enabled
#               `-- *


ports.conf
NameVirtualHost *:80
Listen 80


hosts
127.0.0.1       localhost
192.168.1.104   secure.babycms.com
sites-available/xxx
    <VirtualHost *:80>
            ServerName xn--tjVz18B5xP7pJ.com           #中文域名的punycode编码
            ServerAlias www.xn--tjVz18B5xP7pJ.com      #中文域名的punycode编码
            DocumentRoot /usr/local/www/website/huojiu
            SuexecUserGroup huojiu huojiu
            ErrorLog "/usr/local/www/website/huojiu/error_log"
            CustomLog "/usr/local/www/website/huojiu/access_log" common
    </VirtualHost>


sites-enabled/xxx

make a link from sites-available,like:
sudo ln -s ../sites-available/xxx xxx





Punycode


目录

 [隐藏

[编辑]Introduce

[编辑]More intro

en:

  1. http://en.wikipedia.org/wiki/Punycode#Punycode

chinese:

  1. http://zh.wikipedia.org/wiki/Punycode#Punycode
  2. http://baike.baidu.com/view/1704366.htm


[编辑]Translate class in PHP

PHP:Punycode Library - Google Code link


[编辑]Translate online

http://www.webmasterhome.cn/tool/punycode.asp


[编辑]Example

  1. ЯлюблюКитай.com ----------- xn--80abvfceb2dxfcg.com
  2. भगवान.com ------------------------- xn--31b8an7a7b.com
  3. 神.com ----------------------------- xn--w6c7bp6cl7c7a4e.com
  4. ພຣະເຈົ້າ.com --------------------- xn--zv4b.com
  5. 신.com ----------------------------- xn--gecda3db9c0cc.com
  6. દેવદેવતા.com ----------------------xn--bg-5ja.com
  7. Bóg.com --------------------------- xn--gu-xja.com



[编辑]How to controller






Config the NetBeans



[编辑]Speed up

  1. http://wiki.netbeans.org/FaqNetbeansConf
  2. http://hi.baidu.com/beiqf/item/7a2e1f8833375ac599255fd5
  3. http://tieba.baidu.com/p/1722225498


[编辑]Support "Short tag" for PHP

  1. Right click your project title ,in "Files" tag
  2. click property
  3. Check out "Support short tag"


[编辑]Missing "Refresh Folder" on right click

  1. Tools
  2. Options
  3. Miscellaneous
  4. Files
  5. Disable “Enable auto-scanning of sources”



Ci Framework

目录

 [隐藏

Questions

1.In controller ,can't use $this->load->model('xx')? You should parent::__construct() in __construct.
2.Can't use $this->db->xx(xx)? same as no.1


Good example

   public function get_controller() {
       return $this->router->class;
   }
   public function get_model() {
       return $this->router->method;
   }


[编辑]easy DB

---More in the url---

  1. $query = $this->db->get_where('sites',array('id'=>$list ['sid']),1);
  2. foreach($query->result() as $row){
  3.     $_SESSION ['xx'] = $row->domain_name;


[编辑]new info

load the common variables and function ,with auto-run model. for all models and controllers

  1. application->config->autoload.php ==>$autoload['model'] = array('common_model');
  2. application->models ==>create file "common_model.php"
  3. fill with content:class Common_model extends CI_Model {public $xx; function get_xxx (){....} }

and how to use?

  1. in the controllers, we use this: var_dump($this->common_model->get_xx());die;
  2. in the models,we use this:var_dump($this->common_model->get_xx());die;



DB

$this->db->where('idproduct', $product_id); 
$this->db->update('pre_category_product', array('on_sale'=>'1')); 

$this->db->select('title')->from('mytable')->where('id', $id)->limit(10, 20); 
$query = $this->db->get(); 

       Multi-Table
       $this->db->select('*');
       $this->db->from('pre_category_product a');
       $this->db->where('a.idproduct',$pid);
       $this->db->join('pre_product_ext_attribute b', 'a.idproduct = b.idproduct');
       $query = $this->db->get();


[编辑]old info

1 where to put the js,css,img ?

2 how to load the js..?

3 == how to hide index.php? == More

  1. Create file ".htaccess" under the root path of site
  2. fill with this contant:


RewriteEngine On

RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-f

RewriteCond %{REQUEST_FILENAME} !-d

RewriteCond $1 !^(index\.php|assets|images|js|css|robots\.txt)

RewriteRule ^(.*)$ index.php/$1 [L]



more:

Chinese:Let's go~

English:Let's go~


4 No pemisession to load the resource?

5 how to auto load the libray "session"?



Tablesorter


[编辑]Example

sites_and_paypal_mails


[编辑]code

   <script src="assets/js/jquery.tablesorter.min.js"></script>
   <script>
       {literal}
       $(document).ready(function() 
           { 
               $("#sorttingtable_new").tablesorter(); 
           }
       );
       {/literal}
   </script>
   ....
   <table class="table table-bordered table-striped" id='sorttingtable_new'>
   ....



[编辑]No sort line

if you didn't want to sort first and 5th <th>, just change

  $("#sorttingtable_new").tablesorter(); 

to

  $("#sorttingtable_new").tablesorter({headers:{0:{sorter:false},4:{sorter:false}}});


Phing

目录

 [隐藏
[编辑]============== Principle

1.[build] read svn,get lastest version,get the changing file list,and copy files to folder "build", by build.sh

2.[send] according to folder "build", send the files to server ,by phing



[编辑]============== How to install

follow this ==> http://www.phing.info/trac/wiki/Users/Download

but need pear.how to fix it?

  1. sudo apt-get install php-pear
  1. pear channel-discover pear.phing.info
  1. pear install phing/phing

[to check]when you write "phing" ,it will notice that:Buildfile: build.xml does not exist!


[编辑]============== How to use

<1> [add $PATH]

  1. nano ~/.profile

[add this command in tail]

  1. #someone add . to PATH
  2. PATH="$PATH:."


<2> [Make ~/.profile runs]

  1. . ~/.profile


<3> [Go to deploy folder]

  1. cd /home/rudon/NetBeansProjects/with_secure/deploy/



<4> [Check build.sh get the right to execute]

  1. ls -alrt

[if build.sh no right to be -x]

  1. chmod +x build.sh


<5> [svn update]

  1. svn update

<6> [How to run phing? see at README.TXT]

  1. cat README.TXT

[Be Careful, last sentense "prd.server.properties" is the real one,Please use "phing -Dpropertiesfile=dev.server.properties -Dfrom_svn_rev=268 "]


<7> [Go!]

  1. phing -Dpropertiesfile=dev.server.properties -Dfrom_svn_rev=999999999




[编辑]============== Problems

...

[编辑]============== More info

...




Htaccess

目标输入:http://babycms.com/pure/con/model/
目标跳转:http://babycms.com/ci/index.php/con/mod/





-------------------- Case 1
规则:
RewriteRule ^(.*)/ha/$  $1/admin/inde.kl [L]
例子:
http://babycms.com/admin/ha/
链接:
/admin/admin/inde.kl






-------------------- Case 2
规则:
RewriteRule ^(.*)/ha/$  $1/admin/inde.kl [L]
例子:
http://babycms.com/admin/ha/
链接:
/admin/admin/inde.kl





SiteScreenShot PHP


目录

 [隐藏

Use

To get screenshot picture for one page, by url.
Just like: we need different style with picture, for choose style for one site.
So it need to use PHP to save the screenshot for existing-beautiful-site.


Introduce

  1. People submit to save style,with picture as site-screen-shot.
  2. Server(PHP) get this request, know URL to take picture.
  3. Run main php script to link to API "STW" ---for "takeScreenShotOnline" --- hosting by http://www.shrinktheweb.com/
  4. Get small picture comes from API.
  5. Save and use in PHP.



Source Script



Account

Access Key: 4e435345dasa65basdas23dcas6752342dcfgdf80e004df028
Secret Key: d333346586797890seasd3 (or you sign up one new.)



More

1. Pictures are 200*150, you need pay if you want bigger.
2. There's limit of quantity of picture for every month and day. 3. Now we are Looking for other way to create picture as screenshot,not using API but runing GD library in PHP.





Readdir PHP


目录

 [隐藏

[编辑]Introduce

For read list of files or dir, from target path.(Not Recursive)

if ($handle = opendir('.')) {
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {
            echo "$file\n";
        }
    }
    closedir($handle);
}


[编辑](Fun)Target

To know why the order of result, is not using alphabetical order, but a mass.
(In fact, it's readding in order by filesystem. ----- you can use "ls -U" to check. )


[编辑](Fun)How to do?

  1. Read Manual,says that it's in The entries are returned in the order in which they are stored by the filesystem. inhttp://php.net/manual/en/function.readdir.php
  2. So try terminal "ls" or "ls -alrt" in Linux, but fail, not the same order.
  3. (You should check how to get real order in filesystem, but I just think it's most standrad way by "ls".)
  4. So I visit "Stack Overflow" for answer, in "http://stackoverflow.com/questions/541510/php-readdir-not-returning-files-in-alphabetical-order"
  5. It should be "ls -U" to get order by filesystem.( BTW: ls -U lists the files in the order their directory entries are stored in the directory. – Bodo Thiesen Feb 12 '09 at 14:44 )
  6. That's it.


[编辑](Fun)Learn the way

  1. Need try terminal when you know filesystem. (filesystem => ternimal in Ubuntu)
  2. Should check command to get "real order in filesystem with ls". (real order => check ls command, not only think ls -alrt is ok.)
  3. Be careful of details in "Stack Overflow", even you dont know the english word, check it.



Convert Picture in command line with PHP

目录

 [隐藏

Target

convert or resize pictures with php and command line, in linux.


where are we

  1. Ubuntu system
  2. PHP 5



Tools will use

  1. image magick


Order

Install image magick

  1. Download from http://www.imagemagick.org/script/install-source.php#unix
  2. install it.

Put files

  1. mkdir /home/work/products
  2. copy all images to /home/work/products, with folders like:
    /home/work/products/iphone/1.jpg
    /home/work/products/iphone/2.jpg
    /home/work/products/nokia/xx.png
    ...
  3. create PHP file, /home/work/process.php, and set the php code.
  4. Run it in terminal: rudon@rudon-Lenovo:~/work$ php process.php


Code

<?php
    /**
     * Target
     * 
     * 1.get list 
     * 2.convert
     */

    $limitMaxFileSize = true;
    $maxFileSize = 100; // KB
    
    $limitAllowedExt = false;
    $allowedExt = array('jpg', 'png', 'bmp');

    // Add '/'
    $convert = array();
    $arr = array();
    //$path = dirname(__FILE__) . '/products/';
    $path = 'products/';
    $path = rtrim($path, '/') . '/';

    // Go
    $handle = opendir($path);
    while (false !== ($folder = readdir($handle))) {
        if ($folder != '.' && $folder != '..') {
            if( is_dir($path. $folder)){
                $one_pro = rtrim($path. $folder, '/') . '/';
                $handle2 = opendir($one_pro);
                while (false !== ($file = readdir($handle2))) {
                    if ($file != '.' && $file != '..' && is_file($one_pro. $file)) {
                        $pic_path = $one_pro. $file;
                        
                        $filesize = intval(filesize($pic_path) / 1024);
                        if($limitMaxFileSize && $maxFileSize > $filesize){
                            // dont convert
                            
                        } else {
                            $pathinfo = pathinfo($pic_path);
                            if(!$limitAllowedExt || ($limitAllowedExt && in_array(strtolower($pathinfo['extension']), $allowedExt))){
                                $pathinfo['fileSize'] = $filesize;
                                $convert[] = $pathinfo;
                            }
                        }
                    }
                }
                closedir($handle2);
            }
        }
    }
    closedir($handle);

 
    /* Ready convert */
    if(count($convert)){
        $convert_list = array();
        foreach($convert as $one){
            $one_path = $one['dirname'].'/'.$one['basename'];
            $convert_list[] = $one_path;
        }
        
        /* Go */
        foreach($convert_list as $one){
            $com = "convert {$one} -resize 500x {$one}";
            exec($com);
        }
    }
    die;
?>



Picture Mime in PHP

<<<<<more>>>> http://php.net/manual/zh/function.image-type-to-mime-type.php




                switch($mime){
                    case 'image/gif':
                        $ext = 'gif';
                        break;
                    case 'image/jpeg':
                        $ext = 'jpg';
                        break;
                    case 'image/png':
                        $ext = 'png';
                        break;
                    case 'application/x-shockwave-flash':
                        $ext = 'swf';
                        break;
                    case 'image/psd':
                        $ext = 'psd';
                        break;
                    case 'image/bmp':
                        $ext = 'bmp';
                        break;
                    case 'image/tiff':
                        $ext = 'tiff';
                        break;
                    
                    default:
                        break;
                }



Cut string for Wide Characters in PHP

Main-function

    /* Cut string with UTF-8 encoding */
    function utf8Substr($str, $from, $len) {
        return preg_replace('#^(?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$from.'}'.
               '((?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$len.'}).*#s','$1',$str);
    }


How to use

header('Content-Type:text/html; charset=utf-8');
$en = "abcde";
$zn = "你好,我是中文";
$ru = "Японский";

$len = mb_strlen($en);//5
$len = mb_strlen($zn);//7
$len = mb_strlen($ru);//8

echo utf8Substr($en, 0, 4); // abcd
echo utf8Substr($zn, 0, 4); // 你好,我
echo utf8Substr($ru, 0, 4); // Япон



Draw thumbnail in PHP


目录

 [隐藏

Feature

  1. Resize for pic
  2. Draw thumbnail
  3. Save thumbnail



Usage

  1. Include function at below
  2. $bool = img2thumb($src_img, $dst_img, $width=150, $height=150, $cut=0, $proportion = 0, $quality = 100);
  3. Check new file



Link

http://www.open-open.com/lib/view/open1337330620354.html


Function

/**
 * 生成缩略图
 * @author yangzhiguo0903@163.com
 * @param string     源图绝对完整地址{带文件名及后缀名}
 * @param string     目标图绝对完整地址{带文件名及后缀名}
 * @param int        缩略图宽{0:此时目标高度不能为0,目标宽度为源图宽*(目标高度/源图高)}
 * @param int        缩略图高{0:此时目标宽度不能为0,目标高度为源图高*(目标宽度/源图宽)}
 * @param int        是否裁切{宽,高必须非0}
 * @param int/float  缩放{0:不缩放, 0<this<1:缩放到相应比例(此时宽高限制和裁切均失效)}
 * @param int        保真比例(0-100)
 * @return boolean
 */
function img2thumb ($src_img, $dst_img, $width = 75, $height = 75, $cut = 0, $proportion = 0, $quality = 100)
{
    if(!is_file($src_img))
    {
        return false;
    }
    
    if(!is_numeric($quality) || $quality < 0 || $quality > 100){
        $quality = 100;
    }
    
    
    $infodst = pathinfo($dst_img);
    $dst_file_name = $infodst['basename'];
    $ot = strtolower($infodst['extension']);
    
    $otfunc = 'image' . ($ot == 'jpg' ? 'jpeg' : $ot);
    $srcinfo = getimagesize($src_img);
    $src_w = $srcinfo[0];
    $src_h = $srcinfo[1];
    $type  = strtolower(substr(image_type_to_extension($srcinfo[2]), 1));
    $createfun = 'imagecreatefrom' . ($type == 'jpg' ? 'jpeg' : $type);

    $dst_h = $height;
    $dst_w = $width;
    $x = $y = 0;

    /**
     * 缩略图不超过源图尺寸(前提是宽或高只有一个)
     */
    if(($width> $src_w && $height> $src_h) || ($height> $src_h && $width == 0) || ($width> $src_w && $height == 0))
    {
        $proportion = 1;
    }
    if($width> $src_w)
    {
        $dst_w = $width = $src_w;
    }
    if($height> $src_h)
    {
        $dst_h = $height = $src_h;
    }

    if(!$width && !$height && !$proportion)
    {
        return false;
    }
    if(!$proportion)
    {
        if($cut == 0)
        {
            if($dst_w && $dst_h)
            {
                if($dst_w/$src_w> $dst_h/$src_h)
                {
                    $dst_w = $src_w * ($dst_h / $src_h);
                    $x = 0 - ($dst_w - $width) / 2;
                }
                else
                {
                    $dst_h = $src_h * ($dst_w / $src_w);
                    $y = 0 - ($dst_h - $height) / 2;
                }
            }
            else if($dst_w xor $dst_h)
            {
                if($dst_w && !$dst_h)  //有宽无高
                {
                    $propor = $dst_w / $src_w;
                    $height = $dst_h  = $src_h * $propor;
                }
                else if(!$dst_w && $dst_h)  //有高无宽
                {
                    $propor = $dst_h / $src_h;
                    $width  = $dst_w = $src_w * $propor;
                }
            }
        }
        else
        {
            if(!$dst_h)  //裁剪时无高
            {
                $height = $dst_h = $dst_w;
            }
            if(!$dst_w)  //裁剪时无宽
            {
                $width = $dst_w = $dst_h;
            }
            $propor = min(max($dst_w / $src_w, $dst_h / $src_h), 1);
            $dst_w = (int)round($src_w * $propor);
            $dst_h = (int)round($src_h * $propor);
            $x = ($width - $dst_w) / 2;
            $y = ($height - $dst_h) / 2;
        }
    }
    else
    {
        $proportion = min($proportion, 1);
        $height = $dst_h = $src_h * $proportion;
        $width  = $dst_w = $src_w * $proportion;
    }

    $src = $createfun($src_img);
    $dst = imagecreatetruecolor($width ? $width : $dst_w, $height ? $height : $dst_h);
    $white = imagecolorallocate($dst, 255, 255, 255);
    imagefill($dst, 0, 0, $white);

    if(function_exists('imagecopyresampled'))
    {
        imagecopyresampled($dst, $src, $x, $y, 0, 0, $dst_w, $dst_h, $src_w, $src_h);
    }
    else
    {
        imagecopyresized($dst, $src, $x, $y, 0, 0, $dst_w, $dst_h, $src_w, $src_h);
    }
    
    
    
    /* Draw picture */
    //header('Content-Type: image/jpeg');
    //$otfunc($dst, null, $quality);
    
    /* Save into file */
    $otfunc($dst, $dst_file_name, $quality);
    
    imagedestroy($dst);
    imagedestroy($src);
    return true;
}



Intall php5-curl

[编辑]wrong

  1. sudo apt-get install php5-curl
The following packages have unmet dependencies:
 php5-curl : Depends: phpapi-20100525
             Depends: php5-common (= 5.4.9-4ubuntu2.1) but 5.3.10-1ubuntu3 is to be installed
E: Unable to correct problems, you have held broken packages.


[编辑]right

  1. go to https://launchpad.net/ubuntu/precise/amd64/php5-curl/5.3.10-1ubuntu3
  2. download php5-curl_5.3.10-1ubuntu3_amd64.deb
  3. use terminal, go to find where you set the deb file
  4. sudo dpkg -i php5-curl_5.3.10-1ubuntu3_amd64.deb
  5. Finished!




Date span


where is it?



CLass File: /cms_root/admin/classes/class.dateandtime.php


how to use?



Example: http://babycms.com/admin/index.php?module=dashboard&action=dashboard_top

Script File : /cms_root/admin/classes/dashboard.class :: ajax_get_data_by_time()

Example code: _____

  1. $time_span = $this->data_and_time->get_time_span($from, $to);
  2. $time_span_count = count($time_span);
  3. for ($i=0; $i<$time_span_count; $i++) {
  4. if($i != $time_span_count-1){
  5. $next = $i+1;
  6. $real_time_span[] = array(
  7. 'from' => $time_span[$i],
  8. 'to' => $time_span[$next]
  9. );
  10. }
  11. }




[编辑]Building



Building





Array Sortting


目录

 [隐藏

Asc, keep key, 1 level array

   asort($array);


Desc, keep key, 1 level array

   arsort($array);


Asc, rebuild key, 1 level array

   sort($array);


Desc, rebuild key, 1 level array

   rsort($array);



[编辑]multi-level Example

<?php

$arrnum = array(
    '7' => array('id' => 5, 'name' => 1, 'age' => 7),
    '8' => array('id' => 2, 'name' => 3, 'age' => 4),
    '9' => array('id' => 8, 'name' => 10, 'age' => 5),
    '10' => array('id' => 1, 'name' => 2, 'age' => 2)
);

$arr = array(
    'a' => array('id' => 5, 'name' => 1, 'age' => 7),
    'b' => array('id' => 2, 'name' => 3, 'age' => 4),
    'c' => array('id' => 8, 'name' => 10, 'age' => 5),
    'd' => array('id' => 1, 'name' => 2, 'age' => 2)
);



    function multi_array_sort($multi_array, $sort_key, $sort = SORT_DESC, $case_sensitive = true) {
        if (is_array($multi_array)) {
            foreach ($multi_array as $kkk=>$row_array) {
                if (is_array($row_array)) {
                    if(!$case_sensitive){
                        $low_case  = strtolower($row_array[$sort_key]);
                    } else {
                        $low_case  = $row_array[$sort_key];
                    }
                    $key_array[$kkk] = $low_case;
                } else {
                    return false;
                }
            }
        } else {
            return false;
        }
        //print_r($key_array);die;
        array_multisort($key_array, $sort, $multi_array);
        return $multi_array;
    }

//处理

echo '<pre/>';
print_r(multi_array_sort($arrnum, 'age'));
exit;

/* when string is not case sensitive */
multi_array_sort($arr, 'keyname', SORT_STRING, false);

[编辑]Be Careful

if your source array is using Number-Keys, this function will delete them and to use 0,1... Number-Keys











Wiki


1.SideBar Sidebar

2.Create Article under top menu CreateArticle

3.Create Link in article CreateLink

4.picture [upload and link] -- English help Chinese help

5. Give edit right to user GiveEditRightWiki


[编辑]Wiki suppost HTML tags!

tables

variablesvalue
namewiki
sexgirl
age99
nameRudon


<table border='1' style="border: green 2px solid; width:150px;">
    <tr style="background:gray; color:white;">
        <td>variables</td>
        <td>value</td>
    </tr>
    <tr>
        <td>name</td>
        <td>wiki</td>
    </tr>
</table>

Images 
<img src="logo_white.png"/>





目录

 [隐藏
  • Version
    • 1.1 function
    • 1.2 function
    • 1.3 function
  • Function
    • 2.1 function
    • 2.2 function
    • 2.3 function
<h1><b>Version</b></h1>
<h2>function</h2>
<h2>function</h2>
<h2>function</h2>



<h1><b>Function</b></h1>
<h2>function</h2>
<h2>function</h2>
<h2>function</h2>



Sidebar

[编辑]How to Create Menu

1、Go to Cotrol Panel MediaWiki:Sidebar

Format: "http://rudon.net/wiki/index.php?title=MediaWiki:Sidebar"

2、Edit this page

3、Add some Nav title with this format (** url|nav name)

4、Preview and Save



CreateArticle

0.Let's click the "edit" button after you enter some nav~

1.Then, Type some text what you like;


2.How to make new line?

-- Just press "Enter" two times ,to get one new line

3.How to make link?

-- Outsides link: click button "Ab" to make a link inside wiki~ ;

-- Inside like: "A" is to make a link to outside

4....







====================== End ===========================






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Rudon滨海渔村

花的越多,赚得越多...

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值