Why is my function changing boolean value to 'on'? - php

So I'm new to php/the programming world and I'm studying online and other forms and such but I couldn't find anything to help answer my question which is why I'm here. Any help is certainly appreciated, Thanks!
I want to turn the below code into a function that I can call. It works just as it stands below as in it outputs a 1 if I check my check box in my form and remains 0 if I don't touch my checkbox.
$activeMain = (isset($_POST['activateBox'])) ? $_POST['activateBox'] : false;
if ($activeMain == true) {
$activeMain = '1';
}
However when I try to use a function to do the same thing, and I select my checkbox to display a '1', it remains 0 and if I do a var_dump the output is now "on" instead of 1 like how it is supposed to be.
Below is the function I tried:
function activeCheck($activeMain) {
$activeMain = (isset($_POST['activateBox'])) ? $_POST['activateBox'] : false;
if ($activeMain == true) {
$activeMain = '1';
}
return $activeMain;//I messed around with a return value
and as far as I can tell, it has no effect.
}//ends activeCheck function
activeCheck($activeMain);//call to function
In all I'm confused on why it shows "on" when I try to use a function as well as how to get it to work.
EDIT:
How do I turn my original code (first bit of code posted above) into a function?
What values should I use / can I use something else besides _SESSION to check if user has selected the checkbox from the form?
I have a HTML/PHP form in which I give the option to select a checkbox. If users hit the checkbox, the input they provided will output a '1' for a true value.
My HTML/PHP form:
<?php session_start(); ?>
<!DOCTYPE HTML>
<HTML>
<head>
<title>PHP FORM</title>
</head>
<body>
<form method="post" action="processForm.php">
Name: <input type="text" name="names" required = "required"><br>
<input type="submit" value="Create Users" onclick="formNAMES"><br>
Activate: <input type="checkbox" name="activateBox">
<?php
if (isset($_SESSION ['error'])) {
foreach ($_SESSION['error'] as $value) {
echo $value;
}
session_destroy();
unset($_SESSION['error']);
}
/* Above if statement checks if $_SESSION variable has been set in processForm page. If it has,
an error message corresponding to the error shows up on redirect to this form. The unset makes sure
the $_SESSION is destroyed upon completion of the process. */
?>
</form>
</body>
</html>

Change related line to following: The problem is when activateBox is not empty it assings itself to $activeMain naturally.
$activeMain = isset($_POST['activateBox']);
Updated : Check this one.
function activeCheck() {
return isset($_POST['activateBox']);
}
activeCheck();
Updated Answer Due To Updated Question :
I removed session_destory if you execute that and if you have another session variable ex: user isLoggedIn it would be destroyed too. unset is OK for the purpose. Please check XSS, Sql injection attacks around the internet implement logic according to best practises, and validate/sanitize your data before process parameters into DB or etc.
<?php
// formView.php
ob_start();
session_start();
?>
<!DOCTYPE HTML>
<HTML>
<head>
<title>PHP FORM</title>
</head>
<body>
<form method="POST" action="processForm.php">
Name: <input type="text" name="names" required = "required"><br>
<input type="submit" value="Create Users" onclick="formNAMES"><br>
Activate: <input type="checkbox" name="activateBox">
<?php
if (isset($_SESSION ['error'])) {
foreach ($_SESSION['error'] as $value) {
echo $value;
}
unset($_SESSION['error']);
}
/* Above if statement checks if $_SESSION variable has been set in processForm page. If it has,
an error message corresponding to the error shows up on redirect to this form. The unset makes sure
the $_SESSION is destroyed upon completion of the process. */
?>
</form>
</body>
</html>
<?php ob_end_clean(); ?>
<?php
// processForm.php
if (!empty($_POST)) {
$safeParameters = [];
foreach ($_POST as $key => $val) {
// sanitize your inputs. #see XSS, SQL injection etc.
// validate parameters according to your needs.
$safeParameters[$key] = $val;
}
$_POST = [];
checkIsActivated($safeParameters);
// implement other logic,
// save form to database etc.
}
function checkIsActivated($parameters)
{
return !empty($parameters['activateBox']);
}
?>

Related

How to remove and change the value inside of Session php?

I got 2 pages schedule.php and sched_confirmation.php in the schedule.php what I do there is I have a code that calculate a fee and store it in Session,
$calc=$result+$result1+$result2+$result3+$result4+$result5+$result6+$result7+$result8+$result9;
$num_format=number_format($calc,2);
$_SESSION['fee']= $num_format;
and in the sched_confirmation here is I want to show the value of the session
<form method="post">
<?php echo $_SESSION['fee'];
<button class="btn btn-warning" name="cancel">Cancel</button>
</form>
what I want is if I click the cancel button it would remove the value of session and redirect to schedule.php and create a new value for the session.
here is what I got so far
<?php
session_start();
if (isset($_POST["cancel"])) {
if (isset($_SESSION['fee'])) {
unset($_SESSION['fee']);
}else
{
$_SESSION['fee'];
}
header("Location: schedule.php");
}
?>
it does redirect me to the previous page but when I create new value for the session when its done and go to sched_confirmation.php it shows "Undefined index: fee "
How can I fix this? thank you in advance
From your question I can say you always want $_SESSION['fee'] to be available, So this is what you need
<?php
session_start();
if ( isset($_POST["cancel"]) ) {
if (isset($_SESSION['fee'])) {
$_SESSION['fee'] = 'New Value';
}
header("Location: schedule.php");
}
?>
There is no need to unset $SESSION['fee'] if you want it to be available later, Just update the value.
You need to set session value.
try this
<?php
session_start();
if (isset($_POST['cancel'])) {
if (isset($_SESSION['fee'])) {
unset($_SESSION['fee']);
} else {
$_SESSION["fee"] = "Session value";
}
header("Location: schedule.php");
}
?>

PHP class, html forum, print $_POST Array on page

i am beginner php programmer, iv been trying to create a small program that takes input from a forum and then after submission i want it to be printed on the screen. simple and easy i thought, iv been trying and suspiciously it seems to work fine for 1 text field, when i added the remaining 2 text fields called [fam][user] my code stops returning the content to the screen. also i started to recieve an error of an unindex array, therefore i had to use isset to counter this problem, and also, why does my code call the destructor although i never implicitly set my destructor. i dont know how to ask these questions because the errors arent consistent.
code doesnt print my [name][fam][user]
code prints [name] when everything about [fam][user] are ommited from the code.
-code sometimes called the destructor
-code doesnt clear html previous input(e.g, when working with the one text field, lets say i input the [name] john, and click submit it
displays submit, then,i refresh the page, and the name john is still
displayed, why doesnt the destructor clear the memory of name from my
submission.
<form class="nameform" action="book.php" method="post">
<input type="text" name="Name" value="1">
<input type="text" name="Fam" value="2">
<input type="text" name="User" value="3">
<input type="button" name="submit" value="Submit">
</form>
private $name; private $familyName; private $userName;
function __construct($names,$familyNames,$userNames)
{
$this->name = $names;
$this->familyName = $familyNames;
$this->userName = $userNames;
}
function getName()
{
return $this->name;
}
function getFamilyName()
{
return $this->familyName;
}
function getUserName()
{
return $this->userName;
}
public function __destruct()
{
echo "destroyed again";
$this->name;
$this->familyName;
$this->userName;
}
}
if(!isset( $_POST["Name"])||!isset($_POST["Fam"])||!isset($_POST["User"]))
{
echo "Please fill in the data";
} else {
$p1 = new Person($_POST["Name"],$_POST["Fam"],$_POST["User"]);
print $p1->getName();
print $p1->getFamilyName();
print $p1->getUserName();
print_r($_POST);
}
// $n = $_POST["Name"];
// $f = $_POST["Fam"];
// $u = $_POST["User"];
// $p1 = new Person($_POST["Name"],$_POST["Fam"],$_POST["User"]);
?>
code doesnt print my [name][fam][user]
You never echo them out of the destuctor
public function __destruct()
{
echo "destroyed again";
$this->name; //<---- does nothing
$this->familyName;
$this->userName;
}
So I am not sure what this is supposed to do. You have them down at the bottom
print $p1->getName();
print $p1->getFamilyName();
print $p1->getUserName();
But the only thing you'll get from the destruct method is
"destroyed again"
And you will only see that if everything in the form is set. Which it always is when the form is submitted, because type text is always submitted with its form.
Which brings me to this, you should be checking empty instead of isset there
if ('POST' === $_SERVER['REQUEST_METHOD']) { //check if POST
if(empty($_POST["Name"])||empty($_POST["Fam"])||empty($_POST["User"])){
echo "Please fill in the data";
} else {
$p1 = new Person($_POST["Name"],$_POST["Fam"],$_POST["User"]);
print $p1->getName();
print $p1->getFamilyName();
print $p1->getUserName();
print_r($_POST);
}
}
Note that anything falsy will be empty, false, [], '', 0, '0', null etc.
I don't know if this solves all of you problems, but these things could produce some of the behaviour you are experiencing.
Another more advance way to check these is like this:
if ('POST' === $_SERVER['REQUEST_METHOD']) { //check if POST
$post = array_filter( $_POST, function($item){
return strlen($item); //any thing of a length of 0 is removed
});
if(count($post) != count($_POST)){
foreach(array_diff_key( $_POST, $post) as $missing=>$empty) {
echo "Please fill in $missing\n";
}
}else{
$p1 = new Person($_POST["Name"],$_POST["Fam"],$_POST["User"]);
print $p1->getName();
print $p1->getFamilyName();
print $p1->getUserName();
print_r($_POST);
}
}
Output
Please fill in Name
Please fill in Fam
You can test it online Here
Cheers!

Why isn't my function returning the value it should? [duplicate]

So I'm new to php/the programming world and I'm studying online and other forms and such but I couldn't find anything to help answer my question which is why I'm here. Any help is certainly appreciated, Thanks!
I want to turn the below code into a function that I can call. It works just as it stands below as in it outputs a 1 if I check my check box in my form and remains 0 if I don't touch my checkbox.
$activeMain = (isset($_POST['activateBox'])) ? $_POST['activateBox'] : false;
if ($activeMain == true) {
$activeMain = '1';
}
However when I try to use a function to do the same thing, and I select my checkbox to display a '1', it remains 0 and if I do a var_dump the output is now "on" instead of 1 like how it is supposed to be.
Below is the function I tried:
function activeCheck($activeMain) {
$activeMain = (isset($_POST['activateBox'])) ? $_POST['activateBox'] : false;
if ($activeMain == true) {
$activeMain = '1';
}
return $activeMain;//I messed around with a return value
and as far as I can tell, it has no effect.
}//ends activeCheck function
activeCheck($activeMain);//call to function
In all I'm confused on why it shows "on" when I try to use a function as well as how to get it to work.
EDIT:
How do I turn my original code (first bit of code posted above) into a function?
What values should I use / can I use something else besides _SESSION to check if user has selected the checkbox from the form?
I have a HTML/PHP form in which I give the option to select a checkbox. If users hit the checkbox, the input they provided will output a '1' for a true value.
My HTML/PHP form:
<?php session_start(); ?>
<!DOCTYPE HTML>
<HTML>
<head>
<title>PHP FORM</title>
</head>
<body>
<form method="post" action="processForm.php">
Name: <input type="text" name="names" required = "required"><br>
<input type="submit" value="Create Users" onclick="formNAMES"><br>
Activate: <input type="checkbox" name="activateBox">
<?php
if (isset($_SESSION ['error'])) {
foreach ($_SESSION['error'] as $value) {
echo $value;
}
session_destroy();
unset($_SESSION['error']);
}
/* Above if statement checks if $_SESSION variable has been set in processForm page. If it has,
an error message corresponding to the error shows up on redirect to this form. The unset makes sure
the $_SESSION is destroyed upon completion of the process. */
?>
</form>
</body>
</html>
Change related line to following: The problem is when activateBox is not empty it assings itself to $activeMain naturally.
$activeMain = isset($_POST['activateBox']);
Updated : Check this one.
function activeCheck() {
return isset($_POST['activateBox']);
}
activeCheck();
Updated Answer Due To Updated Question :
I removed session_destory if you execute that and if you have another session variable ex: user isLoggedIn it would be destroyed too. unset is OK for the purpose. Please check XSS, Sql injection attacks around the internet implement logic according to best practises, and validate/sanitize your data before process parameters into DB or etc.
<?php
// formView.php
ob_start();
session_start();
?>
<!DOCTYPE HTML>
<HTML>
<head>
<title>PHP FORM</title>
</head>
<body>
<form method="POST" action="processForm.php">
Name: <input type="text" name="names" required = "required"><br>
<input type="submit" value="Create Users" onclick="formNAMES"><br>
Activate: <input type="checkbox" name="activateBox">
<?php
if (isset($_SESSION ['error'])) {
foreach ($_SESSION['error'] as $value) {
echo $value;
}
unset($_SESSION['error']);
}
/* Above if statement checks if $_SESSION variable has been set in processForm page. If it has,
an error message corresponding to the error shows up on redirect to this form. The unset makes sure
the $_SESSION is destroyed upon completion of the process. */
?>
</form>
</body>
</html>
<?php ob_end_clean(); ?>
<?php
// processForm.php
if (!empty($_POST)) {
$safeParameters = [];
foreach ($_POST as $key => $val) {
// sanitize your inputs. #see XSS, SQL injection etc.
// validate parameters according to your needs.
$safeParameters[$key] = $val;
}
$_POST = [];
checkIsActivated($safeParameters);
// implement other logic,
// save form to database etc.
}
function checkIsActivated($parameters)
{
return !empty($parameters['activateBox']);
}
?>

PHP Session Variable Array

Hi I'm trying to understand session variables, in particular using them with arrays. In the example code below, the user enters a letter and I want to add that submission to a session variable so that the next time the user submits a letter I don't lose the previous entry.
So if the user enters 'e' the array displays 'e', and if the user then picks 's' then the array will now display 'e' and 's'. This is my first experiment with PHP and sessions are proving a little difficult to wrap my head around. Can anyone help me understand how to go about getting the result I want, or where I have gone wrong in the code below? Many thanks in advance.
<?php
session_start();
function example()
{
$_SESSION['lettersGuessed'] = array();
$userLetter = $_GET['input'];
array_push($_SESSION['lettersGuessed'],$userLetter);
print_r($_SESSION['lettersGuessed']);
}
if (strlen($_GET['input'])==1) {
if (ctype_lower($_GET['input']))
{
echo "The user-submitted letter is lowercase.<br>";
example();
}
else
{
echo "Invalid submission<br>";
}
}
?>
<form action="" method="get">
<input name="input" value="Enter a letter!" />
<input type="submit" value="Submit" />
</form>
try it out without array_push in a more simple way
There is a simple change in example function.
Following is complete code
<?php
session_start();
function example() {
$userLetter = $_GET['input'];
$_SESSION['lettersGuessed'][] = $userLetter;
print_r($_SESSION['lettersGuessed']);
}
if (strlen($_GET['input']) == 1) {
if (ctype_lower($_GET['input'])) {
echo "The user-submitted letter is lowercase.<br>";
example();
} else {
echo "Invalid submission<br>";
}
}
?>
<form action="" method="get">
<input name="input" value="Enter a letter!" />
<input type="submit" value="Submit" />
</form>
?>
The problem is that your line in the beginning of example() resets the session variable to a blank array every time the function is called.
Update your example() function as follows:
function example()
{
$_SESSION['lettersGuessed'][] = $_GET['input'];
print_r($_SESSION['lettersGuessed']);
}
Thankfully, PHP is loosely-typed, so you don't have to manually define lettersGuessed as an array. Simply using [] afterwards will cause it to be handled as an array, and then using the = assignment operator will push $_GET['input'] into it.

PHP MVC passing form values to controller and model

I'm trying to send POST values to the controller and then pass it to the model in PHP but I'm not sure how to go about doing this.
This part of the controller is to see if the user requests for a view like ?action=game. This works.
But I'm trying to modify it to allow $_POST to be sent to it and then to the model.
function __construct()
{
if(isset($_GET['action']) && $_GET['action']!="" )
{
$url_view = str_replace("action/","",$_GET['action']);
if(file_exists("views/" . $url_view . ".php" ))
{
$viewname = $url_view;
$this->get_view($viewname . ".php");
}
else
{
$this->get_view('error.php');
}
}
else
{
$this->get_view('home.php');
}
}
Here's what I got. In the registration form page, the action of the form is ?process=register but it doesn't work.
if(isset($_POST['process']) == 'register)
{
$this->get_view('register.php')
}
Get_view function determines what model to bind with the view
function get_view($view_name)
{
$method_name = str_replace(".php","",$view_name);
if(method_exists($this->model,$method_name))
{
$data = $this->model->$method_name();
} else {
$data = $this->model->no_model();
}
$this->load->view($view_name,$data);
}
Since the action of your form is ?process=register, then process is still in the $_GET superglobal. What you can do to make it use post is add a hidden input field containing process.
With this:
<form method="post" action="script.php?process=register">
The form is POST'ed to script.php?process=register so you have $_GET['process'], not $_POST['process'].
Try this instead:
<form method="post" action="script.php">
<input type="hidden" name="process" action="register" />
To have $_POST['process']. Alternatively, you could keep the "process" in the GET and switch your if statement to check $_GET instead of $_POST.

Categories