盒子
盒子
文章目录
  1. IDE
  2. 基础
  3. 字符串处理
    1. 字符串转化
    2. 加解密
  4. 时间
  5. 数组/对象
  6. HTTP
  7. 命令行
  8. 特殊函数

环境

IDE

  • PHPStorm

    • 注册码: http://idea.lanyus.com/
    • 配置
      • Appearance->Theme->选择Darcula,暗色调看着比较舒服
        • 字体 -> 微软雅黑,14
      • Editor->font 首先Scheme save自己的方案,然后字体改 Consolas|Courier|Source Code Pro等宽字体,16
        • General->Appearance->Show line numbers && Show whitespace
    • 快捷键:
      • Alt+左键:多选
      • Alt+J: 搜索并选中
      • Ctrl+Alt+Shift+左键:选中多行
      • Ctrl+左键: 跳转到定义
    • 其他
      • Editor->Code Style->PHP:空行 空格
      • Editor->Inspections->Spelling: 取消选中(单词检查)
      • File Encodings-> IDE Encoding: UTF-8;
      • File Encodings-> Project Encoding: UTF-8;
  • 运行工具

    • phpStudy

基础

<?php
// 指定编码类型
header("Content-Type: text/html; charset=utf-8");
// 返回自定义错误
header('HTTP/1.1 404 Not Found');
exit("Not Found");
// GET/POST数据
print_r($_POST);
print_r($_GET);
print_r($_REQUEST); // $_REQUEST = $_POST + $_GET
print_r($_SERVER);
print_r("php://input"); // post数据流

// define ( string $name , mixed $value [, bool $case_insensitive = FALSE ] ) : bool
// case_insensitive: 不区分大小写
define('TEST', 'Hello world');
echo TEST;

// 外变量
$GLOBALS['t'] = 'global_t';
// 类
class Test
{
/**
* @var Test: 单例类变量, 默认为NULL, 无需指定
*/
static $t;

/**
* @return Test: self::$t默认值会影响这里的返回值
*/
static function getInterface()
{
echo $GLOBALS['t']; // 外变量
if(!self::$t)
self::$t = new Test("HelloWorld.");
return self::$t;
}
var $content;
private function __construct($content)
{
$this->content = $content;
}
public function p()
{
echo $this->content;
}
}

$t = Test::getInterface();
$t->p();

字符串处理

// str_replace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] ) : mixed
$_POST = str_replace("\r", "", $_POST);
// substr ( string $string , int $start [, int $length ] ) : string
echo substr('abcdef', 1); // bcdef
echo substr('abcdef', 1, 3); // bcd
echo substr('abcdef', -3, 2); // de

字符串转化

// JSON
json_decode('{"k":"v"}'true); // json -> array,true一定要有,否则返回的是stdClass对象
json_encode(array("k" => "v")); // array -> json

// 类型转换
$foo = "0"; // $foo 是字符串 (ASCII 48)
$foo += 2; // $foo 现在是一个整数 (2)
$foo = $foo + 1.3; // $foo 现在是一个浮点数 (3.3)
$foo = 5 + "10 Little Piggies"; // $foo 是整数 (15)
$foo = 5 + "10 Small Pigs"; // $foo 是整数 (15)

$foo = 1 + "10.5"; // $foo is float (11.5)
$foo = 1 + "-1.3e3"; // $foo is float (-1299)
$foo = 1 + "bob-1.3e3"; // $foo is integer (1)
$foo = 1 + "bob3"; // $foo is integer (1)
$foo = 1 + "10 Small Pigs"; // $foo is integer (11)
$foo = 4 + "10.2 Little Piggies"; // $foo is float (14.2)
$foo = "10.0 pigs " + 1; // $foo is float (11)
$foo = "10.0 pigs " + 1.0; // $foo is float (11)
/**
* 将16进制数串转换为二进制数据的函数
* @param $hexdata
* @return string bindata
*/
function str2bin($hexdata)
{
$bindata="";
for ($i=0;$i < strlen($hexdata);$i+=2) {
$bindata.=chr(hexdec(substr($hexdata,$i,2)));
}
return $bindata;
}

echo bin2hex('abc'); // 3132333435363738
echo str2bin('616263'); // abc
echo hex2bin('616263'); // abc

// 路径
// include dirname(__FILE__) . "/config/config2.php";
echo __FILE__."\r\n";
echo dirname(__FILE__)."\r\n";
echo dirname(__FILE__) . "/config/config2.php"."\r\n";

// 模块:测试附加代码
if (strcasecmp(basename($_SERVER['SCRIPT_NAME']), basename(__FILE__)) == 0)
{
// 直接请求该PHP,运行如下测试代码
// 作为模块被include,则不运行
echo "test";
}
// autoload.php: 根据应用到的类名自动加载对应PHP
<?php
// 注意根目录检查
function autoload($class)
{
$path = array(".", "..", "../..", $_SERVER['DOCUMENT_ROOT']);
foreach($path as $p) {
$fn = $p . '/'. $class . ".php";
$fn = strtr($fn, array("\\" => "/"));
if (file_exists($fn)) {
require_once($fn);
return;
}
}
}

spl_autoload_register("autoload");
// 使用
include_once dirname(__FILE__) . "/../autoload.php";

加解密

//  hash ( string $algo , string $data [, bool $raw_output = FALSE ] ) : string
// $algo: 哈希算法名称,例如:"md5","sha256","haval160,4" 等, 算法清单,见 hash_hmac_algos() 函数
// $raw_output = TRUE: 输出原始二进制数据, 设置为 FALSE 输出小写 16 进制字符串
echo hash('sha256', 'The quick brown fox jumped over the lazy dog.');
// md5 ( string $str [, bool $raw_output = FALSE ] ) : string
echo md5('The quick brown fox jumped over the lazy dog.');
// sha1 ( string $str [, bool $raw_output = false ] ) : string
// crc32 ( string $str ) : int

// hash_file() - 使用给定文件的内容生成哈希值
// md5_file() - 计算指定文件的 MD5 散列值
// sha1_file() - 计算文件的 sha1 散列值

// hash_hmac ( string $algo , string $data , string $key [, bool $raw_output = FALSE ] ) : string
// raw_output: 默认16进制字符串,置为TRUE输出原始二进制字符串
hash_hmac("md5", "数据", "密钥", TRUE);

// base64
$str = 'This is an encoded string';
echo base64_encode($str);
echo base64_decode('VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw==');

时间

// 修改时区,php.ini: date.timezone = "Asia/Shanghai"
date_default_timezone_set("Asia/Shanghai");
// 当前时间
echo date("Y-m-d h:i:s", time()); //2019-09-28 09:58:04

数组/对象

count($arr);    // 数组长度
// 数组:遍历
function getSign($data)
{
$str = "";
foreach($data as $key => $value)
{
if(is_array($value))
$str.=$key."=".getSign($value)."&";
else
$str.=$key."=".$value."&";
}
$str = trim($str, "&");
return $str;
}

$arr = array(
"a" => "b",
"c" => array(
"d" => "e"
),
"e" => "f"
);
echo getSign($arr);

// 数组:排序
// 键排序
ksort($arr);
krsort($arr); // 逆序
// 值排序
sort($arr);
rsort($arr); // 逆序
// 值排序:保持键值对应
asort($arr);
arsort($arr); // 逆序
// 支持自定义排序
uksort(); // 键排序
uasort(); // 值排序

HTTP

// 参数处理
$data = array(
'foo' => 'bar',
'baz' => 'boom',
'cow' => 'milk',
'php' => 'hypertext processor'
);
echo http_build_query($data); // foo=bar&baz=boom&cow=milk&php=hypertext+processor
// 简单GET
var_dump(file_get_contents($url));

// POST:直接Post数据情况
$data = '{"k":"v"}';
$cl = curl_init();
if(stripos($url, 'https://') !== FALSE) {
curl_setopt($cl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($cl, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($cl, CURLOPT_SSLVERSION, 1);
}

curl_setopt($cl, CURLOPT_POST, true);
// 直接POST数据指定数据类型,默认FORM
// 屏蔽掉CURLOPT_HTTPHEADER,$data直接换成 数组即为普通表单提交模式
// POST 文件:array('file1'=>'@/data/1.jpg')
curl_setopt($cl, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Content-Length: '.strlen($data)));

curl_setopt($cl, CURLOPT_URL, $url);
curl_setopt($cl, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($cl, CURLOPT_TIMEOUT,30);//设置30秒超时
curl_setopt($cl, CURLOPT_POSTFIELDS, $data);
$content = curl_exec($cl);
$status = curl_getinfo($cl);
curl_close($cl);
if (isset($status['http_code']) && $status['http_code'] == 200)
echo "success";
else
echo "fail";

// 跨域
header("Content-Type: text/html; charset=UTF-8");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: x-requested-with");
header("Access-Control-Allow-Methods: GET, POST, GET, OPTIONS");

命令行

php_sapi_name(); // cli代表命令行执行, 不同Web环境, 对应不同字符串

// 命令行执行判断: 方式1
if(php_sapi_name() == "cli")
echo "命令行执行";
// 命令行执行判断: 方式2
if(isset($argc))
test();

/**
* 命令行参数
* v: 代表字符串参数
* h $options数组是否包含h代表参数中是否包含-h
* help: $options数组是否包含help代表参数中是否包含--help
* src: 代表字符串参数
* module:: 代表字符串数组参数, 可以指定多个
*/
$options = getopt('v:h', array('help', 'src:','module::'));
var_dump($options);
/**
* 命令行参数解析:
* php test.php -a=check -i=2399013994 -i=2399013993 -g=1
* php test.php --action=check --icafe=2399013994 --icafe=2399013995 --grade=1
* 双冒号代表是可叠加参数, 使用一次是字符串, 使用多次是数组
*/
$shortopts = "a:i::g:"; // 短参数: -a
$longopts = array("action:", "icafe::", "grade:"); // 长参数: --action
$param_arr = getopt($shortopts, $longopts);
print_r($param_arr);

特殊函数

// 注册PHP退出前执行函数,可以注册多个
function shutdown()
{
echo 'Script executed with success', PHP_EOL;
}
register_shutdown_function('shutdown');
支持一下
扫一扫,支持一下
  • 微信扫一扫
  • 支付宝扫一扫