Obtaining value from named form input - php

I have this HTML
<input type="text" name="message"/>
With this PHP
$message = 'Blank message';
if ( isset( $post['message'] ) )
$message = sanitize_text_field( $post['message'] );
$Message is always "Blank message"
I cannot see how this is wrong. After attempting to get the input value, I have no other code so I know the rest of it is working, but I am unable to obtain the value.

sup, you gotta change the way you're calling the array, it is $_POST, and not $post

Look to the method of your form. Are you using the GET method than you use $_GET['variable'] is it the POST method than you use $_POST['variable'].

Related

How many emails can I use in the input type text field and How to pass that multiple emails from one page to another without using session in PHP?

1st issue
I have more the one thousand emails and I am entering manually in the input type text field. I mean just copy from excel sheet and paste in the text field.
Just want to know,
1) Can I add more than one thousand email in the single input text? If yes then how many emails I can add?
2nd Issue
There are thousands of email in the field and I have to send that email from one page to another page without using session.
Page1.php
<form action="process.php?key=addemail" method="post">
<input type="text" name="emailtemplate[]" placeholder="Enter email name" class="form-control">
<input type="text" name="subject" placeholder="Subject" class="form-control">
<textarea name="mailbody" id="editor1" class="form-control"></textarea>
<input type="submit" name="addmail" value="Add mail" class="v-btn v-btn-primary">
</form>
Page2
function addemail($conn)
{
$to=$_POST['emailtemplate'];
$subject =$_POST['subject'];
$mailbody=$_POST['mailbody'];
sendMail($to, $subject, $mailbody );
}
I am trying to cheeck echo $to but i am getting error
Notice: Array to string conversion on line 173
Array
Would you help me in this?
Your addemail function could look something like this in order for things to work:
function addemail( $conn ){
$subject = filter_input( INPUT_POST, 'subject', FILTER_SANITIZE_STRING );
$mailbody = filter_input( INPUT_POST, 'mailbody', FILTER_SANITIZE_STRING );
foreach( $_POST['emailtemplate'] as $t ){
$recipient = filter_var( $t, FILTER_SANITIZE_EMAIL );
sendMail( $recipient, $subject, $mailbody );
}
}
Note that this is untested. I don't see the parameter $conn used for instance... But $_POST['emailtemplate'] is an array, you need to iterate through that. I also filtered your input from the form like you always should. That way you're a lot safer from any code injections...

Passing php form validate error message back to submit form

I'm trying to pass an error message from a server side form validator in a function back to the form it was submitted in. The validator is working as it prevents the rest of the code saving it to a database as planned. However I cant get it to pass back to the form to display the error
function saveComment(){
$validate = array();
$id = isset($_POST["articleId"]) ? $_POST["articleId"] : '';
if ( isset( $_POST['saveChanges'] ) ) {
if ( $_POST['name'] == "" ){
$validate['errorMessage'] = "Please fill out your name.";
header( "Location:".HOME_PATH."/.?action=viewArticle&articleId=".$_POST['articleID']."");
}
I' trying to pass it back to this
if ( isset( $validate['errorMessage'] ) ) {
echo $validate['errorMessage'];
}
When I remove the if on the display function I get the error unidentified index
What do I need to do to get the form to display the error message. Do I need to pass the array to the function that handles the display of the article?
FEEDBACK
For anyone that may find this useful I used #OliverBS post method pretty much unaltered.
Also thank you to #lethal-guitar as he explanation has helped me understand where I went wrong and the various methods that can be used to solve this problem +1
You're setting a variable $validate for your currently executing script. Afterwards, you send a redirect header. This will cause your browser to issue a new request, thus ending the currently executing script and scrapping the variable. The new request will trigger another script invocation, where the variable is not known anymore since it only existed for the duration of the first request.
HTTP is stateless, so every variable you set on the server side will only exist until you finish your current request and respond to the client. What you need is a way to pass this variable to the script handling the second request. There are several ways to do so:
Pass a GET parameter. You could append something like "&validationError=" . $validate['errorMessage'] to the URL you're passing to the Location header, and then in the display page access it via $_GET.
Save the validation status in the $_SESSION. The PHP manual contains a lot of information about sessions (maybe you're already using them?)
Restructure your code in a way that you don't redirect on error, but on success.
Some more information on the 3rd proposal: You write one PHP-Script which displays the form and handles the form post request. If validation fails, you simply redisplay, and insert the echo statement you already have. If it suceeds, you redirect to some success page. This way, the variable will remain accessible, since it's still the same request.
On a quick glance try this
Session way
Make sure to start the session by doing session_start(); at the top of the file where saveComment is and the isset checked.
function saveComment(){
$id = isset($_POST["articleId"]) ? $_POST["articleId"] : '';
if ( isset( $_POST['saveChanges'] ) ) {
if ( $_POST['name'] == "" ){
$_SESSION['errorMessage'] = "Please fill out your name.";
header( "Location:".HOME_PATH."/.?action=viewArticle&articleId=".$_POST['articleID']."");
}
if ( isset( $_SESSION['errorMessage'] ) ) {
echo $_SESSION['errorMessage'];
}
or you can try
POST way
function saveComment(){
$id = isset($_POST["articleId"]) ? $_POST["articleId"] : '';
if ( isset( $_POST['saveChanges'] ) ) {
if ( $_POST['name'] == "" ){
$error = urlencode('Please fill out your name');
header( "Location:".HOME_PATH."/.?action=viewArticle&articleId=".$_POST['articleID']. "&error=" . $error);
}
if ( isset( $_GET['error'] ) ) {
echo urldecode($_GET['error']);
}
I have not tested this but you should get the basic idea of what to do.
When you do a header location your redirecting the user to a new page. Your going to have to either pass the error in the query string or ideally pass it as a variable in the session.
I would suggest doing this all in one file, i.e. The form and the validation as one file.
Then you can do this:
<?php
//set success to 0
$success = 0;
$errormsgs = array();
//check for post
if(isset($_POST['submit'])){
//get the data from the form post and validate it
$valid = validateFuntion($_POST['data'])
//the is function will validate the data. If it is not valid, it will add a message to $errormsgs
//check for errors
if(!$errormsgs){
//data validation was successful, do stuff
}
}//if validation fails, it will fall out of the this code block and move on
?>
<html>
<body>
<?php
//check for errors
if($errormsgs){
$content .= '<ul class="errors">';
foreach($errormsgs as $error){
$content .= "<li>" . $error . "</li>";
}
$content .= "</ul>";
echo $content;
}
?>
<form name="name" action="" method="post">
<input name="name" value="<?= (isset($_POST['data']) ? $_POST['data'] : '') ?>" type="text">
</form>
</body>
</html>
You're redirecting the user to the "error" page with the header statement. The problem is, of course, this is a completely new page, there's no state left over, so none of your variables exist any more.
There's two ways to do it, either pass it on the query string (so add &error=...) and parse that in your template, or save it to the session.
Of course, you should really be doing this before your template is presented using a different means, but that's a complete rework of your code.

Passing an array of errors to a function which is called frequently

I have a question concerning the right way to pass an array to a function
After validating a form, I get an array of errors corresponding to each form field. i.e.
$errors = array(
"First_Name" => "Missing first name",
"Email" => "Invalid email address",
...
)
In order to display this errors I created a function
function print_error_message($field, $errors) {
if($errors[$field])
echo '<span class="error-msg">' . $errors[$field] . '</span>';
}
And I call this function after every html field to check whether this field has an error:
<input name="First_Name" value="<?php echo $First_Name ?>" />
<?php print_error_message("First_Name", $errors) ?>
...
So, since I have a lot of form fields, and a lot of errors, is it a good practice to pass '$errors' array every time I call the function. Or should I use global or passing by reference?
It is fine to do it the way you are doing it. Certainly don't use globals, and there's no need to pass by reference either.
Instead of if($errors[$field]), you could use if (array_key_exists($field, $errors)).

How to check if a text area 'contains' a certain phrase with javascript / php?

I'm trying to work out how to go about checking a text area to see if it contains a certain phrase.
I believe I could maybe use .indexOf?
It's just I have a validation script to check the contents of a contact form. Lately I have been receiving a fair bit of spam through. I have noticed that all these spam messages contain the phrase [url= and I thought, if I could perhaps add a small script to check if the text area contained such a phrase and, if so, stop the message being sent.
At present I have this simple snippet of javascript to check whether the text area is blank:
if (message.val()=='') {
message.addClass('highlight');
message.focus();
return false;
} else message.removeClass('highlight');
Any good ways to add something to check if the message field contains [url=
I also have a similar php validation script:
if (!$message) $errors[count($errors)] = 'Please click back and enter your message.';
Any ideas how I could add a similar validation script to check if message contains [url= in php too?
Any help would be greatly appreciated! :o)
It's unlikely that you'll stop spam by checking the contents of your textarea at the client side:- the spammer is more than likely POSTing directly to your server side script, so you'll need to do your filtering there. Also checking for a particular pattern will only work until the pattern changes and then you'll have to update your script.
A common solution to this problem is the use of a One-Time Form Token.
When you serve the form you generate a random string of characters and place that token in a hidden field in the form. You also store the token on the server in a session or in a database. When the form is submitted you match the stored and submitted tokens. This way you can be more sure that the form itself was filled in and submitted and that you aren't receiving data from a bot.
For extra security you can only allow each token to be used once only, guarding against multiple submissions.
UPDATE
A very simple, one page example
<?php
session_start();
/**
* Process the form if we have a token that we recognise
* otherwise just present the form again, you probably want to handle this a bit better
*/
if( isset( $_POST['token'] ) && isset( $_SESSION['token'] )
&& $_POST['token'] === $_SESSION['token'] ) {
// no more submissions using this token
unset( $_SESSION['token'] );
$name = clean( $_POST['name'] );
$comment = clean( $_POST['comment'] );
// process the input and redirect to a confirmation
// just echoing data for example
echo "$name said $comment";
die();
} else {
$token = uniqid();
$_SESSION['token'] = $token;
}
/**
* Stub function that cleans user input
* #param String $str
*/
function clean( $str ) {
return $str;
}
?>
<html>
<head>
<title>Form token example</title>
</head>
<body>
<form method="post">
<label>
Name<br/>
<input type="text" name="name"/>
</label>
<br/>
<label>
Comment<br/>
<textarea name="comment"></textarea>
</label>
<br/>
<label>
<input type="submit"/>
</label>
<br/>
<br/>
The token field would normally be hidden, it's displayed here so that the user can change it for testing<br/>
<input type="text" name="token" value="<?php echo $token ?>"/><br/>
</form>
</body>
</html>
check out the javascript search method and javascript match method. I prefer search becuase if you only care if it does exist then you do something like this.
var stringToSearch = "stackoverflow";
if (stringToSearch.search("over") >= 0){
//exists
}
By the way your question didn't do something right. I don't know php so i can't help you there
message.val().match('your phrase here')

Good Form Security - no CAPTCHA

Is there a good method of form security that does not involve CAPTCHA? CAPTCHA is so annoying, but I need security because I am getting form spam. My form is PHP.
Here's what I've found to be very effective (and dead simple):
Put a hidden field on your form. Give it a name like "phone" or something similar/common and put in a default junk value.
Put another regular text input field on your form, but hide it with CSS. Make that one empty. Again, give it a "real" sounding name (first_name, phone_number, whatever).
When the form is posted, verify that the hidden field still has the default value and the field you hid with CSS is still empty.
You're basicly taking advantage of the fact that most spam bots will simply fill in every field in the form in order to avoid failing any required field validation checks. Some might be smart enough to ignore hidden fields, but I've never seen one that was smart enough to ignore fields hidden with CSS.
ETA:
To address some comments - Is this a truly "secure" system? no, it certainly isn't. It would be trivially broken by anybody who wanted to specifically target your site. That said, it is still remarkably effective against the automated form spamming bots that most "low value" sites will see.
If you want to stop a determined attacker, you'll need something a bit more invasive. Another poster mentioned Akismet, which is a good option. Re-Captcha would be another. Stopping determined, targeted spammers is hard though. Even Yahoo and Google have a hard time with it.
Try akismet. It's great at flagging spam. The API is easy to use and completely transparent to your users.
This kind of validator is cute and quick!
Obviously, you will want to display one of a many possible animal images, and the list should be randomized as well.
I understand it will only work X% of the time, but adding more options to the list will help reduce spam.
I have already worked something similar.
When you open a form generate one md5() string and put it in session (for example $_SESSION['captha'])
Your form sould have one hidden field and when you open this form write this data from $_SESSION['captha'] into this hidden field
When you receive this post request compare value in session and value which come with this hidden field. If it is same everithing is ok and vice versa. Of course, after you handle this request just delete variable $_SESSION['captha'].
This work for me.
If all you are doing is avoiding spam bots (automated programs that seek <form> tags, fill in all <input> fields, then submit the form), then a simple solution is to do as Paolo said: use JavaScript to add a hidden field. The disadvantage is for people who disable JavaScript.
Feel free to use this:
<form method="post" action="contact.php" id="commentForm">
<label for="name">Name</label>
<input type="text" name="name" id="name" maxlength="64" /><br />
<label for="email">Email</label>
<input type="text" name="email" id="email" maxlength="320" /><br />
<label for="message">Message</label>
<textarea name="message" rows="10" cols="40" id="Message"></textarea><br />
<label for="human">40 + 2 =</label>
<input type="text" name="human" id="human" size="10" maxlength="3" /><br />
<p align="center">
<input type="submit" name="submit" value="Send" class="submit-button" />
</p>
</form>
Then place the following as "contact.php" in the same directory:
<?php
require_once 'lib/swift_required.php';
// Reason for not contacting.
//
$reason = 'default';
error_reporting( 0 );
ini_set( 'display_errors', 0 );
function not_contacted() {
global $reason;
header( 'Location: error.html' );
}
function wms_error_handler($errno, $errstr, $errfile, $errline) {
not_contacted();
return true;
}
function wms_shutdown() {
if( is_null( $e = error_get_last() ) === false ) {
not_contacted();
}
}
set_error_handler( "wms_error_handler" );
register_shutdown_function( 'wms_shutdown' );
$name = trim( $_POST["name"] );
$email = trim( $_POST["email"] );
$message = trim( $_POST["message"] );
$human = trim( $_POST["human"] );
$subject = 'FormSpam';
$contacted = false;
if( is_null( $name ) || empty( $name ) ) {
$reason = 'name';
$human = false;
}
else if( is_null( $email ) || empty( $email ) ) {
$reason = 'email';
$human = false;
}
else if( is_null( $message ) || empty( $message ) ) {
$reason = 'message';
$human = false;
}
else if( is_null( $human ) || empty( $human ) || $human !== '42' ) {
$reason = 'computer';
$human = false;
}
if( $human === '42' ) {
$subject = 'YourCustomSubject - '.$name;
$transport = Swift_SmtpTransport::newInstance( 'localhost', 25 );
$mailer = Swift_Mailer::newInstance( $transport );
$message = stripslashes( $message );
$message = Swift_Message::newInstance()
->setSubject( $subject )
->setFrom( array( $email => $name ) )
->setTo( array( 'YourEmailAddress' => 'Your Name' ) )
->setPriority( 1 )
->setBody( $message )
;
if( $mailer->send( $message ) ) {
header( 'Location: contacted.html' );
$contacted = true;
}
}
if( $contacted === false ) {
not_contacted();
}
?>
Should prevent 99% of spam.
I have not added constants, but I'm sure you can figure out where to change the script. I've removed the part where it redirects to different pages depending on what was (or was not) entered by the user (e.g., missing full name, e-mail address, message, and such). If you want a full version of the script, let me know and I'll fix the code to be more new-developer-friendly.
Note the Swift Mailer dependency.
Yes, I invented and developed a method many years ago called nocaptcha.
I tested employed it in my sites for a year then noticed google also using it.
I released it for Joomla (see
http://shop.ekerner.com/index.php/shop/joomla-nocaptcha-detail )
and since it has been copied by many platforms (see https://www.google.com.au/search?q=nocaptcha ).
I believe the git hosted version via the above link can be deployed to any site, and if you cant find a version for your site then perhaps ask my dev team for a custom solution (see: http://www.ekerner.com/ ).
Math questions are interesting alternative. You can even write your own simple math checker by using random numbers.
Here are couple of plugins:
http://www.codegravity.com/projects/mathguard
http://sw-guide.de/wordpress/plugins/math-comment-spam-protection/
Depends on the type of form spam, general bots made for spamming any form it finds can easily be foiled by a lot less obstructive measures (like "what is the name of this site?"), but if someone has made a bot targeting your site specifically you will need captchas or something equally annoying.
If cutting down spam is the immediate need, putting the form in an iframe has been effective for me.
<iframe src="contactform.php" scrolling="no" height="*" width="*"></iframe>
Set the frame's height and width a little bigger than your form's width and height. Use CSS to make the frame border 0 so users won't notice they're looking at the form within frame.

Categories