Daniel Acevedo
Daniel Acevedo

Reputation: 141

Inserting a variable in a script

I'm learning a little bit of PHP and JSON to make a simple CRUD. I have different categories divided into nodes, I don't want to have to create an individual add page for each node and I'm trying to fetch the categories(node) from URL. I'm fetching the category from the URL with a get, the variable it's fine but I think I'm not using the correct syntax to insert that variable on the rest of the code.

<?php $type = $_GET["type"]; ?>

<h1>You are adding a new type of: <?php echo $type ?></h1>
<form action="add.php" method="POST"  enctype="multipart/form-data">
    <input type="text" name="title" placeholder="Name"/>
    <input type="text" name="code" placeholder="Code"/>
    <input type="text" name="price" placeholder="Price"/>
    <input type="text" name="description" placeholder="Description"/>
    <input type="file" name="myfile" id="photo">
    <input type="submit" name="add"/>

</form>
<?php

if (isset($_POST["add"])) {
    $file = file_get_contents('menu.json');
    $data = json_decode($file, true);
    unset($_POST["add"]);
    $data[" '.$type.' "] = array_values($data[" '.$type.' "]);
    array_push($data[" '.$type.' "], $_POST);
    file_put_contents("menu.json", json_encode($data));
    header("Location: backend.php");
}
?>

Upvotes: 0

Views: 33

Answers (1)

Devon Bessemer
Devon Bessemer

Reputation: 35347

You're going to lose your $_GET value as soon as you submit your form since your action is just 'add.php'.

Either use action="add.php?type=<?php echo $type ?>" or just exclude the action which by default will submit to the current url.


Like pointed out, you're subject to XSS injections with this code. Encode html entities on type to prevent this. (Always encode user input before outputting to the browser):

<?php $type = htmlentities($_GET["type"]); ?>

Upvotes: 3

Related Questions