I have a code that submits data into a cake json 'database', but when I submit using PHP. When I reload the page, the file repeats the code of the last object in the JSON file when I get it. How do I avoid this?
This is my PHP
if(isset($_POST["submit"]))
{
if(empty($_POST["name"]))
{
$error = "<label class='text-danger'>Enter Name</label>";
}
else if(empty($_POST["type"]))
{
$error = "<label class='text-danger'>Enter Type</label>";
}
else if(empty($_POST["diff"]))
{
$error = "<label class='text-danger'>Enter Difficulty</label>";
}
else
{
if(file_exists('../../databases/cakes.json'))
{
$current_data = file_get_contents('../../databases/cakes.json');
$array_data = json_decode($current_data, true);
$extra = array(
'person' => array(
'name' => $_POST['name'],
'difficulty' => $_POST["diff"],
'type' => $_POST["type"],
'isNew' => 'true',
'isVeg' => 'false',
)
);
$array_data[] = $extra;
$final_data = json_encode($array_data);
if(file_put_contents('../../databases/cakes.json', $final_data))
{
//.-.
}
}
else
{
$error = 'JSON File not exits';
}
}
}
?>
<body>
<div id="layout"></div>
<div id="content">
<div id="add">
<div class="form-title"><h1>Add Cake</h1></div>
<form method="post">
<?php
if(isset($error))
{
echo $error;
}
?>
<br />
<div class="input-field">
<label for="name">Cake Name</label>
<input type="text" name="name"/>
</div>
<br />
<div class="input-field">
<label for="diff">Difficulty</label>
<div class="select">
<select name="diff" id="slct">
<option>Choose an option</option>
<option value="male">EZ</option>
<option value="female">Meh</option>
<option value="matthew">Mildy Hard</option>
</select>
</div>
</div>
<br />
<div class="input-field">
<label for="type">Type</label>
<input type="text" name="type"/><br />
Need Suggestions?<br>
</div>
<input class="addCake" type="submit" name="submit" value="Add Cake!"/><br />
See some other cakes
<?php
if(isset($message))
{
echo $message;
}
?>
</form>
Submission Works.
Result:
[[{"cake":{"name":"tes1","diff":"EZ","type":"Deli","isNew":"true","isVeg":"false"}}]]
But when I reload the page I see two of this things...
Result:
[[{"cake":{"name":"tes1","diff":"EZ","type":"Deli","isNew":"true","isVeg":"false"},{"name":"tes1","diff":"EZ","type":"Deli","isNew":"true","isVeg":"false"}}]]
Use ($_SERVER['REQUEST_METHOD'] == 'POST') instead of ($_POST["submit"])
$array_data = array_merge($array_data, $extra); instead of $array_data[] = $extra;
Related
I want to validate if the textbox has a value or not. Right now what I have is a textbox that has a value but the output says it is empty here is it it is like nothing is being conditioned on the code please see me code, thank you
Full Code
-Here is the full code of my form please take a look thank you very much
<form>
<div class="row">
<form method="POST">
<div class="col-md-8">
<?php
$code = 'Code';
$code2 = 'PIN';
if(isset($_POST['btnSubcode'])) {
$lblCode = isset($_POST['lblQrTxt']) ? $_POST['lblQrTxt'] : '';
$code = $lblCode;
$code = explode(":",$code); // code = array("QR Code","444444444|123")
$code = explode("|",$code[1]); // code[1] = "444444444|123"
$code = trim($code[0]); // 444444444
$code2 = $lblCode;
$code2 = explode(":",$code2); // code = array("QR Code","444444444|123")
$code2 = explode("|",$code2[1]); // code[1] = "444444444|123"
$code2 = trim($code2[1]); // 123
}
?>
<div class="form-group">
<label class="form-control-label">code</label>
<input type="text" name="input" id="card-code" value='<?php echo $code ?>' class="form-control">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="form-control-label">pin</label>
<input type="text" id="card-pin" value='<?php echo $code2 ?>' class="form-control" maxlength="3">
</div>
<?php
if(isset($_POST['txtQrtxt']) && $_POST['txtQrtxt'] != '') {
echo "Text Present";
} else {
echo "Text Not Present";
}
?>
<div class="caption">
<div class="jumbotron">
<input type="text" name='txtQrtxt' value='Hello World' class="form-control" >
<textarea class="form-control text-center" id="scanned-QR" name="lblQrTxt"></textarea><br><br><br>
</div>
</div>
</form>
<div class="form-group float-right">
<input value="Topup" class="btn btn-primary topup-button">
</div>
</div>
</div>
</form>
<?php
$txtCodeqr = isset($_POST['txtQrtxt']) ? $_POST['txtQrtxt'] : '';
if (!empty($txtCodeqr)) {
echo "Text";
} else {
echo "Empty Textbox";
}
?>
my textbox
<input type="text" name='txtQrtxt' value='Hello World' class="form-control" >
You might be over complicating it. It is pretty simple.
<?php
if(isset($_POST['txt']) && $_POST['txt'] != '') {
echo "Text Present";
} else {
echo "Text Not Present";
}
?>
Additionally I would recommend you filter all input on post or get. Basically anything that gets information from a user.
Check here - http://php.net/manual/en/function.filter-input.php
<?php
$my_txt = filter_input(INPUT_POST, 'txt');
if(isset($my_txt) && $my_txt != '') {
echo "Text Present";
} else {
echo "Text Not Present";
}
?>
Also you need to add a submit button between your form tags. Like this.
<input type="submit" value="Submit">
Also you should have only one closing tag for every opening tag. This is called valid HTML.
For example a valid form is like
<form method="post">
First name:<br>
<input type="text" name="firstname" value="Mickey"><br>
Last name:<br>
<input type="text" name="lastname" value="Mouse"><br><br>
<input type="submit" value="Submit">
</form>
Ok I have made a simple php test file and tested it works. Your problem is:
You don't have a submit button. The $_POST will not be there if you do not submit a form first.
It would be easier to validate your textarea using javascript instead.
Here is my test file and it works:
<html>
<body>
<form method="POST">
<textarea name="txtQrtxt">
</textarea>
<input type="submit">
</form>
<?php
$var = $_POST['txtQrtxt'];
if (strlen($var)<=0) {
echo "Textarea empty";
} else {
echo "Textarea Okay";
}
?>
</body></html>
This is my view file where form for image and other data exists:
<?php echo form_open_multipart('Login/client_profile'); ?>
<div class="form-group">
<label>Company Name</label>
<input type="text" class="form-control" name="company_name" >
</div>
<div class="form-group">
<label>Upload Profile Picture</label>
<input type="file" name="profile_pic" accept="image/*" class="form-control" required>
</div>
<div class="form-group">
<label>Mobile Number</label>
<input type="number" class="form-control" name="mobile" required>
</div>
<div class="form-group">
<label>Specialist in</label>
<input type="text" class="form-control" name="specialist_in" >
</div>
<div class="form-group">
<label>Position</label>
<input type="text" class="form-control" name="position" >
</div>
<?php
$data7 = array(
'type' => 'submit',
'value' => 'Update',
'class' => 'btn btn-primary ',
);
echo form_submit($data7);
echo form_close();
?>
This is the controller file Client.php
public function client_profile()
{
$client=$this->input->post();
$client['profile_pic']=$this->input->post('profile_pic');
$this->load->model('Clientmodel');
$email=$this->session->userdata('email_id');
$this->Clientmodel->add_client_details($email,$client);
$ppic['pic']=$this->Clientmodel->get_pic($email);
$config['upload_path'] = './profile/';
$config['allowed_types'] = 'jpg|jif|png|jpeg';
$this->load->library('upload', $config);
$field = 'pic';
if ($this->upload->do_upload($field)) {
$temp = $this->upload->data();
$pic = $temp['file_name'];
}
$this->load->view('client/pro_header',$ppic);
$this->load->view('client/client_dashboard',$client);
}
This is model file Clientmodel.php
public function add_client_details($email, Array $client)
{
return $this->db->where(['email'=>$email])
->update('clients',$client);
}
public function get_pic($login_email)
{
$q=$this->db->where(['email'=>$login_email])
->get('clients');
return $q->row()->profile_pic;
}
After entering all the data all the fields other than image can be fetched using $this->input->post when i try to fetch 'profile_pic' it returns nothing.And the image file name is also not inserted in database.Field 'profile_pic' is there in table 'clients'
This is the for uploading it's not checking any validation
public function upload_docs () {
if($this->input->post('action') == 'Upload') {
$company_name = $input->post('company_name');
$position = $input->post('position');
$mobile = $input->post('mobile');
$specialist_in = $input->post('specialist_in');
// capture all your variable like this
$file_path = './assets/images/uploads';
if ($_FILES["profile_pic"]["error"] > 0) {
$data['msg'] = 'your message';
} else {
if(!is_dir($file_path)) #mkdir($file_path, 0777, true);
if (move_uploaded_file($_FILES['profile_pic']['tmp_name'], $file_path.'/'.$_FILES['profile_pic']['name'])) {
$upload_data = array('company_name'=> $company_name,'mobile'=> $mobile,'specialist_in'=> $specialist_in,'profile_pic' => $_FILES['profile_pic']['name']);
$insert_id = $this->Your_model->addRecord($upload_data);
if ($insert_id) {
// redirect('admin/index','refresh');
}
}
}
}
$data['title'] = 'upload';
$this->load->view('admin/upload',$data);
}
I'm experiencing some issues with a php form i have inherited as part of a project.
The form has to be completed in its entirety to successfully submit, which it shouldn't do as there are optional fields here is no message to advise of the errors.
Any help would be most appreciated. Thanks.
Here's the code snippet.
function validateForm()
{
global $error, $data, $errorBox, $successBox, $formShown;
$formShown = true;
$error = array();
$data = array();
$count = 0;
$data = $_POST;
$blocked = array('booooo');
foreach($_POST as $key=>$value)
{
for($i=0;$i<count($blocked);$i++)
{
if(strlen(strstr($value,$blocked[$i]))>0)
{
$error[$key] = ' class="error"';
$count++;
}
}
if($value == "" || (strlen(trim($value)) == 0))
{
if($key == "submit"){
}else{
$error[$key] = ' class="error"';
$count++;
}
}
if($key == "phone" && $value<20)
{
$error[$key] = ' class="error"';
$count++;
}
}
// function to confirm form submission
if($count>0)
{
$echo "Please enter all the areas highlighted in red"
}
else
{
$this->sendForm();
$successBox = '<div class="successBox"><h3>Your e-mail has been sent.</h3></div>';
}
//Get the uploaded file information
$name_of_uploaded_file =
basename($_FILES['logo']['name']);
//get the file extension of the file
$type_of_uploaded_file =
substr($name_of_uploaded_file,
strrpos($name_of_uploaded_file, '.') + 1);
$size_of_uploaded_file =
$_FILES["logo"]["size"]/1024;//size in KBs
//attachment settings
$max_allowed_file_size = 1024; // size in KB
$allowed_extensions = array("jpg", "jpeg", "gif", "bmp");
//Validations
if($size_of_uploaded_file > $max_allowed_file_size )
{
$errors .= "\n Size of file should be less than $max_allowed_file_size";
}
//------ Validate the file extension -----
$allowed_ext = false;
for($i=0; $i<sizeof($allowed_extensions); $i++)
{
if(strcasecmp($allowed_extensions[$i],$type_of_uploaded_file) == 0)
{
$allowed_ext = true;
}
}
if(!$allowed_ext)
{
$errors .= "\n The uploaded file is not supported file type. ".
" Only the following file types are supported: ".implode(',',$allowed_extensions);
}
//copy the temporary uploaded file to uploads folder
$path_of_uploaded_file = $upload_folder . $name_of_uploaded_file; //NEED TO CREATE A FOLDER WITH 777 PERMISSIONS TO DROP THE FILE IN
$tmp_path = $_FILES["uploaded_file"]["tmp_name"];
if(is_uploaded_file($tmp_path))
{
if(!copy($tmp_path,$path_of_uploaded_file))
{
$errors .= '\n error while copying the uploaded file';
}
}
}
function sendForm()
{
global $data, $formShown;
require_once('email.class.php');
date_default_timezone_set('Europe/London');
$data['timeSent'] = date('l, jS F, Y \a\t H:i',time());
// Send email with enquiry details
$contactemail = new Email();
$contactemail->setTemplate("quickcontact");
$contactemail->setTo('jonathan#email.com'); // or mike#email.com?
$contactemail->setSubject("My enquiry");
//$contactemail->setFrom($data['name'],$data['email']);
$contactemail->setFrom("My Enquiry", "jonathan#email.com"); // double check
$contactemail->sendEmail($data);
//attach the file to the email
//$contactemail->addAttachment($path_of_uploaded_file);
// Send email to the visitor to confirm the contact form they sent
$contacteeemail = new Email();
$contacteeemail->setTemplate("quickcontactee");
$contacteeemail->setTo($data['email']);
$contacteeemail->setSubject("My");
$contacteeemail->setFrom("My", "jonathan#email.com"); // double check
$contacteeemail->sendEmail($data);
$this->unsetData();
$formShown = false;
}
Here's the HTML containing the optional fields.
<div class="row orange-underline">
<div class="addressArea hidden">
<div class="duplicateFree">
<label>Free Standing Midwifery Unit:</label>
<input <?=$error["freeStandingUnit"]; ?> type="text" name="freeStandingUnit" id="freeStandingUnit" value="<?=$_POST['freeStandingUnit'] ?>"/>
<label>Free Standing Midwifery Address:</label>
<textarea <?=$error["freeStandingAddresses"]; ?> name="freeStandingAddresses" id="freeStandingAddresses" rows="0" cols="0" ><?=$_POST['freeStandingAddresses'] ?></textarea>
<label>Free Standing Midwifery Postcode:</label>
<input <?=$error["freeStandingPost"]; ?> type="text" name="freeStandingPost" id="freeStandingPost" value="<?=$_POST['freeStandingPost'] ?>"/>
<label>Distance To Main Site:</label>
<input <?=$error["freeMainSiteDistance"]; ?> type="text" name="freeMainSiteDistance" id="freeMainSiteDistance" value="<?=$_POST['freeMainSiteDistance'] ?>"/>
<label>Non-urgent Transfer Time:</label>
<input <?=$error["freeNonUrgentTransfer"]; ?> type="text" name="freeNonUrgentTransfer" id="freeNonUrgentTransfer" value="<?=$_POST['freeNonUrgentTransfer'] ?>"/>
<label>Blue Light Transfer Time:</label>
<input <?=$error["freeBlueLightTransfer"]; ?> type="text" name="freeBlueLightTransfer" id="freeBlueLightTransfer" value="<?=$_POST['freeBlueLightTransfer'] ?>"/>
</div>
</div>
</div>
<div class="row">
<span class="leftSpan"> <span><label>Any Alongside Midwifery Units:</label>
<p>
<select class="region_units">
<option value="select">Select</option>
<?php for($i = 1; $i <= 10; $i++) { ?>
<option value="<?php echo $i; ?>"><?php echo $i . ($i === 1 ? ' unit' : ' units'); ?></option>
<?php } ?>
</select>
</p>
</span> </span>
</div>
<div class="row orange-underline">
<div class="addressArea2 hidden">
<div class="duplicate">
<label>Alongside Midwifery Unit:</label>
<input <?=$error["alongsideUnit"]; ?> type="text" name="alongsideUnit" id="alongsideUnit" value="<?=$_POST['alongsideUnit'] ?>"/>
<label>Alongside Midwifery Address:</label>
<textarea <?=$error["alongsideAddresses"]; ?> name="alongsideAddresses" id="alongsideAddresses" rows="0" cols="0" ><?=$_POST['alongsideAddresses'] ?></textarea>
<label>Alongside Midwifery Postcode:</label>
<input <?=$error["alongsideUnitPost"]; ?> type="text" name="alongsideUnitPost" id="alongsideUnitPost" value="<?=$_POST['alongsideUnitPost'] ?>"/>
<label>Distance To Main Site:</label>
<input <?=$error["alongsideMainSiteDistance"]; ?> type="text" name="alongsideMainSiteDistance" id="alongsideMainSiteDistance" value="<?=$_POST['alongsideMainSiteDistance'] ?>"/>
<label>Non-urgent Transfer Time:</label>
<input <?=$error["alongsideNonUrgentTransfer"]; ?> type="text" name="alongsideNonUrgentTransfer" id="alongsideNonUrgentTransfer" value="<?=$_POST['alongsideNonUrgentTransfer'] ?>"/>
<label>Blue Light Transfer Time:</label>
<input <?=$error["alongsideBlueLightTransfer"]; ?> type="text" name="alongsideBlueLightTransfer" id="alongsideBlueLightTransfer" value="<?=$_POST['alongsideBlueLightTransfer'] ?>"/>
</div>
</div>
</div>
<div class="row">
<span class="leftSpan"> <span><label>Any Extra Addresses:</label>
<p>
<select class="extra_region_units">
<option value="select">Select</option>
<?php for($i = 1; $i <= 10; $i++) { ?>
<option value="<?php echo $i; ?>"><?php echo $i . ($i === 1 ? ' unit' : ' units'); ?></option>
<?php } ?>
</select>
</p>
</span> </span>
</div>
<div class="row orange-underline">
<div class="addressArea3 hidden">
<div class="duplicateExtra">
<label>Extra Unit:</label>
<input <?=$error["extraUnit"]; ?> type="text" name="extraUnit" id="extraUnit" value="<?=$_POST['extraUnit'] ?>"/>
<label>Extra Unit Address:</label>
<textarea <?=$error["extraAddresses"]; ?> name="extraAddresses" id="extraAddresses" rows="0" cols="0" ><?=$_POST['extraAddresses'] ?></textarea>
<label>Extra Unit Postcode:</label>
<input <?=$error["extraUnitPost"]; ?> type="text" name="extraUnitPost" id="extraUnitPost" value="<?=$_POST['extraUnitPost'] ?>"/>
<label>Distance To Main Site:</label>
<input <?=$error["extraMainSiteDistance"]; ?> type="text" name="extraMainSiteDistance" id="extraMainSiteDistance" value="<?=$_POST['extraMainSiteDistance'] ?>"/>
<label>Non-urgent Transfer Time:</label>
<input <?=$error["extraNonUrgentTransfer"]; ?> type="text" name="extraNonUrgentTransfer" id="extraNonUrgentTransfer" value="<?=$_POST['extraNonUrgentTransfer'] ?>"/>
<label>Blue Light Transfer Time:</label>
<input <?=$error["extraBlueLightTransfer"]; ?> type="text" name="extraBlueLightTransfer" id="extraBlueLightTransfer" value="<?=$_POST['extraBlueLightTransfer'] ?>"/>
</div>
</div>
</div>
You are missing a ' which could cause an issue in your PHP code.
Replace this:
$successBox = <div class="successBox"><h3>E-Mail Sent.</h3></div>';
With this:
$successBox = '<div class="successBox"><h3>E-Mail Sent.</h3></div>';
Error in your code
$this->sendForm();
$successBox = <div class="successBox"><h3>E-Mail Sent.</h3></div>';
Single quote is missing it should be like this
$this->sendForm();
$successBox = '<div class="successBox"><h3>E-Mail Sent.</h3></div>';
I have a php contact form and all works great going to a single address but I'm trying to modify my script to handle a drop down selector, which enables choosing a recipient (which email address to send to).
Here is the part of the code that I have so far in trying to deal with this issue:
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="recipient" id="recipient">
<p class="text">
Please select recipient<br>
<select name="recipient" size="4"
<?php if (isset($missing)) {
echo 'value="'.htmlentities($_POST['recipient'], ENT_QUOTES).'"';
} ?>
>
<option value="">Select...</option>
<option value="1">Artistic Director</option>
<option value="2">Site Administrator</option>
<option value="3">Someone else</option>
</select>
</p>
</form>
<?php if (array_key_exists('send', $_POST)) {
// mail processing script
if ('recipient' == 1) {
$to = 'soandso#mail.com';
}
elseif('recipient' == 2) {
$to = 'soandso#mail.com';
}
elseif('recipient' == 3) {
$to = 'soandso#mail.com';
}
else {
echo 'Sorry for no recipient';
}
//then remainder code to process the rest which works fine
I'm sure my problem lies in the calling/getting the value of recipient but I can't figure out where to go from here.
You're trying to do something weird here. It should be:
if ($_POST['recipient'] == 1) {
$to = 'soandso#mail.com';
}
else if($_POST['recipient'] == 2) {
$to = 'soandso#mail.com';
}
else if($_POST['recipient'] == 3) {
$to = 'soandso#mail.com';
}
else {
echo 'Sorry for no recipient';
}
Of course 'recipient' will never be equal to 1, 2 or 3.
I also noticed the form and the select has the same name 'recipient'. I don't know is that is an issue though. But I would like to address it anyway.
This code is working 100% :
(function($) {
$('#recipient').on('click', function() {
$('#recipient-form').submit();
});
})(jQuery);
<div id="page">
<?php
$to = '';
if (isset($_POST['recipient'])) :
// mail processing script
if ($_POST['recipient'] == 1) {
$to = 'recipient1';
}
else if($_POST['recipient'] == 2) {
$to = 'reciipient2';
}
else if($_POST['recipient'] == 3) {
$to = 'recipient3';
}
else {
$to = 'Sorry for no recipient';
}
echo $to;
else : ?>
<form action="" method="post" id="recipient-form">
<select id="recipient" name="recipient" size="4">
<option value="">Select...</option>
<option value="1">Artistic Director</option>
<option value="2">Site Administrator</option>
<option value="3">Someone else</option>
</select>
</form>
</div>
<?php endif; ?>
The page in it's (mostly) entirety for clarification purposes hopefully:
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" id="recipient-form">
<p class="text">
Please select recipient<br>
<select id="recipient" name="recipient" size="4">
<option value="">Select...</option>
<option value="1">Artistic Director</option>
<option value="2">Site Administrator</option>
<option value="3">Someone else</option>
</select>
</p>
</form>
<?php if (array_key_exists('send', $_POST)) {
// mail processing script
$to = '';
if ($_POST['recipient']) {
// mail processing script
if ($_POST['recipient'] == 1) {
$to = '';
}
else if($_POST['recipient'] == 2) {
$to = '';
}
else if($_POST['recipient'] == 3) {
$to = '';
}
else {
$to = 'Sorry for no recipient';
}
}
$subject = 'Feedback From Website';
// list expected fields
$expected = array('name', 'email', 'comments', 'subscribe');
// set required fields
$required = array('name', 'email', 'comments');
// set additional headers
$headers = 'From: ';
// set the include
$process = 'includes/process.inc.php';
if (file_exists($process) && is_readable($process)) {
include($process);
}
else {
$mailSent = false;
mail($me, 'Server Problem', "$process cannot be read", $headers);
}
}
?>
<?php
if ($_POST && isset($missing) && !empty($missing)) {
?>
<p class="warning">Please complete the missing item(s) indicated.</p>
<?php
}
elseif ($_POST && $link) {
?>
<p class="warning">Sorry, Messages sent that contain links will not be sent.</p>
<?php
}
elseif ($_POST && !$mailSent) {
?>
<p class="warning">Sorry, there was a problem sending your message. Please try again later.</p>
<?php
}
elseif ($_POST && $mailSent) {
?>
<p class="success">Your message has been sent. Thank you for your message!</p>
<?php } ?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="contact" id="contact" onSubmit="MM_validateForm('name','','R','email','','RisEmail','comments','','R');return document.MM_returnValue">
<p>
<label for="name">Name: <?php
if (isset($missing) && in_array('name', $missing)) { ?>
<span class="warning">Please enter your name</span><?php } ?>
</label>
<input name="name" type="text" class="textInput" id="name"
<?php if (isset($missing)) {
echo 'value="'.htmlentities($_POST['name'], ENT_QUOTES).'"';
} ?>
>
</p>
<p>
<label for="email">Email: <?php
if (isset($missing) && in_array('email', $missing)) { ?>
<span class="warning">Please enter your email address</span><?php } ?>
</label>
<input name="email" type="text" class="textInput" id="email"
<?php if (isset($missing)) {
echo 'value="'.htmlentities($_POST['email'], ENT_QUOTES).'"';
} ?>
>
</p>
<p>
<label for="comments">Message:<?php
if (isset($missing) && in_array('comments', $missing)) { ?>
<span class="warning">Please enter your message</span><?php } ?>
</label>
<textarea name="comments" id="comments" cols="45" rows="5"><?php
if (isset($missing)) {
echo htmlentities($_POST['comments'], ENT_QUOTES);
} ?></textarea>
</p>
<p>
<p class="text">
Please check the box if you would like to sign up for our Mailing List!
<input type="checkbox" name="subscribe" value="Yes"
<?php if (isset($missing)) {
echo 'value="'.htmlentities($_POST['subscribe'], ENT_QUOTES).'"';
} ?>
>
</p>
<p>
<?php
require_once('recaptchalib.php');
$publickey = "6Lf3NdQSAAAAAOAwgPGRybLnY175X6k9PJ1F2vHx"; // you got this from the signup page
echo recaptcha_get_html($publickey);
?>
</p>
<p class="last">
<input type="submit" name="send" id="send" value="Send Message">
</p>
</form>
Hopefully having all of it now will help someone come up with the best solution!
The entirety again. I think/hope we're getting closer:
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" id="getEmail">
<p class="text">Please select recipient</p><br>
<select name="recipient" size="4">
<option value="">Select...</option>
<option value="1">Artistic Director</option>
<option value="2">Site Administrator</option>
<option value="3">Someone else</option>
</select>
<input type='hidden' name='do' value='1'>
</form>
<?php
if (array_key_exists('send', $_POST)) {
if (isset($_POST['do'])) {
// mail processing script
if ($_POST['recipient'] == 1) { $to = ''; }
else if($_POST['recipient'] == 2) { $to = ''; }
else if($_POST['recipient'] == 3) { $to = ''; }
else echo 'Sorry for no recipient';
}
echo $to;
$subject = 'Feedback From Website';
// list expected fields
$expected = array('name', 'email', 'comments', 'subscribe');
// set required fields
$required = array('name', 'email', 'comments');
// set additional headers
$headers = 'From:';
// set the include
$process = 'includes/process.inc.php';
if (file_exists($process) && is_readable($process)) {
include($process);
}
else {
$mailSent = false;
mail($me, 'Server Problem', "$process cannot be read", $headers);
}
}
?>
<?php
if ($_POST && isset($missing) && !empty($missing)) {
?>
<p class="warning">Please complete the missing item(s) indicated.</p>
<?php
}
elseif ($_POST && $link) {
?>
<p class="warning">Sorry, Messages sent that contain links will not be sent.</p>
<?php
}
elseif ($_POST && !$mailSent) {
?>
<p class="warning">Sorry, there was a problem sending your message. Please try again later.</p>
<?php
}
elseif ($_POST && $mailSent) {
?>
<p class="success">Your message has been sent. Thank you for your message!</p>
<?php } ?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="contact" id="contact" onSubmit="MM_validateForm('name','','R','email','','RisEmail','comments','','R');return document.MM_returnValue">
<p>
<label for="name">Name: <?php
if (isset($missing) && in_array('name', $missing)) { ?>
<span class="warning">Please enter your name</span><?php } ?>
</label>
<input name="name" type="text" class="textInput" id="name"
<?php if (isset($missing)) {
echo 'value="'.htmlentities($_POST['name'], ENT_QUOTES).'"';
} ?>
>
</p>
<p>
<label for="email">Email: <?php
if (isset($missing) && in_array('email', $missing)) { ?>
<span class="warning">Please enter your email address</span><?php } ?>
</label>
<input name="email" type="text" class="textInput" id="email"
<?php if (isset($missing)) {
echo 'value="'.htmlentities($_POST['email'], ENT_QUOTES).'"';
} ?>
>
</p>
<p>
<label for="comments">Message:<?php
if (isset($missing) && in_array('comments', $missing)) { ?>
<span class="warning">Please enter your message</span><?php } ?>
</label>
<textarea name="comments" id="comments" cols="45" rows="5"><?php
if (isset($missing)) {
echo htmlentities($_POST['comments'], ENT_QUOTES);
} ?></textarea>
</p>
<p>
<p class="text">
Please check the box if you would like to sign up for our Mailing List!
<input type="checkbox" name="subscribe" value="Yes"
<?php if (isset($missing)) {
echo 'value="'.htmlentities($_POST['subscribe'], ENT_QUOTES).'"';
} ?>
>
</p>
<p>
<?php
require_once('recaptchalib.php');
$publickey = "6Lf3NdQSAAAAAOAwgPGRybLnY175X6k9PJ1F2vHx"; // you got this from the signup page
echo recaptcha_get_html($publickey);
?>
</p>
<p class="last">
<input type="submit" name="send" id="send" value="Send Message">
</p>
</form>
Your form name and select name is the same. also you are echoing the post value inside the select. i think it is left over from your previous input box.
try this;
<form action="" method="post" id="getEmail">
<p class="text">Please select recipient<br></p>
<select name="recipient" size="4">
<option value="">Select...</option>
<option value="1">Artistic Director</option>
<option value="2">Site Administrator</option>
<option value="3">Someone else</option>
</select>
<input type='hidden' name='do' value='1'>
<input type='sumbit' value='Go'>
</form>
<?php if (isset($_POST['do'])) {
// mail processing script
if ($_POST['recipient'] == 1)$to = 'email1';
else if($_POST['recipient'] == 2)$to = 'email2';
else if($_POST['recipient'] == 3)$to = 'email3';
else echo 'Sorry for no recipient';
}
//echo $to;
//to send mail
$sub = 'Mail from web Form';
$msg = 'My message';
$mail_status= mail($to, $sub, $msg);
if($mail_status){do something on success}; else {do something on failure};
?>
I am using Ben Edmunds Ion Auth Library.
I am having a problem with any function that uses the csrf_nonce methods - it is failing the check on post.
I have checked that the flashdata is getting set (I can see it in the form as a hidden input [edit_user for example]), but when you submit the form the flashdata check is failing.
I am using the database for the session if that makes any difference.
Code snippets;
Controller
function edit_user($id) {
$this->data['title'] = "Edit User";
if (!$this->ion_auth->logged_in() || !$this->ion_auth->is_admin()) {
redirect('auth', 'refresh');
} //!$this->ion_auth->logged_in() || !$this->ion_auth->is_admin()
$user = $this->ion_auth->user($id)->row();
$groups = $this->ion_auth->groups()->result_array();
$currentGroups = $this->ion_auth->get_users_groups($id)->result();
//process the phone number
if (isset($user->phone) && !empty($user->phone)) {
$user->phone = explode('-', $user->phone);
} //isset($user->phone) && !empty($user->phone)
//validate form input
$this->form_validation->set_rules('first_name', $this->lang->line('edit_user_validation_fname_label'), 'required|xss_clean');
$this->form_validation->set_rules('last_name', $this->lang->line('edit_user_validation_lname_label'), 'required|xss_clean');
$this->form_validation->set_rules('email', $this->lang->line('create_user_validation_email_label'), 'required|valid_email');
$this->form_validation->set_rules('company', $this->lang->line('edit_user_validation_company_label'), 'required|xss_clean');
$this->form_validation->set_rules('groups', $this->lang->line('edit_user_validation_groups_label'), 'xss_clean');
if (isset($_POST) && !empty($_POST)) {
// do we have a valid request?
if ($id != $this->input->post('id')) {
show_error($this->lang->line('error_csrf'));
} //$this->_valid_csrf_nonce() === FALSE || $id != $this->input->post('id')
$data = array(
'first_name' => $this->input->post('first_name'),
'last_name' => $this->input->post('last_name'),
'company' => $this->input->post('company'),
'email' => $this->input->post('email')
);
//Update the groups user belongs to
$groupData = $this->input->post('groups');
if (isset($groupData) && !empty($groupData)) {
$this->ion_auth->remove_from_group('', $id);
foreach ($groupData as $grp) {
$this->ion_auth->add_to_group($grp, $id);
} //$groupData as $grp
} //isset($groupData) && !empty($groupData)
//update the password if it was posted
if ($this->input->post('password')) {
$this->form_validation->set_rules('password', $this->lang->line('edit_user_validation_password_label'), 'required|min_length[' . $this->config->item('min_password_length', 'ion_auth') . ']|max_length[' . $this->config->item('max_password_length', 'ion_auth') . ']|matches[password_confirm]');
$this->form_validation->set_rules('password_confirm', $this->lang->line('edit_user_validation_password_confirm_label'), 'required');
$data['password'] = $this->input->post('password');
} //$this->input->post('password')
if ($this->form_validation->run() === TRUE) {
$check = $this->ion_auth->update($user->id, $data);
if (FALSE == $check) {
$this->session->set_flashdata('message', $this->ion_auth->errors());
redirect("auth/edit-user/$id", 'refresh');
} else {
//check to see if we are creating the user
//redirect them back to the admin page
$this->session->set_flashdata('message', "User Saved");
redirect("auth/users", 'refresh');
}
} //$this->form_validation->run() === TRUE
} //isset($_POST) && !empty($_POST)
//display the edit user form
$this->data['csrf'] = $this->_get_csrf_nonce();
//set the flash data error message if there is one
$this->data['message'] = (validation_errors() ? validation_errors() : ($this->ion_auth->errors() ? $this->ion_auth->errors() : $this->session->flashdata('message')));
//pass the user to the view
$this->data['user'] = $user;
$this->data['groups'] = $groups;
$this->data['currentGroups'] = $currentGroups;
$this->data['first_name'] = array(
'name' => 'first_name',
'id' => 'first_name',
'type' => 'text',
'value' => $this->form_validation->set_value('first_name', $user->first_name)
);
$this->data['last_name'] = array(
'name' => 'last_name',
'id' => 'last_name',
'type' => 'text',
'value' => $this->form_validation->set_value('last_name', $user->last_name)
);
$this->data['company'] = array(
'name' => 'company',
'id' => 'company',
'type' => 'text',
'value' => $this->form_validation->set_value('company', $user->company)
);
$this->data['email'] = array(
'name' => 'email',
'id' => 'email',
'type' => 'email',
'value' => $this->form_validation->set_value('email', $user->email)
);
$this->data['password'] = array(
'name' => 'password',
'id' => 'password',
'type' => 'password'
);
$this->data['password_confirm'] = array(
'name' => 'password_confirm',
'id' => 'password_confirm',
'type' => 'password'
);
$this->_render_page('auth/admin/users/update', $this->data);
}
function _get_csrf_nonce() {
$this->load->helper('string');
$key = random_string('alnum', 8);
$value = random_string('alnum', 20);
$this->session->set_flashdata('csrfkey', $key);
$this->session->set_flashdata('csrfvalue', $value);
return array(
$key => $value
);
}
function _valid_csrf_nonce() {
if ($this->input->post($this->session->flashdata('csrfkey')) !== FALSE &&
$this->input->post($this->session->flashdata('csrfkey')) == $this->session->flashdata('csrfvalue')) {
return TRUE;
} //$this->input->post($this->session->flashdata('csrfkey')) !== FALSE && $this->input->post($this->session->flashdata('csrfkey')) == $this->session->flashdata('csrfvalue')
else {
return FALSE;
}
}
View;
<h1><?php echo lang('edit_user_heading');?></h1>
<p><?php echo lang('edit_user_subheading');?></p>
<!--<div id="infoMessage" class="info"><?php echo $message;?></div>-->
<?php
if (isset($message)) {
?>
<div id="infoMessage" class="alert alert-info">
<button type="button" class="close" data-dismiss="alert">×</button>
<h4>Message</h4>
<?php echo $message;?>
</div>
<?php
}
?>
<?php echo form_open(uri_string(), 'class="form-horizontal"'); ?>
<div class="control-group <?php echo form_error_class('first_name') ?>">
<label class="control-label" for="first_name">
<?php echo lang('edit_user_fname_label'); ?>
</label>
<div class="controls">
<input type="text"
id="first_name"
name="first_name"
placeholder="<?php echo lang('edit_user_fname_label'); ?>"
value="<?php echo set_value('first_name', $first_name['value']); ?>"
class="error"/>
<?php echo form_error('first_name'); ?>
</div>
</div>
<div class="control-group <?php echo form_error_class('last_name') ?>">
<label class="control-label" for="last_name">
<?php echo lang('edit_user_lname_label'); ?>
</label>
<div class="controls">
<input type="text"
id="last_name"
name="last_name"
placeholder="<?php echo lang('edit_user_lname_label'); ?>"
value="<?php echo set_value('last_name', $last_name['value']); ?>"
class="error"/>
<?php echo form_error('last_name'); ?>
</div>
</div>
<div class="control-group <?php echo form_error_class('company') ?>">
<label class="control-label" for="company">
<?php echo lang('edit_user_company_label'); ?>
</label>
<div class="controls">
<input type="text"
id="company"
name="company"
placeholder="<?php echo lang('edit_user_company_label'); ?>"
value="<?php echo set_value('company', $company['value']); ?>"
class="error"/>
<?php echo form_error('company'); ?>
</div>
</div>
<div class="control-group <?php echo form_error_class('email') ?>">
<label class="control-label" for="email">
<?php echo lang('edit_user_email_label'); ?>
</label>
<div class="controls">
<input type="text"
id="email"
name="email"
placeholder="<?php echo lang('edit_user_email_label'); ?>"
value="<?php echo set_value('email', $email['value']); ?>"
class="error"/>
<?php echo form_error('email'); ?>
</div>
</div>
<div class="control-group <?php echo form_error_class('password') ?>">
<label class="control-label" for="password">
<?php echo lang('edit_user_password_label'); ?>
</label>
<div class="controls">
<input type="password"
id="password"
name="password"
placeholder="<?php echo lang('edit_user_password_label'); ?>"
value="<?php echo set_value('password'); ?>"
class="error"/>
<?php echo form_error('password'); ?>
</div>
</div>
<div class="control-group <?php echo form_error_class('password_confirm') ?>">
<label class="control-label" for="password_confirm">
<?php echo lang('edit_user_password_confirm_label'); ?>
</label>
<div class="controls">
<input type="password"
id="password_confirm"
name="password_confirm"
placeholder="<?php echo lang('edit_user_password_confirm_label'); ?>"
value=""
class="error"/>
<?php echo form_error('password_confirm'); ?>
</div>
</div>
<div class="control-group <?php echo form_error_class('groups') ?>">
<div class="controls <?php echo form_error_class('groups') ?>">
<h3><?php echo lang('edit_user_groups_heading');?></h3>
<?php
foreach ($groups as $group) {
?>
<label class="checkbox">
<?php
$gID=$group['id'];
$checked = null;
$item = null;
foreach($currentGroups as $grp) {
if ($gID == $grp->id) {
$checked= ' checked="checked"';
break;
}
}
?>
<input type="checkbox" name="groups[]" value="<?php echo $group['id'];?>"<?php echo $checked;?>>
<?php echo $group['name'];?>
</label>
<?php
}
?>
</div>
</div>
<?php echo form_hidden('id', $user->id);?>
<?php echo form_hidden($csrf); ?>
<div class="control-group">
<div class="controls">
<input type="submit" class="btn btn-success" value="<?php echo lang('edit_user_submit_btn'); ?>" />
</div>
</div>
<?php echo form_close();?>
First check
$this->session->set_flashdata('message',
$this->ion_auth->errors()
);
having set value
I have found the solution (or this fix works just for me).
I changed the session driver in the config to use native sessions from cookie.
Line 284 of config.php => $config['sess_driver'] = 'native';
Golden rule: never trust CI sessions!
Some notions about FLASHDATA
CSRF and Flashdata:
FLASHDATA will only be available for the NEXT server request, and are then automatically cleared!
e.g.:
AJAX calls function_1, which sends CSRF key/value back to function_1_success
function_1_success sets hidden input fields for CSFR key and value
and enables function_2, which compares POST variables with flashdata
this is how it works (with or without AJAX, that was just an example).
How it doesn't work: if you create a php function which does
$this->session->set_flashdata('item', 'value') and then try to read with echo $this->session->flashdata('item') you will get an empty string, only after a refresh of this function,your flashdata values show