本文主要介绍mysql_real_escape_string对用户提交的表单数据进行转义处理。
并介绍addslashes()以及mysql_escape_string这3个类似功能的函数用法区别。
Mysql查询带引号和不带引号区别
当数据库字段ID为整型时
select ID from table where ID=1
和
select ID from table where ID='1'
两条sql都是可以的,但是第一条sql不用进行隐式转换,速度上比第二条sql略快一些
向mysql数据库中插入带单引号字符串,什么错也没报就是语句执行失败,原因在于单引号等要转义,可以使用函数:mysql_real_escape_string和addslashes函数;
在sql防注入方面,addslashes的问题在于黑客可以用0xbf27来代替单引号,而addslashes只是将0xbf27修改为0xbf5c27,成为一个有效的多字节字符,其中的0xbf5c仍会被看作是单引号,所以addslashes无法成功拦截。
当然addslashes也不是毫无用处,它是用于单字节字符串的处理,多字节字符还是用mysql_real_escape_string吧。
php手册中get_magic_quotes_gpc的例子:
<?php
if (!get_magic_quotes_gpc()) {
$lastname = addslashes($_POST["lastname"]);
} else {
$lastname = $_POST['lastname'];
}
?>
在magic_quotes_gpc已经开放的情况下,还是对$_POST['lastname']进行检查一下。
mysql_real_escape_string和mysql_escape_string这2个函数的区别:
mysql_real_escape_string 必须在(PHP 4 >= 4.3.0, PHP 5)的情况下才能使用。否则只能用 mysql_escape_string ,两者的区别是:
mysql_real_escape_string 考虑到连接的当前字符集,而mysql_escape_string 不考虑。
总结:
addslashes() 是强行加;
mysql_real_escape_string() 会判断字符集,但是对PHP版本有要求;
mysql_escape_string不考虑连接的当前字符集。
方法1,使用google开放api
<?php
/*
二维码
*/
$urlToEncode="http://www.";
generateQRfromGoogle($urlToEncode);
function generateQRfromGoogle($chl,$widhtHeight ='150',$EC_level='L',$margin='0')
{
$url = urlencode($url);
echo '<img src="http://chart.apis.google.com/chart?chs='.$widhtHeight.'x'.$widhtHeight.'&cht=qr&chld='.$EC_level.'|'.$margin.'&chl='.$chl.'" alt="QR code" widhtHeight="'.$size.'" widhtHeight="'.$size.'"/>';
}
?>
方法2,使用php类库PHP QR Code
类库下载:http://sourceforge.net/projects/phpqrcode/
类库中的index.php为演示例子。
下面是自己写的一个例子。
<?php
/*
生成二维码
*/
include('./phpqrcode.php');
// 二维码数据
$data = 'http://www..com';
// 纠错级别:L、M、Q、H
$errorCorrectionLevel = 'L';
// 点的大小:1到10
$matrixPointSize = 4;
// 生成的文件名
$path = "erwei/";
if (!file_exists($path)){
mkdir($path);
}
$filename = $path.$errorCorrectionLevel.'.'.$matrixPointSize.'.png';
QRcode::png($data, $filename, $errorCorrectionLevel, $matrixPointSize, 2);
echo "<img src='/blog_article/$filename/index.html' />";
?>php单例演示示例:
<?php
/**
* php单例
* site www.
*/
class Example
{
// 保存类实例在此属性中
private static $instance;
// 构造方法声明为private,防止直接创建对象
private function __construct()
{
echo 'I am constructed';
}
// singleton 方法
public static function singleton()
{
if (!isset()(self::$instance)) {//判断是否以前创建了当前类的实例
$c = __CLASS__;//获取类名
self::$instance = new $c;//如果没有创建,实例化当前类,这里实现类只实例化一次
}
return self::$instance;//返回类的实例
}
// Example类中的普通方法
public function bark()
{
echo 'Woof!';
}
// 阻止用户复制对象实例
public function __clone()
{
trigger_error('Clone is not allowed.', E_USER_ERROR);
}
}
// 这个写法会出错,因为构造方法被声明为private
$test = new Example;
// 下面将得到Example类的单例对象
$test = Example::singleton();
$test->bark();
// 下面将得到Example类的单例对象
$test = Example::singleton();
$test->bark();
// 复制对象将导致一个E_USER_ERROR.
$test_clone = clone $test;
?>
您可能感兴趣的文章:
php设计模式之单例模式的实例代码
学习php设计模式之单例模式
php实现的单例模式的例子
学习php单例模式及应用实例
php单例模式的演示代码
有关php单例模式介绍及例子
php设计模式之单例模式学习
php单例模式的例子