php curl错误:SSL错误、bool(false)

症状:php curl调用https出错 排查方法:在命令行中使用curl调用试试。 原因:服务器所在机房无法验证SSL证书。 解决办法:跳过SSL证书检查。 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 症状:php curl调用curl_exec返回bool(false),命令行curl调用正常。 排查方法: var_dump(curl_error($ch)); 返回: string(23) “Empty reply from server” 再排查: curl_setopt($ch, CURLOPT_HEADER, true); curl_setopt($ch, CURLOPT_RETURNTRANSFER, false); 返回: HTTP/1.1 100 Continue Connection: close 原因:php curl接收到HTTP 100就结束了,应该继续接收HTTP 200 解决方案: curl_setopt($ch, CURLOPT_HTTPHEADER, array(‘Expect:’)); PHP and cURL: Disabling 100-continue header Published June 15th, 2006 I’ve been using cURL (through PHP) to build a sort of proxy for a project I’m working on. I need to parse the returned headers (to recover the HTTP status), so had included a very simple script to do so. It had worked fine in the past, but for some reason barfed in this case. A closer look at what was being returned revealed that for some reason, Apache was prepending the ‘normal’ headers with an extra response header: HTTP/1.1 100 Continue HTTP/1.1 200 OK Date: Fri, 09 Jun 2006 15:23:42 GMT Server: Apache …A bit of Googling revealed that this was to do with a header that cURL sends by default: Expect: 100-continue …which in turns tells Apache to send the extra header. I poked around a fair bit but couldn’t quite find a workable solution short of manually removing the header in PHP, which seemed a bit clumsy. Finally, on a hunch I tried this: curl_setopt( $curl_handle, CURLOPT_HTTPHEADER, array( ‘Expect:’ ) ); …which basically overrides the original ‘Expect:’ header with an empty one. Hope this helps someone.

检测一个值是否为 null 或 false

使用 === 操作符来检测 null 和布尔 false 值。

PHP 宽松的类型系统提供了许多不同的方法来检测一个变量的值。 然而这也造成了很多问题。 使用 == 来检测一个值是否为 null 或 false,如果该值实际上是一个空字符串或 0,也会误报为 false。 isset 是检测一个变量是否有值, 而不是检测该值是否为 null 或 false,因此在这里使用是不恰当的。 is_null() 函数能准确地检测一个值是否为 null, is_bool 可以检测一个值是否是布尔值(比如 false), 但存在一个更好的选择:=== 操作符。=== 检测两个值是否同一, 这不同于 PHP 宽松类型世界里的 相等。它也比 is_null() 和 is_bool() 要快一些,并且有些人认为这比使用函数来做比较更干净些。

示例

$x = 0;
$y = null;

// Is $x null?
if($x == null)
print(‘Oops! $x is 0, not null!’);

// Is $y null?
if(is_null($y))
print(‘Great, but could be faster.’);

if($y === null)
print(‘Perfect!’);

// Does the string abc contain the character a?
if(strpos(‘abc’, ‘a’))
// GOTCHA! strpos returns 0, indicating it wishes to return the position of the first character.
// But PHP interpretes 0 as false, so we never reach this print statement!
print(‘Found it!’);

//Solution: use !== (the opposite of ===) to see if strpos() returns 0, or boolean false.
if(strpos(‘abc’, ‘a’) !== false)
print(‘Found it for real this time!’);

陷阱

  • 测试一个返回 0 或布尔 false 的函数的返回值时,如 strpos(),始终使用 === 和!==,否则你就会碰到问题。

进一步阅读

wordpress使用Yoast SEO插件

安装完wordpress,发现所有的页面标签中是不包含keywords 和 description的,这无疑不利于SEO, 并且wordpress中本身也没有对此的设置,只好通过插件来添加,我使用的是Yoast seo插件。 看上去还不错,我在发布文章的时候,它给了我如下提示:

  • 正文才36字,太少了,增加一些吧。
  • 关键词/关键词组邮件地址 验证未出现在页面标题。
  • 已指定元描述,但是没有包含目标关键词/关键词组。
  • 此页没有任何图像,请考虑适当增加一些。
  • 关键词没有出现在正文首段,请确保一开始就明确主题。
  • 关键词/关键词组未显示在本页的URL上。如果要重写URL,请确保把原URL使用301重定向到新的URL!
  • 页面标题为9字符,小于推荐的最少40个字符。请在空处添加关键词变体或创建引人注意的文本。
  • 此页没有出站链接,请考虑适当增加一些。
  • 元描述少于120个字符。156可用字符。可用空间少于155个字符,因为Google的页面摘要上也包含发布日期。
  • 正文中没有子标题标签(例如H2标签)。
  • 以前没有使用过此目标关键词,很好。

PHP邮件地址验证

Web 应用可能需要做的一件常见任务是检测用户是否输入了一个有效的邮件地址。毫无疑问你可以在网上找到一些声称可以解决该问题的复杂的正则表达式,但是最简单的方法是使用 PHP 的内建 filter_val() 函数。

理解Python的With语句

With语句是什么?

Python’s with statement provides a very convenient way of dealing with the situation where you have to do a setup and teardown to make something happen. A very good example for this is the situation where you want to gain a handler to a file, read data from the file and the close the file handler. 有一些任务,可能事先需要设置,事后做清理工作。对于这种场景,Python的with语句提供了一种非常方便的处理方式。一个很好的例子是文件处理,你需要获取一个文件句柄,从文件中读取数据,然后关闭文件句柄。 Without the with statement, one would write something along the lines of: 如果不用with语句,代码如下:

1

2

3

file = open``(``"/tmp/foo.txt"``)

data = file``.read()

file``.close()

There are two annoying things here. First, you end up forgetting to close the file handler. The second is how to handle exceptions that may occur once the file handler has been obtained. One could write something like this to get around this: 这里有两个问题。一是可能忘记关闭文件句柄;二是文件读取数据发生异常,没有进行任何处理。下面是处理异常的加强版本:

1

2

3

4

5

file = open``(``"/tmp/foo.txt"``)

try``:

data = file``.read()

finally``:

file``.close()

While this works well, it is unnecessarily verbose. This is where with is useful. The good thing about with apart from the better syntax is that it is very good handling exceptions. The above code would look like this, when using with: 虽然这段代码运行良好,但是太冗长了。这时候就是with一展身手的时候了。除了有更优雅的语法,with还可以很好的处理上下文环境产生的异常。下面是with版本的代码:

1

2

with open``(``"/tmp/foo.txt"``) as file``:

data = file``.read()

with如何工作?

while this might look like magic, the way Python handles with is more clever than magic. The basic idea is that the statement after with has to evaluate an object that responds to an __enter__() as well as an __exit__() function. 这看起来充满魔法,但不仅仅是魔法,Python对with的处理还很聪明。基本思想是with所求值的对象必须有一个__enter__()方法,一个__exit__()方法。 After the statement that follows with is evaluated, the __enter__() function on the resulting object is called. The value returned by this function is assigned to the variable following as. After every statement in the block is evaluated, the __exit__() function is called. 紧跟with后面的语句被求值后,返回对象的__enter__()方法被调用,这个方法的返回值将被赋值给as后面的变量。当with后面的代码块全部被执行完之后,将调用前面返回对象的__exit__()方法。 This can be demonstrated with the following example: 下面例子可以具体说明with如何工作:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

#!/usr/bin/env python

# with_example01.py

class Sample:

def __enter__(``self``):

print "In __enter__()"

return "Foo"

def __exit__(``self``, type``, value, trace):

print "In __exit__()"

def get_sample():

return Sample()

with get_sample() as sample:

print "sample:"``, sample

When executed, this will result in: 运行代码,输出如下

1

2

3

4

bash``-``3.2``$ .``/``with_example01.py

In __enter__()

sample: Foo

In __exit__()

As you can see, The __enter__() function is executed The value returned by it - in this case “Foo” is assigned to sample The body of the block is executed, thereby printing the value of sample ie. “Foo” The __exit__() function is called. What makes with really powerful is the fact that it can handle exceptions. You would have noticed that the __exit__() function for Sample takes three arguments - val, type and trace. These are useful in exception handling. Let’s see how this works by modifying the above example. 正如你看到的, 1. __enter__()方法被执行 2. __enter__()方法返回的值 - 这个例子中是”Foo”,赋值给变量’sample’ 3. 执行代码块,打印变量”sample”的值为 “Foo” 4. __exit__()方法被调用 with真正强大之处是它可以处理异常。可能你已经注意到Sample类的__exit__方法有三个参数- val, type 和 trace。 这些参数在异常处理中相当有用。我们来改一下代码,看看具体如何工作的。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

#!/usr/bin/env python

# with_example02.py

class Sample:

def __enter__(``self``):

return self

def __exit__(``self``, type``, value, trace):

print "type:"``, type

print "value:"``, value

print "trace:"``, trace

def do_something(``self``):

bar = 1``/``0

return bar + 10

with Sample() as sample:

sample.do_something()

Notice how in this example, instead of get_sample(), with takes Sample(). It does not matter, as long as the statement that follows with evaluates to an object that has an __enter__() and __exit__() functions. In this case, Sample()’s __enter__() returns the newly created instance of Sample and that is what gets passed to sample. 这个例子中,with后面的get_sample()变成了Sample()。这没有任何关系,只要紧跟with后面的语句所返回的对象有__enter__()和__exit__()方法即可。此例中,Sample()的__enter__()方法返回新创建的Sample对象,并赋值给变量sample。 When executed: 代码执行后:

1

2

3

4

5

6

7

8

9

10

bash``-``3.2``$ .``/``with_example02.py

type``: <``type 'exceptions.ZeroDivisionError'``>

value: integer division or modulo by zero

trace: <traceback object at 0x1004a8128``>

Traceback (most recent call last):

File "./with_example02.py"``, line 19``, in <module>

sample.do_something()

File "./with_example02.py"``, line 15``, in do_something

bar = 1``/``0

ZeroDivisionError: integer division or modulo by zero

Essentially, if there are exceptions being thrown from anywhere inside the block, the __exit__() function for the object is called. As you can see, the type, value and the stack trace associated with the exception thrown is passed to this function. In this case, you can see that there was a ZeroDivisionError exception being thrown. People implementing libraries can write code that clean up resources, close files etc. in their __exit__() functions. 实际上,在with后面的代码块抛出任何异常时,__exit__()方法被执行。正如例子所示,异常抛出时,与之关联的type,value和stack trace传给__exit__()方法,因此抛出的ZeroDivisionError异常被打印出来了。开发库时,清理资源,关闭文件等等操作,都可以放在__exit__方法当中。 Thus, Python’s with is a nifty construct that makes code a little less verbose and makes cleaning up during exceptions a bit easier. 因此,Python的with语句是提供一个有效的机制,让代码更简练,同时在异常产生时,清理工作更简单。 I have put the code examples given here on Github. 示例代码可以在Github上面找到。 译注:本文原文见Understanding Python’s “With” Statement

PHP使用JQuery, AJAX and JSONP实现跨域请求的例子

If you’ve ever needed to make a cross-domain call via AJAX you’ve probably run into the dreaded same origin policy: _The policy permits scripts running on pages originating from the same site to access each other’s methods and properties with no specific restrictions, but prevents access to most methods and properties across pages on different sites._Today I’ll show you how you can use JQuery to easily do this and I’ll do it with the additional help of PHP. Note: With HTML5 a method was formalized for this particular thing (cross-domain calls) and it’s known as the postMessage interface. It would be great to use this but sadly it’s not implemented on all browsers yet and of course HTML5 has yet to fully reach maturity so things can change (take a look at the recent changes with WebSocket circa 2010 early 2011). The easy part is setting up a PHP page to listen for incoming data and send back a result. Not only will we send back data but we will also send back the function name we want to call on the client’s browser. Here is the PHP code:

<!--?php

header(``"content-type: text/javascript"``);

if``(isset(``$_GET``[``'name'``]) && isset(``$_GET``[``'callback'``]))

{

$obj``--->name = $_GET``[``'name'``];

$obj``->message = "Hello " . $obj``->name;

echo $_GET``[``'callback'``]. '(' . json_encode(``$obj``) . ');'``;

}

?>

You can see two parameters come in: name and callback The name is some user defined string, in this case I will use my actual name. I then format the response to be JavaScript. Note: Keep in mind when you go to test this that you put your HTML file on one site and the PHP file on a different one and that way you can assure it’s working. If you put both the PHP and HTML file on the same site JQuery will actually just default back to a regular AJAX call from what I’ve read. The HTML file is actually pretty simple as well if your familiar with JQuery AJAX:

<``title``>JQuery JSONP</``title``>

<``script src``=``"http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"``></``script``>

<``script``>

$(document).ready(function(){

$("#useJSONP").click(function(){

$.ajax({

url: 'http://domain.com/jsonp-demo.php',

data: {name: 'Chad'},

dataType: 'jsonp',

jsonp: 'callback',

jsonpCallback: 'jsonpCallback',

success: function(){

alert("success");

}

});

});

});

function jsonpCallback(data){

$('#jsonpResult').text(data.message);

}

</``script``>

<``input type``=``"button" id``=``"useJSONP" value``=``"Use JSONP"``><``br``><``br``>

<``span id``=``"jsonpResult"``></``span``>

This creates a simple HTML page with a button and clicking on it produces the desired result (see below). There are two things to note here: 1. You need to set the dataType as jsonp 2. Setting jsonp to callback and then setting jsonpCallback to jsonpCallback makes the querystring look like this:

http://domain.com/jsonp-demo.php?callback=jsonpCallback&name=Chad

Calling the PHP file with the proper querystring produces a result like this:

jsonpCallback({"name":"Chad","message":"Hello Chad"});

Running the code from the HTML page will simply display the results. Update Sept. 21, 2011: A reader pointed out he had some issues with the PHP code in this article and needed to add an additional header to get this to work. If your having issues please try adding these headers to your PHP code:

header(``"content-type: Access-Control-Allow-Origin: *"``);

header(``"content-type: Access-Control-Allow-Methods: GET"``);

Another thing to keep in mind if your using a hosting service or you don’t have complete control over the server that hosts your server side logic, it’s possible your host might block this type of thing (JSONP) as seen in the below Apache config:

Header set Access-Control-Allow-Origin "mydomain.com"

Make sure to check with your web host.

ubuntu14.04 切换 python版本

默认情况下ubuntu14中存在python2.7的版本和3.4的版本。默认版本是2.7 使用命令alias python=python3 如下图所示 python python编辑器安装 apt-get install ipython. 然后输入ipython运行,ipython默认支持的是python2.7. 如果要运行python3.*版本的ipython,则需要安装ipython3 apt-get install ipython3 然后运行ipython3即可。

Navicat连接ubuntu服务器中Mysql报10038错误

第一步:首先设置root用户的host为所有IP: 进入Mysql: mysql -uroot -pyoupass 进入后use mysql 然后,update user set host=’%’ where user=’root’ and host=’localhost’; flush privileges; 上面这一步注意分号,设置完了可以 select user,host from user表看看,设置成功没。 第二步: 如果你是云服务器,要去设置my.cnf 把下面bind-address 设置成你的云服务器的外网IP。