0

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");
}
?>
1
  • 1
    Not your current issue... but... you are open to XSS injections with this code. Commented Sep 8, 2018 at 16:45

1 Answer 1

3

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"]); ?>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.