I am trying to do a find and replace applicaiton the problem is that after cliked submit button all the text fields gets clean nothing displays on the screen What am i doing wrong
<?php
$offset=0;
if(isset($_POST['text'] ) && isset($_POST['searchfor']) && isset($_POST['replacewith'])){
$text=$_POST['text'];
$search=$_POST['searchfor'];
$replace=$_POST['replacewith'];
$searchLength=strlen($search);
if(!empty($text) && !empty($search) &&!empty($replace)){
while ($strpos= strpos($text,$search,$offset)){
echo $offset=$strpos+$searchLength;
}
} else {
echo "<script>alert('errorrrr')</script>";
}
}
?>
<form action="#" method="post">
<textarea name="text" id="" cols="30" rows="10"></textarea><br>
Search For:<br>
<input type="text" name="searchfor"><br>
ReplaceWith<br>
<input type="text"name="replacewith"><br>
<input type="submit" value="Fr..."></>
</form>
Regarding your form, you decided to submit to the same page.
Doing this, the page is obviously fully reloaded when submitted. Hence it is normal that what you typed in has disappeared.
If you want to see it again, you have to display you variables in the HTML code.
For example:
<?php
$myVar = "";
if(isset($_POST['myVar']){
$myVar = $_POST['myVar'];
}
?>
<form>
<input type="text" value="<?php echo $myVar;?>"/>
</form>
NB: I encourage you to filter the user entry.
Regards
there is problems in your code :
1 - echo $offset=$strpos+$searchLength; the echo can't be used in this format. insted use echo $offset; in next line for seeing offset values.
2 - if the text be like 'amir love persepolis' and search for 'amir' to replace it with 'all men's' you will have another issue, because you will have while ( 0 ) situation. think about this too!
Related
I am testing two separate forms to see which generates the best leads and I'm having trouble getting to where I need to. So first we are using WordPress and the two forms are global (non landing page related).
With PHP I am generating a number of 0 or 1. If 0 form A loads, if 1 form B loads. So I got that working, then I looked into do a cookie to store that number so the form for the site visitor is the same if they browse across the site. Currently each page loads generates a new number so they'll see both forms if they click on contact and come back to it again later. Now with the cookie it's the same thing.
$aB = rand(0,1)
setcookie('user', $aB, time() + (86400*7));
if(!isset($_COOKIE['user'])){
echo do_shortcode('[gravityform shortcode form B]');
} else {
echo do_shortcode('[gravityform shortcode form A]');
}
I'm looking into doing sessions but I'm still figuring out how I can keep if the site visitor gets a 0 how do I get that to follow them across the entire site as they browse until either they close or the cookie/session expires. After some testing with the cookies I realized this approach is probably not the best. I'm looking for suggestions in the best way to attach this problem, thanks!
Create custom setting field in website using below code in functions.php,
add_action('admin_menu', 'add_gcf_interface');
function add_gcf_interface() {
add_options_page('form option', 'form option', '8', 'functions', 'editglobalcustomfields');
}
function editglobalcustomfields() {
?>
<div class='wrap'>
<form method="post" action="options.php">
<?php wp_nonce_field('update-options') ?>
<p><strong>Home page mode:</strong><br />
<input type="number" name="alterid" size="5" min="1" max="2" value="<?php echo get_option('alterid'); ?>" /></p>
<p><input type="submit" name="Submit" value="Update Options" /></p>
<input type="hidden" name="action" value="update" />
<input type="hidden" name="page_options" value="alterid" />
</form>
</div>
<?php
}
Use below code where you want alternative results,
session_start();
if($_SESSION['homepagenew'] == '' && $_SESSION['homepageold'] == '')
{
if(get_option('alterid') == 1){
$_SESSION['homepagenew'] = get_option('alterid');
update_option('alterid', 2 );
}
else if(get_option('alterid') == 2){
$_SESSION['homepageold'] = get_option('alterid');
update_option('alterid', 1 );
}
}
if($_SESSION['homepagenew'] == 1)
{
echo do_shortcode('[gravityform shortcode form B]'); // form option 1
exit;
}
else if($_SESSION['homepageold'] == 2){
echo do_shortcode('[gravityform shortcode form A]'); // form option 2
exit;
}
I want form to post automatically if zip variable is passed from URL.
URL looks like: www.sitename.com/maps/zipsearch.php?zip=90210
Form looks like:
<form method="post">
Zipcode:
<input name="zip" value="<?php echo (isset($_GET["zip"]))? $_GET["zip"]:"";?>" />
<input type="submit" name="subbut" value="Find instructors" />
</form>
So it fills the input box with zip code but I would like it to post automatically to see results again if zip is passed.
Maybe an IF / THEN?
Any help would be appreciated.
You mean to echo the value passed in GET parameter?
<input type="submit" name="subbut" value="<?php echo isset($_GET['zip'])?$_GET['zip']:'Find'; ?>" />
EDIT
Or, if you are asking about submitting the form, then something like this might work I believe:
<input type="submit" name="subbut" value="<?php echo isset($_GET['zip'])?$_GET['zip']:'Find'; ?>" />
<?php if( isset( $_GET['zip'] ) ) { ?>
<script>
document.forms["name_of_the_form_here"].submit();
</script>
<?php } ?>
like this:
<form id="form" action="form.php" method="post">
Zipcode:
<input name="zip" value="<?php echo (isset($_GET["zip"]))? $_GET["zip"]:"";?>" />
<input type="submit" name="subbut" value="Find instructors" />
</form>
<?php if (isset($_GET["zip"])): ?>
<script>document.getElementById('form').submit()</script>
<?php endif; ?>
since passing data via URL means GET method, so i think you have a little misconception with your question.
if you would like to post automatically you dont need to show form.
just put this code in your zipsearch.php
if ($_GET['zip'] != ""){
// do what you want if zip parameter is not null
}else{
// do what you want if zip parameter is null
}
It looks like your form is submitting to itself. (Eg. zipsearch.php displays HTML form. When user submits form, it is posted back to zipsearch.php which displays the search results).
If this is the case, you don't have to post anything, because you are already inside the file that handles the form submission. You could do something like this:
<?php
if (isset ($_POST['zip'])) {
$zip = $_POST['zip']; /* Form was submitted */
} else if (isset ($_GET['zip'])) {
$zip = $_GET['zip']; /* "?zip=" parameter exists */
}
if (isset ($zip)) {
/* Display search results */
} else {
/* Display form */
}
I have strange problem with my search form. After I enter keyword and do the search request I get empty parameter value.
For example I type in the search field the word "something"
I see an empty value:
search.php?keyword=
After this I enter the keyword "else" and I recieve:
search.php?keyword=something instead of search.php?keyword=else
They somehow appear with "one step back"
I was trying to debug with print_r and var_dump but I only can print some values that does not explain my problem.
Am I missing something very trivial?
Here is what I have:
My class function:
public function show_search_result() {
$this->search_keywords = strip_tags($_GET['keyword']);
$this->_db->query("SELECT * from posts WHERE post_title LIKE '%$this->search_keywords%' OR post_content LIKE '%$this->search_keywords%' LIMIT 100");
$this->rows_results_found = $this->_db->resultset();
}
And my form:
<form action="search.php?keyword=<?php
if (isset($search_results->rows_results_found) && isset($_POST['search_requested'])) {
print strip_tags($_POST['search_keywords']);
}
?>" method="post">
<input type="hidden" name="search_requested">
<input type="text" name="search_keywords" value="<?php
if (isset($search_results->rows_results_found) && isset($_POST['search_requested'])) {
print strip_tags($_POST['search_keywords']);
}
?>"><input type="submit" value="Search">
</form>
<form action="" method=get>
<input type=text id=se>
<?php
if($_GET != null){
$sekw = $_GET ['se'];
$sql = //the query like='$sekw' limit=100;
?>
<input type=submit>
</form>
A simple code.
Your problem is when you send the form, it does save the keywords until the second send.
change your method from post to get. also i would advice you to use a framework for easy and fast coding. some include symfony2, laravel
How would I send information from a form to a block of PHP code and then back to a text area? I can not find this answer.
To print out the text you entered in the textfield on the next request would look like this assuming you render the same page (i.e. myform.php):
<?php
$fieldValue = htmlentities($_POST['myfield']);
?>
<form action="myform.php" method="post">
<label for="myfield">Your textfield:</label>
<input type="text" name="myfield" id="myfield" value="<?php echo $fieldValue; ?>" />
</form>
A very basic example.
Assuming you have a PHP file named index.php
<?php
$val = 'Nothing in POST';
if (!empty($_POST)) { //$_POST is where stuff posted from the FORM is saved
$val = isset($_POST['text']) ? $_POST['text'] : '';//you're looking for the data with key text which is the name of your textarea element
$val = 'Got something from POST : ' . $val;
}
?>
<form action='index.php' method='post'>
<textarea name='text'><?php echo $val ?></textarea>
</form>
Have a look at this tutorial for the basics : http://net.tutsplus.com/articles/news/diving-into-php/
use ajax!(and use jquery for that ajax!)
suppose you have this html :
<input type="text" id="input">
<textarea id="result"></textarea>
than the script should be:
$('#input').keypress(function(e){
if(e.wich != 13)//not enter
return;
$.get(your_php_file.php,{param1:val1,param2:val2},function(result){
$('#result').val(result);
});
});
when you hit enter on the input field,the ajax function is being called that requests the file your_php_file.php?param1=val1¶m2=val2. With the php's result, the callback function is being called which updates your textarea
I have my form working and all of the errors and everything works.
But if you have an error, it refreshes the page and removes any text that was inserted before the submit button was clicked and you have to re-enter all of the information.
Anyway to fix this?
I think it has something to do with not using $_SERVER["PHP_SELF"] in the action of the form.
Instead I have action=""
I am doing this because the page that needs to be refreshed with the same info has a variable in its url (monthly_specials_info.php?date=Dec10) that was put there from the last page.
I tried using
<form method="post" action="'.$_SERVER["PHP_SELF"].'?date='.$date.'">
and it produced the right url. but the text was all removed anyway when form was submitted (with errors).. any ideas?
Form code:
echo ' <div id="specialsForm"><h3>Interested in this coupon? Email us! </h3>
<form method="post" action="'.$_SERVER["PHP_SELF"].'?date='.$date.'">
Name: <input name="name" type="text" /><br />
Email: <input name="email" type="text" /><br />
Phone Number: <input name="phone" type="text" /><br /><br />
Comment: <br/>
<textarea name="comment" rows="5" cols="30"></textarea><br /><br />
<input type="submit" name="submit" value="Submit Email"/>
</form></div>
<div style="clear:both;"></div><br /><br />';
and the vaildator:
if(isset($_POST['submit'])) {
$errors = array();
if (empty($name)) {
$errors[] = '<span class="error">ERROR: Missing Name </span><br/>';
}
if (empty($phone) || empty($email)) {
$errors[] = '<span class="error">ERROR: You must insert a phone number or email</span><br/>';
}
if (!is_numeric($phone)) {
$errors[] = '<span class="error">ERROR: You must insert a phone number or email</span><br/>';
}
if (!preg_match('/[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}/', strtoupper($email))) {
$errors[] = '<span class="error">ERROR: Please Insert a valid Email</span><br/>';
}
if ($errors) {
echo '<p style="font-weight:bold;text-align:center;">There were some errors:</p> ';
echo '<ul><li>', implode('</li><li>', $errors), '</li></ul><br/>';
} else {
mail( "email#hotmail.com", "Monthly Specials Email",
"Name: $name\n".
"Email: $email\n".
"Phone Number: $phone\n".
"Comment: $comment", "From: $email");
echo'<span id="valid">Message has been sent</span><br/>';
}
}
First: you cannot trust '.$_SERVER it can be modified. Be carefull with that!
Second: you could(should?) use a hidden field instead of specifing it in the action?
But if you have an error, it refreshes
the page and removes any text that was
inserted before the submit button was
clicked and you have to re-enter all
of the information. Anyway to fix
this?
You could use ajax to fix it(I believe plain old HTML has this side-effect?).
A browser doesn't have to (p)refill a form. Some do for convenience, but you cannot rely on it.
In case you display the form again, you could set the values of the inputs like this:
$value = isset($_POST['foo']) : $_POST['foo'] : '';
echo '<input type="text" value="'. $value .'" name="foo" />';
Of course you should check and sanitize the POSTed data before including it in your HTML to not open up any XSS vulnerabilities.
If you want the form to submit to the same page, you don't need to set an action, it works without it as well. Also I'd suggest you to send the date in this way:
<input type="hidden" name="date" value="'.$date.'"/>
A part from the fact that that validator and html code has some big issues inside and things i'd change, what you are asking is: How could i make that the form compiled doesn't remove all the text from my input tags after the refresh.
Basically not knowing anything about your project, where the strings submitted goes, if they are stored in a database or somewhere else, what does that page means inside your project context i cannot write a specific script that makes submitted string remembered in a future reload of the page, but to clarify some things:
If there is a form that is defined as <form></form> and is submitted with a <input type="submit"/> (which should be enough, without giving it a name name="submit") the page is refreshed and it does not automatically remember the input your previously submitted.
To do that you have 2 choice:
Use Ajax (check Jquery as good framework for ajax), which will allow you to submit forms without refreshing the page. I choose it as first way because it is over-used by everyone and it is going to became more and more used because it is new and it works smoothly.
Make a php script that allows you to check if the input has already been submitted; in case the answer is true, then recover the values and get them in this way: <input type="text" value="<?php echo $value ?>"/>.
Also notice that you do not need of '.$_SERVER["PHP_SELF"].'?date='.$date.' since ?date='.$date.' is enough.
Browsers will not re-populate a form for you, especially when doing a POST. Since you're not building the form with fields filled out with value="" chunks, browsers will just render empty fields for you.
A very basic form handling script would look something like this:
<?php
if ($_SERVER['REQUEST_METHOD'] = 'POST') {
# do this only if actually handling a POST
$field1 = $_POST['field1'];
$field2 = $_POSt['field2'];
...etc...
if ($field1 = '...') {
// validate $field1
}
if ($field2 = '...') {
// validate $field2
}
... etc...
if (everything_ok) {
// do whatever you want with the data. insert into database?
redirect('elsewhere.php?status=success')
} else {
// handle error condition(s)
}
} // if the script gets here, then the form has to be displayed
<form method="POST" action="<?php echo $_SERVER['SCRIPT_NAME'] ?>">
<input type="text" name="field1" value="<?php echo htmlspecialchars($field1) ?>" />
<br />
<input type="text" name="field2" value="<?php echo htmlspecialchars($field2) ?>" />
etc...
<input type="submit" />
</form>
?>
Notice the use of htmlspecialchars() in the last bit, where form fields are being output. Consider the case where someone enters an html meta-character (", <, >) into the field. If for whatever reason the form has to be displayed, these characters will be output into the html and "break" the form. And every browser will "break" differently. Some won't care, some (*cough*IE*cough*) will barf bits all over the floor. By using htmlspecialchars(), those metacharacters will be "escaped" so that they'll be displayed properly and not break the form.
As well, if you're going to be outputting large chunks of HTML, and possibly embedding PHP variables in them, you'd do well to read up on HEREDOCs. They're a special construct that act as a multi-line double-quoted string, but free you from having to do any quote escaping. They make for far more readable code, and you don't have to worry about choosing the right kind of quotes, or the right number of quotes, as you hop in/out of "string mode" to output variables.
first, a few general changes:
change
<form method="post" action="'.$_SERVER["PHP_SELF"].'?date='.$date.'">
to
<form method="post" action="'.$_SERVER["PHP_SELF"].'">
<input type="hidden" name="data" value="'.$date.'" />
the answer to your original question:
set each input elements value attribute with $_POST['whatever'] if array_key_exists('whatever', $_POST);
For example: the name field
<input type="text" name="name" value="<?php echo array_key_exists('name', $_POST) ? $_POST['name'] : ''; ?>" />