php can't add data to array - php

here's a question : After entering some data about students, i need to print them in top side of the page (form one). I've managed to print data for single student, but i can't make it to store data in $studenti array, so that it will print data for all students.
here's code that i used(i forgot to mention, i need to use sessions for this):
<?php
session_start();
$_SESSION['aindex'] = $_POST['index'];
$_SESSION['aime']= $_POST['ime'];
$_SESSION['aprosek'] = $_POST['prosek'];
//if ($index != "" && $ime != "" && $prosek !="")
//{
// = $index;
//= $ime;
//=$prosek;
//}
//print ($_SESSION['aindex']);
function inicijalizacija()
{
$studenti = array ();
$ind = $_SESSION['aindex'];
$im = $_SESSION['aime'];
$pr = $_SESSION['aprosek'];
$studenti[$ind]["ime"] = $im;
$studenti[$ind]["prosek"] = $pr;
return $studenti;
}
function dodaj($studenti)
{
$studenti[$_SESSION['aindex']]["ime"] = $_SESSION['aime'];
$studenti[$_SESSION['aindex']]["prosek"] = $_SESSION['aprosek'];
return $studenti;
}
function prikazi($studenti) //ovde u argumentu treba $studenti
{
print ("<h2> Lista Studenata: </h2>");
foreach ($studenti as $ind => $student)
{
if (empty($ind))
continue;
$n = $student["ime"];
$p = $student["prosek"];
print ("Index: " . $ind . " " . "Ime: " . $n . " " . "Prosek: " . $p );
}
print("<hr size ='1'>");
//Forma dodavanja
print (" <form action = 'index.php' method = 'post' >");
print ( " Indeks:&nbsp <input type = 'text' name = 'index' />");
print(" </br>");
print ( " Ime:&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp <input type = 'text' name = 'ime' >");
print(" </br>");
print ( " Prosek : <input type = 'text' name = 'prosek' />");
print(" </br>");
print (" <input type = 'submit' value = 'Dodaj' name = 'Dodaj' />");
}
$studenti = inicijalizacija();
?>
<html>
<head> <title> pokusaj </title> </head>
<body>
<?php
prikazi($studenti);
dodaj($studenti);
?>
</body>
</html>

It seems you're misunderstanding the way PHP works. For efficiency and security, all variables are destroyed when the script has ran and the variables used for this user aren't visible for the script when called by other users.
$_SESSION is an exception; data in $_SESSION will be preserved until the session expires, but it will still only be visible to one unique user (identified by a cookie).
If you want to save the data of a script for use when it is called again (using another session), you'll have to write data to a file or use a database.
PS, your script looks like it will introduce XSS and CSRF vulnerabilities; make sure you won't make the same mistakes that many people before you made.

Related

PHP: $_POST cannot retrieve existing inputs

I'm attempting to make a button that, based on the selected form/inputs on the page, will bring you to a page called "typeDefine.php?openness=3?conscientiousness=2?extroversion=1?agreeableness=2?neuroticism=1"(the numbers varying based on the selected inputs). However, $selectedNum- the variable that would ideally be containing the $_POST for each input- is returning an error immediately once the page is loaded, saying:
Undefined index
<?php
$typeWords = array("openness", "conscientiousness", "extroversion", "agreeableness", "neuroticism");
$typeLetters = array("o", "c", "e", "a", "n");
$typePath = "";
$correspondingLetters = array("I", "II", "III");
$isFirst = true;
foreach($typeWords as $typeWord)
{
$selectedNum = $_POST[$typeWord];//error here!!!
if(isset($selectedNum))//if got $typeWord in a form
{
$separationChar;
if($isFirst)
{
$separationChar = "?";
$isFirst = false;
}
else
{
$separationChar = "&";
}
$typePath = $typePath . $separationChar . $typeWord . "=" . $selectedNum;//e.g. $typePath = "?openness=3?conscientiousness=2?extroversion=1?agreeableness=2?neuroticism=1" for $_GET method after arriving on next page
}
}
echo 'search for type
<div>';
foreach($typeWords as $typeWord)
{
$typeLetter = substr($typeWord, 0, 1);
echo '<form method = "post" class = "column">';
for($i = 1; $i <= 3; $i++)
{
echo '<input type = "radio" name = "' . $typeWord . '" id = "' . $typeLetter . $i . '"><label for = "' . $typeLetter . $i . '">' . $correspondingLetters[$i - 1] . '</label>';//sets each input name to $typeWord for $_POST above
}
echo '<li class = "textHighlight">' . $typeWord . '</li>
</form>';
}
echo '</div>';
?>
What can I do to fix this error, in turn filling $typePath and making the script correctly bring you to the desired url upon the button's click?
Thanks in advance!
You should perform the isset() test on the $_POST element, not the variable that you set from it.
foreach ($typeWords as $typeWord)
{
if (isset($_POST[$typeWord])) {
$selectedNum = $_POST[$typeWord];
$typePath = $typePath . "?" . $typeWord . "=" . $selectedNum;
}
}
Note that multiple parameters need to be separated with &, ? should only be used at the beginning. There's a built-in function that will create a query string from an array, you can use that:
$typeArray = [];
foreach ($typeWords as $typeWord)
{
if (isset($_POST[$typeWord])) {
$selectedNum = $_POST[$typeWord];
$typeArray[$typeWord] = $selectedNum;
}
}
$typePath = $typePath . "?" . http_build_query($typeArray);
You can also replace the loop with:
$typeArray = array_intersect_key($_POST, array_flip($typeWords));
You execute your code immidiately without a present $_POST array.
You have to wrap your post related code with an if statement like this:
if ($_POST) {
$selectedNum = $_POST[$typeWord];
}

I need to iterate through multiple fields and have them inserted into my MySQL database

Ok, I'm really stuck. But I think I'm headed in the right direction. the script that calls this script has multiple fields which are generated dynamically by PHP. I need some way of looping through them and checking if they're set to avoid any undefined variables, and then once I know that they're all set and checked for validity inserting them into the MySQL table passwords. I could really use your help on this one guys.
<?php
require_once('/session/session.php');
require_once('auth/auth.php');
require_once('/MySQLi/mysqliConnect.php');
require_once('check_fields_function.php');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<!-- Copyright 2015 Brock Lynch -->
<?php $page = "passwords"; ?>
<?php require_once('/headerFooter/docHead.php'); ?>
<body>
<?php require_once('/headerFooter/header.php');?>
<div id="boxWrapper"> <!-- beginning of boxWrapper -->
<?php require_once('question_nav.php'); ?>
<div id="display_categories">
<?php
// This is just for reference: check_fields($pattern,$post,$minlength,$maxlength,$name_of_field)
$numOfFields = $_POST['numOfFields'];
for($z = 1;$z <= $numOfFields;$z++) {
if(isset($_POST['password_input$z']) && isset($_POST['group_input$z']) && isset($_POST['belongs_input$z']) && isset($_POST['name_input$z']) && isset($_POST['choice$z'])) {
$password[$z] = check_fields("/([[:alnum:]\!\#\#\$\%\^\&\*\*\(\)\-\_\+\=\[\]\;\'\:\"\'\<\>\?\/\`\~])+/",$_POST['password_input$z'],6,50,'Password$z');
$password_group[$z] = check_fields("/^[a-zA-Z \'\"]+$/",$_POST['group_input$z'],1,50,'Password Group$z');
$password_belongs_to[$z] = check_fields("/^[a-zA-Z \'\"]+$/",$_POST['belongs_input$z'],1,50,'Belongs To$z');
$password_name[$z] = check_fields("/^[a-zA-Z \'\"]+$/",$_POST['name_input$z'],1,50,'Password Name$z');
$changes_periodically[$z] = check_fields("/^[0-1]+$/",$_POST['choice$z'],1,50,'Changes Periodically$z');
}
else {
$password[$z] = false;
$password_group[$z] = false;
$password_belongs_to[$z] = false;
$password_name[$z] = false;
$changes_periodically[$z] = false;
}
}
// Iterate through each array and if they are all set, set the master password_setting to true
function check_all_arrays($fieldArray)
{
global $numOfFields;
$p = 0;
if(isset($fieldArray)) {
foreach($fieldArray as $test) {
echo "Yeah, this seems to be working";
if($test == true) {
$p++;
}
}
}
else {
return false;
}
if($p == $numOfFields) {
return true;
}
else {
return false;
}
}
if(check_all_arrays($password) == true && check_all_arrays($password_group) == true && check_all_arrays($password_belongs_to) == true && check_all_arrays($password_name) == true && check_all_arrays($changes_periodically) == true) {
echo "Got passed master checks, this is good";
// Encrypt the users password before entering it into the database.
// Clean the data before inserting it into the database.
$instance = PasswordCrypt::createWithNewPassword($_POST['password_input']);
$password_pass = mysqli_escape_string($mysqli,$instance->encodePassword($_POST['password_input']));
$token_pass = mysqli_escape_string($mysqli,$instance->getToken());
$key_pass = mysqli_escape_string($mysqli,$instance->getKey());
$group = mysqli_escape_string($mysqli,$_POST['group_input']);
$belongs_input = mysqli_escape_string($mysqli,$_POST['belongs_input']);
$name_input = mysqli_escape_string($mysqli,$_POST['name_input']);
$password_save = "INSERT INTO passwords (password_id,customer_id,password_not_key,token_pass,key_pass,password_group,
changes_periodically,security_status,belongs_to,password_name)VALUES('','" . $_SESSION['customer_id'] . "','" . $password_pass . "','". $token_pass . "','" . $key_pass . "','" . $group . "','" . $choice . "','','" . $belongs_input . "','" . $name_input . "')";
mysqli_query($mysqli,$password_save) OR DIE(mysqli_error($mysqli));
// Echo confirmation message to user
echo "<div style='text-align:center;'>You have successfully stored 1 password</div>";
?>
<form action="myPassword.php">
<button input="submit_back">Back</button>
</form>
<?php
}
else {
// Tell them to use only letters in fields besides the password field.
echo "<div style='text-align:center;'>All fields are required except changes periodically. Password field may have letters, numbers, and special characters and must be at least 6 characters. All other fields may only have letters. Thank you</div>";
?>
<form action="myPassword.php">
<button type="submit">Go Back</button>
</form>
<?php
}
?>
</div> <!-- End of display categories -->
</div> <!-- End of boxWrapper div -->
</body>
<div class="bigBoldFont"></div>
<?php require_once('headerFooter/footer.php'); ?>
</div><!-- end of boxWrapper -->
</body>
</html>
What you have now will work if you change the single quotes on all the $_POST variables to double quotes.
E.g. change isset($_POST['password_input$z']) to isset($_POST["password_input$z"])
You could also make it a little easier to read by wrapping the variable in curly braces {}. isset($_POST["password_input{$z}"])

after form submit,if user already login then form will submit else login first then form should be submit automatically

I am trying to implement a form, if user already login then from will submit, else login first then form should be submit automatically with the help of cookie an error is sowing in my code on last move_uploaded_file.
My code is given as follows
<?php
if(isset($_POST['submit'])
{
$ad_title=$mysqli->real_escape_string($_POST['ad_title']);
$category=$mysqli->real_escape_string($_POST['category']);
$sub_category=$mysqli->real_escape_string($_POST['sub_category']);
$description=$mysqli->real_escape_string($_POST['description']);
$rent_amount=$mysqli->real_escape_string($_POST['rent_amount']);
$rent_security=$mysqli->real_escape_string($_POST['rent_security']);
$contact=$mysqli->real_escape_string($_POST['contact']);
$email=$mysqli->real_escape_string($_POST['email']);
$city=$mysqli->real_escape_string($_POST['city']);
$state=$mysqli->real_escape_string($_POST['state']);
$area=$mysqli->real_escape_string($_POST['area']);
$buy=(isset($_POST['buy'])?1:0);
$sell=(isset($_POST['sell'])?1:0);
$rent=(isset($_POST['rent'])?1:0);
$manufacture=$mysqli->real_escape_string($_POST['company_name']);
$conditions=$mysqli->real_escape_string($_POST['condition']);
$rent_option=$mysqli->real_escape_string($_POST['rent_option']);
$a=$_FILES['file']['name'];
$path="image/product/$a";
$b=$_FILES['file2']['name'];
$path2="image/product/$b";
$c=$_FILES['file3']['name'];
$path3="image/product/$c";
$d=$_FILES['file4']['name'];
$path4="image/product/$c";
$e=$_FILES['file5']['name'];
$path5="image/product/$c";
if(isset($_SESSION['user_id'])){
$query=$mysqli->query("insert into ads(product_name,category,sub_category,description,image_1,image_2,image_3,image_4,image_5,city,state,rent_amount,rent_option,security_amount,contact_no,email,area,buy,sell,rent,user_id,manufacture,conditions)values('$ad_title','$category','$sub_category','$description','$a','$b','$c','$d','$e','$city','$state','$rent_amount','$rent_option','$rent_security','$contact','$email','$area','$buy','$sell','$rent','$user_id','$manufacture','$conditions')");
move_uploaded_file($_FILES['file']['tmp_name'],$path) & move_uploaded_file($_FILES['file2']['tmp_name'],$path2) & move_uploaded_file($_FILES['file3']['tmp_name'],$path3) & move_uploaded_file($_FILES['file4']['tmp_name'],$path4) & move_uploaded_file($_FILES['file5']['tmp_name'],$path5);
if($query)
{
echo "success";
}
}else{
$time = time() + 60;
setcookie('email',$email,$time);
setcookie('ad_title',$ad_title,$time);
setcookie('category',$category,$time);
setcookie('sub_category',$sub_category,$time);
setcookie('description',$description,$time);
setcookie('rent_amount',$rent_amount,$time);
setcookie('rent_security',$rent_security,$time);
setcookie('contact',$contact,$time);
setcookie('city',$city,$time);
setcookie('state',$state,$time);
setcookie('area',$area,$time);
setcookie('buy',$buy,$time);
setcookie('sell',$sell,$time);
setcookie('rent',$rent,$time);
setcookie('manufacture',$manufacture,$time);
setcookie('condition',$conditions,$time);
setcookie('rent_option',$rent_option,$time);
setcookie('file',$a,$time);
setcookie('file2',$b,$time);
setcookie('file3',$c,$time);
setcookie('file4',$d,$time);
setcookie('file5',$e,$time);
header("Location:product/login.php"); }
}
if(isset($_COOKIE['email'])){
$email =$_COOKIE['email'];
$cookie2 = $_COOKIE['ad_title'];
$cookie3 = $_COOKIE['category'];
$cookie4 = $_COOKIE['sub_category'];
$cookie5 = $_COOKIE['description'];
$cookie6 = $_COOKIE['rent_amount'];
$cookie7 = $_COOKIE['rent_security'];
$cookie8 = $_COOKIE['contact'];
$cookie9 = $_COOKIE['city'];
$cookie10 = $_COOKIE['state'];
$cookie11 = $_COOKIE['area'];
$cookie12 = $_COOKIE['buy'];
$cookie13 = $_COOKIE['sell'];
$cookie14 = $_COOKIE['rent'];
$cookie15 = $_COOKIE['manufacture'];
$cookie16 = $_COOKIE['condition'];
$cookie17 = $_COOKIE['file'];
$cookie18 = $_COOKIE['file2'];
$cookie19 = $_COOKIE['file3'];
$cookie20 = $_COOKIE['file4'];
$cookie21 = $_COOKIE['file5'];
$cookie22 = $_COOKIE['rent_option'];
$pat="image/product/$cookie17";
$pat2="image/product/$cookie18";
$pat3="image/product/$cookie19";
$pat4="image/product/$cookie20";
$pat5="image/product/$cookie21";
$query1=$mysqli->query("insert into ads(product_name,category,sub_category,description,image_1,image_2,image_3,image_4,image_5,city,state,rent_amount,rent_option,security_amount,contact_no,email,area,buy,sell,rent,user_id,manufacture,conditions)
values
('$cookie2','$cookie3','$cookie4','$cookie5','$cookie17','$cookie18','$cookie19','$cookie20','$cookie21',
'$cookie9','$cookie10','$cookie6','$cookie22','$cookie7','$cookie8',
'$email','$cookie11','$cookie12','$cookie13','$cookie14','$user_id','$cookie15','$cookie16')");
move_uploaded_file($cookie17,$pat)&
move_uploaded_file($cookie18,$pat2)&
move_uploaded_file($cookie19,$pat3)&
move_uploaded_file($cookie20,$pat4)&
move_uploaded_file($cookie21,$pat5);
if($query1){
echo "Succes";
}
else{
echo "Something went wrong.";
}
}
?>
Not a solution to your question: You have no name assigned to your select menu.
That aside, you need to check for the existence of a session variable - assuming you set some sort of session variable when the user logged in? ie: $_SESSION['username']='fred' etc? You can generate javascript that will submit the form at page load.
<form name="appointment" method="POST" action="appointment.php" role="form">
<!-- form contents -->
</form>
<?php
if( isset( $_SESSION['username'] ) ){
echo "
<script type='text/javascript'>
document.querySelectorAll( form['name=\"appointment\"]' )[0].submit();
</script>";
}
?>

Passing information using post method without session variables

I will admit immediately that this is homework. I am only here as a last resort after I cannot find a suitable answer elsewhere. My assignment is having me pass information between posts without using a session variable or cookies in php. Essentially as the user continues to guess a hidden variable carries over all the past guesses up to that point. I am trying to build a string variable that holds them all and then assign it to the post variable but I cannot get anything to read off of the guessCounter variable i either get an undefined index error at the line of code that should be adding to my string variable or im just not getting anything passed over at all. here is my code any help would be greatly appreciated as I have been at this for awhile now.
<?php
if(isset($_POST['playerGuess'])) {
echo "<pre>"; print_r($_POST) ; echo "</pre>";
}
?>
<?php
$wordChoices = array("grape", "apple", "orange", "banana", "plum", "grapefruit");
$textToPlayer = "<font color = 'red'>It's time to play the guessing game!(1)</font>";
$theRightAnswer= array_rand($wordChoices, 1);
$passItOn = " ";
$_POST['guessCounter']=$passItOn;
$guessTestTracker = $_POST['guessCounter'];
$_POST['theAnswer'] = $theRightAnswer;
if(isset($_POST['playerGuess'])) {
$passItOn = $_POST['playerGuess'];
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
$guessTestTracker = $_GET['guessCounter'];
$theRightAnswer = $_GET['theAnswer'];
}
else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if(isset($_POST['playerGuess'])) {
if(empty($_POST['playerGuess'])) {
$textToPlayer = "<font color = 'red'>Come on, enter something(2)</font>";
}
else if(in_array($_POST['playerGuess'],$wordChoices)==false) {
$textToPlayer = "<font color = 'red'>Hey, that's not even a valid guess. Try again (5)</font>";
$passItOn = $_POST['guessCounter'].$passItOn;
}
if(in_array($_POST['playerGuess'],$wordChoices)&&$_POST['playerGuess']!=$wordChoices[$theRightAnswer]) {
$textToPlayer = "<font color = 'red'>Sorry ".$_POST['playerGuess']." is wrong. Try again(4)</font>";
$passItOn = $_POST['guessCounter'].$passItOn;
}
if($_POST['playerGuess']==$wordChoices[$theRightAnswer]) {
$textToPlayer = "<font color = 'red'>You guessed ".$_POST['playerGuess']." and that's CORRECT!!!(3)</font>";
$passItOn = $_POST['guessCounter'].$passItOn;
}
}
}
}
$_POST['guessCounter'] = $passItOn;
$theRightAnswer=$_POST['theAnswer'];
for($i=0;$i<count($wordChoices);$i++){
if($i==$theRightAnswer) {
echo "<font color = 'green'>$wordChoices[$i]</font>";
}
else {
echo $wordChoices[$i];
}
if($i != count($wordChoices) - 1) {
echo " | ";
}
}
?>
<h1>Word Guess</h1>
Refresh this page
<h3>Guess the word I'm thinking</h3>
<form action ="<?php echo $_SERVER['PHP_SELF']; ?>" method = "post">
<input type = "text" name = "playerGuess" size = 20>
<input type = "hidden" name = "guessCounter" value = "<?php echo $guessTestTracker; ?>">
<input type = "hidden" name = "theAnswer" value = "<?php echo $theRightAnswer; ?>">
<input type = "submit" value="GUESS" name = "submitButton">
</form>
<?php
echo $textToPlayer;
echo $theRightAnswer;
echo $guessTestTracker;
?>
This is a minimal functional example of what you need to do. There are still a couple of minor bugs (like duplicate entries in the history), but I've left these as an exercise for you. Treat this as a starting point and build up what you need from it.
I've added comments to explain what's happening, so hopefully it is clear to you.
$answer = null;
$history = [];
$choices = ['apple', 'grape', 'banana'];
$message = '';
// check if a guess has been made.
if (!empty($_POST) && !empty($_POST['guess'])) {
// check if previous guesses have been made.
if (!empty($_POST['history'])) {
$history = explode(',', $_POST['history']);
}
// check guess.
if (!empty($_POST['answer']) && !empty($_POST['guess'])) {
// check guess and answer are both valid.
if (in_array($_POST['guess'], $choices) && isset($choices[$_POST['answer']])) {
if ($_POST['guess'] == $choices[$_POST['answer']]) {
// correct; clear history.
$history = [];
$message = 'correct!';
} else {
// incorrect; add to history and set previous answer to current.
$history[] = $_POST['guess'];
$answer = $_POST['answer'];
$message = 'incorrect!';
}
} else {
// invalid choice or answer value.
}
}
}
if (empty($answer)) {
// no answer set yet (new page load or correct guess); create new answer.
$answer = rand(0, count($choices) - 1);
}
?>
<p>Guess the word I'm thinking:</p>
<p><?php echo implode(' | ', $choices) ?></p>
<form method="POST">
<input type="hidden" name="answer" value="<?php echo $answer; ?>">
<input type="hidden" name="history" value="<?php echo implode(',', $history); ?>">
<input type="text" name="guess">
<input type="submit" name="submit" value="Guess">
</form>
<p><?php echo $message; ?></p>

php outputs part of code without any echo

Here's my piece of code(full body code):
<body>
<script type='text/javascript'>
function AddEvent(Syear, Smonth, Sday, Eyear, Emonth, Eday, hallNumber){
...
}
</script>
<?php
function GetMonthByCoding($first , $second , $third) {
...
}
function GetDateByCoding($coding){
...
}
function GetDateFromLine($line){
...
}
$userid = '...';
$magicCookie = 'cookie';
$feedURL = "...";
$sxml = simplexml_load_file($feedURL);
foreach ($sxml->entry as $entry) {
$title = stripslashes($entry->title);
if ($title == "HALL") {
$summary = stripslashes($entry->summary);
$date = GetDateFromLine($summary);
echo ("<script type='text/javascript' language='JavaScript'> AddEvent(" . $date['start']['year'] . ", " . $date['start']['month'] . ", " . $date['start']['day'] . ", " . $date['end']['year'] . ", " . $date['end']['month'] . ", " . $date['end']['day'] . "); </script>");
}
}
?>
</body>
AddEvent() is JavaScript function defined earlier.
What I get in my browser is:
entry as $entry) { $title = stripslashes($entry->title); if ($title == "HALL") { $summary = stripslashes($entry->summary); $date = GetDateFromLine($summary); echo (""); } } ?>
Looks like it was an echo but as you can see there is no echo right in the middle of foreach.
Can anyone say what I am doing wrong?
PHP is not installed, or it is not enabled, or the file is not a .php file or the server has not been told to recognise it as a file to parse.
Try View Source and you should see all your PHP code. The only reason part of it shows up is because everything from <?php to the first > is considered by the browser to be an invalid tag.
I found the problem, it was in the name of variable sxml. I renamed it and the problem escaped.

Categories