Error passing php variables to another page via form data - php

I want to pass a variable to another page by form data. I've looked at other tutorials and codes, i've followed them closely, but the contents of the variable doesn't output. Basically php doesn't work inside the value="". Here's the code.
page 1.
<?php
$hi = 1224;
?>
<form method = "post" action = "page2.php">
<input type = "hidden" Name = "var" Value = "<?phpecho$hi;?>"/>
<input type = "submit" Name = "enter" Value = "Submit"/>
</form>
page 2.
<?php
$test = $_REQUEST['var'];
echo $test;
?>
Nothing is outputted.
I've even tried session variables but somehow they worked but once i refreshed the page, the variables were reset. I've started sessions on all pages etc..

It should be <?php echo $hi; ?> instead of <?phpecho$hi;?>. i.e. you need give space between <?php and echo and its $hi variable as like in below.
<input type = "hidden" name = "var" value = "<?php echo $hi; ?>"/>

When something isn't working, make sure to check the source code for error, don't just look browser's rendering. In the source, you'd clearly have seen that <?phpecho$hi;?> wasn't evaluated, but instead just printed in the source.
So in conclusion, <?phpecho$hi;?> is wrong. Write <?php echo $hi;?>.

Change your line
<input type = "hidden" Name = "var" Value = "<?phpecho$hi;?>"/>
to
<input type = "hidden" name = "var" value = "<?php echo $hi; ?>" />
If possible change the name of the hidden textbox to something relevant instead of var , because var is a reserved word in javascript to avoid confusion.

Instead of
<input type = "hidden" Name = "var" Value = "<?phpecho$hi;?>"/>
Should be, you need spaces in php
<input type = "hidden" name = "var" value = "<?php echo $hi; ?>"/>

try this look to $_POST super global for value :
<?php
$test = $_POST['var'];
echo $test;
?>

Related

Multi-word $GET variable problemin PHP

I am currently writing some search engine, where this page is retrieving some _GET variables from a previous page. This is working as intended.
Now I am using those variables as default value in a POST form. However, for some reason, only the first word for each of them is showing up. The form code is as follows:
<form action = "insert.php" method = 'POST'>
<Place name <input type="text" name="name" size = "30" value= <?php echo $_GET['name']; ?> />
Note that when echoing $_GET['name'] anywhere else in the page, everything is fine. Multiple words show up as expected, but when I use it as a text box default value, only the first word shows up on the textbox.
At first, I thought it had something to do with the way those $_GET variables are sent in the URL so I tried this:
$fullname = array();
$fullname = explode("%20", $_GET['name']);
$aaa = implode (' ',$fullname);
...
Place name <input type="text" name="name" size = "30" value= <?php echo $aaa; ?> />
but the result is still the same. If I echo it anywhere else in the page I get the full string, but if it's inside the form only the first word shows up.
What am I missing here?
The value attribute of the input tag needs to be in quotes:
<input type="text" name="name" size = "30" value="<?php echo $_GET['name']; ?>" />"
Otherwise, if $_GET['name'] contains spaces you'll end up with something like: value=John Smith. That will be understood as value=John with an invalid Smith attribute floating around.
Also, consider sanitizing $_GET['name'] with htmlspecialchars. Consider what would happen if $_GET['name'] was "/><script>alert(0)</script><. You'd end up embedding user-controlled code on your website, resulting in a reflected XSS.

My array values keep dissapearing and refreshing in php?

I want to be able to add new values to the array called playlist using functions (is mandatory). But everytime I input another value it replaces the old one instead of just adding on the end of the array. What is wrong?
<?php
$playlist = array("Be more.mp3", "Drift Away.mp3", "Panda Sneeze.mp3");
function add_songs_playlist() {
global $playlist;
?>
<form method = "post">
<input type = "text" name = "name1"/>
<input type = "submit" name = "submit1"/>
</form>
<?php
if (isset($_POST['submit1'])) {
$newsong = $_POST['name1'];
array_push($playlist, $newsong);
}
}
add_songs_playlist();
foreach ($playlist as $value) {
echo $value."<br>";
}
PHP values aren't saved between requests. Every time this page loads, $playlist starts out with those same three values you assign.
If you want to keep data around longer, you'll need to save it somewhere—a cookie, a file, the session, a database, etc.
Alternatively, you could store the values in the HTML itself, by printing an <input type="hidden"> for each song in the playlist. Then when the user enters a new song, you have the new song plus the full list of all the old ones.
Just write the playlist to a file
<?php
if (isset($_POST['submit1'])) {
$song = "\n".$_POST['name1'];
$file = fopen("songs.txt", 'a');
fwrite($file, $song);
fclose($file);
}
$file = file("songs.txt");
foreach ($file as $song) {
echo $song . "</br>";
}
?>
<form method = "post">
<input type = "text" name = "name1"/>
<input type = "submit" name = "submit1"/>
</form>
There is a general mistake you make:
you have to understand that each time you transmit a value the way you do, you php script is started again. It restarts without anything left from the last time.
To be able to take over values the way you want to you have to store those values in a persistant manner after having pushed them to the array. During the next run you first have to read the existing values from that persistant storage, fill the array and only then you can add another value on top of that array. This is a general principle, the basic way this kind of framework works.
Typically a database is used as persistant storage, but also files might be interresting, depending on how many request and how much data you plan to process.
Here is an small mod of your code. I removed the function and stored your array within the form itself.
This one will work without storing any information on the server, bet I don't think it wil be very usable. You should store your content like suggested by #Anonymous in previous reply.
Working code:
<?php
// First check if I get a POST request with list of songs
if (isset($_POST['playlist'])) {
$playlist = $_POST['playlist'];
} else { // Else set my default list
$playlist = array("Be more.mp3", "Drift Away.mp3", "Panda Sneeze.mp3");
}
// You need to get the added son BEFORE you generate the FORM,
// so it can be a part of the form
if (isset($_POST['name1'])) {
$playlist[] = $_POST['name1'];
}
?>
<form method = "post">
<?php
// This loop stores your songs as hidden values within the form,
// so you will get them with your next post
foreach($playlist as $song) {
?>
<input type = "hidden" name = "playlist[]" value = "<?php echo $song?>">
<?php
}
?>
<input type = "text" name = "name1"/>
<input type = "submit" name = "submit1"/>
</form>
<?php
foreach ($playlist as $value) {
echo $value."<br>";
}
An example specific to your repost code would be:
if (isset($_POST['submit1'])) {
$newsong = $_POST['name1'];
$playlist[] = $newsong;
}
Also an error may be the fact your form is within a function... why not just do this
<?php
$playlist = array("Be more.mp3", "Drift Away.mp3", "Panda Sneeze.mp3");
?>
<form method = "post">
<input type = "text" name = "name1"/>
<input type = "submit" name = "submit1"/>
</form>
<?php
if (isset($_POST['submit1'])) {
$newsong = $_POST['name1'];
$playlist[] = $newsong;
}
foreach ($playlist as $value) {
echo $value."<br>";
}
?>
I am not sure if you care if the page refreshes. But if you are fine with a page refresh this should work. If you do not want a refresh you can either save your variables in javascript and do your work in that and use the form button onClick as a function call. Or if you want to work your variables in PHP in-order to reset your php variable without refreshing you will need to make an AJAX call to call back JSON to update your PHP variable.

passing html information through javascript to php

I have two textboxes that are normally disabled. When a user presses a edit button the textbox becomes enabled and they are allowed to type. However when I submit the form the value that was input by the user is not passed to my php code.
Here is my javascript code:
if (timesin%2 == 0){
document.getElementById(score1).disabled = true;
document.getElementById(score2).disabled = true;
} else {
document.getElementById(score1).disabled = false;
document.getElementById(score2).disabled = false;
document.getElementById(score1).value = "";
document.getElementById(score2).value = "";
}
timesin++;
Here on each alternate clicks it disables or enables, probably not the best way to do this but thats not the important part here.
This is the html code for the box
<input type = 'textbox' id = 'columntext".$columncount.$inc.$leaguesarray[$numofleagues]."' name = 'columntext".$columncount.$inc.$leaguesarray[$numofleagues]."' maxlength = '2' disabled style = 'width:15px; text-align:center' value = '".$col_value."' />
So it is disabled. When a button is clicked the function is called and the textbox is enabled. The user then types a value and clicks the edit button again which disables the textbox. So now I have the textbox disabled with a new inputted valued. However when I submit and get the value through php I get a blank variable.
Any ideas?
Thanks,
<input type = 'textbox' id = 'columntext".$columncount.$inc.$leaguesarray[$numofleagues]."' name = 'columntext".$columncount.$inc.$leaguesarray[$numofleagues]."' maxlength = '2' disabled style = 'width:15px; text-align:center' value = '".$col_value."' />
I see a couple of problems. One is that .$columncount.$inc.$leaguesarray[$numofleagues]. isn't HTML. You need the php tags around it and also need to echo those values, which would look like this:
'columntext<?php echo $columncount.$inc.$leaguesarray[$numofleagues] ?>'
Same thing with this line:
value = '".$col_value."'
should be
value = '<?php echo $col_value ?>'
I'm surprised the page rendered, unless you were preparing it within a php echo all along? Either way, clarifying that bit might help narrow down what the problem could be.
I'm not clear enough but... any disabled input is not going to be sent, if you want to be no-editable try with readonly='readonly', and BTW you should make some kind of validation in your php code, don't trust in JS only
good luck
This is an incorrect way of using inline PHP:
<input type = 'textbox' id = 'columntext".$columncount.$inc.$leaguesarray[$numofleagues]."' name = 'columntext".$columncount.$inc.$leaguesarray[$numofleagues]."' maxlength = '2' disabled style = 'width:15px; text-align:center' value = '".$col_value."' />
Instead try something like this:
<?php
$id = "columntext".$columncount.$inc.$leaguesarray[$numofleagues];
?>
<input type="textbox" id="<?php echo($id); ?>" name="<?php echo($id); ?>" maxlength="2" value="<?php echo($col_value); ?>">
Also, you should consider using a separate CSS file to hold your styling rather than place it within the HTML element. It makes life so much easier and helps keep your design DRY.
Assuming this is inside a PHP echo statement, change
<input type = 'textbox' id = 'columntext".$columncount.$inc.$leaguesarray[$numofleagues]."' name = 'columntext".$columncount.$inc.$leaguesarray[$numofleagues]."' maxlength = '2' disabled style = 'width:15px; text-align:center' value = '".$col_value."' />
to
<textarea id = 'columntext".$columncount.$inc.$leaguesarray[$numofleagues]."' name = 'columntext".$columncount.$inc.$leaguesarray[$numofleagues]."' maxlength = '2' disabled style = 'width:15px; text-align:center' />".$col_value."</textarea>
ive never seen <input type = 'textbox'> before

Passing variables from HTML to PHP using form submission

I'm having a problem with the following piece of code. My desire is to have the heading Search results appear when the form is submitted using the 'Search' button, and I'm trying to implement this using the hidden input called searching. The idea is that when the form is submitted, this value is set to 'yes', and that will reveal the heading, but that is not what is happening here. Can anyone please tell me where I've gone wrong?
<html>
<head>
<title>Search</title>
</head>
<body>
<h1>Search</h1>
<form name = "search" action = "<?=$PHP_SELF?>" method = "get">
Search for <input type = "text" name = "find" />
<input type = "hidden" name = "searching" value = "yes" />
<input type = "submit" name = "search" value = "Search" />
</form>
<?php
if ($searching == "yes")
{
echo "<h2>Search results</h2>";
}
?>
</body>
</html>
#chris, you dont have to use a hidden field. you just can check if the form was submitted like this:
if(isset($_GET['search'])) echo 'foo';
#Boris, why should it be more secure to store the global into another var? I would agree if you check the global against a regex or whatever before.
Felix
You need to access the superglobal $_GET:
if($_GET["searching"]=="yes"){
//echo here
}
Unless you're using an old version of PHP, or a really unsecure configure, you're likely not using global variables.
Therefore, you need to first retrieve your $searching variable from the magic $_GET variable.
$searching = $_GET['searching'];

Add text inputs based on user's requirement

<form action = "numbericalInput.php" method = "Get">
Please enter the number of input areas you wish
<input type = "text" name = "amountOfEntry"/>
<input type = "submit" name = "GO"/>
</form>
<?php
if(!empty($_GET("amountOFEntry")){
for($i = 0; $i < $_GET("amountOFEntry"); $i++){
<input type= "text" name = "nums[]" size = "2" />
}
}
?>
What I'm trying to do is ask the user to input a value in to the text area and then for me to present them with an appropriate amount of text inputs for them to enter their values in. So the user enters 10, they have 10 text inputs presented and a submit button or something. I appreciate this line won't work where it is
<input type= "text" name = "nums[]" size = "2" />
but I am sure that's along the right sort of lines? also, what is wrong with this line?
if(!empty($_GET("amountOFEntry")){
thanks
use: isset() http://php.net/manual/en/function.isset.php
<form action = "numbericalInput.php" method = "Get">
Please enter the number of input areas you wish
<input type = "text" name = "amountOfEntry"/>
<input type = "submit" name = "GO"/>
</form>
<?php
if(isset($_GET['amountOfEntry'])){
for($i = 0; $i < $_GET['amountOfEntry']; ++$i){
?><input type= "text" name = "nums[]" size = "2" /><?
}
}
?>
This will check for the existence of $_GET['amountOFEntry'] (Note square brackets as $_GET and $_POST are arrays)
Please also note use of ++$i instead of $i++. There is a minor performance increase here. Not much but it worth doing.
EDIT:::
Please note that the variables will be case sensitive, You are using amountOfEntry in the form and $_GET['amountOFEntry'] in the loop. (Note capitol F)
$_GET is an array, you have to use [] to get the elements. So:
if(!empty($_GET['amountOFEntry']){
As pointed out $_GET returns an array of values. So use the square brackets to find the variable you want. Also you cant mix HTML amd PHP. So you need to make the HTML a string (by quoting it) and user echo (or print) to output the string.
if(!empty($_GET["amountOFEntry"]){
for ($i = 0; $i < $_GET["amountOFEntry"]; $i++) {
echo '<input type= "text" name = "nums[]" size = "2" />';
}
}
Also, as noted by Lizard, you should use isset to determine if the variable is set.
You might as well get the numerical value of the $_GET to avoid runtime errors:
intval($_GET['amountOFEntry'])
If you preferred you could use JavaScript. Using a library like JQuery would help a lot.
JavaScript:
$("#goButton").bind("click",function(e){
numberOfEntries = parseInt($("#numberOfEntries").attr("value"));
for(i=0;i<numberOfEntries;i++){
newInput = document.createElement("input");
$(newInput).attr("type","text").attr("name","nums[]").attr("size","2");
$("#inputEntries").append(newInput);
}
}
);
HTML:
<body>
<input id="numberOfEntries" type = "text" name = "amountOfEntry"/>
<input id="goButton" type = "submit" name = "GO"/>
<div id="inputEntries"></div>
</body>
This is a lot of work just to avoid sending the page back to the server and having the work carried out on the server-side, but thought I might suggest it anyway...

Categories