Home > front end >  Undefined Variable Error Thrown When Using A $_GET Request
Undefined Variable Error Thrown When Using A $_GET Request

Time:05-12

I have a page that connects to a MySQL database via PHP. On this page the data is fetched to load an image and its related details. This page all work OK when the page is loaded.

I also have a module included on this page where users can create a board (which will hold images) along a certain theme.

On other pages this board module works OK, but on a page where a $_GET request happens, which is needed to identify a user's username or an image filename (depending on the page), the board module doesn't work correctly. When you create a new board it fails and I get a PHP error saying Undefined variable: filename in with reference to the line of code ':filename' => $filename in the execute function below.

When this boards module is used to create a new board name I have some JavaScript fetch() code on the page that prevents a hard refresh. I'm not sure if this is causing the problem (although this JS is also used on the pages that don't have a problem, i.e. no $_GET request). On pages where this is no $_GET request everything works as expected.

Note: in the code below $connection is the database connection from a db.php file

PHP on pageload that loads the image and related data

isset($_GET['filename']) ? $filename = $_GET['filename'] : header("Location: login.php");

$image_stmt = $connection->prepare("SELECT * FROM `lj_imageposts` WHERE `filename` = :filename");

$image_stmt -> execute([
    ':filename' => $filename // variable that returns the error
]); 

$image_row = $image_stmt->fetch();

// if the GET url parameter doesn't exist/changed
if ($image_row == 0) { header ("Location: index.php"); exit; }

$db_userid = htmlspecialchars($image_row['user_id']);
$db_image_id = htmlspecialchars($image_row['image_id']);
$db_image_title = htmlspecialchars($image_row['image_title']);
$db_image_filename = htmlspecialchars($image_row['filename']);
$db_image_ext = htmlspecialchars($image_row['file_extension']);
$db_username = htmlspecialchars($image_row['username']);

?>

---- HTML OUTPUT THAT INCORPORATES THE ABOVE VARIABLES

PHP for the boards module

if (isset($_POST['submit-board-name'])) {

    $create_board_name = $_POST['create-board-name'];
    
    if(strlen(trim($create_board_name)) < 10) {
        $error[] = "Board name must be at least 10 characters long";
    }

    if(strlen(trim($create_board_name)) > 150) {
        $error[] = "Board name can be at less than 150 characters long";
    }

    if(!isset($error)) {
    
        try {

            $createBoardSQL = "INSERT INTO lj_boards (board_name, user_id) VALUES (:board_name, :user_id )";
        
            $bstmt = $connection->prepare($createBoardSQL);
            $bstmt->execute([
                ':board_name' => $create_board_name,
                ':user_id' => $db_id
            ]);

        } catch(PDOException $e) {
            echo "Error: " . $e->getMessage();
        }

    }
} else {
    // give values an empty string to avoid an error being thrown before form submission if empty
    $create_board_name = "";
}

CodePudding user response:

This first line is unnecessarily cryptic, making the mistake harder to spot (and harder to fix):

isset($_GET['filename']) ? $filename = $_GET['filename'] : header("Location: login.php");

It's pretending to be an expression, but it's actually an if statement in disguise - it consists of nothing but side effects. Let's write it out more clearly:

if ( isset($_GET['filename']) ) {
    $filename = $_GET['filename'];
}
else {
    header("Location: login.php");
}

Now we can look more clearly at what each branch does:

  • The if branch sets a variable. If the code takes that branch, everything should be fine.
  • The else branch sets a header to be included when PHP sends the response. It doesn't do anything else, and it doesn't set the variable, so if this path is taken, you'll have a problem later.

What you probably intended to happen was for the else branch to set that header and then immediately stop processing. For that you need an exit; statement (also known as die;

if ( isset($_GET['filename']) ) {
    $filename = $_GET['filename'];
}
else {
    header("Location: login.php");
    exit;
}
  •  Tags:  
  • php
  • Related