$_POST and code manipulation - php

I want to grab the value of a field using $_POST, manipulate it, then pass the value back to the same page to the same field before the PHP code manipulates it.
If I put the PHP code after the field, it manipulates the code, reloads the page but doesn't put the manipulated code back into the field.
if (!isset($input)) {
$input = '';
}
echo '<form id="testform" method="post" action="">';
echo '<input type="text" name="inputText" value="' . $input . '">';
echo '<button type="submit" name="button"> Button </button>';
echo '</form>';
$input = $_POST['inputText'];
if(isset($_POST['inputText'])) {
$input = $input . ' manipulated';
}
echo $input; //test
If I put the PHP code before the field, it can't find the field to manipulate the value...
if (!isset($input)) {
$input = '';
}
$input = $_POST['inputText'];
if(isset($_POST['inputText'])) {
$input = $input . ' manipulated';
}
echo $input; //test
echo '<form id="testform" method="post" action="">';
echo '<input type="text" name="inputText" value="' . $input . '">';
echo '<button type="submit" name="button"> Button </button>';
echo '</form>';
Obviously the first approach is more correct, but how do I pass the $input variable to the field before the rest of my PHP manipulation code executes?
I tried $_POST['inputText'] = $input as a desperate attempt but nothing..

Well, from what I've understood in your explanation, you want to change the input value to something else and show it in he same field. If that's correct, you may want to do this:
<form id="testform" method="post" action="">
<input type="text" name="inputText" value="<?php echo ( isset($_POST['inputText']) ) ? sprintf( '%s manipulated', $_POST['inputText'] ) : ''; ?>">
<button type="submit"> Send </button>
</form>
Let me know if that's what you wanted. Regards !

Try
$input = isset($_POST['inputText']) ?$_POST['inputText'] :'';
in the begining instead of
if (!isset($input)) {
$input = '';
}

Related

Calling a function on button click, getting a url

I am new to wordpress. I am trying to call function myprefix_edit_user_cb() to get the edit form after user clicks on edit.
function getdata()
{
$blogusers = get_users();
foreach ( $blogusers as $user ) {
echo '<span>' . esc_html( $user->user_email ) . '</span>';
$editUrl = ??
echo "<a href='".$editUrl. "'>Edit User</a>";
echo '<br>';
}
}
with function:
function myprefix_edit_user_cb(){
$user = intval($_REQUEST['user']);
echo '
<form action="' . $_SERVER['REQUEST_URI'] . '" method="post">
<label>Username</label>
<input type="text" value="' .$user->user_login . '"
<input type="submit">
';
}
According to me you need to put some request flag with your edit url.
Try the below code.
function getdata(){
$blogusers = get_users();
foreach ( $blogusers as $user ) {
echo '<span>' . esc_html( $user->user_email ) . '</span>';
$deleteUrl = add_query_arg(array('action'=>'myprefix_delete_user', 'user_id'=>$user->ID));
$editUrl = add_query_arg(array('action'=>'myprefix_edit_user', 'user'=>$user));
echo "<a href='".$deleteUrl. "'>Delete User</a>";
echo "<a href='".$editUrl. "&edit=1'>Edit User</a>";
echo '<br>';
}
}
with action and callback function with flag :
add_action('init','myprefix_edit_user_cb');
function myprefix_edit_user_cb(){
$user = intval($_REQUEST['user']);
if($user == '')
return;
if($_REQUEST['edit'] == 1 )
{
echo '
<form action="' . $_SERVER['REQUEST_URI'] . '" method="post">
<label>Username</label>
<input type="text" value="' .$user->user_login . '"
<input type="submit">
';
}
}
What you are asking all depends on where you would like to allow the user to be edited. Here is my preferred option (assuming you are doing everything on the front side of the website):
Create a page with a page template.
By default most themes come with some basic templates for how a page will look. Seeing as you may wish to add an edit form to a page, creating a custom page template would be a straight forward move. A good tutorial for creating these can be found here. Once created you would add some code like this to the template:
<?php if (isset($_GET['user_id'])): ?>
<?php $user = get_user_by('id', intval($_GET['user_id'])); ?>
<form action="#" method="post">
<label>Username</label>
<input type="text" value="<?= esc_attr($selected_user->user_login); ?>" />
<input type="submit" />
...
</form>
<?php else: ?>
<p>Error, please specify a user id!</p>
<?php endif; ?>
Which would do a basic test to make sure user_id had been passed to the page, then load the form accordingly (to improve on this I would also check to see if get_user_by returns an object before showing an edit form just in-case the user_id is invalid). In the provided example a URL (with permalinks set to page-name) would look like this:
https://example.com/edit-page/?user_id=55
There are ways of making the URL cleaner, however for now I am just trying to make sure your question is answered with a correct working example.
Koda

Fill input with array

In my jquery code I have:
$("#show").append("<img src=" +attachment.url+" alt="+attachment.alt+" title="+attachment.title+" description="+attachment.caption+" class='img-responsive img-thumbnail'/><input type='hidden' name='my_image_URL[]' value="+attachment.url+"></span>");
My jquery code adds fields for news selected images and fills inputs names my_image_URL[].
In PHP:
if ( isset( $_POST['my_image_URL'] ) ) {
$urls = $_POST['my_image_URL'];
echo '<input type="hidden" name="imagens_home" value="'.$urls.'"/>';
}
I trying to add $urls array in the hidden input.
And after, if its works ok:
<?php
if ($urls != '' ) {
foreach ($urls as $url) {
?>
<img src="<?php echo $url;?>" class="img-responsive img-thumbnail " />
<input name="my_image_URL[]" value="<?php echo $url;?>"/>
</div>
<?php
};
}
?>
But this part of code not fill the input:
if ( isset( $_POST['my_image_URL'] ) ) {
$urls = $_POST['my_image_URL'];
echo '<input type="hidden" name="imagens_home" value="'.$urls.'"/>';
}
---------- UPDATE --------
options.php
register_setting(
'tema-setting-group',//string $option_group
'imagens_home' //string $option_name
//calback $sanitize_calback
);
---
add_settings_field(
'home-imagens-top',//string $id
'Imagens',//String $title
'tema_home_imgs',//string $calback
'opcoes_do_tema',//string $page
'tema-home-options'//string $section
//string $args
);
//calback
function tema_home_imgs(){
$urlsImagens = esc_attr( get_option( 'imagens_home' ) ); // RETURN DB DATA
include( get_template_directory() . '/inc/templates/selecao_imagens.php');
if ( isset( $_POST['my_image_URL'] ) ) {
$urls = $_POST['my_image_URL'];
echo '<input name="imagens_home" value="'.$json_encode($urls).'" style="width:300px"/>';
}
}
selecao_imagens.php
<input id="my_upl_button" type="button" value="Escolher Imagens" /><br/>
<div class="row">
<div id="exibe" class="sortable">
<?php
$urls = json_decode($urlsImagens, true);
if ($urls != '' ) {
foreach ($urls as $url) {
?>
<img src="<?php echo $url;?>" class="img-responsive img-thumbnail " />
<input name="my_image_URL[]" value="<?php echo $url;?>"/>
<?php
};
}
?>
</div>
</div>
theme_options.php
<?php settings_errors();?>
<form method="post" action="options.php">
<?php settings_fields ('tema-setting-group'); ?>
<?php do_settings_sections (
'opcoes_do_tema'//string $page
); ?>
<?php submit_button ();
?>
</form>
-------- UPDATE 2 -------
I tried:
echo '<input name="imagens_home" value="' . htmlspecialchars(json_encode($urls)) . '" />';
but it is not yet filling in the input.
I also tried only:
If (isset ($ _POST ['my_image_URL'])) {
Print_r ($ _ POST ['my_image_URL']);
}
But after the submit does not appear anything on the screen, in the form correctly saves all other inputs except what I am trying to save the array, if I put some manual information goes ok. But I do not understand why it is not capturing the my_image_URL [] names of each image input. The action in form is like this:
<Form method = “post” action = “options.php”>
I’m using the Settings API
Thanks
I trying to add $urls array in the hidden input.
If I understand, you're trying to store an array value in a hidden input, so you can retrieve it later. Problem is, this doesn't work...
echo '<input type="hidden" name="imagens_home" value="'.$urls.'"/>';
...because when you echo a PHP array all you get is the string Array, not the actual array contents.
You could turn the array into a json string though:
echo '<input type="hidden" name="imagens_home" value="'.$json_encode($urls).'"/>';
Now your hidden input has a regular string. Later, when the form is POSTed, you could retrieve it:
$urls = json_decode($_POST['imagens_home'], true)

How to get the total value of to two rand() variables that match on the input value of a text form?

I found out that whenever I press submit button it does change the current value of the rand() the reason why it doesn't match on my input value.
I want to use this as validation to my form. Before the user can submit the message he/she must answer the question first.
here is my code:
<?php
session_start();
$numa = rand(1,5);
$numb = rand(0,4);
$_SESSION['valid_res'] = $numa + $numb;
echo 'Answer this '.$numa . ' + ' . $numb .' = ';
?>
<form name="form" method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<input type="text" name="input" /><input type="submit" name="submit" value="Submit" />
</form>
<?php
if(isset($_POST['submit'])){
if(intval($_POST['input']) != $_SESSION['valid_res']){
echo 'You enter have entered '. intval($_POST['input']) .' it is wrong answer';
}else{
echo 'Congratulations you have entered '. intval($_POST['input']) .' it is the correct answer.';
}
}
?>
You are overwriting the session value on each page load. Write it only on first load and use the subsequent value for the check.
You also have to convert the session variable to integer form.
Try this:
if(!isset($_POST['submit']))
{
$numa = rand(1,5);
$numb = rand(0,4);
$_SESSION['valid_res'] = $numa + $numb;
echo 'Answer this '.$numa . ' + ' . $numb .' = ';
}
else
if(intval($_POST['input']) != intval($_SESSION['valid_res']))
{
...
Use !== instead of !=. Use the code below
<?php
session_start();
$numa = rand(1,5);
$numb = rand(0,4);
$_SESSION['valid_res'] = $numa + $numb;
echo 'Answer this '.$numa . ' + ' . $numb .' = ';
?>
<form name="form" method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<input type="text" name="input" /><input type="submit" name="submit" value="Submit" />
</form>
<?php
if(isset($_POST['submit'])){
if(intval($_POST['input']) !==$_SESSION['valid_res']){
echo 'You enter have entered '. intval($_POST['input']) .' it is wrong answer';
}else{
echo 'Congratulations you have entered '. intval($_POST['input']) .' it is the correct answer.';
}
}
?>
Hope this helps you

php dropdown with another form and submit

Hey this problem may look really easy to solve but i can't find any solution, my dropdown isn't saving
<?php
// the relative path to the file
$fname = "Erros1.txt";
$fname2 = "Comentarios.txt";
// read in the file if present
if(file_exists($fname)) $txt = file_get_contents($fname);
if(file_exists($fname2)) $Comentarios = file_get_contents($fname2);
// if the user pushes the submit button
if(isset($_POST["Comentarios"])){
$Comentarios = $_POST["Comentarios"]; // get the entered content
file_put_contents($fname2,$Comentarios); // write the content to the file
}
if (isset($_POST["dropdown"])) {
// cast to integer to avoid malicious values
$dropdown = (int)$_POST["dropdown"];
}
?>
<form method="post" action="#">
<textarea name = "txt" cols = "120" rows = "20">
<?php echo $txt; ?>
</textarea>
<textarea name = "Comentarios" cols = "120" rows = "10">
<?php echo $Comentarios; ?>
</textarea>
// here is the dropdown
<select name="dropdown";>
<?php
for ($x=1; $x<=4; $x++) {
echo '<option value="' . $x . '">' . $x . '</option>' . PHP_EOL;
}
echo $_POST['dropdown']
?>
</select>
<input type="submit" name="submit" value="submit" />
</form>
</body>
</html>
Only my Comentarios Box is saving, maybe i need to change the submit or create another form

Detecting which form was submitted in php

What would be a reliable way to detect which form was submitted in a situation like below? All submit to the same page, which in turn does things based on which form was submitted. Many drawbacks have been pointed out to the way this is being done. To top it all, even querystrings go to the same script. How would you suggest this be done?
Form one has two input fields, form two has three.
<?php
if ( isset($_POST['valOne']) && isset($_POST['valTwo']) && isset($_POST['valThree']) ) {
echo 'This is form three';
} elseif ( isset($_POST['valOne']) && isset($_POST['valTwo']) ) {
echo 'This is form two';
} else {
echo 'Neither one or two';
}
$formOne = '<form method="post" action="http://localhost/dev/form.php">';
$formOne .= 'Name: <input type="text" name="valOne" value="Foo" autocomplete="off"><br>';
$formOne .= 'Description: <input type="text" name="valTwo" value="Bar" autocomplete="off"><br>';
$formOne .= '<input type="hidden" name="secretVal" value="secretKey">';
$formOne .= '<input value="Add This" type="submit">';
$formOne .= '</form>';
$formTwo = '<form method="post" action="http://localhost/dev/form.php">';
$formTwo .= 'Name: <input type="text" name="valOne" value="Foo" autocomplete="off"><br>';
$formTwo .= 'Description: <input type="text" name="valTwo" value="Bar" autocomplete="off"><br>';
$formTwo .= 'URL: <input type="text" name="valThree" value="Tar" autocomplete="off"><br>';
$formTwo .= '<input type="hidden" name="secretVal" value="secretKey">';
$formTwo .= '<input value="Add This" type="submit">';
$formTwo .= '</form>';
$formThree = '<a href="http://localhost/dev/form.php?do=getIt">This is GET. Get it?<a/>';
echo $formOne;
echo '<br>';
echo $formTwo;
echo '<br>';
echo $formThree;
?>
You could use a hidden input with different names for the 2 forms and on server side you can check with if(isset($_POST['hidden_for_form1'])) or if(isset($_POST['hidden_for_form2'])).
You could add a form_id parameter to the form action.
<form method='post' action='http://localhost/dev/form.php?form_id=1'>
Then in your code switch on $_GET["form_id"];
I'd use hidden inputs
<input type="hidden" name="form" value="form1">
Also on a side note, is there any reason you're storing the form code in a variable?
Add a hidden input:
<input type="hidden" name="form" value="one">
<?switch($_POST['form']){
case "one":
...
?>
You can also assign the name and value to a submit button, but that doesn't work if the user presses enter
You need to assign some name in submit, like:
<input type="submit" name="form1" value="Add This">
<input type="submit" name="form2" value="Add This">
<input type="submit" name="form3" value="Add This">
so..
if(isset($_POST['form1'])){ //do some stuff }
if(isset($_POST['form2'])){ //do some stuff }
if(isset($_POST['form3'])){ //do some stuff }

Categories