分类 PHP 下的文章

PHP查询指定日期内的内容

if(IS_POST){
    $rqstart = I('rqstart');
    $rqend = I('rqend');
    $begintime = strtotime($rqstart. ' 00:00:00');
    $endtime = strtotime($rqend. ' 23:59:59');

    //日期范围内查询条件
    $map['billing_time'] = array(array('EGT', $begintime), array('ELT', $endtime));

    $alipay    = $Billing->where($map)->where(array('billing_pay_manner'=>'alipay'))->sum('billing_price');
    $weixinpay = $Billing->where($map)->where(array('billing_pay_manner'=>'weixinpay'))->sum('billing_price');

    //组装数据
    if($weixinpay>0 or $alipay>0){
        $data=array("alipay"=>"$alipay","weixinpay"=>"$weixinpay");
        $this->ajaxReturn($data);
    }else{
        $data="-1";
        $this->ajaxReturn($data);
    }
}

修正Thinkphp 3.2 分页Page类以支持URL路由

最终目的实现以http://www.fl900.com/product/lists/1-0-0-1.html这样的URL形式且支持分页。

路由配置:

'/^product\/lists\/(\d+)-(\d+)-(\d+)-(\d+)$/'  => 'Product/lists?id=:1&aid=:2&sid=:3&p=:4',

修正Library\Think\Page.class.php分类以支持路由

//在23行,修改访问修饰符private为public
public $url='';
//在70行,防止经过传参后会出现问题urlencode('[PAGE]')转为小写,修改为
$this->url = str_replace(strtolower(urlencode('[PAGE]')), $page, $this->url);//开启URL不区分大小写时处理
return str_replace(urlencode('[PAGE]'), $page, $this->url);
//在80行,修正为以下实现自定义URL
/* 生成URL */
        if(empty($this->url)){
            $this->parameter[$this->p] = '[PAGE]';
            $this->url = U(ACTION_NAME, $this->parameter);
        }
//使用示例
$Page       = new \Think\Page($count,15);// 实例化分页类 传入总记录数和每页显示的记录数(25)
$page_tpl = urlencode('[PAGE]'); 
$Page->url   =   U("Product/list/{$this->id}-{$this->aid}-{$this->sid}-{$page_tpl}");
$show       = $Page->show();

转载:http://www.thinkphp.cn/topic/22114.html

ThinkPHP模板中判断volist循环的最后一条记录的验证方法

对于用过smarty做过php开发的朋友来说,应该都知道在smarty模板里面判断foreach循环是否是最后一个可以$smarty.foreach.name.last来判断循环是否到了最后一条记录,在thinkphp的模板中常见的循环是volist,但是volist的各种属性中并没有直接判断最后一条记录的属性,那么在thinkphp中如何判断呢?下面的代码可以实现ThinkPHP中volist断最后一条记录。

举例代码如下:

<volist name='lists' id='list'>
<li <if condition="$i eq count($lists)">class="last"</if>>
<a href="http://www.cnweed.com/">野草博客</a>
</li>
</volist>

转载:http://www.jb51.net/article/51718.htm

MySQL group by 用法解析

GROUP BY语法可以根据给定数据列的每个成员对查询结果进行分组统计,最终得到一个分组汇总表。SELECT子句中的列名必须为分组列或列函数。列函数对于GROUP BY子句定义的每个组各返回一个结果。

某个员工信息表结构和数据如下:

id  name  dept  salary  edlevel  hiredate
1 张三 开发部 2000 3 2009-10-11
2 李四 开发部 2500 3 2009-10-01
3 王五 设计部 2600 5 2010-10-02
4 王六 设计部 2300 4 2010-10-03
5 马七 设计部 2100 4 2010-10-06
6 赵八 销售部 3000 5 2010-10-05
7 钱九 销售部 3100 7 2010-10-07
8 孙十 销售部 3500 7 2010-10-06

例如,我想列出每个部门最高薪水的结果,sql语句如下:

SELECT DEPT, MAX(SALARY) AS MAXIMUM
FROM STAFF
GROUP BY DEPT

查询结果如下:

DEPT  MAXIMUM
开发部 2500
设计部 2600
销售部 3500

解释一下这个结果:
1、满足“SELECT子句中的列名必须为分组列或列函数”,因为SELECT有GROUP BY DEPT中包含的列DEPT。
2、“列函数对于GROUP BY子句定义的每个组各返回一个结果”,根据部门分组,对每个部门返回一个结果,就是每个部门的最高薪水。
注意:计算的是每个部门(由 GROUP BY 子句定义的组)而不是整个公司的 MAX(SALARY)。
例如,查询每个部门的总的薪水数:

SELECT DEPT, SUM( SALARY ) AS total
FROM STAFF
GROUP BY DEPT

查询结果如下:

DEPT  total
开发部 4500
设计部 7000
销售部 9600

将 WHERE 子句与 GROUP BY 子句一起使用
分组查询可以在形成组和计算列函数之前具有消除非限定行的标准 WHERE 子句。必须在GROUP BY 子句之前指定 WHERE 子句。
例如,查询公司2010年入职的各个部门每个级别里的最高薪水

SELECT DEPT, EDLEVEL, MAX( SALARY ) AS MAXIMUM
FROM staff
WHERE HIREDATE > ’2010-01-01′
GROUP BY DEPT, EDLEVEL
ORDER BY DEPT, EDLEVEL

查询结果如下:

DEPT  EDLEVEL  MAXIMUM
设计部 4 2300
设计部 5 2600
销售部 5 3000
销售部 7 3500

注意:在SELECT语句中指定的每个列名也在GROUP BY子句中提到。未在这两个地方提到的列名将产生错误。

GROUP BY子句对DEPT和EDLEVEL的每个唯一组合各返回一行
在GROUP BY子句之后使用HAVING子句可应用限定条件进行分组,以便系统仅对满足条件的组返回结果。为此,在GROUP BY子句后面包含一个HAVING子句。HAVING子句可包含一个或多个用AND和OR连接的谓词。每个谓词将组特性(如AVG(SALARY))与下列之一进行比较:
例如:寻找雇员数超过2个的部门的最高和最低薪水:

SELECT DEPT, MAX( SALARY ) AS MAXIMUM, MIN( SALARY ) AS MINIMUM
FROM staff
GROUP BY DEPT
HAVING COUNT( * ) >2
ORDER BY DEPT

查询结果如下:

DEPT  MAXIMUM  MINIMUM
设计部 2600 2100
销售部 3500 3000

例如:寻找雇员平均工资大于3000的部门的最高和最低薪水:

SELECT DEPT, MAX( SALARY ) AS MAXIMUM, MIN( SALARY ) AS MINIMUM
FROM staff
GROUP BY DEPT
HAVING AVG( SALARY ) >3000
ORDER BY DEPT

查询结果如下:

DEPT MAXIMUM MINIMUM
销售部 3500 3000

转载:https://blog.phpha.com/backup/archives/353.html

thinkphp volist循环嵌套if标签判断

thinkphp volist循环嵌套if标签判断
今天用volist循环嵌套if标签判断的时候,if判断不能成功,报错,如下示例:

<volist name="list" id="vo">
<volist name="slist" id="s">
<if condition="$s.sid eq $vo.id">
内容。。。。。
</if>
</volist>
</volist>

如果if语句像上面那样写,数据永远也取不出来,因为condition里面写的是PHP原生代码,所以如果是数组要换成中括号的写法,将IF语里的condition表达式换成:$s[‘id’] eq $vo.sid 或者:$s[‘id’] eq $vo[‘sid’],当前的volist的值可不用换成PHP原生数组的形式,上一级的换就OK,也可两个都换成原生数组的形式进行比较。以下是正确代码:

<volist name="list" id="vo">
<volist name="slist" id="s">
<if condition="$s.sid eq $vo['id']">   //或者<if condition="$s['sid'] eq $vo['id']">
内容。。。。。
</if>
</volist>
</volist>

转载:http://www.web-fish.com/program/535.html

ThinkPHP3.2 UEditor 添加在线管理图片删除功能

第一,需要添加一个 php 文件来实现删除功能,文件添加到:ueditor\php\action_delete.php 代码内容:

<?php

/*---------------------------
 * Flyヽ
 * http://lfei.org
 * 2016-02-04
 * action_delete.php
 * 删除 Ueditor 目录下的文件
 *---------------------------*/

try {
    //获取路径
    $path = $_POST['path'];
    $path = str_replace('../', '', $path);
    $path = str_replace('/', '\\', $path);
    
    //安全判断(只允许删除 ueditor 目录下的文件)
    if(stripos($path, '\\ueditor\\') !== 0)
    {
        return '非法删除';
    }
    
    //获取完整路径
    $path = $_SERVER['DOCUMENT_ROOT'].$path;
    if(file_exists($path)) {
        //删除文件
        unlink($path);
        return 'ok';
    } else {
        return '删除失败,未找到'.$path;
    }
} catch (Exception $e) {
    return '删除异常:'.$e->getMessage();
}

第二,需要在ueditor\php\controller.php文件的switch中添加命令 deleteimage 的处理:

....

switch ($action) {

    ....
   
    /* 删除图片命令处理 */
    case 'deleteimage':
         $result = include('action_delete.php');
         break;
    
    /* 在 default 之前添加 */
    default:
        $result = json_encode(array(
            'state'=> '请求地址出错'
        ));
        break;

}

....

第三,在图片上添加删除按钮,需要修改 Js 文件:ueditor\dialogs\image\image.js

....

/* 在这两句之后添加 */
item.appendChild(img);
item.appendChild(icon);

/* 添加删除功能 */
item.appendChild($("<span class='delbtn' url='" + list[i].url + "'>✖</span>").click(function() {
    var del = $(this);
    try{
        window.event.cancelBubble = true; //停止冒泡
        window.event.returnValue = false; //阻止事件的默认行为
        window.event.preventDefault();    //取消事件的默认行为  
        window.event.stopPropagation();   //阻止事件的传播
    } finally {
        if(!confirm("确定要删除吗?")) return;
        $.post(editor.getOpt("serverUrl") + "?action=deleteimage", { "path": del.attr("url") }, function(result) {
            if (result == "ok") del.parent().remove();
            else alert(result);
        });
    }
})[0]);

/* 在这一句之前添加 */
this.list.insertBefore(item, this.clearFloat);

....

第四,为删除按钮添加一个样式,修改文件:ueditor\dialogs\image\image.css在最底部添加如下代码:

/* 在线管理删除按钮样式 */
#online li .delbtn {      
    position: absolute;
    top: 0;
    right: 0;
    border: 0;   
    z-index: 3;
    color: #ffffff;
    display: inline;
    font-size: 12px;
    line-height: 10.5px;
    padding:3px 5px;
    text-align: center;
    background-color: #d9534f;
}

效果如下:
1454606856781543

转自:http://lfei.org/ueditor-manage-image-delete/

ThinkPHP验证数据的长度

在ThinkPHP里面通过自动验证定义来验证数据的长度是否符合要求,在你的模型类里面添加下面的定义即可:

protected $_validate = array(
array('title','5,100','标题长度不符!',3,'length'), // 验证标题长度
array('phone','11','电话长度不符!',3,'length'), // 验证电话号码长度
);

PHP程序 - 将MYSQL数据库表转换UTF-8

The following mini script is used to convert existing database tables to UTF-8. Upload the script to your account as "convert.php" and modify the database connection parameters and the character set, then execute the script.

To execute the script, you simply would visit the script in any web browser. If you upload the file to your public_html folder you'd visit "http://your-domain.com/convert.php".

Don't forget to replace your-domain.com with your actual domain name. Also, to get your languages to work on your site the collation will need to be utf8.

Code to convert your database to UTF-8

<?php  
     
// Fill in your Server, User, Database, Password, and Collation configuration below   
$db_server = 'localhost';   
$db_user = 'database user';   
$db_password = 'password';   
$db_name = 'database name';   
$char_set = 'new character set';  


// Adds the header information
header('Content-type: text/plain');  


// Connects to the MySQL database    
$connection = mysql_connect($db_server, $db_user, $db_password) or die(mysql_error() );      
$db = mysql_select_db($db_name) or die( mysql_error() ); 


// Runs the SQL query on teh database     
$sql = 'SHOW TABLES'; $result = mysql_query($sql) or die( mysql_error() ); 


// Runs a loop that finds all collations within the database and changes it to the new collation    
   while ( $row = mysql_fetch_row($result) )   {     
      $table = mysql_real_escape_string($row[0]);  
      $sql = "ALTER TABLE $table CONVERT TO CHARACTER SET $char_set COLLATE utf8_general_ci";     
      mysql_query($sql) or die( mysql_error() );       
      print "$table changed successfully.\n";  
   }    


// Update the Collation of the database itself  
$sql = "ALTER DATABASE CHARACTER SET $char_set;";  
mysql_query($sql) or die( mysql_error());     
print "Database collation has been updated successfully.\n";     


// close the connection to the database  
mysql_close($connection);     


?>
Note! You can use this script to change the database to any character set you wish. You need to define the character set in the script to change character sets:
$char_set = 'character set';

You will need the change the utf8_general_ci to match the character set you defined in the step above. So, if you want to change the character set to "Hebrew" you'd change the line to:

$sql = "ALTER TABLE $table CONVERT TO CHARACTER SET $char_set COLLATE hebrew_general_ci";

转载:http://www.inmotionhosting.com/support/website/databases/how-to-convert-a-database-to-utf-8

DSO (mod_php) vs. CGI vs. suPHP vs. FastCGI

This is one of the most common topics that I see customers will ask about. As highly important as PHP handlers are, they often the least understood. They seem complicated, but its not too hard to understand. You don’t have to know that exact science of how it all works, but one should learn the basics if you want to take your website seriously. Picking the right PHP handler for your website will give you the optimal speeds you want and maybe allow you to save some money by using a cheaper hosting package. So I invite you to take a few minutes and learn something new.

What are PHP handlers

In order to run a PHP site, the server must interpret the PHP code and generate a page when visitors access the website. It interprets the code based on which PHP library you are using, such as PHP 4 or PHP 5. A PHP handler is what actually loads the libraries so that they can be used for interpretation. PHP handlers determine how PHP is loaded on the server.

There are multiple different handlers that can be used for loading PHP: CGI, DSO, suPHP, & FastCGI. Each handler delivers the libraries through different files and implementations. Each file and implementation affects Apache’s performance, because it determines how Apache serves PHP.

It is critical for your server’s performance that you select the handler that fits your situation. Selecting the right handler is just as important as the PHP version itself. One handler is not necessarily always better than another; it depends on your unique setup. What caching do you need, what modules do you need, etc…

  • Note: You may assign different PHP handlers to different versions of PHP. For example, version 5 may be handled by CGI while PHP 4 is handled by DSO.

How to change the handler

Changing the handler on cPanel is very easy to do and only takes seconds. Log into WHM and navigate to: Main >> Service Configuration >> Configure PHP and SuExec

You simply select your PHP handler choice from the drop-down menu. Then hit “Save New Configuration”.

  • Note: If you do not see your desired choice in the drop-down menu, it may need to be compiled on the server first. Run an “Easy Apache” to compile it.

List of PHP handlers

DSO (mod_php)

DSO is also known as mod_php. DSO stands for: Dynamic Shared Object. This is an older configuration but is generally considered the fastest handler. It runs PHP as an Apache module. This means that PHP scripts will run as the Apache user, which is the user: ‘nobody’.

DSO has two drawbacks. First, all files created by a PHP script will have the ownership of ‘nobody’. They will not be readable from the web. Websites that need to upload files through PHP will run into file permission issues. This is common with WordPress users that upload files through the WordPress interface or utilize the auto-update feature. These will fail with DSO.

The second drawback is a security issue. Created files will have the ‘nobody’ ownership. If a hacker finds an exploit in your PHP script, they could implement a file that has the same privileges as important system files that are also owned by ‘nobody’. This will give them the ability to modify files outside of that user’s account. This is really bad for anyone who does reselling or simply is hosting other person’s sites. You would not one user to be able to affect another user. However, if there is only one account on the server (or if all the accounts are yours), then DSO may be right for you. The speeds benefits of DSO are unquestionable.

An easy way to prevent the hack issue is to always keep your site’s software up to date. Check with your PHP script’s developer to keep up on the new releases. If you are the only one being hosted on the server, this is easy to do as it’s part of your webmaster duties already. However, if you’re reselling, it would be unreasonable to expect all your user’s to keep their software up to date. They simply may not be as diligent as you.

DSO’s low CPU usage typically amounts in higher speeds and load times over most other handlers. It is also the default setting on most servers.

CGI

CGI stands for: Common Gateway Interface. The CGI handler will run PHP as a CGI module as opposed to an Apache module. CGI still runs PHP processes as the Apache ‘nobody’ user. However, if you have suEXEC enabled, it will allow you to see the user that made the request.

The CGI method is intended as a fallback handler for when DSO is not available. According to cPanel’s own documentation, this method is neither fast nor secure, regardless of whether or not suEXEC is enabled.

http://docs.cpanel.net/twiki/bin/view/AllDocumentation/WHMDocs/MorePhphandlers

suPHP

suPHP stands for Single user PHP. suPHP also runs PHP as a CGI module instead of an Apache module. It differs from CGI in that PHP scripts that are called from the web will run under the user that owns them, as opposed to ‘nobody’. suPHP is typically the default handler and is recommended by cPanel for serving PHP because you will be able to see which user owns the account that is running the PHP script.

suPHP is beneficial in that if you are using a file upload tool on your site (such as an automatic updater or theme/plug-in installer for WordPress), the files will already have the right ownership & permissions. Uploading and other WordPress functions will not work without suPHP or FastCGI.

suPHP also offers a security advantage that any php script that is not owned by the particular user (such as another account or root) will not be executable. Also, files that have permissions set to world writeable will likewise be non-executable. This means that if one account is compromised, the malicious scripts will not be able to infect other accounts.

The drawback is that suPHP generally runs a much higher CPU load. In addition, you CANNOT use an Opcode Cache (such as Xcache or APC) with suPHP. It is strongly recommend that you install a caching plug-in to supplement this ned. If you find that your server is still continually struggling with CPU usage, you will want to consider switching to DSO or FastCGI.

*If you DO switch to either suPHP or FastCGI, you will need to update the file permissions and ownership. See my other article for automatic fixperms on cPanel servers: http://boomshadow.net/tech/fixes/fixperms-script/

FastCGI

FastCGI (aka: mod_fcgid or FCGI) is a high performance variation of CGI. It has the security/ownership benefits of suPHP in that PHP scripts will run as the actual cPanel user as opposed to ‘nobody’. The difference with FastCGI is that it can drastically save on CPU performance and give speeds close to that of DSO. It can also be used with an opcode cacher like eAccelerator or APC, which can help further speed the loading of pages.

The drawback is FastCGI has a high memory usage. This is because rather than creating the PHP process each time it is called, like suPHP, it keeps a persistent session open in the background. This is what lets it work with an opcode caching software.

If you like the security/ownership benefits of suPHP and you can afford a major increase in memory usage (meaning you already have a low average memory usage), you may wish to consider using FastCGI.

Comparison Graph

DSO CGI SuPHP FastCGI
Low CPU usage
Low Memory consumption
Runs PHP as site owner instead of Apache

only w/ suEXEC
Good security

Special Note for WordPress Users

If you are using WordPress to run your site, please consider the following:

  • Functions that require uploading files to the server (such as Auto-updates or Plug-in/Theme installation) will NOT work unless PHP is loaded as a CGI module. This means they will ONLY work with suPHP or FastCGI. This will ensure they are uploaded with the correct ownership & permissions.
  • CMS platforms such as WordPress will notoriously run a high CPU load. You will want to install a caching plug-in such as WP Super Cache, especially if you are running suPHP. If you find that your server is still continually struggling with CPU usage, you may want to consider switching to DSO or FastCGI.

转载:http://boomshadow.net/tech/php-handlers/

php发送get、post请求的几种方法

方法1: 用file_get_contents 以get方式获取内容

<?php  
$url='http://www.domain.com/';  
$html = file_get_contents($url);  
echo $html;  
?>  

方法2: 用fopen打开url, 以get方式获取内容

<?php  
$fp = fopen($url, 'r');  
//返回请求流信息(数组:请求状态,阻塞,返回值是否为空,返回值http头等)  
stream_get_meta_data($fp); 
while(!feof($fp)) {  
$result .= fgets($fp, 1024);  
}  
echo "url body: $result";  
fclose($fp);  
?>  

方法3:用file_get_contents函数,以post方式获取url

<?php  
$data = array ('foo' => 'bar');  
//生成url-encode后的请求字符串,将数组转换为字符串  
$data = http_build_query($data);  
$opts = array (  
<span style="white-space:pre">  </span>'http' => array (  
<span style="white-space:pre">      </span>'method' => 'POST',  
<span style="white-space:pre">      </span>'header'=> "Content-type: application/x-www-form-urlencoded\r\n" .  
<span style="white-space:pre">      </span>"Content-Length: " . strlen($data) . "\r\n",  
<span style="white-space:pre">      </span>'content' => $data  
<span style="white-space:pre">  </span>)  
);  
//生成请求的句柄文件  
$context = stream_context_create($opts);  
$html = file_get_contents('http://localhost/e/admin/test.html', false, $context);  
echo $html;  
?>  

方法4:用fsockopen函数打开url,以get方式获取完整的数据,包括header和body,fsockopen需要 PHP.ini 中 allow_url_fopen 选项开启

<?php  
function get_url ($url,$cookie=false)  
{  
$url = parse_url($url);  
$query = $url[path]."?".$url[query];  
echo "Query:".$query;  
$fp = fsockopen( $url[host], $url[port]?$url[port]:80 , $errno, $errstr, 30);  
if (!$fp) {  
return false;  
} else {  
$request = "GET $query HTTP/1.1\r\n";  
$request .= "Host: $url[host]\r\n";  
$request .= "Connection: Close\r\n";  
if($cookie) $request.="Cookie:   $cookie\n";  
$request.="\r\n";  
fwrite($fp,$request);  
while()) {  
$result .= @fgets($fp, 1024);  
}  
fclose($fp);  
return $result;  
}  
}  
//获取url的html部分,去掉header  
function GetUrlHTML($url,$cookie=false)  
{  
$rowdata = get_url($url,$cookie);  
if($rowdata)  
{  
$body= stristr($rowdata,"\r\n\r\n");  
$body=substr($body,4,strlen($body));  
return $body;  
}  
    return false;  
}  
?>  

方法5:用fsockopen函数打开url,以POST方式获取完整的数据,包括header和body

<?php  
function HTTP_Post($URL,$data,$cookie, $referrer="")  
{  
    // parsing the given URL  
$URL_Info=parse_url($URL);  
    // Building referrer  
if($referrer=="") // if not given use this script as referrer  
$referrer="111";  
    // making string from $data  
foreach($data as $key=>$value)  
$values[]="$key=".urlencode($value);  
$data_string=implode("&",$values);  
    // Find out which port is needed - if not given use standard (=80)  
if(!isset($URL_Info["port"]))  
$URL_Info["port"]=80;  
    // building POST-request:  
$request.="POST ".$URL_Info["path"]." HTTP/1.1\n";  
$request.="Host: ".$URL_Info["host"]."\n";  
$request.="Referer: $referer\n";  
$request.="Content-type: application/x-www-form-urlencoded\n";  
$request.="Content-length: ".strlen($data_string)."\n";  
$request.="Connection: close\n";  
    $request.="Cookie:   $cookie\n";  
    $request.="\n";  
$request.=$data_string."\n";  
    $fp = fsockopen($URL_Info["host"],$URL_Info["port"]);  
fputs($fp, $request);  
while(!feof($fp)) {  
$result .= fgets($fp, 1024);  
}  
fclose($fp);  
    return $result;  
}  
?>  

方法6:使用curl库,使用curl库之前,可能需要查看一下php.ini是否已经打开了curl扩展

<?php  
$ch = curl_init();  
$timeout = 5;  
curl_setopt ($ch, CURLOPT_URL, 'http://www.domain.com/');  
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);  
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);  
$file_contents = curl_exec($ch);  
curl_close($ch);  
echo $file_contents;  
?>  

转载:http://blog.csdn.net/haha00217/article/details/7969504