show the form only if submit is not set - php

I am trying to show the form only if submit is not set, and if set then upload file and show link to the same page so that a new file could be uploaded again.
It shows the form even after I click on the submit button. I have not added an upload script now.
<body>
<?php
if (isset($_POST['submit']))
{
$output_form == 'no';
echo 'hiiiii';
}
else {
$output_form = 'yes';
}
if($output_form = 'yes')
{
?>
<form enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="file" name="uploadpic" />
<input type="submit" value="Upload" name="submit" />
</form>
<?php
}
?>
</body>

$output_form == 'no'; should be $output_form = 'no';
if ($output_form = 'yes') should be if ($output_form == 'yes')
= is assignment, whereas == is a comparison.
Also, your form will use GET because you did not ask it to use POST with method="POST".

You're missing your method on the form element.
<form enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
You can also use print_r($_POST) to see what's in the array.
Here's an example of it working, as well as the code.
http://www.wecodesign.com/demos/stackoverflow-7018639.php

if($output_form = 'yes')
should be
if($output_form == 'yes')
The way you have it now, you're assigning a value.

It should be
if($output_form == 'yes')

You doing assignment, use comparison:
if($output_form == 'yes')

Ensure that you're actually SETTING the no value as well:
$output_form == 'no';
Should be
$output_form = 'no';

Related

Refresh a PHP page after checking/unchecking a checkbox

I'm pretty new with PHP, so help please.
I need a web page in php with a checkbox. That page should refresh itself each time I do an action to the checkbox (so for both check or uncheck). Once it’s refreshed the page should keep the latest value of the checkbox.
I tried the following example modifying another code I took from StackOverflow, but it doesn’t works as I wish.
Any suggestion?
<?php
session_start();
$checked = "";
if($_SESSION['myaction'] != $_SESSION['value'])
{
if(isset($_POST['sharks']))
{
$_SESSION['value'] = $_POST['sharks'];
}
else
{
$_SESSION['value'] = '';
echo ":(";
}
$_SESSION['myaction'] = $_SESSION['value'];
}
?>
<form action="" method="POST">
<?php
print '<input name="sharks" type="checkbox" value="1" id="sharks" ';
if ($_SESSION['value'] == 1)
{
echo "checked='checked'";
}
$myaction = 2;
print ">";
?>
</form>
<form method='POST'>
<input name='sharks' type='checkbox' value='1' id='sharks' />
</form>
Some simpple, vanilla, Javascript that makes use of the localStorage ( or sessionStorage ). The click handler will set the checked status and on page load that value will help re-check, or not, the checkbox. Javascript is intended for this sort of purpose - though it is entirely possible to use PHP to re-check the checkbox when the page reloads provided it has some means to check a value against a stored value or a form submission.
document.addEventListener('DOMContentLoaded',()=>{
let chk=document.querySelector('input[type="checkbox"][name="sharks"]');
chk.checked=localStorage.getItem( chk.name )==null || localStorage.getItem( chk.name )=='false' ? false : true;
chk.addEventListener('click',e=>{
localStorage.setItem( chk.name, chk.checked )
location.reload();
});
});
Don't use a checkbox if you don't want the behaviour of a checkbox.
If you are submitting data, use a submit button. Users expect submit buttons to trigger a reload of the page.
<?php
$current_state = get_state_from_database_or_session_or_whatever();
if (isset($_POST['new_state'])) {
if ($_POST['new_state']) == "on") {
$current_state = "off";
} else {
$current_state = "on";
}
update_datebase_or_session_or_whatever_with_new_state($current_state);
}
$other_state = "off";
if ($current_state == "off") {
$other_state = "on";
}
?>
<p>The current state is <?php echo $current_state; ?></p>
<form method="post">
<button name="state" value="<?php echo $other_state; ?>">Set state to <?php echo $other_state; ?></button>
</form>
What you need to is pretty simple- assuming you are submitting the form on the same page.
<?php
$filterUsers=array();
if(isset($_GET['users'])){
foreach($_GET['users'] as $key){
$filterUsers[]=$key;
}
function valueInFilter($value){
if(in_array($value, $filterUsers)){
echo "checked";
}else{
echo "";
}
}
?>
<html>
<head>Filter </head>
<body>
<form method="get" action="<?php echo
htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
<input type="checkbox" name="users[]" value="john" id="1" <?php
valueInFilter("john",$filterUsers) ?>>
<label for="1"> John doe</label><br>
<input type="checkbox" name="users[]" value="john" id="2" <?php
valueInFilter("mayor",$filterUsers) ?>>
<label for="2"> John Mayor</label><br>
</form>
</body>
</html>
This is not an job for PHP like Professor Abronsius wrote.
Write it in JavaScript like this:
(() => {
// on page reloaded
const checkboxNode = document.getElementById('sharks')
if (localStorage.getItem('sharkCheckBox')) {
// the checkbox is stored as CHECKED
// e.g. check the checkbox again or what ever:
checkboxNode.checked = true
} else {
// the checkbox is stored as NOT checked
}
// handle the click
checkboxNode.addEventListener('click', function() {
// get the checkbox status
const isChecked = this.checked
// store the checked status inside the browser cache
localStorage.setItem('sharkCheckBox', isChecked)
// there are several ways to to an page reload. Here an example
// see details here https://stackoverflow.com/a/39571605/7993505
location.reload()
})
})()

Having a html input as a variable for php

This is my first post. So sorry if I get the format wrong :)
Im trying to build a program, that asks for a input using html, sets that input as a php variable, and then calculates that variable. Everything is ready except for the input part, which I find extremely challenging. My code is as follows:
<?php
$x = 1;
$answer = ($x = 1);
if($answer) {
echo "The answer is: True";
} else {
echo "The answer is: False";
}
?>
The variable I'm trying to set is the ($x = 1) part. The codes purpose is to see if a mathematical calculation is true or false. The code has already been tested.
I have already searched the internet for an answer, and sadly I only saw answers for questions that were way different.
There's one small issue with your current code: You're using = to compare a value to another, which will not work, single = is used to assign a variable. You should use == instead.
When you want to use a user's input, you will need something called $_POST, this is a method that you can set in a form using the method="POST" attribute. When the form is submitted it will create an array with the values in the form.
You can then access these values using a certain key, which is equal to the name="" attribute of the input, select or textarea in the form.
Example
Consider this form, with some PHP code:
<form method="post">
<input type="text" name="myName" placeholder="Enter your name!">
<input type="submit" value="Submit">
</form>
<?php
// When the server gets a $_POST request
if($_SERVER['REQUEST_METHOD'] == 'POST') {
// Set the variable name to whatever the user put in
$name = $_POST['myName']; // equal to the name="" attribute in the form
echo "Hello, " . $name . "!";
}
?>
If I submit the form with my name, it will echo: Hello, rpm192!
For your situation, it would look something like this:
<form method="post">
<input type="number" name="answer" placeholder="Your answer">
<input type="submit" value="Submit answer">
</form>
<?php
// When the server gets a $_POST request
if($_SERVER['REQUEST_METHOD'] == 'POST') {
// Set the variable X to whatever the user put in
$x = $_POST['answer'];
$answer = ($x = 1);
// Check if $answer is true or false
if($answer) {
echo "True!";
} else {
echo "False!";
}
}
?>
For that you need to have a form which can submit values to calculation script or same page if script is in same page.
Also in your script you are not comparing anything as the condition is always true as answer is always 1 and condition is always satisfied, so for that you can compare the user input to answer as I did in example.
For example calc.php
<?php
echo"<form method="POST" action="">Your answer:<input type="text" name="val" /><br><input type="submit" /></form>";
#$val=$_POST['val'];
if($val){
$answer = 1;
if($answer==$val) {
echo "The answer is: True";
}
else {
echo "The answer is: False";
}
}
?>
In PHP '=' means assignment operator.
Equal check operator should be '=='.
So, your code should be refactored as:
<?php
$x = 1;
$answer = ($x == 1); // this will return true or false
if($answer) {
echo "The answer is: True";
} else {
echo "The answer is: False";
}
?>
You can also use ternary operator to shorten your code instead of if/else statement like this:
<?php
$x = 1;
$answer = ($x == 1); // this will return true or false
echo $answer ? 'The answer is: true' : 'The answer is: false';
?>
you need to create form to get input from html. there is many different approaches to create form.
I think your are begginer, so simply you can create form on the same page.
you can separate php code from html form write your php code on the top of the page like example below
<?php
if(isset($_POST['submit'])){
$x = $_POST['myinput'];
$answer = $x;
if($answer) {
echo "The answer is: True";
} else {
echo "The answer is: False";
}
}
?>
<form method="POST" action="">
<input type="Text" name="myinput" >
<inpu type="submit" name="submit" value="submit button">
</form>
action="" is used for same page. if you want to use separate page for html part you can give action="yourPHPPage.php"
Did u mean this?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<?php
if (isset($_POST['submit'])) {
$answer = $_POST['input'];
if($answer == 1) {
echo "The answer is: True";
} else {
echo "The answer is: False";
}
}
?>
<form action="" method="post">
Enter value: <input name="input" type="text" />
<input name="submit" type="submit" />
</form>
</body>
</html>
As the purpose is to check if a mathematic function's value is True or False, I propose a simple CLI script.
<?php
print ((isset($argv[2]) && ($argv[2] === 1)) ? "\nAnswer is True\n\n" : "\nAnswer is false\n\n");
Save this as myfile.php
Open command line navigate to the folder and type in
>php myfile.php 1 // Returns Answer is True
So if you want to change the input you can do that also..
>php myFile.php 4 // Answer is False
Note that if you're passing String "1", this would also return True.

if(isset($_POST['submit'])) function is not set when working with radio buttons

Okay, first off I apologise if this question has been answered before but because of my lack in php knowledge I do not actually fully know what the problem is.
My $_POST['submit'] does not appear to be set even after the submit button is clicked. I have tried this method before but with text fields, so I'm assuming I am doing something wrong with the configuration of the radio buttons. The way I know its not getting through isset() is because it is not echoing out "in isset" therefore can not reach the rest of my code. Also I have tried replacing $_POST['submit'] with $_POST['onoff'] but both return the same result.
function getRadioState()
{
global $ac;
if (isset($_POST['submit'])) {
echo "in isset";
$selected_radio = $_POST['onoff'];
if ($selected_radio == 'On') {
$ac = 1;
} else if($selected_radio == 'Off') {
$ac = 0;
}
}
}
and here is my html code:
<form>
On: <input type="radio" name="onoff" value="On"><br>
Off: <input type="radio" name="onoff" value="Off"><br>
<input type="submit" name="submit" value="submit">
</form>
Thank you in advance for any responses helping to answer my question :)
That's because form defaults to GET when omitting the method.
Use <form method="post">
Sidenote: Omitting the action defaults to self, should that be the intention.
It's the same as doing action=""
Where you calling this function function getRadioState(){ ???
You have to save the page extension in php
And,
3.form method to POST
<form method="POST" action="test.php">
In test.php
if(isset($_POST['submit'])){
echo "in isset";
$selected_radio = $_POST['onoff'];
if($selected_radio == 'On'){
$ac = 1;
}else if($selected_radio == 'Off'){
$ac = 0;
}
}

How do I check that random value equals entered value to input in php on post

I'am new to php and I have no idea why my code in php is always echoing FALSE.
I do not want to use another hidden input like:
<input type="hidden" name="storeRandVal" value="<?php echo $randomValue; ?>
to store my generated random value, and then checking if the entered value in input is equal with value that was generated and entered to hidden input. Is there any way around to do it in php also without involving cookies?
Here is my code:
<?php
$buttonPost = $_POST['button_post'];
$enteredValue = htmlspecialchars(trim($_POST['test_input_p']));
$randomValue = rand(1,100);
if(isset($buttonPost))
{
if($randomValue == $enteredValue)
{
echo "TRUE";
}
elseif($randomValue != $enteredValue)
{
echo "FALSE";
}
else
{
echo "Er__!";
}
}
?>
<html>
<head>
<meta></meta>
</head>
<body>
<form action="" method="post">
<fieldset>
<label for="test_input" id="label_input">Enter value: <?php echo $randomValue; ?></label>
<input id="test_input" name="test_input_p">
<input type="submit" id="ibutton_send" name="button_post" value="Send">
</fieldset>
</form>
</body>
</html>
Why not store the random value in a session? Re-set the session only when a form is not submitted (eg; when a user comes to this page from a different page)
As #Fred commented, you have to include the hidden input. By its nature, PHP's rand() function gives you a different answer every time you load the page.
You'll need to compare the $_POST['test_input_p'] and $_POST['storeRandVal'] values in order to confirm that the user entered the correct values.
Here's what you can do:
Store the hidden value in a variable then compare it with that value.
(Unless you will be using this for more than 2 pages, sessions are not needed, not for this since you're using your entire code inside the same page.)
<?php
$buttonPost = $_POST['button_post'];
$enteredValue = htmlspecialchars(trim($_POST['test_input_p']));
$hidden = $_POST['storeRandVal'];
$randomValue = rand(1,100);
if(isset($buttonPost))
{
if($enteredValue == $hidden)
{
echo "TRUE";
}
elseif($randomValue != $hidden)
{
echo "FALSE";
}
else
{
echo "Er__!";
}
}
?>
<html>
<head>
<meta></meta>
</head>
<body>
<form action="" method="post">
<input type="hidden" name="storeRandVal" value="<?php echo $randomValue; ?>">
<fieldset>
<label for="test_input" id="label_input">Enter value: <?php echo $randomValue; ?></label>
<input id="test_input" name="test_input_p">
<input type="submit" id="ibutton_send" name="button_post" value="Send"></input>
</fieldset>
</form>
</body>
</html>

hide HTML elements after logging in

I try to login with one PHP file, without any HTML files. So when I'm successfully logged in I want to hide the HTML post button and the textboxes.
Here's my code..:
<?php
$showHTML = true;
if ($showHTML) { ?>
<h1> Bitte einloggen! </h1>
<form action="test2.php" method="POST">
<input name="user" type="test"><br>
<input name="pass" type="password"><br>
<input type="submit" value"Login">
</form>
<?php
}
if ( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
if ( $_POST['user'] == "test" && $_POST['pass'] == "a123" ) {
echo "user = test";
$showHTML = false;
}
}
Of course that doesn't hide the HTML code again, because its already executed I think.
Is there any way to hide the HTML output again?
Of course that doens´t hide the HTMLCode again, because its already executed I think.
Correct
Is there any way to hide the HTML output again?
Move the test so it appears before the HTML you (don't) want to output.
Short: put the HTML under the PHP.
Long: Use a decent login system. Use sessions.
You can't use a server side variable to control the already rendered html content.
<?php
if ( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
if ( $_POST['user'] == "test" && $_POST['pass'] == "a123" ) {
echo "user = test";
  }
} else { ?>
<h1> Bitte einloggen! </h1>
<form action="test2.php" method="POST">
<input name="user" type="test"><br>
<input name="pass" type="password"><br>
<input type="submit" value"Login">
</form>
<?php } ?>

Categories