月度归档 2014年11月30日

通过清心醉

PHP静态方法使用实例

<?php
class Max_if
{
public static function Max($num1, $num2) {
return $num1 > $num2 ? $num1 : $num2; //判断大小
} //静态方法MAX
public static function Max2($num1, $num2, $num3) {
$a = self::Max($num1, $num2); //判断12的参数大小 self为调用静态方法/成员.
$b = self::Max($num2, $num3); //判断23的参数大小
$c = self::Max($a, $b); //在判断上面两句的$
return $c; //判断的最大值返回
} //静态方法MAX2
}
/*赋值*/
$a = 100; $b = 101;$c = 99;
echo “显示 $a $b $c 中的最大值是<br />”;
echo Max_if::Max2($a, $b, $c); //对静态方法直接调用,方法格式为类名::方法/成员
//对应传值给$num1 2 3
?>

通过清心醉

NGINX+APACHE+PHP+MYSQL整合

NGINX+APACHE+PHP+MYSQL整合

#需要的朋友可以下载文档,复制过来的文章修改的部分红色标准没有了.可能对新手来说看的会比较辛苦.

APACHE和NGINX各有优势。APACHE来说吧,处理动态是第一的选择,同时他还有丰富的扩展支持,可是占用的内存实在不敢想象,而且就作者4GB内存的VPS来说吧,一个AB命令基本就已经进入负荷状态了。NGINX对静态的支持可以说是目前最好的,占用资源也低,但如果处理动态数据,就经常出错了。

为此,要让APACHE和NGINX同时存在,让APACHE处理后端的动态数据,NGINX处理前端的静态页面。

首先,安装NGINX:

在 /etc/yum.repos.d/ 目录下,建立名叫nginx.repo的软件源配置文件。
默认是没有nginx的软件源的,自己增加个下载配置.
[nginx]
name=nginx repo
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
gpgcheck=0
enabled=1
[root@qingxinzui ~]# yum install nginx

接着我们在/etc/nginx下创建两个文件:分别是proxy.conf和proxy.conf

写入内容:

#proxy.conf

proxy_redirect          off;

proxy_hide_header      Vary;

proxy_set_header        Accept-Encoding ”;

proxy_set_header        Host            $host;

proxy_set_header        X-Real-IP      $remote_addr;

proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;

client_max_body_size    10m;

client_body_buffer_size 128k;

proxy_connect_timeout  90;

proxy_send_timeout      90;

proxy_read_timeout      90;

proxy_buffer_size      4k;

proxy_buffers          32 4k;

proxy_busy_buffers_size 64k;

 

#gzip.conf

gzip on;

gzip_http_version 1.0;

gzip_disable      “MSIE [1-6]\.”;

gzip_disable      “Mozilla/4”;

gzip_comp_level  3;

gzip_proxied      any;

gzip_vary        on;

gzip_buffers      4 16k;

gzip_min_length  1100;

gzip_types        text/plain text/xml text/css application/xml application/xhtml+xml application/rss+xml application/atom_xml application/javascript application/x-javascript;

 

接着我们修改下nginx.conf,添加#########内的两行(即刚才写的配置文件)

[root@qingxinzui ~]# vi/etc/nginx/nginx.conf

include       /etc/nginx/mime.types;

##########################################

include       /etc/nginx/proxy.conf;

include       /etc/nginx/gzip.conf;

##########################################

 

接下来修改默认站点的配置文件:

[root@qingxinzui ~]# vi/etc/nginx/conf.d/default.conf

server {

#其他内容…

location / {

root   /var/www/html;   #修改网站目录

index  index.php index.html index.htm; #修改index.php头

}

#其他内容…

location ~ .*\.(php?|cgi|pl|py)$ {

proxy_pass   http://127.0.0.1:9999; #这是将以上4个脚本类型交给9999的APACHE端口处理

}

location ~ /\.ht {

deny  all;

}

location ~ /.+\.(inc|conf|cnf) {

deny  all;

}

#其他内容…

}

 

好了,到这里位置,NGINX的前端配置基本已经完成了,接下来是后端的APACHE

[root@qingxinzui ~]# yum install httpd

[root@qingxinzui ~]# vi /etc/httpd/conf/httpd.conf

#修改以下5项->

Listen 80 -> Listen 127.0.0.1:9999

Options Indexes FollowSymLinks -> Options ExecCGI FollowSymLinks

AllowOverride None -> AllowOverride All

ServerSignature On -> ServerSignature Off

#AddHandler cgi-script .cgi -> AddHandler cgi-script .cgi .pl .py

 

安装PHP、MYSQL支持

[root@qingxinzui ~]# yum -y install php php-mysql php-gd php-xml php-mbstring mysql-server

安装mcrypt模块:

CentOS官方已经不再对mcrypt模块进行支持,作者所以使用了Fedora的扩展库,EPEL (Extra Packages for Enterprise Linux).

32位的可以去:http://mirrors.sohu.com/fedora-epel/6/i386/

64位的:http://mirrors.sohu.com/fedora-epel/6/x86_64/

搜索epel-release

如作者的64,下载扩展先:

rpm -ivh http://mirrors.sohu.com/fedora-epel/6/x86
_64/epel-release-6-8.noarch.rpm

完成后#yum update 更新下
在中间会有个提示更新其他的咨询是否下载,按N,否则系统就会全部进行更新下载。

然后查看#yum repolist

[root@qingxinzui ~]# yum repolist

Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
* base: centos.mirror.ndchost.com
* epel: mirrors.solfo.com
* extras: mirror-centos.hostingswift.com
* updates: mirror.hmc.edu
repo id       repo name                                            status
base          CentOS-6 – Base                                       6,367
epel          Extra Packages for Enterprise Linux 6 – x86_64       11,128
extras        CentOS-6 – Extras                                        15
updates       CentOS-6 – Updates                                    1,608
repolist: 19,118

说明已经有了.接下来是安装:

[root@qingxinzui ~]# yum –y install php-mcrypt

 

安装php加速器eaccelerator和php-pecl-memcached模块,提高性能

[root@qingxinzui ~]# yum install php-eaccelerator php-pecl-memcached

使用默认设置已经足够使用了。

 

好了,我们在/var/www/html文件夹内创建个index.php并写入以下代码:

<?php

phpinfo();

?>

 

#接着启动nginx|httpd|mysql

[root@qingxinzui ~]# service nginx restart

[root@qingxinzui ~]# service httpd restart

[root@qingxinzui ~]# service mysqld restart

 

访问:127.0.0.1

phpinfo()函数打印出了所有的PHP信息,但这样我们不知道,是否动态脚本完全提交给了APACHE?

很简单:关闭HTTPD服务

[root@qingxinzui ~]# service httpd stop

再次访问:127.0.0.1

An error occurred.

Sorry, the page you are looking for is currently unavailable.
Please try again later.

If you are the system administrator of this resource then you should check theerror log for details.

Faithfully yours, nginx.

看来动态脚本的确是有提交给APACHE,以上就是说明没有PHP支持。

为了保险起见,在/var/www/html文件夹内创建个index.html写入内容:NGINX静态测试

看看在关闭了HTTPD的情况下,NGINX是否可以独立打开。

访问:127.0.0.1

可以访问。

表示NGINX处理前端,APACHE处理后端的基础配置已经基本完成。

通过清心醉

nginx结合php-fpm

作者前几篇文章有写yum安装nginx+php+mysql,但是结合让环境可以使用好像没有写上来,因此在这附加上:

默认PHP-fpm是通过9000接受nginx传递过来的PHP数据,是不需要修改的。

nginx的配置文件位置:

/etc/nginx/conf.d/default.conf

server {
listen       80;
server_name  qingxinzui.gicp.net;

#charset koi8-r;
#access_log  /var/log/nginx/log/host.access.log  main;

location / {
root   /opt/www;
index  index.php index.html index.htm;
}

#error_page  404              /404.html;

# redirect server error pages to the static page /50x.html
#
error_page   500 502 503 504  /50x.html;
location = /50x.html {
root   /usr/share/nginx/html;
}

# proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
#location ~ \.php$ {
#    proxy_pass   http://127.0.0.1;
#}

# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
    location ~ \.php$ {
        root           /opt/www;
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        include        fastcgi_params;
    }

# deny access to .htaccess files, if Apache’s document root
# concurs with nginx’s one
#
#location ~ /\.ht {
#    deny  all;
#}
}

红色字体的是修改的目录。

紫色字体是要取消的注释

通过清心醉

wordpress之评论安全设置

最近发现了一个评论的问题,以为是个漏洞,结果后台发现有这么一个控制方法:

在评论显示之前

在评论显示之前


切忌不能使用评论者必须有评论通过了审核,否则的话,别人可以借用已通过评论的用户及邮箱,直接无限制的评论,虽然wordpress对防注入做的还是挺不错的,但还是安全第一。

通过清心醉

PHP过滤所有$_POST数据

过滤所有$_POST

首先假设我们有个form表单,并且以POST的类型把数据提交到服务器,比如接收form表单数据的PHP页面

if(is_array($_POST)&&count($_POST)>0)
{
if((isset($_POST[“user”])&&!empty($_POST[“user”]))&&(isset($_POST[“password”])&&!empty($_POST[“password”])))
{
$i=$_POST[“user”];$o=$_POST[“password”]; //我们假设POST过来user和password两个参数,然后下面是作者写的小函数,可以在接收有POST的数据上增加
/***************调用开始*******************/
$login=array($i,$o,);//把POST的数据数组化,你有多少POST的数据要过滤就增加多少个.
require_once(“filtration.php”); //包含过滤文件
$filtration->filtration($login);  //调用过滤函数,并且把数组传递给filtration的数组参数.
/***************调用结束*******************/
echo “无过滤字符号,成功登陆”; //过滤之后的响应方法
}
else
{
echo “请完整输出”;exit;
}
}

让我们来看看filtration.php的文件:

<?php
header(“Content-Type:text/html;charset=utf-8”);
error_reporting( E_ALL&~E_NOTICE ); //除去 E_NOTICE 之外的所有错误信息
class Filtration
{
private $str=array();//私有数组成员,用于接收POST的数组
function filtration($arrayfiltration=array()) //过滤函数,带一个数组变量$arrayfiltration,
{
$this->str=$arrayfiltration; //函数的$arrayfiltration数组接收POST的数组传值给私有数组$str
$str1=array(
‘过滤1′,’过滤2’,
‘过滤3′,’过滤4’,
‘过滤5′); //需要过滤的数值
$arraystr=count($this->str); //判断POST过来的数组有多少个元素
for($o=0;$o<$arraystr;$o++) //根据POST过来的数组数量进行循环判断
{
for($i=0;$i<count($str1);$i++) //根据预定义的过滤数组进行循环
{
$j=substr_count($this->str[$o],$str1[$i]); //根据POST的数组元素数量执行$this->str和预定义的过滤数组$str1
/*
这比等于for一次循环是根据POST的元素数量来执行,POST多少个执行多少次
然后$o++表示执行的次数字+1,一直到等于POST的元素数量的时候中指。
然后,每执行一次$this->str[$o],调用一次POST过来的数组的数据,然后在进行for二次循环
对定义的过滤数组循环判断。直到所有的过滤数组都完成,跳出for二次循环
在判断一次循环的for条件(即POST的数组数量是否达),如果还有次数,对POST过来的数组的其他元素
以+1的方式,再一次进行二次for循环。直到一次循环完成。
*/
if($j>0) //只要有一条如果条件为真
{
echo “出现非法字符”;exit; //中止脚本。
}
}
}
}
}
$filtration=new Filtration(); //实例化对象。
?>

 

如果是用文件来过滤的话: 新增一个文件filtration.txt,写入要过滤的内容,以行为单位,然后PHP修改为:

<?php
header(“Content-Type:text/html;charset=utf-8”);
error_reporting( E_ALL&~E_NOTICE ); //除去 E_NOTICE 之外的所有错误信息
class Filtration
{
private $str=array();//私有数组成员,用于接收POST的数组
function filtration($arrayfiltration=array()) //过滤函数,带一个数组变量$arrayfiltration,
{
$this->str=$arrayfiltration; //函数的$arrayfiltration数组接收POST的数组传值给私有数组$str
$file=’filtration.txt’;//过滤文件
$openfile=file_get_contents($file); //执行打开文件并读入到字符串
$str1=explode(“\r\n”,$openfile); //获取数组”\r\n”表示是换行
$arraystr=count($this->str); //判断POST过来的数组有多少个元素
for($o=0;$o<$arraystr;$o++) //根据POST过来的数组数量进行循环判断
{
for($i=0;$i<count($str1);$i++) //根据预定义的过滤数组进行循环
{
$j=substr_count($this->str[$o],$str1[$i]); //根据POST的数组元素数量执行$this->str和预定义的过滤数组$str1
if($j>0) //只要有一条如果条件为真
{
echo “出现非法字符”;exit; //中止脚本。
}
}
}
}
}
$filtration=new Filtration(); //实例化对象。
?>

如果是从文本读入,第一行请留空,否则第一行是无法过滤的.

如果是MYSQL里存放过滤数据的话,一样循环读入到数组

并且修改$str1的值=mysql里获取的数组数据.就可以进行判断了.

通过清心醉

PHP $this传递对象

<?php
class B_
{
private $a; //定义私有$a
function cout()
{
$this->a=new A_(); //$this->a//也就是$a对象=A_类
$this->a->main1(); //调用A_类的main1()函数
}
}
class A_
{
function main1()
{
echo “mail1”;
}
}
$b=new B_(); //实例B_类
$b->cout(); //调用B_类的cout函数
?>

通过清心醉

PHP自写论坛检测结果

小论坛文章介绍:http://www.qingxinzui.com/?p=1162

拿去安全检测了下,发现不安全的还蛮多的.

具体看图.

jiance

[高危]跨站脚本攻击漏洞::

xiufu1

[高危]SQL注入漏洞(盲注)1::2::

xiufu2

[警告]页面异常导致本地路径泄漏1::2::3::

xiufu3

[轻微]SQL注入漏洞1::2::

xiufu4

[轻微]发现服务器启用了TRACE Method

这个就是比较简单的了.也是比较容易见的.

xiufu5

至于前面的,都是对POST的数据未进行过滤的关系,由于作者都是自编自写,疏忽造成.

方法思路其实也很简单,

新建个php文件,包含在有表单的地方,在这文件里对所有POST和GET的数据进行判断过滤.

我们看看论坛放线上服务器的效果吧.

xiufu

 

[警告]页面异常导致本地路径泄漏
如果是PHP应用程序/Apache服务器,可以通过修改php脚本、配置php.ini以及httpd.conf中的配置项来禁止显示错误信息:
修改php.ini中的配置行: display_errors = off
修改httpd.conf/apache2.conf中的配置行: php_flag display_errors off
修改php脚本,增加代码行: ini_set(‘display_errors’, false);[高危]跨站脚本攻击漏洞
避免XSS的方法之一主要是将用户所提供的内容输入输出进行过滤,许多语言都有提供对HTML的过滤:
可以利用下面这些函数对出现xss漏洞的参数进行过滤
PHP的htmlentities()或是htmlspecialchars()。

[高危]SQL注入漏洞(盲注)

1.在网页代码中需要对用户输入的数据进行严格过滤。
2.部署Web应用防火墙
3.对数据库操作进行监控

建议过滤用户输入的数据,切记用户的所有输入都要认为是不安全的。

[轻微]SQL注入漏洞
如下一些方法能够防止注入攻击:
1.在网页代码中需要对用户输入的数据进行严格过滤。
2.部署Web应用防火墙
3.对数据库操作进行监控

作者这几天抽个时间,写个字符过滤吧.到时一并附上.

 

 

 

通过清心醉

PHP类和对象类的继承及重写(方法重写)

<?php
class  A_class //基类A_class
{
protected  $Number = 2; //定义个保护的成员.
//封装的属性
public function getNumber()
{
return $this->Number; //返回值=protected  $Number的参数
}
public function  main1()
{
return  “基类的方法1”;
}
public function  main2()
{
return  “基类的方法2”;
}
}
$classa = new A_class(); //实例化
echo “A_class基类有”.$classa->getNumber().”个方法 </br>”; //这时会调用return $this->Number;
echo $classa->main1().”</br>”.$classa->main2();echo “</br></br>”;

class B_class extends A_class //A_class的派生类B_class
{
private $name = “子类专有::”; //定义私有成员
public function getName()
{
return $this->name;
}
public function main1() //对main1()函数进行重写.
{
return  $this->name.”子类对基类的方法重写”;
}
public function text()
{
return  “子类自己的方法”;
}
}
$classb = new B_class();//实例化
echo $classb->getName().”B_class子类有”.$classb->getNumber().”个方法</br>”;
//调用派生类的getName()和基类的getNumber()
echo $classb->main1().”</br>” ;
//调用派生类的main1()
echo $classb->main2().”</br>”;
//调用基类的main2()
echo $classb->text();
//调用派生类自己的函数text()

/*
可以这么说:子类可以继承基类的protected保护和public公有的类型,
同时可以自己有新的方法.至于重写:比如文中所说的main1()
基类已经有了,可派生类重写这个函数,
所以当$classb->main1()调用的时候,调用的是派生类的main1()函数

重写方法与访问权限
子类中的覆盖方法不能使用比父类中被覆盖方法更严格的访问权限。
*/
?>

通过清心醉

PHP类和对象的最简单介绍

<?php
$o=100; //架设值=$_POST
class CLASS_
{
protected $a;
function setA($_a) {
$this->a = $_a;
}
function getA() {
return $this->a;
}
}
$class = new CLASS_();
$class->setA($o); //给$_a赋值
echo $class->getA();
?>

通过清心醉

PHP自写论坛

这一个星期闲着无聊没事做,故以自己的一套思路开发了一个小论坛程序.

先来说说功能吧

一::后台安装后,自动生成admin管理员帐号密码.

二::前端用户注册,进入审核状态,MYSQL里有个yesno的字段,用于判断是否审核通过,登陆时必须验证mysql的yesno.同时增加用户注册时间,注册IP获取写入MYSQL;

三::在用户登陆后,生成$_SESSION[“add”],参数为用户名,(注册的时候对名字进行了重复判断,所以不会重复)而且,在登陆的时候,除了判断用户名和md5的密码,还同时判断competence字段里是否=1,如果没有,输出普通用户登陆成功的信息,如果=1,表示是管理员,除了生成$_SESSION[“add”],还要生成一个$_SESSION[“competence”];用于记忆管理员的登陆参数.

四::后台管理员功能:基本控制文件在admin_shell.php文件里,而且做了$_SESSION[“competence”];管理员权限的验证,如果不存在该值,直接返回主页.管理员的验证函数在class.php里可以查找到.

1:前端功能:新用户注册提醒\用户发表文章提醒\用户评论提醒;因为这些都是需要验证的.

2:后端功能:

A:修改系统LOGO大图,修改页头TITLE,修改页头论坛名字URL,修改页脚名字(可以附加URL);

B:修改用户的状态:审核/未审核及删除用户.

C:修改文章的状态:修改文章名字(SQL进行了文章名字重复中止),修改文章分类(同时修改评论),修改文章审核状态,删除文章;

D:修改分类的状态:修改分类名字(更新文章所指向的分类及评论指向文章的分类,后面删除会说),新增分类(SQL防重复),删除分类(同时删除当前分类内所有的文章及评论,所以作者在文章和评论的字段里都加有分类的字段,同步删除.),删除分类但移动该分类内所有文章到其他分类;

五::用户权限:发布文章,发布评论(都会进入审核状态并在管理员的前端显示提醒),审核之后正式SQL调用显示.

六::分类,文章,默认显示8个,如果有更多,需点更多进入查看(该方法未进行翻页实现,写的好累.)

七::文章的显示顺序,按SQL里的倒序读取,保证显示在前面的是最新的文章,如果用户没点分类,就显示所有文章最新的,如果用户有查看某一分类的文章,就调用当前分类所有最新的文章优先显示.

八::该代码基于PHP+MYSQL为主,字符集为UTF-8,如果有不懂设置UTF-8的,可以参考作者前面写的文章,LINUX和WINDOWS版都有写出来. 同时该论坛的传值方式都是基于GET和POST进行,没有通过return的返回值操作.原因很简单,作者也是刚自学PHP不久,只是有些C++的小基础上进行思维上的编写,并不保证程序的安全运行.同时界面基于table形式,未进行太多的DIV+CSS处理.

好了,以下是作者写的小论坛的所有源码:自写论坛

欢迎自学的朋友们下载来玩玩,如果有更多好的意见,可以反馈给作者

admin@qingxinzui.com

清心醉

通过清心醉

PHP MYSQL实例

由于作者是包含了config.php配置连接MYSQL
如果您是单独练习,请新增个变量做连接,
比如:$con=mysql_connect(“localhost”,”root”,””); //数据库地址,用户,密码
mysql_query($sql1,$con); //后面增加个$con连接SQL变量

假设:用户表名user,里面有字段id,name,password,email,time //表示用户的ID,名字,密码,注册时间
$sql=”select * from user”; //读取USER表
$sql1=mysql_query($sql);
echo “<table>”;
echo “<tr><td>ID</td><td>NAME</td><td>EMAIL</td><td>TIME</td></tr>”; //密码不输出
while($o=mysql_fetch_object($sql1))
{
//执行while循环,$o->来提取对象的数据.并且过滤掉了password字段的数据
<tr><td>$o->id</td><td>$o-name</td><td>$o->email</td><td>$o->time</td></tr>
}
echo “</table>”; //输出表格结束
echo “</div>”;

如果说,做一个注册页面,用户注册后,需要等待审核,
那么我们给user字段里增加一个yesno,然后设置1为审核通过,0为未审核用户:
mysql_query(“INSERT INTO user(id,name,password,email,time,yesno)VALUES(‘$id’,’$user’,'”.md5($password).”‘,’$email’,’$time’,’0′)”)
每个变量的值自己可以做个表单POST过来,里面的md5为加密形式.然后默认的YESNO审核状态为0即未审核,;
可以干什么用,来看注册之后,登陆的话
$i=$_POST[“userlogin”]; //临时用户名
$o=md5($_POST[“passwordlogin”]); //临时密码
$sql=”select * from user where name=’$i’ and password=’$o’ “; //帐号密码先判断下
$rs=mysql_query($sql);
if(mysql_num_rows($rs)!=0) //如果不等于0表示结果为真
{   // 帐号密码正确的话,再一次读取该用户的yesno权限
$sql2=”select * from user where name=’$i’ and yesno=’1′”;  //如果在USER表里的用户($i已取值)并且YESNO=1
$rs2=mysql_query($sql2);
if(mysql_num_rows($rs2)==0)  //SQL判断是否为真,如果不为真的执行以下代码.
{
echo “<script language=\”JavaScript\”>alert(\”您的帐号还在审核中\”);</script>”;
echo “<script>setTimeout(\”this.location=’index.php’\”,0);</script>”;
exit; //EXIT退出脚本
}
echo “<script language=\”JavaScript\”>alert(\”登陆成功\”);</script>”;
$_SESSION[“user”]=$i; //记忆用户的session值.
echo “<script>setTimeout(\”this.location=’index.php’\”,1000);</script>”;
}

如果我们要修改用户的审核状态为1,那么就变为更改user表yesno
SQL命令
$i=$_POST[“userlogin”]; //同样先获得用户名
$sql=”UPDATE user SET yesno=’1′ where user=’$o’ “;//update更新指定$o的用户名
mysql_query($sql) //如果没包含连接SQL文件,改为mysql_query($sql,$con)
/*
作者包含的config.php文件里有,所以直接执行mysql_query($sql)就可以了.
$localhost=”localhost”;
$user=”root”;
$password=””;
$con=mysql_connect($localhost,$user,$password);
$sqlname=”qingxinzui”;
mysql_select_db($sqlname,$con);
*/
在这主要用到的SQL语句方法:(当然也可以在phpmyadmin里去修改,看他给出的命令是什么)
SELECE * FROM user //读取USER表
UPDATE user SET text=’123′ where user=’admin’//更新指定user字段=admin 的text值为123
DELETC FROM user where names = ‘admin’ //删除指定names字段内为admin的一行数据
where是指定
比如UPDATE来说
如果:mysql_query(“UPDATE user SET text=’123′”);
那么就会将user表里面的text字段全部修改为123

通过清心醉

Linux CentOS SSH无法连接

昨天给家里的CentOS放了自己新写的PHP,由于需要创建config.php配置文件,所以给了777的权限(话说755好像是足够的,只是怕权限不够一次给了777),结果今天开机,导致无法SSH连接,在那电脑上,以为是系统文件的错误,可是观察系统的启动,进程,SSH也是完好的启动,怀疑到了是权限的问题.

果然,/var的权限太高,导致无法连接.才想起来,作者是在根目录直接执行chmod

恢复的办法当然也很简单了, chmod 755 /var

如果是VPS无法执行的话,但愿你还有安装phpmyadmin这种东西,把数据库拷贝出来重装过或者叫客服人员帮忙解决哦.

注:权限太高未必是好事.注意使用.

通过清心醉

错误 SET CHARACTER SET ‘utf8’;

修改了mysql的字符集为utf8之后,提示错误 SET CHARACTER SET ‘utf8’;

Aborted connection 1 to db: ‘unconnected’ user: ‘pma’ host: ‘localhost’ (init_connect command failed)

开始以为不能使用utf8字集了,后来查看了下my.ini配置文件

发现有这么一句:

错误init-connect=\’SET NAMES utf8\’

把这句注释掉就可以了。

通过清心醉

PHP实例-编写自己的PHP通讯录7-多用户注册审核及权限设置

#先写个用户注册先. login登陆的时候根据yesno的值得来判断是否允许登陆.
#1为已允许注册可登陆,0为审核状态.用户登陆时返回审核状态.
#注册文件代码:registration.php
echo “</br></br></br></br></br>”;
echo ‘<html>’;
echo ‘<title>注册</title>’;
echo ‘<body>’;
echo ‘</br></br></br></br></br>’;
echo ‘<form method=”post” action=”registrationsql.php”>’;
echo ‘<table width=”400″ align=”center”>’;
echo ‘<tr>’;
echo ‘<td>注册帐号:</td>’;
echo ‘<td><input name=”userregistration” type=”text” size=”30″ maxlength=”500″></td>’;
echo ‘</tr>’;
echo ‘<tr>’;
echo ‘<td>注册密码:</td>’;
echo ‘<td><input name=”registrationpassword” type=”text” size=”30″ maxlength=”500″></td>’;
echo ‘</tr>’;
echo ‘<td>备注:</td>’;
echo ‘<td><input name=”text1″ type=”text” size=”30″ maxlength=”500″></td>’;
echo ‘</tr>’;
echo ‘</table>’;
echo ‘<div align=”center”><input type=”submit” value=”注册”></div>’;
echo ‘</form>’;
echo ‘</body>’;
echo ‘</html>’
#然后是注册registrationsql.php执行代码
if (is_array($_POST)&&count($_POST)>0)//先判断是否通过POST传值了
{
if(!empty($_POST[“userregistration”])&&!empty($_POST[“registrationpassword”]))//是否存在参数
{
$i=$_POST[“userregistration”];
$o=md5($_POST[“registrationpassword”]); //密码实现md5加密后在对比
$j=$_POST[“text1″];//备注信息
//数据库里获取出来的帐号密码
$sql=”select * from admin where user=’$i'”;
$rs=mysql_query($sql,$con);        //连接读取表并且执行$sql里的SQL语句.
if(mysql_num_rows($rs)!=0) //如果有相等的数据.
{
echo “帐号已存在</br>”;
echo “<script>setTimeout(\”this.location=’registration.php’\”,3000);</script>”;
}
else
{
$sql1 = mysql_query(“select max(userid) sqlmaxuserid from admin”);
//定义一个查询contacts表,列为id的变量,输入的名字为sqlmaxuserid;
while($sqlmaxid = mysql_fetch_object($sql1)) //循环读取
$tempmaxid = $sqlmaxid->sqlmaxuserid; //提取出sqlmaxuserid.即管理员ID主键的最大值
$insqlmaxid=$tempmaxid+1;//注册的用户id=最大的+1
mysql_query(“INSERT INTO admin(userid,user,password,competence,yesno,text)VALUES(‘$insqlmaxid’,’$i’,'”.md5($o).”‘,’100′,’0′,’$j’)”);
//执行插入语句,id为最大的id+1,最后一个yesno默认为0,即等审核状态.competence为100,默认非管理员,因为管理员是1,以后可以通过后台对该值进行修改.
echo “注册成功,等待管理员审核</br>”;
echo “<script>setTimeout(\”this.location=’index.php’\”,2000);</script>”;
}
}
else
{
echo “请填写完整数据”;
echo “<script>setTimeout(\”this.location=’registration.php’\”,3000);</script>”;
}
}
else
{
echo “非法访问”;
echo “<script>setTimeout(\”this.location=’index.php’\”,3000);</script>”;
exit;
}

#注册好了,在contacts.php显示页面里,增加个判断是否有用户注册的功能:
#找个合适的位置加上:
/************判断是否有等待审核的用户,适用于管理员权限************/
$sql=”select * from admin where yesno=’0′”; //sql读取admin表的yesno审核列
$rso=mysql_query($sql,$con);
if(mysql_num_rows($rso)!=0)
{
echo “<a href=’useryesno.php’>有需要审核的用户</a>”;
}
/************************/

#然后实现注册的表单useryesno.php:
$sql=”select * from admin where yesno=’0′”;  //SQL读遍admin表yesno列的值为0的所有数据
$rsosql=mysql_query($sql,$con);
echo ‘<link rel=”stylesheet” type=”text/css” href=”style.css” />’;
echo ‘<div>’;
echo “<table>”;
echo ‘<tr><td>姓名</td><td>备注</td><td>操作</td></tr>’;
while($row=mysql_fetch_object($rsosql))
{
echo “<tr><td>$row->user</td><td>$row->text</td>”;
echo “<td><a href=’useryessql.php?user=$row->user’>允许</a> / <a href=’usernosql.php?user=$row->user’>禁止并删除</a></td></tr>”;
}
//其实只传递ID值也可以,然后从新从SQL里获取数据显示在表里。
echo “</table>”; //输出表格结束
echo “</div>”;
echo “<a href=’index.php’>返回主页</a>”
#表单里循环读取admin表yesno列为0的数据并显示.
#并且允许的释放yesno值=1即可以登陆,禁止就删除掉当前数据.

#先来看看useryessql.php允许的实现代码.
$o=$_GET[“user”];
$sql=”UPDATE admin SET yesno=’1′ where user=’$o’ “;//update更新指定$o的用户名并将yesno的值=1即审核通过
$yessqluser=mysql_query($sql,$con);
if($yessqluser)
{
echo “用户:”.$o.”审核通过</br>”;
echo “正在为您返回用户管理页面,请稍后”;
echo “<script>setTimeout(\”this.location=’useryesno.php’\”,2000);</script>”;
}
else
{
echo “审核通过用户:”.$o.”失败”;
echo “<script>setTimeout(\”this.location=’useryesno.php’\”,2000);</script>”;
}
/*
如果需要修改用户权限,把compentence的值由100改为1即可.方法上面的即可实现
$sql=”UPDATE admin SET compentence=’1′ where user=’$o’ “;
*/

#再来看usernosql.php禁止并删除的代码.
$o=@$_GET[“user”];
$sql = “delete from admin where user = ‘$o’ “; //禁止通过审核并且删除当前GET过来的user在admin表user列
$delsqluser=mysql_query($sql,$con);
if($delsqluser)
{
echo “用户:”.$o.”审核禁止通过</br>”;
echo “删除用户:”.$o.”成功”;
echo “<script>setTimeout(\”this.location=’useryesno.php’\”,2000);</script>”;
}
else
{
echo “删除用户:”.$o.”失败”;
echo “<script>setTimeout(\”this.location=’useryesno.php’\”,2000);</script>”;
}
#这样 简单的注册,并且管理员审核的功能就已经实现
#接下来就是要实现用户在登陆的时候,如果登陆成功,判断是否具备管理权限及是否已注册.
#在loginsql.php文件里,如果帐号密码审核正确的话,再进行一次状态和权限的审核
#实现代码:

$sql2=”select * from admin where user=’$i’ and yesno=’1′”; //SQL语句查询登陆的用户是否审核通过并且值为1了。
$rs2=mysql_query($sql2,$con);
if(mysql_num_rows($rs2)==0)
{
echo “您的帐号还在审核中”;
exit;
echo “<script>setTimeout(\”this.location=’index.php’\”,2000);</script>”;
}
#同时因为有权限字段competence,1为管理员,100为普通用户,默认注册的全部为100;
$sql1=”select * from admin where user=’$i’ and competence=’1′”; //用户名字和权限参数
$rs1=mysql_query($sql1,$con);
if(mysql_num_rows($rs1)!=0)
{
echo “欢迎您,管理员</br>”;
$_SESSION[“compectece”]=$i;
/*
如果数据库里的compectece的为1表示管理员,创建$_SESSION
*/
}现在完整的数据包:需要的可以下载测试玩玩.

htdocs20141117

 

通过清心醉

PHP实例-编写自己的PHP通讯录6-用户退出

在contacts.php显示通讯录的页面,找个位置加个退出链接
echo ‘<a href=”logout.php”>退出</a>’;
实现退出,其实就是销毁$_SEESION
<?php
header(“Content-Type:text/html;charset=utf-8”);
require_once(“inc.config.php”);
unset($_SESSION[‘add’]); //退出当前$_SESSION的add
/*
unset ($_SESSION[‘add’])删除单个session,unset($_SESSION[‘add’])
用来unregister一个已注册的session变量。
如果支持多用户登陆,切忌不可使用session_destroy()和session_unset();
因为这会清除所有的$_SESSION.
当然,如果是在后台要进行维护,T掉所有在线人员的时候可以使用.
*/
if(!isset($_SESSION[“add”]))
{
echo “退出成功”;
echo “<script>setTimeout(\”this.location=’index.php’\”,2000);</script>”;
exit;
}
else
{
echo “退出错误”;
echo “<script>setTimeout(\”this.location=’index.php’\”,2000);</script>”;
exit;
}
?>

如果想要查看代码现状,可下载:htdocs

通过清心醉

CentOS配置nginx+php-fpm+mysql

大家都说nginx怎么怎么的好,所以想尝试下效果.
昨天特地把VPS的apache换成nginx,结果导致部分FLV视频无法播放,很简单,nginx的模块没添加支持,可是配置比较麻烦,而且是第一次配置nginx.所以留着在家里的电脑慢慢试,暂时恢复apache+php+mysql.现在来说说如何简单配置.
[root@linux ~]# yum remove httpd* php* mysql*
#首先我们要把旧版的apache和php和mysql彻底删除,如果您的是新系统没有安装,可以跳过这步

#安装nginx并且设置开机启动
[root@linux ~]# yum install nginx
[root@linux ~]# chkconfig –level 345 nginx on
[root@linux ~]# service nginx start #启动nginx
#接下来是安装php-fpm模块,同样加如开机启动
[root@linux ~]# yum install php php-fpm
[root@linux ~]# chkconfig –level 345 php-fpm on
[root@linux ~]# service php-fpm #启动php-fpm

#别忘记了安装MYSQL等其他模块,MYSQL也别忘记加入开机启动哦

[root@linux ~]# yum install php-gd php-mysql php-mbstring php-xml mysql-server
[root@linux ~]# chkconfig –level 345 mysqld on
[root@linux ~]# yum install php-mcrypt
#也许你会好奇,一次把php-mcrypt安装上不就OK?何必重新在这yum执行
#因为CentOS官方已经不再对mcrypt模块进行支持了,所以得使用fedora的扩展库.更多的请参考:http://www.qingxinzui.com/?p=783

以下为64位的安装方法:
在 /etc/yum.repos.d/ 目录下,建立名叫nginx.repo的软件源配置文件。
默认是没有nginx的软件源的,自己增加个下载配置.
[nginx]
name=nginx repo
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
gpgcheck=0
enabled=1
[root@linux ~]# yum install nginx
[root@linux ~]# yum install php php-fpm php-mysql
[root@linux ~]# yum install php-gd php-mbstring php-xml mysql-server
启动服务后别忘记修改MYSQL密码
mysql> SET PASSWORD FOR ‘root’@’localhost’ = PASSWORD(‘newpassword’);

进入nginx的default.conf配置的话,和32位是一样的.
//修改nginx/conf.d/default.conf.d
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
//因为yum源安装的nginx user=user
//vi /etc/php-fpm.d/里面的配置文件里的用户及用户组为对应nginx,具体查看自己nginx.conf

通过清心醉

xampp for Linux修改mysql字符集为UTF-8

最近给自己测试PHP代码的电脑换了个快速XAMPP for linux版本,却老是UTF-8字符乱码
以修改yum源安装的方式修改好像没效果.
直接上方法吧:
[root@linux~]# vi /opt/lampp/etc/my.cnf
配置里有不同的mysql的设置,比如字符,端口什么的
[client] #在这端里面加入
default-character-set=utf8 #增加默认为UTF8

[mysqld]
character-set-server=utf8

[mysql]
character-set-server=utf8
然后重启就可以了.

通过清心醉

magento paypal多货币支付 快速支付

以下为快速支付方式,其实和标准支付差不多,只是多了些修改:

这个功能的修改涉及到5个核心文件

先来说下需要修改的几个文件路径

app/code/core/Mage/Paypal/Model/Express.php

app/code/core/Mage/Paypal/Model/Cart.php

app/code/core/Mage/Paypal/Model/Express/Checkout.php

app/code/core/Mage/Sales/Model/Order/Payment.php

app/code/core/Mage/Core/Model/Store.php

主要要修改什么 先在这里说明一下,大家都知道paypal是可以支付多种货币的,关于这点可以下载官网的示例来看,想要改变支付的货币种类 要修改的一个是传给paypal的参数也就是货币符号,另外一个就是价格,虽然magento前台页面以及购物车看到的是日元,关键在于再给paypal传产品价格的时候用的是基础货币,而不是当前货币换算出来的结果,下面我就来发出关键代码,为有需要的同学提供方便

app/code/core/Mage/Paypal/Model/Express.php

/**
* Order payment
*
* @param Mage_Sales_Model_Order_Payment $payment
* @param float $amount
* @return Mage_Paypal_Model_Express
*/
public function order(Varien_Object $payment, $amount)
{
<span style=”white-space:pre”> </span>…
//修改 :去掉getBaseCurrentCurrency() 中的Base
$formatedPrice = $order->getCurrentCurrency()->formatTxt($amount);
<span style=”white-space:pre”> </span>…

/**
* Capture payment
*
* @param Mage_Sales_Model_Order_Payment $payment
* @param float $amount
* @return Mage_Paypal_Model_Express
*/
public function capture(Varien_Object $payment, $amount)
{
n style=”white-space:pre”> </span>…
$formatedPrice = $order->getCurrentCurrency()->formatTxt($amount);//修改

n style=”white-space:pre”> </span>…

/**
* Place an order with authorization or capture action
*
* @param Mage_Sales_Model_Order_Payment $payment
* @param float $amount
* @return Mage_Paypal_Model_Express
*/
protected function _placeOrder(Mage_Sales_Model_Order_Payment $payment, $amount)
{
$order = $payment->getOrder();

// prepare api call
$token = $payment->getAdditionalInformation(Mage_Paypal_Model_Express_Checkout::PAYMENT_INFO_TRANSPORT_TOKEN);
$api = $this->_pro->getApi()
->setToken($token)
->setPayerId($payment->
getAdditionalInformation(Mage_Paypal_Model_Express_Checkout::PAYMENT_INFO_TRANSPORT_PAYER_ID))
->setAmount($amount)
->setPaymentAction($this->_pro->getConfig()->paymentAction)
->setNotifyUrl(Mage::getUrl(‘paypal/ipn/’))
->setInvNum($order->getIncrementId())
->setCurrencyCode(Mage::app()->getStore()->getCurrentCurrencyCode())//修改
->setPaypalCart(Mage::getModel(‘paypal/cart’, array($order)))
->setIsLineItemsEnabled($this->_pro->getConfig()->lineItemsEnabled)
;
if ($order->getIsVirtual()) {
$api->setAddress($order->getBillingAddress())->setSuppressShipping(true);
} else {
$api->setAddress($order->getShippingAddress());
$api->setBillingAddress($order->getBillingAddress());
}

// call api and get details from it
$api->callDoExpressCheckoutPayment();

$this->_importToPayment($api, $payment);
return $this;
}

/**
* Call DoAuthorize
*
* @param int $amount
* @param Varien_Object $payment
* @param string $parentTransactionId
* @return Mage_Paypal_Model_Api_Abstract
*/
protected function _callDoAuthorize($amount, $payment, $parentTransactionId)
{
$api = $this->_pro->resetApi()->getApi()
->setAmount($amount)
->setCurrencyCode(Mage::app()->getStore()->getCurrentCurrencyCode())//修改
->setTransactionId($parentTransactionId)
->callDoAuthorization();

$payment->setAdditionalInformation($this->_authorizationCountKey,
$payment->getAdditionalInformation($this->_authorizationCountKey) + 1
);

return $api;
}
app/code/core/Mage/Paypal/Model/Cart.php
/**
* (re)Render all items and totals
*/
protected function _render()
{
if (!$this->_shouldRender) {
return;
}

// regular items from the sales entity
$this->_items = array();
foreach ($this->_salesEntity->getAllItems() as $item) {
if (!$item->getParentItem()) {
$this->_addRegularItem($item);
}
}
end($this->_items);
$lastRegularItemKey = key($this->_items);

// regular totals
$shippingDescription = ”;
if ($this->_salesEntity instanceof Mage_Sales_Model_Order) {
$shippingDescription = $this->_salesEntity->getShippingDescription();
$this->_totals = array(
self::TOTAL_SUBTOTAL => $this->_salesEntity->getSubtotal(),//修改
self::TOTAL_TAX => $this->_salesEntity->getTaxAmount(),//修改
self::TOTAL_SHIPPING => $this->_salesEntity->getShippingAmount(),//修改
self::TOTAL_DISCOUNT => abs($this->_salesEntity->getDiscountAmount()),//修改
);
$this->_applyHiddenTaxWorkaround($this->_salesEntity);
} else {
$address = $this->_salesEntity->getIsVirtual() ?
$this->_salesEntity->getBillingAddress() : $this->_salesEntity->getShippingAddress();
$shippingDescription = $address->getShippingDescription();
$this->_totals = array (
self::TOTAL_SUBTOTAL => $this->_salesEntity->getSubtotal(),//修改
self::TOTAL_TAX => $address->getTaxAmount(),//修改
self::TOTAL_SHIPPING => $address->getShippingAmount(),//修改
self::TOTAL_DISCOUNT => abs($address->getDiscountAmount()),//修改
);
$this->_applyHiddenTaxWorkaround($address);
}
$originalDiscount = $this->_totals[self::TOTAL_DISCOUNT];
/**
* Check the line items and totals according to PayPal business logic limitations
*/
protected function _validate()
{
$this->_areItemsValid = false;
$this->_areTotalsValid = false;

$referenceAmount = $this->_salesEntity->getGrandTotal();//修改

$itemsSubtotal = 0;
foreach ($this->_items as $i) {
$itemsSubtotal = $itemsSubtotal + $i[‘qty’] * $i[‘amount’];
}
$sum = $itemsSubtotal + $this->_totals[self::TOTAL_TAX];
if (!$this->_isShippingAsItem) {
$sum += $this->_totals[self::TOTAL_SHIPPING];
}
if (!$this->_isDiscountAsItem) {
$sum -= $this->_totals[self::TOTAL_DISCOUNT];
}

/**
* Add a usual line item with amount and qty
*
* @param Varien_Object $salesItem
* @return Varien_Object
*/
protected function _addRegularItem(Varien_Object $salesItem)
{
if ($this->_salesEntity instanceof Mage_Sales_Model_Order) {
$qty = (int) $salesItem->getQtyOrdered();
$amount = (float) $salesItem->getPrice();//修改
// TODO: nominal item for order
} else {
$qty = (int) $salesItem->getTotalQty();
$amount = $salesItem->isNominal() ? 0 : (float) $salesItem->getCalculationPrice();//修改
}
// workaround in case if item subtotal precision is not compatible with PayPal (.2)
$subAggregatedLabel = ”;
if ($amount – round($amount, 2)) {
$amount = $amount * $qty;
$subAggregatedLabel = ‘ x’ . $qty;
$qty = 1;
}

// aggregate item price if item qty * price does not match row total
if (($amount * $qty) != $salesItem->getRowTotal()) {//修改
$amount = (float) $salesItem->getRowTotal();//修改
$subAggregatedLabel = ‘ x’ . $qty;
$qty = 1;
}

return $this->addItem($salesItem->getName() . $subAggregatedLabel, $qty, $amount, $salesItem->getSku());
}

/**
* Add “hidden” discount and shipping tax
*
* Go ahead, try to understand ]:->
*
* Tax settings for getting “discount tax”:
* – Catalog Prices = Including Tax
* – Apply Customer Tax = After Discount
* – Apply Discount on Prices = Including Tax
*
* Test case for getting “hidden shipping tax”:
* – Make sure shipping is taxable (set shipping tax class)
* – Catalog Prices = Including Tax
* – Shipping Prices = Including Tax
* – Apply Customer Tax = After Discount
* – Create a shopping cart price rule with % discount applied to the Shipping Amount
* – run shopping cart and estimate shipping
* – go to PayPal
*
* @param Mage_Core_Model_Abstract $salesEntity
*/
private function _applyHiddenTaxWorkaround($salesEntity)
{
$this->_totals[self::TOTAL_TAX] += (float)$salesEntity->getHiddenTaxAmount();//修改
$this->_totals[self::TOTAL_TAX] += (float)$salesEntity->getShippingHiddenTaxAmount();//修改
}
app/code/core/Mage/Paypal/Model/Express/Checkout.php
/**
* Checkout with PayPal image URL getter
* Spares API calls of getting “pal” variable, by putting it into cache per store view
* @return string
*/
public function getCheckoutShortcutImageUrl()
{
// get “pal” thing from cache or lookup it via API
$pal = null;
if ($this->_config->areButtonsDynamic()) {
$cacheId = self::PAL_CACHE_ID . Mage::app()->getStore()->getId();
$pal = Mage::app()->loadCache($cacheId);
if (-1 == $pal) {
$pal = null;
} elseif (!$pal) {
$pal = null;
$this->_getApi();
try {
$this->_api->callGetPalDetails();
$pal = $this->_api->getPal();
Mage::app()->saveCache($pal, $cacheId, array(Mage_Core_Model_Config::CACHE_TAG));
} catch (Exception $e) {
Mage::app()->saveCache(-1, $cacheId, array(Mage_Core_Model_Config::CACHE_TAG));
Mage::logException($e);
}
}
}

return $this->_config->getExpressCheckoutShortcutImageUrl(
Mage::app()->getLocale()->getLocaleCode(),
$this->_quote->getGrandTotal(),//修改去掉base
$pal
);
}

/**
* Reserve order ID for specified quote and start checkout on PayPal
* @return string
*/
public function start($returnUrl, $cancelUrl)
{
$this->_quote->collectTotals();

if (!$this->_quote->getGrandTotal() && !$this->_quote->hasNominalItems()) {
Mage::throwException(Mage::helper(‘paypal’)->__(‘PayPal does not support processing orders with zero amount. To complete your purchase, proceed to the standard checkout process.’));
}

$this->_quote->reserveOrderId()->save();
// prepare API
$this->_getApi();
$this->_api->setAmount($this->_quote->getGrandTotal())//修改去掉base
//->setCurrencyCode($this->_quote->getBaseCurrencyCode())///修改为当前货币code
->setCurrencyCode(Mage::app()->getStore()->getCurrentCurrencyCode())
->setInvNum($this->_quote->getReservedOrderId())
->setReturnUrl($returnUrl)
->setCancelUrl($cancelUrl)
->setSolutionType($this->_config->solutionType)
->setPaymentAction($this->_config->paymentAction)
app/code/core/Mage/Sales/Model/Order/Payment.php
/**
* Capture the payment online
* Requires an invoice. If there is no invoice specified, will automatically prepare an invoice for order
* Updates transactions hierarchy, if required
* Updates payment totals, updates order status and adds proper comments
*
* TODO: eliminate logic duplication with registerCaptureNotification()
*
* @return Mage_Sales_Model_Order_Payment
* @throws Mage_Core_Exception
*/
public function capture($invoice)
{
if (is_null($invoice)) {
$invoice = $this->_invoice();
$this->setCreatedInvoice($invoice);
return $this; // @see Mage_Sales_Model_Order_Invoice::capture()
}
$amountToCapture = $this->_formatAmount($invoice->getGrandTotal());//修改
$order = $this->getOrder();

/**
* Decide whether authorization transaction may close (if the amount to capture will cover entire order)
* @param float $amountToCapture
* @return bool
*/
protected function _isCaptureFinal($amountToCapture)
{
$amountToCapture = $this->_formatAmount($amountToCapture, true);
$orderGrandTotal = $this->_formatAmount($this->getOrder()->getGrandTotal(), true);//修改
if ($orderGrandTotal == $this->_formatAmount($this->getAmountPaid(), true) + $amountToCapture)//修改

{

if (false !== $this->getShouldCloseParentTransaction()) {
$this->setShouldCloseParentTransaction(true);
}
return true;
}
return false;
}
app/code/core/Mage/Core/Model/Store.php

/**
* Round price
*
* @param mixed $price
* @return double
*/
public function roundPrice($price)
{ //类的内容修改为以下: JYP是使用计价货币
if(Mage::app()->getStore()->getCurrentCurrencyCode()==’JPY’){
return round($price,0);
}else{
return round($price, 2);
}
}

/**
* Format price with currency filter (taking rate into consideration)
*
* @param double $price
* @param bool $includeContainer
* @return string
*/
public function formatPrice($price, $includeContainer = true)
{  //重写该类的方法.
if ($this->getCurrentCurrency()) {
if(Mage::app()->getStore()->getCurrentCurrencyCode()==’JPY’){
return $this->getCurrentCurrency()->format($price, array(‘precision’=>0), $includeContainer);
}else{
return $this->getCurrentCurrency()->format($price, array(), $includeContainer);
}
}
return $price;
}

通过清心醉

PHP实例-编写自己的PHP通讯录5-修改/删除联系人

修改/删除联系人,都是通过唯一ID来进行操作,为什么呢?

因为如果根据名字,可能会有相同,性别更不可能了.而ID是自增的唯一的.

在contacts.php输出文件里有了修改和删除的功能.

<a href=’modification.php?id=$row->id&names=$row->names&sex=$row->sex&phone=$row->phone&address=$row->address’>修改</a>/<a href=’delete.php?id=$row->id’>删除</a>

删除的话,根据ID就可以了,而修改的话,因为除了ID外的姓名/性别/电话/地址,都是可以修改的项目.所以都传递过去可以知道自己具体修改的是哪些.

先来看看删除:

<a href=’delete.php?id=$row->id’>删除</a>

当把id以GET的方式传递了之后

<?php

#delete.php
header(“Content-Type:text/html;charset=utf-8”);
//20141112
require_once(“inc.config.php”);
require_once (“config.php”);
$deluserid=@$_GET[“id”]; //获得要删除的ID
if (is_array($_GET)&&count($_GET)>0)//是否通过POST传值了
{
if(isset($_GET[“id”]))
{
$delusersql=”DELETE FROM contacts WHERE id = ‘$deluserid'”;
if(!mysql_query($delusersql,$con))
{
die(‘删除出错: ‘ .mysql_error());
}
echo “删除成功</br>”;
mysql_close($con);
echo “正在返回首页,请稍后…”;
echo “<script>setTimeout(\”this.location=’index.php’\”,2000);</script>”;
exit;
}
else{    echo “非法访问”;}
}
echo “非法访问”;
?>

MYSQL语句里根据传递的ID,删除ID列为GET传递的数据.

然后我们再来看看修改联系人

<?php
header(“Content-Type:text/html;charset=utf-8”);
//修改联系人代码
require_once(“inc.config.php”);
require_once (“config.php”);
$modificationid=@$_GET[“id”]; //获得要删除的ID
$modificationnames=@$_GET[“names”];
$modificationsex=@$_GET[“sex”];
$modificationphone=@$_GET[“phone”];
$modificationaddress=@$_GET[“address”];
if (is_array($_GET)&&count($_GET)>0)//是否通过GET传值了
{
if(isset($_GET[“id”]))//传递的值是否有ID.由于不增加代码繁琐,所以只验证ID
/*说明::
readonly元素:禁止用户修改,参与$_GET和$_POST传递参数
disabled元素:禁止用户修改,不参与$_GET和$_POST传递参数
由于需要通过ID来进行判断修改的MYSQL数据是哪一个
而前面增加数据的时候,是通过最大的ID+1的方式,就不会有重复.
如此一来,就必须要禁止掉用户进行ID的表单修改和允许传递参数.
$_GET获取的ID值,在通过$_POST传递到后面处理代码页面.
*/
{
echo ‘<form method=”post” action=”modificationsql.php”>’;
echo “</br></br></br></br>”;
echo “<table width=’400′ align=’center’>”;
echo “<tr>”;
echo “<td>编号</br><input readonly=’value’ name=’modification0′ type=’text’ size=’30’ maxlength=’500′ value=’$modificationid’></td>”;
echo “</tr>”;
echo “<tr>”;
echo “<td>名字</br>
<input name=’modification1′ type=’text’ size=’30’ maxlength=’500′ value=’$modificationnames’></td>”;
echo “</tr>”;
echo “<tr>”;
echo “<td>性别</br>
<input name=’modification2′ type=’radio’ size=’30’ maxlength=’30’ value=’男’>男”;
echo “<input name=’modification2′ type=’radio’ size=’30’ maxlength=’30’ value=’男’>女</td>”;
echo “</tr>”;
echo “<tr>”;
echo “<td>联系电话</br>
<input name=’modification3′ type=’text’ size=’30’ maxlength=’500′ value=’$modificationphone’></td>”;
echo “</tr>”;
echo “<tr>”;
echo “<td>联系地址</br>
<input name=’modification4′ type=’text’ size=’30’ maxlength=’500′ value=’$modificationaddress’></td>”;
echo “</tr>”;
echo “<tr>”;
echo “<td align=’center’><input type=’submit’ value=’修改’></td>”;
echo “</tr>”;
echo “</table>”;
}
else{    echo “非法访问”;}
}
else
{
echo “非法访问”;
}
?>

#首先对GET过来的变量进行输出处理,如果用户不去修改,则保存默认的数据,但ID限制了修改.

操作方法:

<?php
header(“Content-Type:text/html;charset=utf-8”);
//修改联系人代码
require_once(“inc.config.php”);
require_once (“config.php”);
$tempcationid=@$_POST[“modification0”];
$tempcationnames=@$_POST[“modification1”];
$tempcationsex=@$_POST[“modification2”];
$tempcationphone=@$_POST[“modification3”];
$tempcationaddress=@$_POST[“modification4”];
/*获取用户修改的数据*/
if (is_array($_POST)&&count($_POST)>0)//判断POST传值
{
if(isset($_POST[“modification0”])&&isset($_POST[“modification1”])&&isset($_POST[“modification2”])&&isset($_POST[“modification3”]))//判断要修改的数据是否全部传递
{
//进行名字,性别,电话,地址的修改,WHERE id=’$tempcationid’表示限制修改这个变量的参数ID
if(!eregi(“^[0-9]+$”,$tempcationphone))
{
echo “电话号码非数字”;
echo “<script>setTimeout(\”this.location=’index.php’\”,2000);</script>”;
exit;
}
$modificationinsql=”UPDATE contacts SET
names= ‘$tempcationnames’,
sex=’$tempcationsex’,
phone=’$tempcationphone’,
address=’$tempcationaddress’
WHERE id=’$tempcationid'”;
mysql_query($modificationinsql,$con);
echo “修改成功</br>”;
mysql_close($con);
echo “正在返回首页,请稍后…”;
echo “<script>setTimeout(\”this.location=’index.php’\”,2000);</script>”;
}
else{    echo “请完整填写数据!”;
echo “<script>setTimeout(\”this.location=’index.php’\”,2000);</script>”;
}
}
else
{
echo “非法访问”;
}

?>
由于contacts.php传递到表单的方式是GET的方式传递参数到modification.php,GET进行处理后,再以POST的方式传递到modificationsql.php中.

那是怎么知道我们修改的是哪一行的用户数据呢?

$modificationinsql=”UPDATE contacts SET
names= ‘$tempcationnames’,
sex=’$tempcationsex’,
phone=’$tempcationphone’,
address=’$tempcationaddress’
WHERE id=’$tempcationid'”;

前面的4行是要写入到哪一列的列名=$变量数据

最后一句:WHERE id=’$tempcationid'”; #//最后面的分号是语句上的

表示,只写入ID=$tempcationid的参数,$tempcationid的参数是从上一个modification.php页面POST过来的,modification.php里又是从contacts.php里的URL里以GET的方式传递过来的.在contacts.php里已经有?id=$row->id传递.

顺序来写吧:

contacts.php从URL里?id=$row->id以GET方式传递到modification.php表单;

modification.php表单通过input readonly元素限制修改,在以value=’$modificationid’的方式保留原ID参数以POST方式传递给modificationsql.php页面(注:$modificationid是$_GET[“id”]的一个变量)

然后modificationsql.php修改的时候,因为WHERE id=’$tempcationid'”来限制在某一行,就不会全部进行修改.到此,整个PHP+MYSQL基础通讯录就完成了.

 

 

 

通过清心醉

PHP实例-编写自己的PHP通讯录4-添加联系人

添加联系人的话,其实就是插入MYSQL数据,相对来说还是容易理解的.

只是在添加的时候,唯一的ID值必须+1,才能确保不会重复,这样对后续的修改和删除会有帮助.比较容易管理.

<?php
header(“Content-Type:text/html;charset=utf-8”);
//增加联系人表单
require_once(“inc.config.php”); //增加验证.防止恶意文件访问增加数据
?>
<html>
<title>添加联系人</title>
<body>
<form method=”post” action=”increasesql.php”>
<table width=”400″ align=”center”>
<tr>
<td>联系人名字(NAME):</td>
<td><input name=”contactsname” type=”text” size=”30″ maxlength=”500″></td>
</tr>
<tr>
<td>联系人性别(SEX):</td>
<td><input name=”contactssex” type=”radio” size=”30″ maxlength=”30″ value=”男”>男
<input name=”contactssex” type=”radio” size=”30″ maxlength=”30″ value=”男”>女</td></td>
</tr>
<tr>
<td>联系人电话(PHONE):</td>
<td><input name=”contactsphone” type=”text” size=”30″ maxlength=”500″></td>
</tr>
<tr>
<td>联系人地址(ADDRESS):</td>
<td><input name=”contactsaddress” type=”text” size=”30″ maxlength=”500″></td>
</tr>
</table>
<div align=”center”><input type=”submit” value=”添加”></div>
</form>
</body>
</html>

#因为ID不能由用户自己设置,所以在SQL执行的位置对ID进行特别处理,具体请看:

<?php
header(“Content-Type:text/html;charset=utf-8”);
//增加联系人SQL操作.
require_once(“inc.config.php”); //验证身份
require_once (“config.php”);//获取数据库信息
$contactsname= @$_POST[“contactsname”];
$contactssex= @$_POST[“contactssex”];
$contactsphone= @$_POST[“contactsphone”];
$contactsaddress= @$_POST[“contactsaddress”];
if (is_array($_POST)&&count($_POST)>0)
{
if(!empty($_POST[“contactsname”])&&!empty($_POST[“contactssex”])&&!empty($_POST[“contactsphone”])&&!empty($_POST[“contactsaddress”]))
//!empty比isset好的就是,isset是判断是否存在,!empty是判断是否为空值
{
if(!eregi(“^[0-9]+$”,$contactsphone)) //判断是否非数字
{
echo “电话号码非数字”;
echo “<script>setTimeout(\”this.location=’index.php’\”,2000);</script>”;
exit;
}
$contacts = mysql_query(“select max(id) sqlmaxid from contacts”);
//定义一个查询contacts表,列为id的变量,输入的名字为sqlmaxid;
while($sqlmaxid = mysql_fetch_object($contacts)) //循环读取
$tempmaxid = $sqlmaxid->sqlmaxid;
//定义临时变量,参数=while循环变量的sqlmaxid指向sql语句中的max(id),命名为sqlmaxid(第10行的sql语句中)
$insqlmaxid=$tempmaxid+1;
//定义写入SQL的id,值=while循环提出出来的最大id值+1;
$increasesql=”INSERT INTO contacts(id,names,sex,phone,address) VALUES(‘$insqlmaxid’,’$contactsname’,’$contactssex’,’$contactsphone’,’$contactsaddress’)”;
mysql_query($increasesql,$con);//插入$_POST的数据和+1的id参数到数据库
mysql_close($con); //关闭MYSQL
echo “添加联系人成功</br>”;
echo “正在返回首页,请稍后…”;
echo “<script>setTimeout(\”this.location=’index.php’\”,2000);</script>”;
}
else
{
echo “请完整填写数据!”;
echo “<script>setTimeout(\”this.location=’index.php’\”,2000);</script>”;
}
}
else
{
echo “非法访问”;
}
?>

#从这代码应该可以看出来,通过while循环读取contacts表里的id列,max是最大的意思,然后由于读出后,要给他命名,作者命名为sqlmaxid.