LoginSignup
0
0

More than 3 years have passed since last update.

【PHP】デバッグ

Last updated at Posted at 2020-09-13

PHPについて学習内容を備忘録としてまとめます。

デバッグについて

開発中にエラーが発生した際に、デバッグをすると思います。
その中でも私がデバッグ方法を記載します。

var_dump

コードの中で値を確認する際に利用することができます。
例えば、下記のような従業員がログインするコードで見ていきます。

#staff_login.php

<form method="post"action="staff_login_cheak.php">
スタッフコード<br />
<input type="text" name="code"><br />
パスワード<br />
<input type="password" name="pass"><br />

#staff_mypage.php

$staff_code=$_POST['code'];
$staff_pass=$_POST['pass'];

var_dump($staff_code);

※本当は間にDBから該当のユーザーを取得する処理がありますが、省略しています。
このように記載すると、staff_login_cheak.phpにスタッフコードフォームで記入したコード番号が表示されます。

image.png

↓ ログイン

image.png

デバッグを別ファイルで管理

ajaxなどでデバッグを実施する際に、上記のやり方だと表示されません。
バックエンドの処理なので一度デバッグ情報をファイルに出力する方法をとります。

方法としては_debug()という関数を作成し、引数に確認したい値等を入れると表示される処理を行います。

#_debug()関数を作成
  function _debug( $data, $clear_log = false ) {
    $uri_debug_file = $_SERVER['DOCUMENT_ROOT'] . '/debug.txt';
    if( $clear_log ){
      file_put_contents($uri_debug_file, print_r($data, true));
    }
    file_put_contents($uri_debug_file, print_r($data,true), FILE_APPEND);
    }

上記関数は自分がわかるところで作成してください。
それではいいね機能のajaxファイルにて、いいねした際のデバッグを見ていきます。

if(isset($_POST)){

  $current_user = get_user($_SESSION['staff_code']);
  $page_id = $_POST['page_id'];
  $post_id = $_POST['post_id'];

  $profile_user_id = $_POST['page_id'] ?: $current_user['id'];

  if(check_favolite_duplicate($current_user['code'],$post_id)){
    $action = '解除';
    $sql = "DELETE
            FROM favorite
            WHERE :user_id = user_id AND :post_id = post_id";
  }else{
    $action = '登録';
    $sql = "INSERT INTO favorite(user_id,post_id)
            VALUES(:user_id,:post_id)";
  }
 _debug($action);  //ここを追加

いいねボタンを押した結果、設定したdebug.txtにて$actionの値が入っていればデバッグ成功です。

image.png
↓いいねボタンをクリック
image.png

今度はいいね解除ボタンをクリック
image.png

image.png

解除が追記されている。
_debug()関数は_debug('',true)と定義するとdebug.txtが空になるように作成されています。

参考URL

0
0
1

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
0