Array value from a forum input element [closed] - php

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I was under the impression that what ever is inserted into a <input type="text" name="something"> would be recieved as a string in PHP with $_POST['something'].
But now im running a tools to test my website and somehow $_POST['something'] can be an array.
How is that possible ?

If in your form you have inputs like <input name="something[]" ... /> you can have many of them or <select name="something[]" multiple ... />, etc.
$_POST['something'] would be an array.

It's common 'hack'. You should always verify that variables you get are in format you expect.
Example with $_GET:
http://127.0.0.1/hack_test.php?a[]=3&a[]=5?a[]=3&a[]=5
Example with $_GET and 'keys' of array:
http://127.0.0.1/hack_test.php?a[3]=3&a[hack_name]=5
If you put:
<?php
var_dump($_GET);
In hack_test.php it will show:
array(1) {
["a"]=>
array(2) {
[0]=>
string(1) "3"
[1]=>
string(1) "5"
}
}
Variable $_GET['a'] is array with 2 elements!
It's like that in PHP, because website forms sometimes require that feature.
Example:
<form ..>
<input type="checkbox" name="multicheckbox[]" value="chicken" />
<input type="checkbox" name="multicheckbox[]" value="apple" />
<input type="checkbox" name="multicheckbox[]" value="sugar" />
</form>
I called it 'hack', because:
If you use other PHP feature 'string is array of bytes' then someone can send you modified data to script, ex. $x = "abc"; $a = $x[0]; echo $a; -> 'a'
If you put data from input [form] in SQL query without verification, hacker can use it to make 'invalid query format' and in some cases, it let him get some information from database!

Related

PHP table creation with name and score [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I am having some serious trouble for some reason with creating a basic PhpMyAdmin database and making a page with a scoreboard. There will be a game that you play, and when you're done you can input a score and your name using basic form elements. When you press submit the page will reload and you will be able to see the top ten scores, ranked by highest first.
My issue is that I have no idea where to start with this. I have just started Php and don't wish for anything crazy. I have the ~/php/db_connect.php set up correctly already; I just need to make the function work.
How do you recommend I go through with this? Example code is extremely helpful.
I know the first response is "what have you tried?" and I haven't tried much.
This is what I have right now:
// define variables and set to $name = $myArray[0];
$babyinfo = fgets($myfile);
$myfile = scoreboard-dk;
$myArray = explode(',', );
$score = $myArray[1];
$name = $myArray[2];
$insertStmt = "INSERT INTO scoreboard-dk ('score','name') VALUES ('$score','$name')";
// Inserting Babynames into database
$db->query($insertStmt);
?>
<form action=" $db;?>" method="post">
Name: <input type="text" name="name" value=" echo $name;?>" required><br>
Score: <input type="text" name="score-dk" value=" echo $score;?>" required><br>
<input class="btn btn-primary" type="submit">
</form>
<tr> <th scope=row> echo $i;?></th> <td> echo $score;?></td> <td> echo $name;?></td> <td> echo $votes;?></td> </tr>
Thanks in advance.
Ok. First some mistakes you made:
$myfile = scoreboard-dk; isn't working. This way it would be a constant. You need the "$" or quotation marks if it should be a string.
$myArray = explode(',', ); I don't know what you want to do? The second argument is missing. This statement won't work. Second argument has to be a string.
You have to properly escape the query before executing the statement.
You can do this by replacing the following line before building the string:
$score = $db->real_escape_string($myArray[1]);
$name = $db->real_escape_string($myArray[2]);
Furthermore are you sure you use the correct indices for the array access? Counting starts with 0, not with 1.
You can't use PHP code without the opening tags. I thought that you cut that away at the start of the file. You always have to open PHP code blocks with
Perhaps you should search for example code elsewhere. I think stack is more for specific questions. But the code actually shows that you lack of some basic knowledge ... no offense.
The reason people can't help you is that your question is way too broad and everyone will have a different approach about how to implement it.
That being said, here is the pseudo code I would use to implement this. It can be done in a single file. Good luck!
File: score_keeper.php
<?php
error_msg = array
if (form submitted)
$name = name from form
$score = score from form
// Do validation to ensure name and score is as expected.
if name is empty
error_msg[] = 'Name cannot be empty'
if score is not numeric
error_msg[] = 'Score must be numeric'
if empty(error_msg)
// INSERT
// Make sure you use parameterized queries
SQL = INSERT into table (name, score) VALUE (?, ?)
end-if
end-if
// READ top 10
SQL = SELECT name, score FROM table WHERE ...
if !empty(error_msg)
show error_msg
?>
<form method="post">
<input name="name">
<input name="score">
</form>
HTML table
<?php
// output top 10 results

How to name an array after content from a string [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I've a form tag which sends the name for an array to a function but how can I name my array after this? Ok, code says more than thousand words:
<?php
function dynamic($id, $name, ... ){
...
echo "<select id='$id' name='$name' size='...' multiple>";
...
echo "<select id='$id' name='$name'>";
...
}
?>
<form ... method="post">
<p>
<?php
echo dynamic("dynamic1", "choice1", ...);
?>
</p>
<p>
<?php
echo dynamic("dynamic2", "choice2", ...);
?>
</p>
<p>
<?php
echo dynamic("dynamic3", "choice3", ...);
?>
</p>
<input type="submit" value="send"/>
</form>
I want to create a list where you can select multiple items but for this $name needs ot be an array. The array should named like the second variable. In one case it should be named choice1 in another choice2
Like how do I get from $name = "choice1"; to choice1[]
#edit Added a new line in function to show my problem. somtimes $name needs to be and array and sometimes not
Any ideas?
You are looking to use dynamic variable names, which is possible in PHP, but you need to be careful with this. Production code using this can be difficult to maintain and throw errors quite easily.
Anyway, lets say you have a value in the form $_POST that you want to use as a variable name. You would do so like this.
$id = "gettheidsomewhere";
${$id}[] = "whatever";
Like i said, use this carefully. Dynamic variable names are dangerous and very hard to debug when things break.
If you do not know the value used for $id, then you will need to loop through your post variables and assign them accordingly. I would assume you want to add some extra logic, but here is a basic example.
Using a key value loop you can obtain the name of the post variable, stored as $key and the value. So for $_POST["something"] = "test", when this line is looped over, $key will be "something" and $value will be "test".
foreach ($_POST as $key => $value)
{
${$key}[] = $value;
}

Save the whole PHP file to another one with $_POST variables [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
For example, I have a simple form with POST target to PHP file:
<form action="language_foo.php" method="post">
<input type="text" name="fname" />
<input type="text" name="age" />
<input type="Submit" name="Submit">
</form>
In language_foo file, I have:
$lang = "$_lang['item.desc']" = $_POST['fname'];
How can I save the user input with exact the same structure, e.g:
$lang = "$_lang['item.desc']" = "Jane";
To another PHP file? I can do file_put_contents, but it will only put "Jane" to file.
Any suggestions?
Simply file_put_contents the below variable $variable_to_put_in_file
$variable_to_put_in_file = '$lang = "$_lang[\'item.desc\']" = "' . $_POST['fname'] . '";';
Are you looking for serialize() ? After filling your $_lang array, you can serialize the whole array to a string and dump it into a file by doing file_put_contents(..., serialize($_lang)), and load it back later with $_lang = unserialize(file_get_contents(...)).

My code is not responding as i want it to be? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
My php is not responding correctly here is my HTML code
<html>
<body>
<form name="myform" method="post" action="lol.php">
<input type="text" name="man" value="">
<input type="submit" name="submit" value= "post">
</form>
</body>
</html>
Here is my PHP code
<?php
if ($_POST['man']= null )
{print ('has no value');}
else {print ($_POST['man']);
}
?>
use == operator for comparison instead of = because the second one is for assignment.
if ($_POST['man']== null )
{
print ('has no value');}
else {
print ($_POST['man']);
}
See PHP Comparison Operators
Change
if ($_POST['man']= null )
to
if ($_POST['man'] == null )
You are receiving any error?
Try:
if (isset($_POST['man'])) {
echo $_POST['man'];
}
else {
echo 'Nothing';
}
And to confirm everything is working use this:
var_dump($_POST);
The you will see the values on $_POST
At First, you should use isset instead of =, second and very important: = is an assignment, but what you want is an comparison, so use == and compare against an empty string

Modifying $_POST variable before submitting

I'm making a quiz generator, and I have an HTML form with radio buttons for multiple choice answers. Right now, when I submit my form, the contents of the $_POST variable looks like this when I submit it:
Array ( [a1] => Bob [a2] => Bobby )
(Bob and Bobby are the radio button choices I picked)
I'm generating this form using a PHP function, which returns an array of answers in addition to echoing the HTML form. Is there a way to modify the $_POST variable to have an 'answer' field (for checking my answers), like this:
Array( [a1] => Bob [a2] => Bobby [answers] => Array( [0] => Bob [1] => Bilbo ))
The above was one way I thought of to check answer array with $_POST array.
Edit: More info on what I have so far:
I have a PHP function getTest() that echoes the HTML form, and returns an array with the correct answers.
getTest() generates each question randomly, and as such the correct answers are random.
The main problem is that I have two separate PHP files, questions.php and verify.php.
questions.php echoes the form using getTest(), and has the array of answers.
verify.php only has the contents of $_POST, BUT NOT the array of correct answers.
Is there a better way to check the results of the form submission in general? Thanks!
The best way to do a quiz is to have an answers array and a user input array. Loop through one and compare to the other using the same increment.
You can take all of your post variables and create an array print_r($_POST); Then, loop through this.
$inputArray = //the post data into an array
$answerArray = array('a','b','a');
$numCorrect = 0;
for($a = 0; $a < count($inputArray); $a++)
{
if($inputArray[$a] == $answerArray[$a])
{
$numCorrect++;
}
}
If you want to transmit the answers when submitting the form, you could use inputs of hidden type (like ) which are invisible on the page. However it only takes the user checking the source HTML of the page to see these answers, so it might not be good for your use. Hope this helps
I think what you need to do is a have a look at sessions.
That way on questions.php you can save the answers to a session variable,
Then on verify.php you can read the answers from the session variable and compare them to answered supplied by the $_POST variable
If you really wanted to, you could probably just use a hidden field in your form for submitting an answer array. However, anyone can change your source and modify what the correct answer is.
The best way is to just have an array in your processing script with the same keys (a1, a2), but with the correct answers.
Your processing script would look like this:
$answers = array('a1'=>'Robert', 'a2'=>'Hobo');
foreach($_POST as $key => $value)
{
if (!array_key_exists($key, $answers))
{
continue;
}
if (trim($value) == $answers[$key])
{
// correct
}
else
{
// incorrect
}
}
If you want $_POST to contain an array you can simply use the bracket array notation on the name field of your form.
For example:
<fieldset class="Question1">
<input type="radio" name="answers[]" value="Question1Answer1">Question1Answer1<br>
<input type="radio" name="answers[]" value="Question1Answer2">Question1Answer2<br>
<input type="radio" name="answers[]" value="Question1Answer3">Question1Answer3<br>
</fieldset>
<fieldset class="Question2">
<input type="radio" name="answers[]" value="Question2Answer1">Question2Answer1<br>
<input type="radio" name="answers[]" value="Question2Answer2">Question2Answer2<br>
<input type="radio" name="answers[]" value="Question2Answer3">Question2Answer3<br>
</fieldset>
<fieldset class="Question3">
<input type="radio" name="answers[]" value="Question3Answer1">Question1Answer1<br>
<input type="radio" name="answers[]" value="Question3Answer2">Question1Answer2<br>
<input type="radio" name="answers[]" value="Question3Answer3">Question1Answer3<br>
</fieldset>
(Note that the fieldset tag is optional, I just included it to group things together)
The output in post will be an array $_POST['answers'] that will have one element for each question. So if you selected answer 1 for question 1, answer 2 for question 2, and answer 2 for question 3 you'd have:
$_POST['answers'] = [ 'Question1Answer1', 'Question2Answer2', 'Question3Answer2' ]
Not sure, but looks like you are asking for solution Y, whereas your problem is X (XY Problem)
The XY problem is when you need to do X, and you think you can use Y
to do X, so you ask about how to do Y, when what you really should do
is state what your X problem is. There may be a Z solution that is
even better than Y, but nobody can suggest it if X is never mentioned.
Usually it is not recommended to modify $_POST array, and also not to transmit Answers with the questions to client-side. Instead, the approach should be that because questions.php dont need answers, but verify.php does, so only verify.php shoul have access to answers.
For example, answer-lists are never transported to examination halls along with the question papers on the occasion of exams.
I have taken the liberty to modify your code structure. If you still want to go with your own code, please post it, and then you can get the answers you want.
Try to use this:
question.php:
<form action="verify.php" method="POST">
<fieldset class="Question1"> Complete this: ___<b>bar</b>
<input type="radio" name="answers[]" value="foo">Foo<br>
<input type="radio" name="answers[]" value="too">Too<br>
<input type="radio" name="answers[]" value="cho">Cho<br>
</fieldset>
<fieldset class="Question2"> Complete this: ___<b>overflow</b>
<input type="radio" name="answers[]" value="stack">Stack<br>
<input type="radio" name="answers[]" value="stock">Stock<br>
<input type="radio" name="answers[]" value="stick">Stick<br>
</fieldset>
</form>
answers.php:
//correct answers
$answers = array("foo", "stock");
verify.php:
include("answers.php");
$user_answers = $_POST["answers"];
$user_answers_count = count($user_answers);
$error = "";
for($i=0;$i<$user_answers_count;$i++)
if($user_answers[$i] !== $answers[$i]) //verify
$error[] = "Answer for Question ".($i+1)." is wrong!";
if(empty($error))
//Notify that user has passed the Quiz
else
//Notify that user has NOT passed the Quiz
//print the $error array
Couple of Notes:
I have used answers.php as a different file, but if there is no special requirement, consider merging answers.php & verify.php (put answers.php code on top of verify.php) Even better, you could also merge all these three files into one.
I have assumed that $_POST is sanitized.
Sequence of Questions & answers array is same. i.e. answers[foo] is correct answer for $_POST["answers"][foo]

Categories