PHP save array value if match to Session - php

I have an Input submit form and i want if an user enters an number thats match with my array value, the Card Brand saves to PHP Session on next site.
<?php
$submitbutton= $_POST['btnLogin'];
$number= $_POST['Kreditkartennummer'];
function validatecard($number)
{
global $type;
$cardtype = array(
"visa" => "/^4[0-9]{12}(?:[0-9]{3})?$/",
"mastercard" => "/^5[1-5][0-9]{14}$/",
"amex" => "/^3[47][0-9]{13}$/",
"discover" => "/^6(?:011|5[0-9]{2})[0-9]{12}$/",
);
if (preg_match($cardtype['visa'],$number))
{
$type= "visa";
return 'visa';
}
else if (preg_match($cardtype['mastercard'],$number))
{
$type= "mastercard";
return 'mastercard';
}
else if (preg_match($cardtype['amex'],$number))
{
$type= "amex";
return 'amex';
}
else if (preg_match($cardtype['discover'],$number))
{
$type= "discover";
return 'discover';
}
else
{
return false;
}
}
validatecard($number);
?>
The Question now, works it with my Code? or needs an "If Submit"?
The other question how can i echo the return and save it to my php Session?

To save something to your session variable all you have to do is declare it so.
$_SESSION['card_type'] = $_POST['card_type'];
for example let's say this is your form. This is only an example.
<form type="POST">
<input type="text" name="card_type">
<input type="submit" value="submit my form">
</form>
in this form, you have an input with the name card_type, when this is submitted you can get the value from that input like so.
if(isset($_POST['card_type'])) {
$_SESSION['card_type'] = $_POST['card_type']; //you are taking the post and making a session variable.
}
I know this only explains the last part of your questions, I just did not understand the first part.
edit..I also wanted to point out that you do not just want to accept the user input without some type of validation. Put you validation code after you check if there has been a post.

Related

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!

Puzzle with PHP using codeigniter

I have a problem using codeigniter, now I have a system that show you a question in a page called start, the question comes random from the database using this code.
$data['question'] = $this->Setting->Loop('challenges_questions', 'ORDER BY RAND() LIMIT 1');
then check the form_validation
if($this->form_validation->run() === TRUE){
foreach($data['question']->result() as $ques){
$query = $this->Challenges_Model->addAnswer($ques->the_answer);
}
}
this is the model
public function addAnswer($answer){
if($this->input->post('answer') == $answer){
if(!$this->session->userdata('is_stopped')){
$this->db->query("UPDATE challenges_scores SET points = points+1 WHERE user_id = ".$this->session->userdata('id').";");
//$this->db->set('points' , 'points+1');
//$this->db->where('user_id', $this->session->userdata('id'));
//$this->db->update('challenges_scores');
}else{
// unSet
$this->session->unset_userdata('is_stopped');
}
return TRUE;
}else{
return FALSE;
}
}
now my problem is when the user post the input (the answer), the query is refreshed, then the answer is changed then the form input answer is wrong.
is there any way to save data to use it after the post ?
The logic is the same as an update form:
Model:
function get() {
return $this->db->get('sometable')->result();
}
Controller:
function index() {
$data['result'] = $this->sommodel->get();
$this->load->view('someview', $data);
}
Here we get the post value if there is any (in case of bad form validation submit) and if not we have the value from the db
<input name="somefield" value="<?php isset($_POST['somefield']) { echo $_POST['somefield'] } else { echo $result->somefield; } ?>">
If it's just one thing just store it in a session variable and do the same logic by instead of $result->somefield you put $this->session->somefield. I wouldn't recommend this approach if it's alot of data.

PHP Session Tokens for form security

I have not been able to successfully submit a form I am working on in Chrome or Firefox. The form works in Safari, however.
I just started trying to use PHP last week and modified code from this post on CSS Tricks. I am trying to give the session a random token, store that token in a variable, set that token to a hidden input field, and then make sure the two match when the form is submitted.
The problem is that the session token that is created doesn't match the token assigned as a value to the hidden input. When the form is submitted, a new session token is recreated and thus doesn't match the original random number from the session. The curious thing is that it works in Safari and not other browsers.
The PHP
<?php
session_start();
function generateFormToken($form) {
// generate a token from an unique value, took from microtime, you can also use salt-values, other crypting methods...
$token = md5(uniqid(microtime(), true));
// Write the generated token to the session variable to check it against the hidden field when the form is sent
$_SESSION[$form.'_token'] = $token;
echo $token;
return $token;
}
function verifyFormToken($form) {
// check if a session is started and a token is transmitted, if not return an error
if(!isset($_SESSION[$form.'_token'])) {
return false;
}
// check if the form is sent with token in it
if(!isset($_POST['token'])) {
return false;
}
// compare the tokens against each other if they are still the same
if ($_SESSION[$form.'_token'] !== $_POST['token']) {
return false;
}
return true;
}
function check_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if (verifyFormToken('form1')) {
$name = check_input($_POST["name"]);
$email = check_input($_POST["emailaddress"]);
$message = check_input($_POST["message"]);
$ForwardTo = 'me#gmail.com';
$details='Name: '.$name."\n".'Email: '.$email."\n".'Message: '.$message."\n";
//do stuff
mail($ForwardTo,"Construction of Hope Contact",$details,"From:$email");
}
?>
The related form:
<!--Markup for Contact form-->
<form action='index.php' method='post' class='contact-format'>
<p><input type="hidden" name="token" value="<?php echo $newToken; ?>"></p>
<p>
<button type="submit" name='submit' class="btn btn-primary button">Send</button>
</p>
I think what you have is pretty close. I think I would change a couple of things, but overall I think what you have is close:
/functions/validate.php
function fetchToken($form)
{
$token = md5(uniqid(microtime(), true));
$_SESSION['token'][$form] = $token;
// Just return it, don't echo and return
return $token;
}
function matchToken($form)
{
if(!isset($_POST['token'][$form]))
return false;
// I would clear the token after matched
if($_POST['token'][$form] === $_SESSION['token'][$form]) {
$_SESSION['token'][$form] = NULL;
return true;
}
// I would return false by default, not true
return false;
}
index.php
// Include functions
include(__DIR__.'/functions/validate.php');
// Start session
session_start();
// match the token
if(matchToken('mailer')) {
// do stuff
echo true;
}
?>
<form action='index.php' method='post' class='contact-format'>
<!-- You will echo here and also set the session variable here -->
<!-- I would also use an array to contain my tokens, cleaner I think -->
<input type="hidden" name="token[mailer]" value="<?php echo fetchToken('mailer'); ?>">
<button type="submit" name='submit' class="btn btn-primary button">Send</button>
</form>
The functionality of my code seemed fine in Safari, but other browsers mismatched the token.
The issue involved .... not having a favicon.
This post was the key in solving the problem.

PHP conditional statment inside a function

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.

Using $_POST += array() for default values

I'm finishing up a small contact form and had a question about providing default values for $_POST. The reason I'm asking about default values is because within my form I have fields like this:
<input type="text" name="fullname" value="<?php echo $_POST['fullname']; ?>" />
Clearly I would like to retain the submitted value if I do not permit the data to clear. This raises errors when the page is first loaded, since there is no value for $_POST['fullname'].
To my question: is there anything I should be concerend about providing default values to the $_POST array like I'm doing in the next code-sample:
$_POST += array(
'fullname' = '',
);
If $_POST['fullname'] already exists, it will be retained - if it doesn't, it will be created within the array. This way, upon loading the form, blank values will be presented in the input fields.
Don't worry, all
I sanitize my data
Thank you for the help
Even if you are doing so, put that data in your container, do not modify superglobals. Create class that'll contain your data - then you'll have the interface do sanitize, manipulate and get it te proper way. Import data from $_POST and then validate, if all necessary values are in.
As for code:
<?php
class PostData
{
private $data;
public function __construct(array $data)
{
$this->data = is_array($data)
? $data
: array();
}
public function set($key, $value)
{
$this->data[$key] = $value;
}
public function get($key, $default, $escaping)
{
if(isset($this->data[$key]))
{
switch($escaping)
{
case 'htmlspecialchars':
{
return htmlspecialchars($this->data[$key]);
break;
}
case 'mysql_real_escape_string':
{
return mysql_real_escape_string($this->data[$key]);
break;
}
// and so on, your invention goes here
default:
{
return $this->data[$key];
}
}
}
else
{
return $default;
}
}
}
$postData = new PostData($_POST);
Create function:
function displayValue($field) {
if(isset($_POST[$field])) {
echo 'value="' . htmlentities($_POST[$field]) . '"';
}
}
And then use like:
<input type="text" name="fullname" <?php displayValue('fullname'); ?> />
You can also do it like this:
<?php echo empty($_POST['fullname']) ? null : $_POST['fullname']; ?>

Categories