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.
Related
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']);
}
?>
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']);
}
?>
I have not been able to find out how to do this, but I think that it can be done.
I want to receive information about name ($ime) and display drugiDio() after I get that. I am using isset as I also want to not display prviDio() after input of name, but I think that that part I can find alone.
Here is the code I tried:
<?php
class igra {
function prviDio() {
global $lang;
$kreni = $lang['kreni'];
echo "<h1>".$lang['naslov']."</h1><p>".$lang['opis']."</p>";
echo '<form metod="post">'
.$lang['unesite-ime'].
'<input name="ime" type="text" id="ime" size="40" maxlength="40" /><br /><br />
<input type="submit" name="kreni" value="'.$kreni.'" /></form>';
}
function drugiDio() {
global $lang;
$ime=$_GET['ime'];
echo $lang['vase-ime']. $ime;
}
}
$igra = new igra;
echo $igra->prviDio();
if(isset($igra->$_GET['kreni'])) {
echo $igra->drugiDio();
}
?>
What can I do with this for it to work?:
if(isset($igra->$_GET['kreni'])) {
echo $igra->drugiDio();
}
I also tried
if(isset($igra->_GET['kreni'])) {
echo $igra->drugiDio();
}
and many other combinations but none of them don't work...
Text from variables is in language files. This is just the PHP part. On the page everything is visible, and it works fine when I echo name without isset() like echo $igra->drugiDio();.
Do this:
if(isset($_GET['kreni'])) {
echo $igra->drugiDio();
}
Note:
$_GET and $_POST are superglobal variables so you can access them directly, provided that they are set. For more information please read the manual here.
I've just started learning to do oop and I just wanted to put the most basic set of code together to make sure I'm understanding things correctly. I wanted to capture a form entry in the $_POST variable and pass it to an object to have it output something back to the browser. No SQL, no Security measures, just proof of understanding.
Here is the form:
<html>
<head>
<title>SignUp Form</title>
</head>
<body>
<?php
if(!empty($_POST['name'])) {
include_once "class.php";
} else {
?>
<form method="post" action="signup.php">
<label for="name">Enter name below:</label></br>
<input type="text" name="name" id="name"></br>
<input type="submit" value="Submit">
</form>
<?php
}
echo $name->processName($_POST['name']); ?>
</body>
</html>
And here is the class:
<?php
class Process {
public $entry;
function __construct($entry) {
$this->entry = $entry;
}
public function processName($entry) {
return "You entered " . $this->entry . ".";
}
}
$name = new Process($_POST['name']); ?>
This is working without error right now but it doesn't seem like I should have to enter the $_POST in the echo statement on the form page and in the object on the class page. Is this correct? Should I instead be collecting that in the $entry property. It's working, but I don't think the execution is correct. Thanks in advance!
Your right you don't need to enter the $_POST variable into that function, you could change it to this and it would work without entering the post:
public function processName() {
return "You entered " . $this->entry . ".";
}
Because right now processName function doesn't do anything with the class's public $entry variable, it just echoes out what you put in when you call the function.
What you likely want to do instead is:
Change public $entry; to protected $entry;
Then:
public function getEntry() {
return $this->entry;
}
Then in your html, after constructing the class, you can just put this to get the $entry variable:
echo $name->getEntry();
Coming from Symfony framework background. You could do something right this:
<?php
class Process
{
protected $post_var;
public function __construct($p)
{
$this->post_var = $p;
}
public function getData()
{
//checking if not post request
if(count($this->post_var) == 0) {
return false;
}
$result_arr = [];
//populating $result_arr with $_POST variables
foreach ($this->post_var as $key => $value) {
$result_arr[$key] = $value;
}
return $result_arr;
}
}
$process = new Process($_POST);
$data = $process->getdata();
if($data)
{
echo $data["name"];
}
?>
<form action="" method="post">
<input type="text" name="name"/>
<input type="submit" name="submit"/>
</form>
I am trying to create function that takes two arguments one for the user input and the other a message for error. I initially have an associative array with the two input fields and the corresponding error.
When the function is submitted without any entry I get two similar output; I thought I would get 'test1' and 'test2'. I am passing different arguments each time but I get the same result. The code is below
$valid = TRUE;
//$errors='';
$errors=array('desc_error'=>'please enter valid description',
'title_error'=>'provide valid title','no_error'=>'',);
function sanitizeText($input,$error){
//$input;
if($input!='')
{
$input= filter_var($input, FILTER_SANITIZE_STRING);
if($input==''){
global $errors;
$errors[$error];
$valid=FALSE;
return $errors[$error];
}
else{
$input;
echo 'test 1';
return $input;
}
}
else if($input=='')
{
if($input==$_POST['desc'])
{
echo 'the description field is required<br/>';
$valid=FALSE;
}
else{
//
}
}
}
if(isset($_POST['submit']))
{
$title=sanitizeText($_POST['title'],'title_error');
$desc=sanitizeText($_POST['desc'],'desc_error');
}
?>
<form method="post" action="">
<p>Book Title:<input type="text" name="title" maxlength="100" value=""/></p>
<p>Desc:<input type="text" name="desc" maxlength="100" value=""/></p>
<p><input type="submit" name="submit" value="Submit"/></p>
</form>
I think you are trying to validate form using php you can also user javascript to validate but to do it using php please refer following links.
http://myphpform.com/required-optional-fields.php
http://coredogs.com/lesson/form-and-php-validation-one-page
http://www.phpf1.com/tutorial/php-form.html?page=3
and
http://www.montanaprogrammer.com/php-web-programming/php-form-validation/
Your code does not make sense logic wise. Firstly, you check if $input is an empty string, or is not, and then within that first check.. you again make the same exact check. Since ifs are evaluated in order, and input is not ever going to be an empty string, the first if will always execute.
Then, your first 'else'; it will only execute if the $input variable is an empty string.. I can sort of see what you're attempting to do, but it won't work as it is right now. In order for it to work, it would have to look something like the below:
function sanitizeText($input,$error) {
global $errors;
global $valid;
$input_val = filter_var($_POST[$input], FILTER_SANITIZE_STRING);
if ($input_val != '') {
$valid = TRUE;
return $input;
}
else if ($input_val == '') {
$valid = FALSE;
echo $errors[$error].'<br />';
}
}
if(isset($_POST['submit']))
{
$title=sanitizeText('title','title_error');
$desc=sanitizeText('desc','desc_error');
}
If the input value is not an empty string, it will return the input value. If it is, it will not return anything and will instead echo the appropriate error.