欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

开发错误集锦

发布时间:2025/4/16 编程问答 44 豆豆
生活随笔 收集整理的这篇文章主要介绍了 开发错误集锦 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

emoji

utf8 编码问题 https://laravel-china.org/top...

function nickname_encode($s){$chars = preg_split('//u', $s, null, PREG_SPLIT_NO_EMPTY);foreach ($chars as &$c) {if (strlen($c) > 3 || $c === "%"){$c = urlencode($c);}}return implode($chars);} 解码直接用urldecode就行了。

strtotime

var_dump(date("Y-m-d", strtotime("2017-06-31"))); //输出2017-07-01 var_dump(date("Y-m-d", strtotime("-1 month", strtotime("2017-03-31")))); //输出2017-03-03 var_dump(date("Y-m-d", strtotime("+1 month", strtotime("2017-08-31")))); //输出2017-10-01 var_dump(date("Y-m-d", strtotime("next month", strtotime("2017-01-31")))); //输出2017-03-03 var_dump(date("Y-m-d", strtotime("last month", strtotime("2017-03-31")))); //输出2017-03-03var_dump(date("Y-m-d", strtotime("last day of -1 month", strtotime("2017-03-31")))); //输出2017-02-28 var_dump(date("Y-m-d", strtotime("first day of +1 month", strtotime("2017-08-31")))); 输出2017-09-01 var_dump(date("Y-m-d", strtotime("first day of next month", strtotime("2017-01-31")))); 输出2017-02-01 var_dump(date("Y-m-d", strtotime("last day of last month", strtotime("2017-03-31")))); 输出2017-02-28需要获得多少天之前 $day mktime(0, 0, 0, date("m", $startTime), date("d", $startTime) - $day, date("Y", $startTime));这个坑在carbon中一样的有. 比如:Carbon::now()->subMonth(1)->startOfMonth() 一样的会出现上面说的问题. 你必须这样写:Carbon::now()->startOfMonth()->subMonth(1)Carbon::now()->subMonthNoOverflow(1)->startOfMonth() https://laravel-china.org/articles/17317$i = 12;while($i >= 1) {echo date('Y-m', strtotime('-' . $i . ' month', strtotime('2018-8'))) . "\n";$i--; }

https://laravel-china.org/art...
解决方法

??

运算符可 用于判断$a变量不存在的情况(也可用于数组),而使用三元运算符判断一个未定义的变量,PHP会抛出异常。也正是因为这样,用??判断一个赋值为0的变量的时候结果是不一样的。https://laravel-china.org/articles/17304?#reply64712 $a=0; $c=1; $b=$a??$c; echo 'a:'.$a.',b:'.$b.',c:'.$c; //a:0,b:0,c:1 $a=0; $c=1; $b=$a?$a:$c; echo 'a:'.$a.',b:'.$b.',c:'.$c; //a:0,b:1,c:1

Error while reading line from the server. [tcp://127.0.0.1:6379]

redis 加了代理 Twemproxy,而 predis 对这个配置默认执行 select 操作,导致了连接错误。

大家以后要注意,如果 redis 有代理的话,别忘了把 'database' => 0,这个配置删掉。
https://laravel-china.org/top...

PHP empty 函数判断结果为空

class person {protected $attributes = [];public function __construct(array $attributes){$this->attributes = $attributes;}public function __get($name){return $this->attributes[$name] ?? null;} } https://laravel-china.org/articles/12530/the-shock-php-empty-function-is-empty-but-the-actual-value-is-nonemptyhttps://laravel-china.org/topics/3021/isset-is-not-right-after-upgrading-php7 var_dump($person->firstName,empty($person->firstName),isset($person->firstName),is_null($person->firstName) );

Laravel Redis 多个进程同时取队列问题

Laravel 使用 Redis 的 list 作为队列的数据结构,并会为每个队列分配一个 ID
Laravel 中入队列方法

public function pushRaw($payload, $queue = null, array $options = []) {$this->getConnection()->rpush($this->getQueue($queue), $payload);return Arr::get(json_decode($payload, true), 'id'); } 用的是 Redis 的 rpush 命令。Laravel 中取队列方法public function pop($queue = null) {$original = $queue ?: $this->default; $queue = $this->getQueue($queue); $this->migrateExpiredJobs($queue.':delayed', $queue); if (! is_null($this->expire)) {$this->migrateExpiredJobs($queue.':reserved', $queue);} list($job, $reserved) = $this->getConnection()->eval(LuaScripts::pop(), 2, $queue, $queue.':reserved', $this->getTime() + $this->expire); if ($reserved) {return new RedisJob($this->container, $this, $job, $reserved, $original);} } 这里用的是 lua 脚本取队列,如下:public static function pop() {return <<<'LUA' local job = redis.call('lpop', KEYS[1]) local reserved = false if(job ~= false) then reserved = cjson.decode(job) reserved['attempts'] = reserved['attempts'] + 1 reserved = cjson.encode(reserved) redis.call('zadd', KEYS[2], ARGV[1], reserved) end return {job, reserved} LUA; }

那么结论是:从 Laravel 的处理方式和打印的日志结果看,即使多个进程读取同一个队列,也不会读取到一样的数据。

队列执行失败之后根本不会执行failed方法

执行队列侦听器时加上 --tries参数即可,failed()方法只有在重试指定次数完成后才会调用failed()方法如:
http://blog.zhouchenxi.cn/pos...
php artisan queue:listen --queue=default,listeners --tries=3
顺便提一下:如果指定了队列名称必须在侦听器的参数上加上 --queue参数才行,不然没有指定的队列是不会运行的。
event 指定队列

public $queue = 'listeners'; public function queue($queue, $job, $data){if (isset($this->queue, $this->delay)) {return $queue->laterOn($this->queue, $this->delay, $job, $data);}if (isset($this->queue)) {return $queue->pushOn($this->queue, $job, $data);}if (isset($this->delay)) {return $queue->later($this->delay, $job, $data);}return $queue->push($job, $data);}

php7不支持 preg_replace e修正符

车轮升级PHP7踩过的一些坑 http://php.swoole.com/wiki/%E...

php5 php7不兼容的地方:https://segmentfault.com/a/11...

$joinStr = preg_replace("/__([A-Z_-]+)__/e",$prex.".strtolower('$1')",$joinStr); //替换为 preg_replace_callback("/__([A-Z_-]+)__/",function($r) use (&$joinStr){$joinStr = $prex.strtolower($r[1]); },$joinStr);

内存溢出

//https://laravel-china.org/articles/16312/handling-large-amounts-of-data-to-write-files-to-avoid-memory-overflow-and-response-timeout $beginIndex = 0;$pageLimit = 50000;$endIndex = $beginIndex + $pageLimit;while ($pageData = \DB::connection('hub_log')->select("SELECT * FROM `{$tableName}` WHERE id > {$beginIndex} and id <= {$endIndex}")) {foreach ($pageData as $row) {file_put_contents(storage_path('mcd_rawdata/'.$tableName.'.txt'), $row->Content . "\n", FILE_APPEND);}$beginIndex += $pageLimit;$endIndex += $pageLimit;}$public_path = $time.'test.txt';DB::table('20171220')->orderBy('id')->chunk(10000,function($data) use ($public_path){$arr = '';foreach ($data->toArray() as $key => $value) {$arr .= $value->Content."\n";}file_put_contents(public_path($public_path),$arr, FILE_APPEND);unset($data);unset($arr);});

git bash 输入python命令停滞

$ python -i
$ winpty python -3

保留两位小数

round(a,2)
r = lambda f: f - f % 0.01
int(a*100)/100
print("%.2f" %a)

后期绑定

https://www.v2ex.com/t/482659...

def testFun():return(lambda x : i*x for i in range(4)) for everyLambda in testFun():print(everyLambda(2)) & python test.py 0 2 4 6 def testFun():temp = [lambda x : i*x for i in range(4)]return temp for everyLambda in testFun():print(everyLambda(2)) & python test.py 6 6 6 6 第一个是括号(), 为生成器, 返回 generator 第二个是中括号[], 为列表生成式, 返回数组 列表表达式是即时计算的, 而生成器是迭代时才会计算

{} + []

({}).valueOf() // [] // 返回来的是个对象,继续调用 toString https://www.v2ex.com/t/480998#reply11 [].toString() // ""[] + 1// "1" [] + 'a' // "a"

echo 后发送 header

使用 fastcgi_finish_request();( PHP-fpm )可以强制断开客户端连接 session 本质上是 header set-cookie,所以不算输出。这里的输出指的是 response body 的部分
https://www.v2ex.com/t/481127...

isset在php5.6-和php7.0+的一些差异

https://segmentfault.com/a/1190000016097997 class ProductCategory {const TYPES = [1 => 'type1',2 => 'type2', ];public function getType(){return isset(self::TYPES[$this->type]) ? self:TYPES[$this->type] : 'unrecognized_type';} } //把汉字拆分为数组 function ch2arr($str) {return preg_split('//u', $str, null, PREG_SPLIT_NO_EMPTY); }

laravel 中使用 导出 excel 时报错

PHPExcel_Calculation_Exception: Q5!A65 → Formula Error: An unexpected error occured in /application/www/web_git-pull/vendor/phpoffice/phpexcel/Classes/PHPExcel/Cell.php:291

原因:

在excel中一个单元格如果是以=开头,则说明这个单元格是根据其他单元格的值算出来的,=后面必须跟着一个合法的表达式,而那个字符串是用户的输入,很明显不应该是一个合法的表达式,所以应该在代码中过滤掉

解决:
$str = "\t".$str;//同时解决 如 11111111111 显示成 1.11111E+29
参考
https://github.com/Maatwebsit...
https://stackoverflow.com/que...

gzip UnicodeDecodeError

gzip解码问题

import urllib.request import gzip# 注意要先读取内容才可以解压缩 data = urllib.request.urlopen(url).read() try:html =data.decode("utf-8") except:html =gzip.decompress(data).decode("utf-8")

Intervention/Image 图片写入中文

https://laravel-china.org/topics/13642/problems-encountered-in-writing-chinese-with-interventionimage-pictures-and-solutions function to_unicode($string) {$str = mb_convert_encoding($string, 'UCS-2', 'UTF-8');$arrstr = str_split($str, 2);$unistr = '';foreach ($arrstr as $n) {$dec = hexdec(bin2hex($n));$unistr .= '&#' . $dec . ';';}return $unistr; }

获取某字段修改前的值

Issue::saving(function(Issue $issue){if ($issue->isDirty('title')) {$user = Auth::user()->username;$oldTitle = $issue->getOriginal('title'); // 原始值$newTitle = $issue->title; // 新值ActionLog::log("$user 把标题 $oldTitle 修改为 $newTitle");} });

前一天

https://www.cnblogs.com/lhm166/articles/6066762.html $mytime=mktime(0, 0, 0, date('m'), date('d')-1, date('Y'));//获取时间戳 $mytime=date("Y-m-d H:i:s", strtotime("-1 day")); //获取格式为2016-12-30 13:26:13 $timetoday = strtotime(date("Y-m-d",time())); function mdate($time = NULL) {$text = '';$time = $time === NULL || $time > time() ? time() : intval($time);$t = time() - $time; //时间差 (秒)$y = date('Y', $time)-date('Y', time());//是否跨年switch($t){case $t == 0:$text = '刚刚';break;case $t < 60:$text = $t . '秒前'; // 一分钟内break;case $t < 60 * 60:$text = floor($t / 60) . '分钟前'; //一小时内break;case $t < 60 * 60 * 24:$text = floor($t / (60 * 60)) . '小时前'; // 一天内break;case $t < 60 * 60 * 24 * 3:$text = floor($time/(60*60*24)) ==1 ?'昨天 ' . date('H:i', $time) : '前天 ' . date('H:i', $time) ; //昨天和前天break;case $t < 60 * 60 * 24 * 30:$text = date('m月d日 H:i', $time); //一个月内break;case $t < 60 * 60 * 24 * 365&&$y==0:$text = date('m月d日', $time); //一年内break;default:$text = date('Y年m月d日', $time); //一年以前break;}return $text; }function friend_date($time) {if (!$time)return false;$fdate = '';$d = time() - intval($time);$ld = $time - mktime(0, 0, 0, 0, 0, date('Y')); //得出年$md = $time - mktime(0, 0, 0, date('m'), 0, date('Y')); //得出月$byd = $time - mktime(0, 0, 0, date('m'), date('d') - 2, date('Y')); //前天$yd = $time - mktime(0, 0, 0, date('m'), date('d') - 1, date('Y')); //昨天$dd = $time - mktime(0, 0, 0, date('m'), date('d'), date('Y')); //今天$td = $time - mktime(0, 0, 0, date('m'), date('d') + 1, date('Y')); //明天$atd = $time - mktime(0, 0, 0, date('m'), date('d') + 2, date('Y')); //后天if ($d == 0) {$fdate = '刚刚';} else {switch ($d) {case $d < $atd:$fdate = date('Y年m月d日', $time);break;case $d < $td:$fdate = '后天' . date('H:i', $time);break;case $d < 0:$fdate = '明天' . date('H:i', $time);break;case $d < 60:$fdate = $d . '秒前';break;case $d < 3600:$fdate = floor($d / 60) . '分钟前';break;case $d < $dd:$fdate = floor($d / 3600) . '小时前';break;case $d < $yd:$fdate = '昨天' . date('H:i', $time);break;case $d < $byd:$fdate = '前天' . date('H:i', $time);break;case $d < $md:$fdate = date('m月d日 H:i', $time);break;case $d < $ld:$fdate = date('m月d日', $time);break;default:$fdate = date('Y年m月d日', $time);break;}}return $fdate; }

phpstorm xdebug

https://www.cnblogs.com/baoch...
https://www.cnblogs.com/niuxi...
https://laravel-china.org/top...
https://laravel-china.org/art...
https://laravel-china.org/art...

如果出现Can't start listening for connections from 'xdebug': Port 9000 is busy 可修改端口号,要修改两个地方 第一个地方是刚才php.ini里面的xdebug.remote_port=9000 第二个地方是phpstorm - setting - Languages&Frameworks - 相应的语言(比如PHP) - debug - 修改里面的Debug port

Python for 循环中的陷阱

https://www.v2ex.com/t/470443...

pyinstaller 打包 exe

pyinstaller -p venv_path (中间一定要有空格) you.py https://www.v2ex.com/t/476247...
http://ju.outofmemory.cn/entr...

php捕获fatal error

function fatal_handler() {$errfile = "unknown file";$errstr = "shutdown";$errno = E_CORE_ERROR;$errline = 0;$error = error_get_last();if($error){//发送邮件队列也可以http://www.iamtb.cn/2017/11/17/php-catch-fatel-error/file_put_contents('./testerror11.txt', json_encode($error));} } register_shutdown_function("fatal_handler"); try{$db=new db(); }catch(Exception $e){ echo $e->error_msg(); }

PHP7开始,含十六进制字符串不再被认为是数字

$str = "0xffff";//https://segmentfault.com/q/1010000004829059 $int = filter_var($str, FILTER_VALIDATE_INT, FILTER_FLAG_ALLOW_HEX); if (false === $int) {throw new Exception("Invalid integer!"); } var_dump($int); // int(65535) $t1 = 0x3FFFFFFF & (1 * (0xd5b42e11)); $t2 = 0x3FFFFFFF & (1 * (filter_var("0xd5b42e11", FILTER_VALIDATE_INT, FILTER_FLAG_ALLOW_HEX)));var_dump($t1,$t2);

php artisan config:cache

cat config/sentry.php return array('dsn' => env('SENTRY_LARAVEL_DSN'),// capture release as git sha// 'release' => trim(exec('git log --pretty="%h" -n1 HEAD')),// Capture bindings on SQL queries'breadcrumbs.sql_bindings' => true,// Capture default user context'user_context' => false,//transport function'transport'=>function(Raven_Client $raven_Client,&$data){$raven_Client->setTransport(null);$raven_Client->close_curl_resource();\Queue::pushOn('sentry',new \App\Commands\sentry($raven_Client,$data));}, );'transport'=>new \app\SentryTransport(), class SentryTransport {public static function __set_state($arr){return function($raven_Client,&$data){\Queue::pushOn('sentry',new \App\Commands\sentry($raven_Client,$data));};} }

curl超时

//重试 $ch = curl_init(); // curl_setopt ($ch, CURLOPT_URL, 'produc_redis.php.com'); curl_setopt ($ch, CURLOPT_URL, '11.11.11.1');https://segmentfault.com/a/1190000011188541 // I changed UA here curl_setopt ($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1');curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 2); curl_setopt ($ch, CURLOPT_AUTOREFERER, true); curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 2);$html = curl_exec($ch);var_dump($html,curl_error($ch));$num=3; for($i=1;$i<=$num;$i++){if(curl_getinfo($ch,CURLINFO_HTTP_CODE)=='0' && $i<=$num){echo "retry $i 次".PHP_EOL;if($i==3){curl_setopt ($ch, CURLOPT_URL, '220.181.57.217');}$html = curl_exec($ch);} }var_dump($html);var_dump(curl_error($ch));// var_dump(curl_getinfo($ch));/*** curl请求*https://segmentfault.com/a/1190000010197068* @param $url* @param string $postData* @param int $timeout* @return array|mixed* @throws Exception*/ protected static function post($url, $postData = '', $timeout = 5) {$ret = array();$times = 5;do {$ch = curl_init();curl_setopt($ch, CURLOPT_URL, $url);curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");curl_setopt($ch, CURLOPT_POST, true);curl_setopt($ch, CURLOPT_HEADER, false);if ($postData != '') {curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);}curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);// 重要, 该处不能丢 curl 执行最大秒数curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);$output = curl_exec($ch);if ($errNo = curl_errno($ch)) {error_log("Error [$errNo]: " . curl_error($ch));} else {$ret = json_decode($output, true);// 解析的结果集为空时停止查询if (!is_array($ret) && !trim($ret)) {throw new Exception(__METHOD__ . ": cURL调用失败, 信息为: " . $output);}unset($output);}curl_close($ch);if (isset($ret[0]) && $ret[0]) {return $ret;}} while ($times--);exit(__METHOD__ . ": cURL请求重试至 {$times} 次后仍无响应, 执行退出"); }

cURL error 28

cURL error 28: See http://curl.haxx.se/libcurl/c/libcurl-errors.html $client=new GuzzleHttp\Client(); try {$tmp = $client->get($url,array("timeout"=>3,"connect_timeout"=>3));$res = json_decode(strval($tmp->getBody()),1); } catch (\Exception $e) {$res = [];\Log::info('error', ['url' => $url, 'msg' => $e->getMessage()]); } $client=new GuzzleHttp\Client();$requests=[$client->createRequest('GET',$url,["timeout"=>3,"connect_timeout"=>3]),$client->createRequest('GET',$url2,["timeout"=>3,"connect_timeout"=>3]),]; $result = Pool::batch($client, $requests, ['pool_size' => 2]); //$result->getResult($requests[0]) instanceof GuzzleHttp\Message\Response if ($result[0] instanceof Response && $result[0]->getStatusCode() == 200) {$data = json_decode($result[0]->getBody(), true);}

格式化

import prettytable as pt https://www.v2ex.com/t/483984#reply15 ## 按行添加数据 tb = pt.PrettyTable() tb.field_names = ["City name", "Area", "Population", "Annual Rainfall"] tb.add_row(["Adelaide",1295, 1158259, 600.5]) tb.add_row(["Brisbane",5905, 1857594, 1146.4]) tb.add_row(["Darwin", 112, 120900, 1714.7]) tb.add_row(["Hobart", 1357, 205556,619.5])print(tb)#str.ljust 和 rjust 才是王道,谁用谁知道!+-----------+------+------------+-----------------+ | City name | Area | Population | Annual Rainfall | +-----------+------+------------+-----------------+ | Adelaide | 1295 | 1158259 | 600.5 | | Brisbane | 5905 | 1857594 | 1146.4 | | Darwin | 112 | 120900 | 1714.7 | | Hobart | 1357 | 205556 | 619.5 | +-----------+------+------------+-----------------+

unicode

Unicode 每个字符的详情,可以查官方文档: https://www.unicode.org/charts/
python2 代码:

for i in range(0x005b,0x005f):
print (unichr(i))#print (chr(i))
python3 代码请查看 http://www.chenxm.cc/post/683...
unicode 字符表示方法 u + 16 进制数值,例如 u0001 print(''.join(chr(u) for u in range(0, 0x41))) u0040 这里 0040 就是 16 进制的,range 是左闭右开的,所以u0020-u0040 的码点范围是 range(0x00, 0x40+1)
0b 二进制 0o 八进制 0x 16 进制
0b10 // 2
0o10 // 8
0x10 // 16
unicode 字符表示方法 u + 16 进制数值,例如 u0001
print(u'u0061') // ahttps://www.v2ex.com/t/484923...

laravel更新后读取数据失败

https://laravel-china.org/articles/16566/take-a-laravel-mysql-to-verify-the-experience-of-bug#reply62596 //创建数据 $meeting = meeting::create($data);//查询数据 $meeting = meeting::findOrFail($meeting->id);//纪录操作日志 Log::insert($meeting); 线上数据库是读写分离的,主库写入,但更新数据后马上查询,从库可能没来得及更新数据 当网络不好时遇到从库更新不及时 findOrFail 就会报 404,导致后面所有操作都失效,自然验证也失效了 解决方法更新完后,查询指定使用主库 更新后禁止查询,直接使用 create 返回的 model 实例,对于数据库中的有默认值的字段,手动加入到 model 实例中

批量更新

//https://laravel-china.org/topics/6864/how-to-batch-update-accumulate-a-field https://laravel-china.org/articles/16620/laravel-project-execl-batch-import-database-data-update-data-no-insertion $arr = [ // user_id => reward'1' => 50,'2' => 30,'3' => 60 ]; User::find(array_keys($arr))->each(function ($query) use ($arr) {$query->increment('award' , $arr[$query->id]); }); # 批量更新相同的 award User::find(array_keys($arr))->each->increment('award', 30);/*** 批量更新表的值,防止阻塞* @note 生成的SQL语句如下:* update mj_node set sort = case id* when 13 then 1* when 1 then 4* when 7 then 5* when 8 then 6* when 9 then 7* when 10 then 8* when 11 then 9* when 12 then 10* end where id in (13,1,7,8,9,10,11,12)* @param $conditions_field 条件字段* @param $values_field 需要被更新的字段* @param $conditions* @param $values* @return int*/public function batchUpdate($conditions_field, $values_field, $conditions, $values){$table = $this->model->getFullTableName();//返回完整表名,自己在项目中定义$sql = 'update ' . $table . ' set '. $values_field .' = case ' .$conditions_field;foreach ($conditions as $key => $condition) {$sql .= ' when ' . $condition . ' then ?';}$sql .= ' end where id in (' . implode(',', $conditions) . ')';return DB::update($sql, $values);//项目中需要引入DB facade}

cat 多换行

https://www.v2ex.com/t/188162 调试shell脚本可以使用 sh -x ****.sh,有详细输出内容 Bash的echo默认在末尾加了换行符"\n",所以你cat那个文件多了一个换行符,给echo加上-n参数就能不自动加换行符了。var= cat tmp.txt;echo $var"abc" 改成如下的形式var= `cat tmp.txt`;echo $var"abc"或者 #注意不是单引号,是tab键上面1前面的那个符号 var=$(cat tmp.txt);echo $var"abc"

grep and or

https://blog.csdn.net/jackaduma/article/details/6900242 grep -E 'Tech|Sales' employee.txt grep -v 'pattern1' filename $ grep -E 'Manager.*Sales|Sales.*Manager' employee.txt # -E 'pattern1.*pattern2' egrep "php.*artisan.*$1" egrep 'pattern1|pattern2' filename

memcached 默认的过期时间则 不能大于 30 天

https://laravel-china.org/top...

cron 内容最后一行未回车

https://segmentfault.com/a/11... crontab -u www -e

unix:///tmp/supervisor.sock refused connection

[root@localhost supervisor]# supervisorctl -c /etc/supervisord.conf unix:///tmp/supervisor.sock refused connection supervisor> exitrm -f /tmp/supervisor.sock [root@localhost supervisor]# ps aux|grep super root 48 0.0 0.0 0 0 ? S 2017 2:17 [sync_supers] root 8246 0.0 0.1 208064 13404 ? Ss 18:17 0:00 /usr/bin/python /usr/bin/supervisord -c /etc/supervisord.conf supervisord是服务端,是个deamon,supervisorctl是客户https://www.v2ex.com/t/210122 修改supervisor.conf文件后,要执行supervisorctl reload,重新加载配置文件 vi artisan.conf [root@localhost supervisor]# supervisorctl status unix:///tmp/supervisor.sock no such file [root@localhost supervisor]# ps aux|grep super root 48 0.0 0.0 0 0 ? S 2017 2:17 [sync_supers] root 19472 0.0 0.0 103256 844 pts/5 S+ 19:57 0:00 grep super [root@localhost supervisor]# supervisord -c /etc/supervisord.conf Error: Invalid user name www in section 'program:artisan_queue' (file: '/etc/supervisor/artisan.conf') For help, use /usr/bin/supervisord -h [root@localhost supervisor]# vi /etc/supervisor/artisan.conf [root@localhost supervisor]# supervisord -c /etc/supervisord.conf [root@localhost supervisor]# supervisorctl status artisan_queue BACKOFF Exited too quickly (process log may have details)http://blog.51cto.com/jxlwc/2112062 https://www.jianshu.com/p/3658c963d28b

Specified key was too long

https://laravel-china.org/articles/17094/larave-admin-installation?#reply64528 默认的数据库字符集,现在utf8mb4包括存储emojis支持。如果你运行MySQL v5.7.7或者更高版本,则不需要做任何事情。 https://laravel-china.org/articles/4195/laravel-54-common-error-specified-key-was-too-long https://segmentfault.com/a/1190000008416200 把config下的database.php下的mysql设置中,将'strict' => false就行了.. Schema::defaultStringLength(191); 是设置好的默认的字符串长度,也就是说,迁移中的字段没有设置长度的话,varchar 字段会被默认成长度只有 191 use Illuminate\Support\Facades\Schema;public function boot() {Schema::defaultStringLength(191); }

laravel with 查询中只查询个别字段

select 的时候没有 id 的话就会为 null https://laravel-china.org/articles/17379 public function brand(){return $this->belongsTo(Brand::class, 'brandId')->select('id', 'briefCode');}$result = Brand::with(['brand' => function($query){$query->select('id', 'briefCode'); }])->get();

PHP输出A到Z

for($i='A'; $i<='Z'; $i++) {echo $i . '<br>'; } for($i=ord('A'); $i<=ord('Z'); $i++) {echo chr($i) . '<br>'; } for($i = 'A'; $i != 'BB'; $i++) {echo $i . '<br>'; }$al = 'A'; while($al != 'BB') {echo $al++ . '<br>'; }

env函数的小坑

dump(env('APP_ENV') === null); // true 因为没有执行 config:cache 命令,而项目上线后为了优化访问速度,生成了缓存文件,导致env取值失败 如果使用了config:cache,env函数只能在config目录下的配置文件的php里使用,不可以在其他地方使用。一个非常简单的办法就是将 env('APP_ENV')改为config('app.env') config函数会优先读取 bootstrap/cache/config.php 中缓存的配置,如果没有缓存文件,则会直接读取 config 目录下的所有配置文件 https://www.jianshu.com/p/83f9cd407751

任务调度的列表

//1. 加载Console内核 app()->make(\Illuminate\Contracts\Console\Kernel::class);//2. 获取计划任务列表 $scheduleList = app()->make(\Illuminate\Console\Scheduling\Schedule::class)->events();

在模型事件中获取某字段修改前的值

Issue::saving(function(Issue $issue){if ($issue->isDirty('title')) {$user = Auth::user()->username;$oldTitle = $issue->getOriginal('title'); // 原始值https://laravel-china.org/wikis/16169$newTitle = $issue->title; // 新值ActionLog::log("$user 把标题 $oldTitle 修改为 $newTitle");} });

laravel SerializesModels

因为我们在任务类里引用了 SerializesModels 这个 trait,使得 Eloquent 模型在处理任务时可以被优雅地序列化和反序列化。如果你的队列任务类在构造器中接收了一个 Eloquent 模型,那么只有可识别出该模型的属性会被序列化到队列里。当任务被实际运行时,队列系统便会自动从数据库中重新取回完整的模型。这整个过程对你的应用程序来说是完全透明的,这样可以避免在序列化完整的 Eloquent 模式实例时所带来的一些问题。https://laravel-china.org/top...

composer require失败

cat composer.json "monolog/monolog": "^2.0@dev",$ composer require dees040/laravel-api-responses1/1: https://packagist.laravel-china.org/p/provider-latest$0449728151603 e355a0ee137fb34881e699652e41e3e1de11ba9c4ea7a47a312.jsonFinished: success: 1, skipped: 0, failure: 0, total: 1 Using version dev-master for dees040/laravel-api-responses ./composer.json has been updated Loading composer repositories with package information Updating dependencies (including require-dev) Your requirements could not be resolved to an installable set of packages.Problem 1- The requested package monolog/monolog (locked at 1.23.0, required as ^2.0@dev ) is satisfiable by monolog/monolog[1.23.0] but these conflict with your requiremen ts or minimum-stability.Problem 2- laravel/framework v5.5.42 requires monolog/monolog ~1.12 -> satisfiable by mo nolog/monolog[1.x-dev].- laravel/framework v5.5.42 requires monolog/monolog ~1.12 -> satisfiable by mo nolog/monolog[1.x-dev].- laravel/framework v5.5.42 requires monolog/monolog ~1.12 -> satisfiable by mo nolog/monolog[1.x-dev].- Can only install one of: monolog/monolog[2.x-dev, 1.x-dev].- Installation request for monolog/monolog ^2.0@dev -> satisfiable by monolog/m onolog[2.x-dev].- Installation request for laravel/framework (locked at v5.5.42, required as 5. 5.*) -> satisfiable by laravel/framework[v5.5.42].$composer require "monolog/monolog:~1.12"1/1: https://packagist.laravel-china.org/p/provider-latest$d12a81f48a3e1dad512c1d2c375298e3a8ea414dff5000d5f345939429c6b29b.jsonFinished: success: 1, skipped: 0, failure: 0, total: 1 ./composer.json has been updated Loading composer repositories with package information Updating dependencies (including require-dev)1/1: https://dl.laravel-china.org/monolog/monolog/c465e1144536862e03f519cb3d65e924062cabfb.zipFinished: success: 1, skipped: 0, failure: 0, total: 1 Package operations: 0 installs, 1 update, 0 removals- Removing monolog/monolog (1.23.0)- Installing monolog/monolog (1.x-dev c465e11): Cloning c465e11445 from cache Package phpoffice/phpexcel is abandoned, you should avoid using it. Use phpoffice/phpspreadsheet instead. Writing lock file Generating optimized autoload files > Illuminate\Foundation\ComposerScripts::postAutoloadDump > @php artisan package:discover Discovered Package: 96qbhy/hyid Discovered Package: appstract/laravel-opcache Discovered Package: appstract/lush-http Discovered Package: barryvdh/laravel-debugbar Discovered Package: barryvdh/laravel-dompdf Discovered Package: barryvdh/laravel-ide-helper Discovered Package: base62/base62 Discovered Package: cblink/laravel-excel-zip Discovered Package: cblink/laravel-sso Discovered Package: chumper/zipper Discovered Package: encore/laravel-admin Discovered Package: encore/redis-manager Discovered Package: fideloper/proxy Discovered Package: foryoufeng/laravel-generator Discovered Package: ibrand/laravel-miniprogram-poster Discovered Package: intervention/image Discovered Package: itsgoingd/clockwork Discovered Package: jacobcyl/ali-oss-storage Discovered Package: jellybool/flysystem-upyun Discovered Package: jenssegers/agent Discovered Package: jenssegers/mongodb Discovered Package: laravel-admin-ext/helpers Discovered Package: laravel/tinker Discovered Package: latrell/lock Discovered Package: lubusin/laravel-decomposer Discovered Package: maatwebsite/excel Discovered Package: nesbot/carbon Discovered Package: overtrue/laravel-query-logger Discovered Package: overtrue/laravel-socialite Discovered Package: prettus/l5-repository Discovered Package: sentry/sentry-laravel Discovered Package: simplesoftwareio/simple-qrcode Discovered Package: spatie/laravel-tail Discovered Package: tymon/jwt-auth Discovered Package: zgldh/qiniu-laravel-storage Package manifest generated successfully.$ composer require dees040/laravel-api-responses1/1: https://packagist.laravel-china.org/p/provider-latest$14d9ca1b35af157c565d6c564cde71c59043d7457135c5a4317471625a1db2e7.jsonFinished: success: 1, skipped: 0, failure: 0, total: 1 Using version dev-master for dees040/laravel-api-responses ./composer.json has been updated Loading composer repositories with package information Updating dependencies (including require-dev)1/1: https://dl.laravel-china.org/dees040/laravel-api-responses/9aec7eb323fc45e17f1dbb9c6e203d240836f91b.zipFinished: success: 1, skipped: 0, failure: 0, total: 1 Package operations: 1 install, 0 updates, 0 removals- Installing dees040/laravel-api-responses (dev-master 9aec7eb): Cloning 9aec7eb323 from cache Package phpoffice/phpexcel is abandoned, you should avoid using it. Use phpoffice/phpspreadsheet instead. Writing lock file Generating optimized autoload files > Illuminate\Foundation\ComposerScripts::postAutoloadDump > @php artisan package:discover$ composer require phpoffice/phpspreadsheet1/2: https://packagist.laravel-china.org/p/provider-latest$8512051929ea08e8189e440a1f5293135717f61525e93d6f4577794143032dd5.json2/2: https://packagist.laravel-china.org/p/provider-2018-10$4f971ac341cf575b7ed47aa09773abb926ec0c2baad56a0da2c9eed868beb649.jsonFinished: success: 2, skipped: 0, failure: 0, total: 2 Using version dev-master for phpoffice/phpspreadsheet ./composer.json has been updated Loading composer repositories with package information Updating dependencies (including require-dev) Your requirements could not be resolved to an installable set of packages.Problem 1- maatwebsite/excel 3.0.9 requires phpoffice/phpspreadsheet ^1.2 -> satisfiable by phpoffice/phpspreadsheet[1.2.0, 1.2.1, 1.3.0, 1.3.1, 1.4.0, 1.4.1, 1.5.0] but these conflict with your requirements or minimum-stability.- maatwebsite/excel 3.0.9 requires phpoffice/phpspreadsheet ^1.2 -> satisfiable by phpoffice/phpspreadsheet[1.2.0, 1.2.1, 1.3.0, 1.3.1, 1.4.0, 1.4.1, 1.5.0] but these conflict with your requirements or minimum-stability.- maatwebsite/excel 3.0.9 requires phpoffice/phpspreadsheet ^1.2 -> satisfiable by phpoffice/phpspreadsheet[1.2.0, 1.2.1, 1.3.0, 1.3.1, 1.4.0, 1.4.1, 1.5.0] but these conflict with your requirements or minimum-stability.- Installation request for maatwebsite/excel (locked at 3.0.9) -> satisfiable by maatwebsite/excel[3.0.9].Installation failed, reverting ./composer.json to its original content.suping3@BJ-D-212361A MINGW64 /d/code/blog $ composer require "phpoffice/phpspreadsheet:^1.2"1/3: https://packagist.laravel-china.org/p/provider-2018-10$edb575ac09ff566f26e69fb52521dbd7b5bd90cb0e97c11c04a834f1ba157b0b.json2/3: https://packagist.laravel-china.org/p/provider-latest$f7aba8aec5290950424531a654a2519842e07f0dcd995755aa8e64e7f622ad17.json3/3: https://packagist.laravel-china.org/p/provider-2018-07$1f1ac5377ce1027162f91a3db54217c36e38f7ae18744629e6e89c5e6d410c78.jsonFinished: success: 3, skipped: 0, failure: 0, total: 3 ./composer.json has been updated Loading composer repositories with package information Updating dependencies (including require-dev)1/1: https://dl.laravel-china.org/phpoffice/phpspreadsheet/2dfd06c59825914a1a325f2a2ed13634b9d8c411.zipFinished: success: 1, skipped: 0, failure: 0, total: 1

Fatal error: Class 'PHPUnit_Framework_TestCase' not found

https://github.com/dees040/laravel-api-responses/issues/2 vi vendor/dees040/laravel-api-responses/tests/ResponseTest.phpclass ResponseTest extends \PHPUnit\Framework\TestCase$ phpunit vendor/dees040/laravel-api-responses/tests/ResponseTest.php PHPUnit 6.5.3 by Sebastian Bergmann and contributors............... 14 / 14 (100%)Time: 378 ms, Memory: 16.00MB

Laravel 的 collection

$collection = new \Illuminate\Database\Eloquent\Collection(['item a', 'item b', 'item c']); $collection = $collection->unique(); 执行时候会报错PHP Fatal error: Call to a member function getKey() on string in /Project/nginx/webbpm-dev.ssl.lol/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Collection.php on line 259[Symfony\Component\Debug\Exception\FatalErrorException]Call to a member function getKey() on string 这是因为 Illuminate\Database\Eloquent\Collection 通过调用自身的 getDictionary 方法,使用根据主键去重复的逻辑覆盖了 Illuminate\Support\Collection 的逻辑。以上代码改成https://laravel-china.org/topics/18696$collection = collect(['item a', 'item b', 'item c']); $collection = $collection->unique();

使用"mews/captcha:~2.0" 验证码图片不显示问题

Symfony\Component\Debug\Exception\FatalThrowableError: Call to undefined function Intervention\Image\Gd\imagettfbbox() in file /usr/share/nginx/html/LaraBBS/vendor/intervention/image/src/Intervention/Image/Gd/Font.php on line 85如果已经开启了gd,请参考下 https://laravel-china.org/articles/18815?#reply69185 FROM php:7.0-fpm RUN apt-get update && apt-get install -y \ libfreetype6-dev \ libjpeg62-turbo-dev \ libmcrypt-dev \ libpng-dev \ && docker-php-ext-install -j$(nproc) iconv mcrypt \ && docker-php-ext-configure gd --with-freetype-dir=/usr/include/ --with-jpeg-dir=/usr/include/ \ && docker-php-ext-install -j$(nproc) gd

在解析外部变量时的一个问题

//https://segmentfault.com/a/1190000017051950 <form method="post"><input type="text" name="id[]" value="1"><input type="text" name="id[]_text" value="a"><input type="text" name="id[]" value="2"><input type="text" name="id[]_text" value="b"><input type="submit"> </form> var_export($_POST); array ('id' => array (0 => '1',1 => 'a',2 => '2',3 => 'b',), ) $foo["id"] = 1; $foo["id[]_text"] = 2;var_export($foo);extract($foo);var_export(get_defined_vars());

Laravel with () limit

比如如何取得每篇文章中的前10条评论 下面为错误写法:https://laravel-china.org/articles/19932essay::with(['comment' => function($query) {$query->take(10) }]) public function products() {return $this->belongsToMany(Hproduct::class,'hproduct_has_type','type_id','product_id'); }public function topTenproducts() {return $this->products()->with('supplier')->where('is_sale','=',1)->limit(4); }public function getProdcutsWithtopTenproducts($col) {$model = $this->whereIn('id',$col)->get();$model->each(function ($model) {$model->load('topTenproducts');});return $model->toArray(); }

laravel 5.5 索引长度超过限制

laravel5.4中改变了默认的编码类型(utf8 => utf8mb4), 从而使email字段索引长度超过了的默认限制长度 https://laravel-china.org/articles/18306 InnoDB 引擎中:uft8 varchar 最大长度 255 utf8mb4 varchar 最大长度 191 设置一下 varchar 的长度不超过 191 即可table->string('email')->index(); varchar会使用utf8mb4编码, utf8mb4编码(4bytes)属于utf8编码(3bytes)的扩展类型, 由此可以计算索引长度为255*4+2=1022 >767 $ php artisan migrate Migration table created successfully.In Connection.php line 664:SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 1000 bytes (SQL: alter table `users` add unique`users_email_unique`(`email`))

golang序列化失败

ret, _ := json.Marshal(result)//https://www.hchstudio.cn/article/2018/2622/ 发现是结构体定义有问题,当定义结构体时首字母必须大写才能序列化成功,这个特点在golang里面很是明显,在函数调用时首字母小写的函数在其他文件里面是调不到的。下面给出正确的结构体定义 type ResultCode struct {Msg string `json:"msg"`Code int `json:"code"`Data string `json:"data"` }

总结

以上是生活随笔为你收集整理的开发错误集锦的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。