how to set a default value in codeigniter? - php

is there any sugestion to store default value that is posted to database from form html?
my aplication is using mysql as the rdmbs and codeigniter for backend process.
right now, i just using html method at the submit form.
<input type="hidden" id="" name="" value="">
at the html page and set the value there.
but the value is visible when you open the source code in any other browser.
is there any method to store value that is not visible from user in codeigniter?

If your form is posting the data on the same method wherefrom it is rendered then the best approach is that; keep the value in the method itself and use it after form submit.
public function edit() {
$id = 12;
if ($this->form_validation->run()) {
$dataComm = array(
'id' => $id
'name' => $this->input->post('name')
);
$result_comm = $this->Common_model->insert_data('cw_franchise_commission', $dataComm);
}
$this->data['title'] = "Edit User";
$this->load->view('edit', $this->data);
}
And if your form action is another method then you can encode the value and decode it after form submission.
To Encode
bin2hex(base64_encode($id))
To Decode
base64_decode(hex2bin($this->input->post('id')));
One more thing if you are using hidden inputs then you should name it something confusing not clear at all. Otherwise, anyone can understand the purpose of the field.

There is no such a way but you can keep it in encoding format using
base64_encode()
<input type="hidden" name="id" value="<php echo base64_encode('1231231231'.$id); ?>">
"1231231231" just for additional security which will preprend with the id
cut "1231231231" in controller like below to get the id
function abc() {
if (isset($_POST['id']) && !empty($_POST['id'])) {
$id = substr(base64_decode($_GET['id']), 10); // to remive extra string
if (!empty($id)) {
// you get id here
} else {
//if someone attempt to tamper with the id then it will retrive blank
}
} else {
//redirect or show error
}
}

Related

How to pass input value inside filter function in Wordpress?

I have an issue with filter hook function,
So I have a form with input type number which I show in my template:
if( isset($_GET['submit']) ) {
$my_text = esc_attr($_GET['my_text']);
}
?>
<form id="my-form" method="get">
<input id="my_text" type="text" name="my_text" value="<?php echo $my_text; ?>" />
<input type="submit" name="submit" value="search">
</form>
<?php
So now I want when user type a text in this input and click submit button, the value should be passed inside my filter hook function:
function _themename_excerpt_more() {
return 'here should be a value from input';
}
add_filter( 'excerpt_more', '_themename_excerpt_more' );
Is it possible? I can't find out right answers.
Thanks in advance!
I don't know particular answer for wordpress, but I can explain how this works in PHP in general. PHP is executed only once when the page is requested. After the response is sent to the client, you may not access any values in inputs or anything in html using that same PHP code. There are 2 ways to do that: either get the values in javascript
<script>
document.getElementById('my-form').addEventListener('submit', () => {
const input = document.getElementById('my_input')
const value = input.value
// Do something with this value
alert(value)
})
</script>
The second option is to use html forms as "intended". When you press the submit button, user will be redirected to a page that you specify in action attribute. If it's empty, the user will be redirected to current page. And the value of your input will be in query parameters ($_GET) and have the name that you specify in name attribute. So you could use a different route (for example /submit or whatever would be appropriate for you application) and check the input there:
<!-- Add name to input -->
<input
name="my_text"
id="my_text"
type="text"
name="my_text"
value="<?php echo $my_text; ?>"
/>
function _themename_excerpt_more() {
return $_GET['my_text'];
}
if(isset($_GET['my_text']) {
// Don't forget to escape that if you need
$value = $_GET['my_text'];
add_filter('excerpt_more', '_themename_excerpt_more');
} else {
// Replace with some more logic
exit('Error: no input provided');
}
Or check it inside the function
function _themename_excerpt_more() {
if(isset($_GET['my_text']) {
return $_GET['my_text'];
} else {
// Replace with some logic
echo('Error: no input provided');
// You may use a default value
return 'default value';
}
}
// Don't forget to escape that if you need
add_filter('excerpt_more', '_themename_excerpt_more');

Deleting user function SQL query doesn't send anything (PHP)

So basically, I've got a function in PHP that deletes an user from the same row when a form is submit, the form does submit, the function does do it's thing, but the user is not deleted.
$html = '';
$html .= '<table><form method="post" action="index.php?controller=user&action=delUser">';
foreach( $auser as $user) {
$html .= '<tr><td><input type="hidden" value="'.$user['id'].'"><input type="submit" name="delUserSubmit" value=""> '.$user["id"].' '.$user["voornaam"].' '.$user["tv"].' '.$user["achternaam"].'</td></tr>';
}
$html .= '</form></table>';
return $html;
}
So in this form, it sends the id through a hidden input field which carries the user id
public function delUser()
{
if(isset($_POST['delUserSubmit'])) {
$sql = "DELETE FROM user WHERE id = ".$_POST['id'];
$this->oDb->insUpdDelQuery($sql);
unset($_POST);
header("Location: index.php?controller=user&action=show");
}
}
When it reaches the above function, it goes through the isset $_POST etc. Since when everytime I do submit the form, I go to the page at which the header is pointing.
But when it reaches the user page, the user is still there.
Now the problem could either be:
I don't actually send the id
I do send the id, but the $sql doesn't get the id somehow? the delUser() function is empty whereas something like show($id=null) shows all the users.
the delUser() needs something like $_POST['id'], but that would give unexpected characters in my editor.
Can't fix this, anybody able to help?
POST values are submitted using the name attribute on the input field.
Change your HTML input to
<input type="hidden" name="id" value="'.$user['id'].'">
You have not set anything in the from to $_POST['id']. The name of the posted element is taken from the name in the html form. The input tag that has the value of id needs to have the the name set to id:
<input type="hidden" value="'.$user['id'].'" name="id">

How do I create a server-side form submission script that has client-side characteristics?

I'm working in PHP to build a form. I know how to display the form and then take submitted values from the $_POST variable, and I know how to validate those variables and display a "Thank You" or an "Error" page depending on the input.
What I don't know how to do, though, is create a client-side-like system wherein despite having my users hit a "back" button a separate screen I can then take the information I gathered from the first submission and display dynamic error messages like "Please provide a valid email address" or "First name is a required field" next to the fields that were entered incorrectly. I'd also like to retrieve any previously submitted data that was valid and have it populate in the form so users don't get frustrated by losing everything they entered.
What is the right approach to accomplishing something like this in PHP? I originally thought if I could pass back an array of error messages with an input type="hidden" tag I could then pull my values and display messages dynamically with PHP, but I keep getting stuck in that approach.
You could add the errors a php session, but this creates issues for users who have multiple browser tabs open.
My preferred method is to have the form submit to the same page and put the errors directly on that page so the user does not have to click the back button. That way you can highlight the fields directly in the form (make the background or outline red or something similar.)
<input type="text"
<?php (empty($_POST['field']?'style="backgroung-color: red;"':''))?>
name="field" value="<?php echo $_POST['field']?>" />
You can put <input type="text" name="field" value="<?php echo $_POST['field']?>" /> to get the old value.
Because the web is, by definition, stateless, there is no really good way to track what the user does when they hit the back button. There are hacks that work using a hidden iframe, but that is way more trouble that what you are looking for.
Don't mix client logic with server logic. The exact same script can output the form and take it's input. In case input successfully validates, it goes on. If not, it will display the form again, this time with error messages and the already-entered data.
Next time the user submits the form, validation starts again until it passes successfully.
So you extend the form with input values and error messages in the first place, but you only display them if flagged/set.
This can be done just with additional variables next to $_POST - or if you like it - by using a complete form abstraction from a framework, like zend framework (which might be overhead for what you like to do) or just with a library/component like the popular HTML_QuickForm2.
Edit:
This is some very bare code to demonstrate the overall methodology, if you use a library it is much nicer (and you don't have to code it instead you can concentrate on the actual form like the definition on top). This code is more for reading and understanding the flow than for using, I quickly typed it so it (most certainly has) syntax errors and it's not feature complete for a full blown form. This one has only one email field and is even missing the submit button:
/* setup the request */
$request->isSubmit = isset($_POST['submit']);
/* define the form */
$form->fields = array
(
'email' => array
(
'validate' => function($value) {return filter_var($value, FILTER_VALIDATE_EMAIL);},
'output' => function($value, $name) {return sprintf('<input type="text" value="%s" id="%s">', htmlspecialchars($value), htmlspecialchars($name)},
'default' => 'info#example.com',
),
);
/**
* Import form data from post request
*
* #return array data with keys as field names and values as the input strings
* or default form values.
*/
function get_form_post_data($form, $request)
{
$data = array();
foreach($form->fields as $name => $field)
{
$data[$name] = $field->default;
if ($request->isSubmit && isset($_POST[$name]))
{
$data[$name] = $_POST[$name];
}
}
return $data;
}
/**
* Validate form data
*/
function validate_form_data($form, $data)
{
foreach($form->fields as $name => $field)
{
$value = $data[$name];
$valid = $field['validate']($value);
if (!$valid)
{
$form->errors[$name] = true;
}
}
}
function display_form($form, $data)
{
foreach($form->fields as $name => $field)
{
$value = isset($data[$name]) ? $data[$name] : '';
$hasError = isset($form->errors[$name]);
$input = $field['output']($name, $value);
$mask = '%s';
if ($hasError)
{
$mask = '<div class="error"><div class="message">Please Check:</div>%s</div>';
}
printf($mask, $input);
}
}
// give it a run:
# populate form with default values -or- with submitted values:
$form->data = get_form_post_data($form, $request);
# validate form if there is actually a submit:
if ($request->isSubmit)
{
validate_form_data($form, $form->data);
}
# finally display the form (that can be within your HTML/template part), works like echo:
display_form($form, $form->data)
Use the form to submit to the same page, and if the form validates, use a header to redirect the user into the thank you page.
header("Location: thank-you.php");
If the form fails validation, you could easily display all the errors on the same page.

How to use <button type=button>

I’m usually Using input type submit eg: <input type=“submit” name=“assign” value=“Assign”/>
and using this is no problem for me but now I want to use button eg:<button type=“button” class=“button” id=“deleteb”><div>Assign Student</div></button>
but don’t know how to used it or call it to my controller.
this is my controller function
if($assign_student)//<input type="submit" name="assign" value="Assign"/>
{
if($maxMember->max_members > $countMember)
{
if($countMember+1 == 1)
{
$is_leader = 1;
}
else
{
$is_leader = $this->input->post('is_leader');
}
$student = array(
'user_id' => $this->input->post('student'),
'group_no' => $this->input->post('group'),
'is_leader' => $is_leader
);
$this->admin_db->save_group($student['group_no'],$student);
}
else
{
$data['max_error'] = "<p class='error'>Sorry, This group reached the maximum number of members!</p>";
}
}
If you want the button to submit the form you must have type="submit"
If you want the button to send a value, it's better to use a hidden input to send along additional information. Example:
<input type="hidden" name="assign" value="Assign" />
You can set a name and value to the <button>, but guess what?: In IE6, the actual html content of the button will be sent as the post data instead. It's one of my favorite bugs.
It's not very clear why you posted your controller code, but if you are checking for a "trigger" value before processing, like $this->input->post('assign'), you can check for the presence of any other of the form values instead, or the presence of any $_POST values, or as I mentioned: a hidden input.
If you press a submit-button, you are posting a form to some
script, in this case PHP.
if you submit the form, your browser sends the information
contained in the form to the receiving script.
eg, if you make a page with a form that contains:
You can check like this...
if (isset($_POST["deleteb"]))
{
//Do stuffs
}

Retaining values in forms fields when validation of data fails

I am having problems figuring out how to retain users data when the validation fails. I am somewhat new to PHP so I might be making some huge mistakes in my logic.
Currently if the validation fails all the fields are wiped clean and $_Post data is also gone.
Here is some code assuming the user enters an invalid email I want the Name field to be retained. This code is not working.
<?php
if($_POST['doSubmit'] == 'Submit') {
$usr_name = $data['Name'];
$usr_email = $data['Email'];
if (isEmail($usr_email)==FALSE){
$err = "Email is invalid.");
header("Location: index.php?msg=$err");
exit();
}
//do whatever with data
}
if (isset($_GET['msg'])) {
$msg = mysql_real_escape_string($_GET['msg']);
echo "<div class=\"msg\">$msg</div><hr />";
}
if (isset ($_POST['Name'])){
$reusername = $_POST['Name'];}
else{$reusername = "NOTHING";}//to test
?>
<form action="index.php" method="post" >
<input name="UserName" type="text" size="30" value="<?echo $reusername;?>">
<input name="Email" type="text" size="30">
<input name="doSubmit" type="submit" value="submit">
</form>
}
You can use AJAX to submit your form data to your PHP script and have it return JSON data that specifies whether the validation was successful or not. That way, your fields won't be wiped clean.
Another way is to send back the recorded parameters to the posting page, and in the posting page, populate the fields using PHP.
However, I think the first solution is better.
UPDATE
The edit makes your code clearer and so I noticed something. Your input field is called UserName in the HTML, but you are referring to Name in PHP. That's probably why it's not working. Is your field always being filled with the value NOTHING? Make sure the name of the input field and the subscript you are using in $_POST are the same.
Also, there's no need to redirect to another page (using header) if you have an error. Maintain an $errors array or variable to print error messages in the same page. But like I mentioned before, it's probably better to use the JSON approach since then you can separate your view layer (the html) from the PHP (controller layer). So you'd put your HTML in one file, and your PHP in another file.
EDIT:
Vivin had commented that my assumption regarding the header was incorrect and he was right in that. Further more it looks like what the OP is doing is essentially what i layed out below albeit in a less structured fashion. Further Vivin - caught what is likely the actual problem here - the html name and the array key $_POST do not match.
Its wiped clean because you are using header to redirect to another page. Typicaly you would have a single page that validates the data and if ok does something with it and returns a success view of some sort, or that returns an error view directly showing the form again. By using header youre actually redirecting the browser to another page (ie. starting up an entirely new request).
For example:
// myform.php
if(strtolower($_SERVER['REQUEST_METHOD']) == 'get')
{
ob_start();
include('form.inc.php'); // we load the actual view - the html/php file
$content = ob_get_clean();
print $content; // we print the contents of the view to the browser
exit;
}
elseif(strtolower($_SERVER['REQUEST_METHOD']) == 'post')
{
$form = santize($_POST); // clean up the input... htmlentities, date format filters, etc..
if($data = is_valid($form))
{
process_data($data); // this would insert it in the db, or email it, etc..
}
else
{
$errors = get_errors(); // this would get our error messages associated with each form field indexed by the same key as $form
ob_start();
include('form.inc.php'); // we load the actual view - the html/php file
$content = ob_get_clean();
print $content; // we print the contents of the view to the browser
exit;
}
}
so this assumes that your form.inc.php always has the output of error messages coded into it - it just doesnt display them. So in this file you might see something like:
<fieldset>
<label for="item_1">
<?php echo isset($error['item_1']) ? $error['item_1'] : null; ?>
Item 1: <input id="item_1" value="<?php echo $form['item_1'] ?>" />
</label>
</fieldset>
Could do something similar to if failed then value=$_POST['value']
But vivin's answer is best. I don't know much about AJAX and wouldn't be able to manage that.
Ok, firstly header("Location: index.php?msg=$err"); is not really required. It's best practice not to redirect like this on error, but display errors on the same page. Also, redirecting like this means you lose all of the post data in the form so you can never print it back into the inputs.
What you need to do is this:
<input name="Email" type="text" size="30" value="<?php print (!$err && $usr_email ? htmlentities($usr_email, ENT_QUOTES) : '') ?>">
Here I'm checking whether any errors exist, then whether the $usr_email variable is set. If both these conditions are matched the post data is printed in the value attribute of the field.
The reason I'm using the function htmlentities() is because otherwise a user can inject malicious code into the page.
You appear to be processing the post on the same page as your form. This is an OK way to do things and it means you're nearly there. All you have to do is redirect if your validation is successful but not if it fails. Like this
<?php
if( isset( $_POST['number'] ) ) {
$number = $_POST['number'];
// validate
if( $number < 10 ) {
// process it and then;
header('Location: success_page.php');
} else {
$err = 'Your number is too big';
}
} else {
$number = '';
$err = '';
}
?>
<form method="POST">
Enter a number less than 10<br/>
<?php echo $err ?><br/>
<input name="number" value="<?php echo $number ?>"><br/>
<input type="submit">
</form>

Categories