“Notice: Undefined variable”, “Notice: Undefined index”, and “Notice: Undefined offset” using PHP

后端 未结 28 1183
盖世英雄少女心
盖世英雄少女心 2021-01-24 14:18

I\'m running a PHP script and continue to receive errors like:

Notice: Undefined variable: my_variable_name in C:\\wamp\\www\\mypath\\index.php on line 10

28条回答
  •  梦谈多话
    2021-01-24 14:58

    Try these

    Q1: this notice means $varname is not defined at current scope of the script.

    Q2: Use of isset(), empty() conditions before using any suspicious variable works well.

    // recommended solution for recent PHP versions
    $user_name = $_SESSION['user_name'] ?? '';
    
    // pre-7 PHP versions
    $user_name = '';
    if (!empty($_SESSION['user_name'])) {
         $user_name = $_SESSION['user_name'];
    }
    

    Or, as a quick and dirty solution:

    // not the best solution, but works
    // in your php setting use, it helps hiding site wide notices
    error_reporting(E_ALL ^ E_NOTICE);
    

    Note about sessions:

    • When using sessions, session_start(); is required to be placed inside all files using sessions.

    • http://php.net/manual/en/features.sessions.php

提交回复
热议问题