首页 > 代码库 > lamp开发基础

lamp开发基础


一.php速度入门及mysql基础
1。php与shell与perl基本语法及一些常见处理的比较
比较方面:变量,字符串,数组,判断,循环,函数 ,命令行参数,时间,文件,数组操作,调试
比较项目php   shell   perl  
变量弱类型语言,变量可以任意代表任何类型
$age = 13;
$name = "pengpeng";
$money = 150.53;
$isBoy = true;

这里等号前后空格是为了整齐好看。

例子
<?php
$age = 13;
print $age;
?>
运行方式
php t.php
弱类型语言
age=13
name="pengpeng"
money=150.53
isBoy=true

注意:这里等号前后不能空格,shell的语法规则导致。
再次调用变量的时候需要加$ 符号。
例子

#!/bin/bash
age=13
echo $age
运行方式
sh t.sh


shell的逻辑变量样例
#!/bin/bash
test1=true
if  $test1 ; then
echo "ok";
fi
test2=false;
if  $test2 ; then
    echo "false";
fi
弱类型语言
my $age = 13;
my $name = "pengpeng";
my $money = 150.53;
my $isBoy = true; 
例子
#! /usr/bin/perl
my $age = 13;
print $age;
运行方式
perl t.pl
字符串及连接$str1 = "str1";
$str2 = "str2";
$str3 = $str1.$str2;
$str4 = $str1."test".$str2;
print $str3."\n";
print $str4."\n";
#!/bin/bash
str1="str1";
str2="str2";
str3=$str1$str2; #直接放到一起即可连接
str4=$str1"test"$str2; #直接放到一起即可连接
echo $str3;
echo $str4;
#! /usr/bin/perl
my $str1 = "str1";
my $str2 = "str2";
my $str3 = $str1.$str2;
my $str4 = $str1."test".$str2;
print $str3."\n";
print $str4."\n";
数组遍历<?php
$colorArr = array(‘red‘,‘blue‘,‘green‘,‘yellow‘);
foreach ($colorArr as $color){
     print  $color."\n";
}
?>
#!/bin/bash
colorArr=(‘red‘ ‘blue‘ ‘green‘ ‘yellow‘)
for  i  in "${colorArr[@]}" ; do
     echo $i
done
#! /usr/bin/perl
my @colorArr = (‘red‘,‘blue‘,‘green‘,‘yellow‘);

foreach $color(@colorArr)
{
     print $color."\n";
}
哈希数组及遍历<?php
$ageArr = array(‘zhang‘=>13,‘li‘=>14,‘wang‘=>15,‘qian‘=>12);
foreach ($ageArr as $name => $age){
     print "$name = $age\n";
}
?>
不知道#! /usr/bin/perl
my %ageArr = (‘zhang‘=>13,‘li‘=>14,‘wang‘=>15,‘qian‘=>12);

 foreach my $name(keys %ageArr)
 {
          print "$name = ".$ageArr{$name}."\n";
 }
条件判断<?php
$user=`whoami`;
if($user != "work" || ! isset($argv[1]) )
{
        echo "必须是work账户,同时为./release.sh sss 或者 ./release.sh hhhh";
            exit ;
}

?>
1.逻辑变量判断
2.逻辑表达式判断
user=`whoami`;
if [ $user != "work" ] || [ ! $1 ];then
    echo "必须是work账户,同时为./release.sh sss 或者 ./release.sh hhhh";
    exit 0;
fi
#! /usr/bin/perl
 my $user=`whoami`;
 if($user != "work" || ! defined($ARGV[0]) )
 {
             print "必须是work账户,同时为./release.sh sss 或者 ./release.sh hhhh";
                         exit ;
 }
循环<?php
for($i=0;$i<10;$i++)
{
     print $i."\n";
}
?>
for((i=1;i<10;i++))
do
echo $i
done
for($i=0;$i<10;$i++)
{
     print $i."\n";
函数定义<?php
function send_content_mail($maillist, $subject, $content)
{
     $headers = "MIME-Version: 1.0" . "\r\n";
     $headers .= "Content-type:text/html;charset=utf-8" . "\r\n";
     $headers .= ‘From: stat@mmm.com‘ . "\r\n";
     $subject = "=?UTF-8?B?" . base64_encode($subject) . "?=";
     $content.="<center>如有疑问,咨询管理员曾文杰wenjiezeng@mmm.com</center";
      mail($maillist, $subject, $content, $headers);
}

send_content_mail("wenjiezeng@mmm.com", "test", "testMail");
?>
 #!/bin/sh 
 function send_content_mail()
 {
    echo $3."有问题请咨询wenjiezeng@mmm.com" |mail -s "$2"  $1
 }
 send_content_mail "wenjiezeng@mmm.com" "testMail" "test";
#!\usr\bin\perl -w
use Net::SMTP;

sub send_content_mail($$$)
{
    my $to_mail = shift;
    my $subject = shift;
    my $content = shift;
    $smtp = Net::SMTP->new(‘127.0.0.1‘);    #邮件服务器地址
    $smtp->mail(‘stat@mmm.com‘);                 #发件人
    $smtp->to($to_mail);
    $smtp->data();
    $smtp->datasend("From: <stat\@mmm.com>\n");
    $smtp->datasend("To: ".$to_mail."\n" );

    $smtp->datasend("Subject: ".$subject."\n");   #主题

    $smtp->datasend($content."\n");
    $smtp->dataend();
    $smtp->quit;
}

send_content_mail("wenjiezeng\@mmm.com","testpl","testplcontent");
命令行参数$argv
<?php
    print_r($argv);
?>

php t.php 1 2 3
Array
(
    [0] => t.php
    [1] => 1
    [2] => 2
    [3] => 3
)
$1 $2 $3

 #!/bin/sh
 echo $1;
 echo $2;
 echo $3;

[root(0)@nxlog 13:37:44 ~]# sh t.sh 1 2 3
1
2
3
@ARGV

#!\usr\bin\perl -w
use Data::Dumper;
print Dumper(@ARGV);

[root(0)@nxlog 13:43:11 ~]# perl t.pl  1 2 3
$VAR1 = ‘1‘;
$VAR2 = ‘2‘;
$VAR3 = ‘3‘;
时间处理
          date_default_timezone_set(‘PRC‘);
$today = date("Y-m-d",time());
$yesterday =  date("Y-m-d",time()-86400);
$yesterday = date("Ymd",strtotime("-1 day"));
today=`date +%Y%m%d`;
yesterday=`date  +"%Y%m%d" -d "-1 days"`;
echo $today;
echo $yesterday;
#!/usr/bin/perl -w
use POSIX qw(strftime);
my $today = strftime("%Y%m%d", localtime(time ));
my $yesterday = strftime("%Y%m%d", localtime(time - 24*3600));#获取昨天的日期
print $today."\n";
print $yesterday."\n";

小文件
按行处理
$cc = file_get_contents($file);
$tmpArr = preg_split(‘/\r|\n/‘,$cc,-1,PREG_SPLIT_NO_EMPTY);
foreach($tmpArr as $line)
{
     //do with $line
}
for i in `cat list`
do
### $i is line
done

open(FILE,"<","list")||die"cannot open the file: $!\n";
@linelist=<FILE>;
foreach $eachline(@linelist){
    print $eachline;
}
close FILE;
大文件逐行<?php
$handle = @fopen("/tmp/inputfile.txt", "r");
if ($handle) {
    while (!feof($handle)) {
        $buffer = fgets($handle, 4096);
        echo $buffer;
    }
    fclose($handle);
}
?>  
shell尽量不要处理大文件,会很慢很耗费资源my $logFile = "list";
if(open(FH, ‘<‘, $logFile))
{
     while(<FH>)
     {
        chomp;
        print $_."\n";
     }

     close FH;
}

数组函数arsort()  asort() count() krsort() ksort()这个我不知道shift()  push() pop() sort()
调试函数var_dump() 
print_r()
这个我不知道#!\usr\bin\perl -w
use Data::Dumper;
print Dumper(@ARGV); 
字符替换$file = preg_replace(‘/\.less$/‘,‘.css‘,$file);file=`echo "$file"|sed s/\.less/.css/`$file =~ s/\.less$/css/

2.再次强调编码规则

1)无论变量还是函数的命名
都采用第一个单词小写,后面的单词首字母大写的规则
例如 php shell perl 都这样

2)超过100行代码的函数,尽量归类命名拆分为多个函数【单个函数压制在百行内】 


3. 收集一些常用的函数 
输入192.168.5.12/26 返回所有ip
function iprange($ip,$mask=24,$return_array=FALSE) {
    $corr=(pow(2,32)-1)-(pow(2,32-$mask)-1);
    $first=ip2long($ip) & ($corr);
    $length=pow(2,32-$mask)-1;
    if (!$return_array) {
    return array(
        ‘first‘=>$first,
        ‘size‘=>$length+1,
        ‘last‘=>$first+$length,
        ‘first_ip‘=>long2ip($first),
        ‘last_ip‘=>long2ip($first+$length)
        );
    }
    $ips=array();
    for ($i=0;$i<=$length;$i++) {
        $ips[]=long2ip($first+$i);
    }
    return $ips;
}

$test1=iprange(‘192.168.5.12‘,26,TRUE);
//$test2=iprange(‘221.1.1.0‘,24,TRUE);
print "192.168.5.12/26<br>";
  print_r($test1 ) ;

?>
 
在当前路径输出日志
     function addLog($msg)
     {
          $now_date_day = date("Ymd", time());
          $logtime = date("Ymd H:i:s", time());
          $fileLog = dirname(__FILE__)."/log/myLogRS".$now_date_day.".txt";
          file_put_contents($fileLog,"[".$logtime."]".$msg."\n",FILE_APPEND);
     }
html2txt
     function html2txt($document){
          $search = array(‘@<script[^>]*?>.*?</script>@si‘,  // Strip out javascript
                            ‘@<style[^>]*?>.*?</style>@siU‘,    // Strip style tags properly
                            ‘@<[\/\!]*?[^<>]*?>@si‘,            // Strip out HTML tags
                            ‘@<![\s\S]*?--[ \t\n\r]*>@‘,        // Strip multi-line comments including CDATA
                            ‘@&nbsp;@‘
          );
          $text = preg_replace($search, ‘‘, $document);
          return $text;
     }
判断是否内网ip
     function is_i_ip($hostsearch) {
         if (preg_match("/^127\./", $hostsearch)) {
          return true;
         }

         if (preg_match("/^10\./", $hostsearch)) {
          return true;
         }

         $regexp = "/^172\.((1[6-9])|(2[0-9])|(3[01]))\./";
         if (preg_match($regexp, $hostsearch)) {
          return true;
         }

         if (preg_match("/^192\.168\./", $hostsearch)) {
          return true;
         }
         return false;
     }


mysql基础 
1)基础知识
mysql命令含义
mysql -uroot -p 输入密码输入密码登陆数据库
show databases显示所有的数据库
use 数据库名进入我们要操作的库
show tables;查看有哪些数据表
desc tblXXX;查看表的结构
select * from tblXXX limit 10;查看此表10行
select * from sms201406 where phone=‘15010796740‘  order by id desc limit 10\G;  
set names utf8;设定数据库字符集utf8,以便显示正常
select  
select DATE_FORMAT(sendtime,‘%Y-%m-%d‘), count(DATE_FORMAT(sendtime,‘%Y-%m_%d‘)) as cc from sms201406 group by DATE_FORMAT(sendtime,‘%Y-%m-%d‘) order by cc ;查询数据
show full process list;显示正在查询的sql的状态

2)常见mysql关键词及坑
order by排序
group by 分组
max峰值
min最小值
sum汇总
avg均值

例子
数据表 bandWidth 
idint(11)自增字段 
 insertTimedatetime数据插入时间
bwfloat(9,2) 当前带宽 Mbit/s


数据
insertTimebw
2014-06-17 10:0020.77
2014-06-17 10:0522.33
2014-06-17 10:1021.09
......

重要,联立应用,分组后累加,平均,峰值

每日峰值select DATE_FORMAT(insertTime,‘%Y-%m-%d‘) as day,max(bw) from bandWidth group by day;
每日总流量select DATE_FORMAT(insertTime,‘%Y-%m-%d‘) as day,sum(bw) from bandWidth group by day;
每日均值select DATE_FORMAT(insertTime,‘%Y-%m-%d‘) as day,avg(bw) from bandWidth group by day;



一个坑:_符号之坑

Mysql中

下划线表示匹配任意字符

 

mysql> select * from student where name like‘_____‘;
假如我们要查找的名字包括5个字母,我们就可以使用特殊的字母"_"(下划线)。将列好在表student中包括5个字母学生的名字 

path
0_1
0_1_2
0_1_2_3
0_1_4
0_1_6 

$children = $Servicetree->where("path like ‘%\_".$tree_id."\_%‘")->select();

一个坑:类型转化之坑
现象如下:
mysql> select servicetree_id,server_id from  servicetree_server where  servicetree_id in (‘1584‘,‘notreeid‘) ;
+----------------+-----------+
| servicetree_id | server_id |
+----------------+-----------+
|              0 |      1153 | 
|              0 |      1170 | 
|           1584 |      9008 | 
|           1584 |      9011 | 
|           1584 |     19339 | 
|           1584 |     20468 | 
|           1584 |     20459 | 
|           1584 |     20457 | 
|           1584 |     20458 | 
|           1584 |     20460 | 
|           1584 |     20465 | 
|           1584 |     20463 | 
|           1584 |     20466 | 
|           1584 |      5033 | 
|           1584 |      1183 | 
|           1584 |      5034 | 
|           1584 |      5035 | 
|           1584 |      5036 | 
|           1584 |      9010 | 
+----------------+-----------+
19 rows in set, 1 warning (0.02 sec)
 
mysql> select servicetree_id,server_id from  servicetree_server where  servicetree_id in (‘1584‘,‘-1‘) ;
+----------------+-----------+
| servicetree_id | server_id |
+----------------+-----------+
|           1584 |      9008 | 
|           1584 |      9011 | 
|           1584 |     19339 | 
|           1584 |     20468 | 
|           1584 |     20459 | 
|           1584 |     20457 | 
|           1584 |     20458 | 
|           1584 |     20460 | 
|           1584 |     20465 | 
|           1584 |     20463 | 
|           1584 |     20466 | 
|           1584 |      5033 | 
|           1584 |      1183 | 
|           1584 |      5034 | 
|           1584 |      5035 | 
|           1584 |      5036 | 
|           1584 |      9010 | 
+----------------+-----------+
17 rows in set (0.00 sec)
原因:
servicetree_id字段类型为int
字符串"notreeid"被转成0
 建议:
不要自己使用字符串拼凑 mysql搜索中的 in 字符串,
尽量使用php中的implode函数组装,则不必附加此类的字符串
使用implode也应该注意一下当implode的数组为空的情况下,会导致查询失败,直接返回null,所以要对implode的数组先进行一下空判断


 
 

3)导入导出
目的,数据从正式库拿到测试库
数据从测试库切去正式库
导出导入
  mysqldump -uroot -pXXX  mc roles> mc.r.sql./source /root/mc.r.sql
     SELECT * from tblXXX INTO OUTFILE ‘/tmp/logXXX‘ LOAD DATA INFILE ‘/tmp/logXXX‘ INTO TABLE ‘/tmp/logXXX‘;



4)-e 作输出,以便可以使用管道,shell,或者吐出到文本

mysql -uroot -p pPass -e "select * from tblXXX"
 


lamp开发基础