I am facing a problem in pushing value to a global array.
A user uploads multiple documents. Everytime he uploads a document, a webservice is called which returns 'id' and 'type' (which is working fine). I need to store it in a array so that I can encode it into JSON and send it when the user clicks on Submit button.
My code is:
//global variable
<?php
$idarray = array();
$typearray = array();
?>
//form
<form method="post">
<input type="submit" name="upload" value="Upload">
<input type="submit" name="submit" value="Submit">
</form>
<?php
if(isset($_POST['upload']))
{
include 'webservice_call.php';
$url='http://localhost:8080/MyProject/getEntityRequest';
$response=curl_get_call($url); //this function is inside webservicecall.php
$json_string = json_decode($response);
$id=$json_string->gstdtls->entcd; //this is working fine
$ty=$json_string->gstdtls->stcd; //this is working fine
func1($idarray, $typearray, $id, $ty);
}
if(isset($_POST['submit']))
{
$docls=array();
global $idarray;
global $typearray;
for ($i=0; $i < sizeof($idarray); $i++) {
$docls[] = array (
'id' => $idarray[$i],
'ty' => $typearray[$i],
);
}
$json_formatted['docls']=$docls;
echo json_encode($json_formatted);
}
function func1($idarray, $typearray, $a, $b){
array_push($idarray, $a);
array_push($typearray, $b);
}
?>
When the user finally submits, it should give me the content of an array in a encoded format. Which is not happening. I know I am not using the global array in the way it should be used.
what u need is to store values somewhere like database or session instead of an array when you call upload and when you call submit button retrieve those values and convert them to json and echo them .
Here is a example of that using session
<?php
$json_formatted=array();
if (!session_start()) {
session_start();
}
?>
<?php
if(isset($_POST['upload']))
{
$_SESSION["idarray"][]=rand(0,5);
$_SESSION["typearray"][]=rand(0,5);
}
if(isset($_POST['submit']))
{
$docls=array();
$idarray=$_SESSION["idarray"];
$typearray=$_SESSION["typearray"];
for ($i=0; $i < sizeof($idarray); $i++) {
$docls[] = array (
'id' => $idarray[$i],
'ty' => $typearray[$i],
);
}
$json_formatted['docls']=$docls;
echo "<pre>";
print_r(json_encode($json_formatted));
echo "</pre>";
session_destroy();
}
function func1($idarray1, $typearray1, $a, $b){
array_push($idarray, $a);
array_push($typearray, $b);
}
?>
<form method="post">
<input type="submit" name="upload" value="Upload">
<input type="submit" name="submit" value="Submit">
</form>
Related
I have the following code Multiple text and type File Using an array to upload file and Text.
in this code, if I remove type file this code is working. but after use file is not work
Here is the Form
<form method="post" enctype="multipart/form-data">
<?php
$data_array = array('text','text2','file','file2');
foreach($data_array as $data_name){ ?>
<input type="hidden" name="data_name[]" value="<?php echo $data_name; ?>">
<?php if(strpos($data_name,'text') !== false){ ?>
<input name="data_value[]" type="text" />
<?php }
if(strpos($data_name,'file') !== false){ ?>
<input name="data_value[]" type="file" /> <?php }
} ?>
<input type="submit" name="submit" value="Add" />
</form>
Here is The Php Code, I Think More Improvement on $_FILE Part
if(isset($_POST['submit'])){
if(isset($_FILES['data_name'])){
foreach(array_combine($_FILES['data_name'],$_POST['data_value']) as $dataname => $datavalue){
$file_name = $_FILES['data_name']['name'];
echo file_name;
}
}
if(isset($_POST['data_name'])){
foreach(array_combine($_POST['data_name'],$_POST['data_value']) as $dataname => $datavalue){
echo $dataname.' - '.$datavalue;
}
}
}
Here is The Error of File..
Warning: array_combine(): Both parameters should have an equal number
of elements in pagename.php on line 25
Warning: Invalid argument supplied for foreach() in pagename.php on line 25
I Need Output Like This -
text = value
text2 = value2
file = file.jpg
file2 = file2.jpg
As stated explicitly in the error message, $_FILES['data_name'] and $_POST['data_value' are not the same size. (And I'm pretty sure the foreach is failing because the array_combine failed).
That is explained by you here: "if I remove type file this code is working. but after use file is not work".
If you want to use array_combine(), the arrays must be of the same size.
If you add a filter (eg if(strpos($data_name,'file') !== false)) the potential exists that the arrays will not match (as this problem indicates).
One approach would be to filter out the "data_name[]" inputs with the same condition as the "data_value[]" inputs.
Or the other way round: add an else on the above mentioned if that produces <input name="data_value[]" type="hidden" /> (notice the type). This will ensure the arrays are the same size. You will have to figure out what to do with these "dummy" inputs in the php code. Perhaps give them a value (like value="dummy") that you can test on.
replace your php-code with this:
function get_names_for_entity($name, $arr)
{
if (!empty($arr)) {
$ret = array_values(
array_filter(
$arr,
function ($itm) use ($name) {
return strpos($itm, $name) !== false;
}
)
);
} else {
$ret = [];
}
return $ret;
}
$names_a = [
'file' => get_names_for_entity('file', $_POST['data_name']),
'text' => get_names_for_entity('text', $_POST['data_name'])
];
if (isset($_POST['submit'])) {
if (isset($_POST['data_value'])) {
foreach ($_POST['data_value'] as $dataname_idx => $datavalue) {
echo $names_a['text'][$dataname_idx].' - '.$datavalue;
}
}
if (isset($_FILES['data_value'])) {
foreach ($_FILES['data_value']['name'] as $dataname_idx => $datavalue) {
$file_name = $_FILES['data_value']['name'][$dataname_idx];
echo $names_a['file'][$dataname_idx].' - '.$file_name;
}
}
}
I really need help on this.
I have an array that takes data from my input radio buttons. But the problem is these input buttons may not follow the exact numbers because of my where clause in the select statement.
<form method="post" action="<?php echo base_url();?>index.php/Question/resultdisplay">
<?php foreach($questions as $row) {
?>
<?php $ans_array = array($row->correct, $row->wrong, $row->wrong1, $row->wrong2);
shuffle($ans_array);
?>
<p><?=$row->quiz_question?></p>
<input type="radio" name="quizid<?=$row->id?>" value="<?=$ans_array[0]?>" required/><?=$ans_array[0]?><br/>
<input type="radio" name="quizid<?=$row->id?>" value="<?=$ans_array[1]?>"/><?=$ans_array[1]?><br/>
<input type="radio" name="quizid<?=$row->id?>" value="<?=$ans_array[2]?>"/><?=$ans_array[2]?><br/>
<input type="radio" name="quizid<?=$row->id?>" value="<?=$ans_array[3]?>"/><?=$ans_array[3]?><br/>
<?php
}
?>
<br/>
<input type="submit" value="Finish"/>
</form>
public function resultdisplay()
{
$this->data['checks'] = array(
'ques1' => $this->input->post('quizid1'),
'ques2' => $this->input->post('quizid2'),
'ques3'=> $this->input->post('quizid3'),
'ques4'=> $this->input->post('quizid4'),
'ques5'=> $this->input->post('quizid5'),
'ques6'=> $this->input->post('quizid6'),
'ques7'=> $this->input->post('quizid7'),
'ques8'=> $this->input->post('quizid8'),
'ques9'=> $this->input->post('quizid9'),
'ques10'=> $this->input->post('quizid10'),
'ques11'=> $this->input->post('quizid11'),
);
$this->load->model('quizmodel');
$this->data['results'] = $this->quizmodel->getQuestions();
$this->load->view('result_display', $this->data);
}
I want the array to be dynamic. because if the data in the database is more than eleven(11) then the user will not get result for the rest of the quiz.
If you change your resultdisplay() function round to first fetch the questions and then look for an answer to each question...
public function resultdisplay()
{
$this->load->model('quizmodel');
$this->data['results'] = $this->quizmodel->getQuestions();
$this->data['checks'] = [];
for ( $i = 1; $i <= count($this->data['results']); $i++ ) {
$this->data['checks'][] = $this->input->post('quizid'.$i);
}
$this->load->view('result_display', $this->data);
}
This will end up with an array (with a numeric index - you can change that by changing $this->data['checks'][$keyName]= with whatever you want as $keyName). Any missing answers will have null, again you can change this if needed at :null;.
I've got some code working that takes the text from my input box and moves it across to a function. I'm now trying to change it so I add another form element, a radio button and I want to access the choice within my functions.php file.
This is my current code which works for the post name, but what if I want to also grab the colours boxes that was selected too?
main.php
<?php
if (isset($_POST['submit'])) {
$data = $_POST['name']; // the data from the form input.
}
?>
...
<form action="/" method="post">
<input type="text" name="name" placeholder="Acme Corp"/>
<input name="colour" type="radio" value="red">Red<br>
<input name="colour" type="radio" value="blue">Blue<br>
<input name="colour" type="radio" value="green">Green<br>
<input type="submit" name="submit" value="Submit">
</form>
<img src="pngfile.php?data=<?php print urlencode($data);?>"
alt="png php file">
I guess I confused because currently it is calling this:
pngfile.php
<?php
require_once 'functions.php';
$inputData = urldecode($_GET['data']);
process($inputData);
exit;
?>
Which calls functions.php
<?php
function process($inputdata)
{
...
EDIT: What I have tried:
main.php [Change]
$data = $_POST['name'] && $_POST['colour']
But I'm not really sure how to progress.
Never trust user input. Sanitize and validate your inputs before using them.
This can be arranged better, but the basics are still true.
PHP Manual: filter_input_array()
PHP Manual: filter_var_array()
Small Function Library
function sanitizeArray($filterRules)
{
return filter_input_array(INPUT_POST, $filterRules, true)
}
function validateArray($filteredData, $validationRules)
{
return filter_var_array($filteredData, $validationRules, true);
}
function checkFilterResults(array $testArray, array &$errors)
{
if (!in_array(false, $testArray, true) || !in_array(null, $testArray, true)) {
foreach($testArray as $key => $value)
{
$errors[$key] = '';
}
return true;
}
if ($testArray['name'] !== true) { //You can make a function and do various test.
$errors['name'] = 'That is not a valid name.';
}
if ($testArray['clour'] !== true) { //You can make a function and do many test.
$errors['colour'] = 'That is not a valid colour.';
}
return false;
}
function processUserInput(array &$filteredData, array $filterRulesArray, array $validationRulesArray, array &$cleanData, array &$errors)
{
$filteredInput = null;
$tempData = sanitizeArray($filterRulesArray);
if (!$checkFilterResults($tempData, $errors)){
throw new UnexpectedValueException("An input value was unable to be sanitized.");
//Consider forcing the page to redraw.
}
$filteredData = $tempData;
$validatedData = validateArray($filteredData, $validationRulesArray);
if (!$checkFilterResults($validatedData, $errors)){
return false;
}
$errors['form'] = '';
$cleanData = $validatedData;
return true;
}
function htmlEscapeArray(array &$filteredData)
{
foreach($filteredData as $key => &$value)
{
$value = htmlspecialchars($value, ENT_QUOTES | ENT_HTML5, 'UTF-8', false);
}
return;
}
Basic Main Line
try {
$filterRulesArray = []; //You define this.
$filteredData = []; //A temporary array.
$validationRulesArray = []; //You define this.
$validatedData = null; //Another temporary array.
$results = null; //Input processing results: true or false.
$cleanData = null; //Filtered and validated input array.
$errors = []; //Any errors that have accumulated.
if (isset($_POST, $_POST['submit'], $_POST['colour']) && !empty($_POST)) {
$results = processUserInput($filteredData, $filterRulesArray, $validationRulesArray, $cleanData, $errors);
} else {
$errors['form'] = "You must fill out the form."
}
if ($results === true) {
$name = $cleanData['name']; //You can do what you want.
$colour = $cleanData['colour']; //You can do what you want.
//header("Location: http://url.com/registration/thankYou/")
//exit;
}
//Prepare user input for re-display in browser
htmlEscapeArray($filteredData);
} catch (Exception $e) {
header("Location: http://url.com/samePage/"); //Force a page reload.
}
Let the form redraw if input processing fails.
Use the $errors array to display error messages.
Use the $filteredData array to make the form sticky.
<html>
<head>
<title>Your Webpage</title>
</head>
<body>
<h1>My Form</h1>
<form action="/" method="post">
<!-- Make spots for error messages -->
<input type="text" name="name" placeholder="Acme Corp" value="PUT PHP HERE"/>
<!-- No time to display sticky radios! :-) -->
<input name="colour" type="radio" checked="checked" value="red">Red<br>
<input name="colour" type="radio" value="blue">Blue<br>
<input name="colour" type="radio" value="green">Green<br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
Tip:
It may be better to submit numbers for radios, as opposed to longer string values like (red, green, blue). Numbers are easier to sanitize and validate. Naturally, then you must translate the input number into its corresponding string. You would do that after validation has finished, but before using the values. Good luck!
you can access this using array like this.
$data[] = $_POST['name'];
$data[] =$_POST['colour'];
Or combine both variable
$data = $_POST['name'].'&'.$_POST['colour'];
Use Array in php for this process as follows:
if (isset($_POST['submit'])) {
$array_val = array(
"name"=> $_POST['name'],
"color"=> $_POST['color']
);
}
I need to be able to update my form data once the submit button is pressed on the same page.
I have a csv file. And at the moment, I have worked out how to edit data inside it, and save it in the csv file (through a form).
-(I have attached the main code below, but even any suggestions would be helpful)
The form and php execution is on the same page, but once the user edits the values and presses submit, the data goes back to the original data. So it updates in the csv file, but not in the form.
This is the form:
for ($i=0; $i<200; $i++) {
if(empty($SearchResults[$i][0]) == false){ //If its full
?>
<form method="post" action="">
Full Name: <input name = "Name2" type="text" value="<?php echo $SearchResults[$i][0] ?>"/>
Weight (kg): <input name="Weight2" type="number" value="<?php echo $SearchResults[$i][1] ?>"/>
Weight of belongings (kg): <input name="WeightOfBelongings2" type="number"value="<?php echo $SearchResults[$i][2] ?>"/>
<input name="submit" type="submit" />
</form>
<?php
$i++;
}else if (empty($SearchResults[$i][0]) == true){ //If it is empty
$i =201;
}
}
This is what happens when the submit button is pressed:
if (isset($_POST['submit'])) {
$FullName = $_POST['Name2'];
$Weight = $_POST['Weight2'];
$WeightOfBelongings = $_POST['WeightOfBelongings2'];
//Creates a new felon from the class in felen.php and assigns it to this variable $Felon
$Felen = new felen;
//This refers to a function in the class Felen. From this information it calculates the costs, ammounts etc. And saves it to a variable that can be called.
$Felen -> CreateFelen($FullName, $Weight, $WeightOfBelongings);
//This is a for loop that checks when there is an avaliable line to put the data into.
if ($FullName != "") {
$i = 0;
for ($i=0; $i<200; $i++) {
if(empty($csv[$i][0]) == false){ //If its full
if($csv[$i][0] == $_POST['Name2']){
//its only printing it if it is in the first row?
$csv[$i][0] = $FullName;
$csv[$i][1] = $Weight;
$csv[$i][2] = $WeightOfBelongings;
$csv[$i][3] = $Felen->FelenTotalWeight;
$csv[$i][4] = $Felen->UnassembliumRequired;
$csv[$i][5] = $Felen->ReassembliumRequired;
$csv[$i][6] = $Felen->CostOfUnassemblium;
$csv[$i][7] = $Felen->CostOfReassemblium;
$csv[$i][8] = $Felen->TotalCostOfJourney;
$i = 201;
}
}
}
//Saves the previous data and new changes to the csv file
//This opens to file as a write file
$fp = fopen('data.csv', 'w');
//This takes the array that has had data ddded to it and adds it to the file
foreach ($csv as $fields) {
fputcsv($fp, $fields);
}
//This closes the file
fclose($fp);
}
}
Thank you very much!
I have both PHP and HTML in one file, following the pattern:
-HTML1
-PHP1
-HTML2
<-script>
-PHP2
<-/script>
-rest of HTML
In the PHP2 section, I call a function in PHP1 which returns an array.
I can get a value for count($arr), but I cannot print the values in the array. It simply shows as an empty string when I examine the source code in the browser.
When I copy the statements in the function from PHP1 to PHP2, everything works - I can print the values of the array.
Code follows:
<?
include('pathdata.php');
function getThePath($node1, $node2){ //pass strings
$n1 = $matchIDtoNum[$node1]; //get int (from pathdata)
$n2 = $matchIDtoNum[$node2];
$res = array();
$res[0] = $n1;
$res[1] = $n2;
return $res;
}
$node1='';
$node2='';
if($_GET["node1"]){
$node1 = $_GET["node1"];
}
if($_GET["node2"]){
$node2 = $_GET["node2"];
}
if ($node1!='' && $node2!=''){
$arr = getThePath($node1,$node2);
}
?>
<html>
<head><title>Paths</title>
<script>
function init(){
<?
echo ("document.getElementById('msg1').innerHTML = 'test';\n");
if($node1!='' && $node2!=''){
//$n1 = $matchIDtoNum[$node1];
//$n2 = $matchIDtoNum[$node2];
//$res = array();
//$res[0] = $n1;
//$res[1] = $n2;
//$arr=$res;
$num = count($arr);
$str = implode(' ', $arr);
echo ("document.getElementById('msg1').innerHTML = '$arr[0]';\n"); //Empty string
echo ("document.getElementById('msg2').innerHTML = '$str';\n"); //String with one space character
echo ("document.getElementById('msg3').innerHTML = '$num'+' '+'$node1'+' '+'$node2';\n"); //this always works
}
?>
}
</script>
</head>
<body onload="init()">
<h1>Given two Nodes, return Shortest Path</h1>
<form name="inputform" action="getpath.php" method="get">
<input type="text" name="node1" />
<input type="text" name="node2" />
<input type="submit" value="Submit" />
<input type="reset" value="Clear" />
<br/>
<p id ="msg1"></p>
<p id ="msg2"></p>
<p id ="msg3"></p>
<br/>
</form>
</body>
</html>
Any advice on where I might be going wrong?
Thanks!
Edited to Add: What worked for me was putting global $matchIDtoNum; inside the function. i.e.
function getThePath($node1,$node2){
global $matchIDtoNum;
$n1 = $matchIDtoNum[$nd1];
//etc
}
This gave the expected output for me.
Thanks to all the commenters and answerers!
Mmm.. on this line:
$n1 = $matchIDtoNum[$node1]; //get int (from pathdata)
It seems you want to get an array value from $matchIDtoNum. You can not take a array value from outside of a function, unless you call it as a function. For example like this:
$n1 = getMatchIDtoNum($node1); // get int (from pathdata)
and on file pathdata.php there a line like this:
function getMatchIDtoNum($arg){
// Your code here
return $matchIDtoNum[$arg];
}
use the $node1 and $node2 as global variables. like
function getThePath(){ //don't pass strings
global $node1, $node2;
.....
}
//call function as
$arr = getThePath();
Now you will get your array