0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

strcmpを空文字比較で使うな

Last updated at Posted at 2017-10-31

if(strcmp($str,'')==0);を見つけたら抹殺しておけ

Badコード

//memberは必須やで
if(isset($_GET['MEMBER']) && strcmp($_GET['MEMBER'], '') == 0){
  http_response_code(404);
  exit;
}

絶対に許さない。$_GET['MEMBER'] === ''でいいだろ。
というか、GETパラメータに配列入ってくるとかちゃんと考えてるのかと小一時間
$_GETは入ってればArray以外はstrで返すからまだマシ(ほんとに?)だが、
falseも通るしnullも通る。そこに使ってほんとに良いのか?考えて実装してほしい。


$method = $_SERVER['REQUEST_METHOD'];
if(strcmp($method, 'GET') == 0){
  $request['hoge'] = isset($_GET['hoge']) ? $_GET['hoge'] : null;
}

完全一致は===で良いだろ!いい加減にしろ!
わざわざ出現位置を調べる必要が無い。

Goodコード

仮に文字検索なら
出現を調べるならstrposなど**pos関数です。
strstrを使う人が居ますが、strposのほうが探す だけ なら適切です

if(strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== false){
  http_response_code(404);
  exit;
}

脳死実装はやめて意味を考えて

新規コードはともかく、既存コードの変更で上や下の既存コードを何も考えずパクってくるのは大いに結構だが、安直に実装するなかれ。

※擁護するとstrcmpはPHP4時代やPHP5.0時代のnullバイト攻撃に対処するために最初の開発者は実装したのではと考えてるが真意は不明。

0
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?