I have created a form where a user can add a review. Perhaps this is very obvious but how can I avoid a user inserting a url in the text area. Is there a way to check this?
I have put in a captcha to check for humans.
<form action="" method="POST" name="form">
some other input fields
<span id="sprytextarea1">
<textarea name="Comments" cols="50" rows="3" ></textarea>
<span class="textareaRequiredMsg">A value is required.</span></span></p>
<img id="captcha" src="/securimage/securimage_show.php" alt="CAPTCHA Image" /><input type="text" name="captcha_code" size="10" maxlength="6" />
[ Different Image ]
<input name="Submit" type="submit" value="Submit your form ">
<input type="hidden" name="MM_insert" value="form">
</form>
Any suggestions welcome.
Just put the if condition,before insert db.
if(preg_match("/\b(?:(?:https?|ftp|http):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$_POST['comment'])){
echo 'error please remove URLs';
}else
{....
Using PHP you can try two things using preg_match() and strip_tags() or a combination of them both. below will clean the textarea, escape it as well for database.
Once the form is submitted try this.
$post = array();
foreach($_POST as $k => $v){
// strip all HTML and escape values for database
$post[$k] = strip_tags(mysql_real_escape_string($v));
}
// check of we have URL in text area
if(preg_match('/www\.|http:|https:/'i,$post['Comments']){
// prevent form from saving code goes here
echo 'error please remove URLs';
}else{
// let form be saved
}
Simply, there is no any automatic way to check a URL in input text. You just have to use a human check for the user input.
For example: suppose that you tried to apply regex check for a URL and I want to trick it, I may able to write infinite string that shown as a URL:
http: example .com
h ttp:// ecxampleDOTcom
ht-tp: / / ecample. Com
etc
So any commenting system to achieve the ultimate spam protection, it applies moderator review in which a human being check the content.
Related
My company want to make things easier. We always create a letter for our customers to say our thank you. We have a letter that has the same content. As an example:
hi (customer_name),
thank you for doing business with us! we will contact u at (customer
number)
What I want to do is to let my staff edit the content of the letter from a form like:
Customer name: _________________
phone: _________________
[submit button]
On click of the submit button, the data from here will be saved into a DB and append to the letter just now and the letter will also saved into a DB.
<?php
if($_SERVER['REQUEST_METHOD']=='POST') {
$letter = 'hi (customer_name),
thank you for doing business with us! we will contact u at (customer_number)';
$letter = str_replace('(customer_name)', $_POST['customer_name'], $letter);
$letter .= str_replace('(customer_number)', $_POST['customer_number'], $letter);
//db save code here..
//save $letter variable into db
}
?>
<form method="post">
<input type="text" name="customer_name" /><br />
<input type="text" name="customer_number" /><br />
<input type="submit" value="Submit" />
</form>
It isn't that hard. Firstly, you need to create a form.
<form method="post" action="path/to/file.php">
<input type="text" name="customerName" placeholder="Customer Name">
<input type="text" name="phoneNumber" placeholder="Phone Number">
<input type="submit" value="Generate">
</form>
So, now when the button is clicked, the data will be sent through a POST request to the URL specified in the action attribute defined in the <form> tag. So, to fetch a value from what was entered in the form, you have to access the $_POST super global. Every single form that is submitted with the method attribute set to post, all the input fields data is moved on to the $_POST super global, and to access a specific value for a specific input field, you will have to fetch it from the index in the $_POST super global which is equal to the value specified in the input field name attribute. So, for example, to get the customer name, you would try to get it from $_POST['customerName'.
So, you can do something like this:
$string = "hi " . $_POST['customerName'] . ",<br /><br />thank you for doing business with us! we will contact u at " . $_POST['phoneNumber'];
And now, you can save this $string to your database in a table.
More information on this topic can be found here:
http://www.w3schools.com/php/php_forms.asp
http://php.net/manual/en/tutorial.forms.php
http://myphpform.com/
http://www.the-art-of-web.com/php/form-handler/
I'm creating a php-post form, containing: Who, What, Where, Contact and date_created.
I've made a database with these rows.
Here's my HTML Form code:
<form id="contactform" action="post.php">
<p class="contact"><label for="who">Who</label></p>
<input id="who" name="who" placeholder="Who are you? (First & Second name)" required="" tabindex="1" type="text">
<p class="contact"><label for="email">What</label></p>
<input id="what" name="what" placeholder="What do you want?" required="" type="text">
<p class="contact"><label for="username">Where</label></p>
<input id="where" name="where" placeholder="Country, City, Street..." required="" tabindex="2" type="text">
<p class="contact"><label for="password">Contact</label></p>
<input type="text" id="contact" name="contact" placeholder="Phone number or email"required="">
<br><br>
<input class="buttom" name="submit" id="submit" tabindex="5" value="Submit" type="submit">
And here's the php post.php code:
<?php
// Grab our POSTed form values
// Note that whatever is enclosed by $_POST[""] matches the form input elements
$who = $_POST["who"];
$what = $_POST["what"];
$where = $_POST["where"];
$contact = $_POST["contact"];
// Connect to our DB with mysql_connect(<server>, <username>, <password>)
$sql_connection = mysql_connect("server_name", "admin", "password");
mysql_select_db("database_name", $sql_connection);
$sql = "INSERT INTO content (
who,
what,
where,
contact,
date_created
)
VALUES (
'$who',
'$what',
'$where',
'$contact',
NOW()
)";
mysql_query($sql, $sql_connection);
mysql_close($sql_connection);
?>
When I try to post something, nothing is happening. The screen is just white, the database is empty and the url is like this:
http://my-website.com/post.php?who=Firstname+Secondname&what=Some+sentences+here-and&where=America&contact=some#website.com&submit=Submit%21
Just as HamZa DzCyberDeV said, you didn't specify which method you're using in <form> tag.
For situations when you're POSTing something in your database, just as you are now - use method="post" and for forms when you're searching for something, use method="get".
In case of using post method, your URL will change to only my-website.com/post.php and in case of using get method, your URL will change to something like my-website.com/post.php?... (where your things which you're getting are going) - just how you got URL after submitting.
The screen is just white because post.php (where you're going after clicking on submit button) doesn't contain anything to send to output, which you can easily do with echo.
For instance, you can make a new html page which will be written down with echo:
echo '
<html
<body>
This is my website!
</body>
</html>
';
Also, what you could do is to use include() php script which has already formed HTML, or you can check out here for some other redirect methods:
http://php.about.com/od/learnphp/ht/phpredirection.htm
Just remember that PHP is language which server is processing and only HTML tags (with CSS and JS) are sent to other browser to be read.
For more about POST and GET method you can read here:
http://php.net/manual/en/reserved.variables.post.php
http://php.net/manual/en/reserved.variables.get.php
why don't you try this to get an error or a clue to what is going wrong, enclose your code in try and catch blocks:
try {
// your code
} catch ( Exception $e ) {
echo $e->getMessage();
}
I have a basic contact form on my website and I am trying to add the PHP ucwords() function of PHP to the form for the users first_name and last_name fields so they capitalize the first letter correctly. How would I add this to the actual HTML form?
Edit: I want these changes to be applied only after the user submits the form. I don't really care about how the user types it in. I just need someone to actually show me an example.
Like how would I add the PHP ucwords() code to this simple form?
<!DOCTYPE html>
<html>
<body>
<form action="www.mysite.com" method="post">
First name: <input type="text" name="first_name" value="" /><br />
Last name: <input type="text" name="last_name" value="" /><br />
<input type="submit" value="Submit" />
</form>
</body>
</html>
I am assuming I do something like value='<php echo ucwords() ?>' but I have no idea how?
Thanks!
When user submit the form you can access the submitted information through $_POST variable [because method="post"] of PHP and in action you have to specify the actual page where you need the submitted information to be process further
<?php
// for example action="signup_process.php" and method="post"
// and input fields submitted are "first_name", "last_name"
// then u can access information like this on page "signup_process.php"
// ucwords() is used to capitalize the first letter
// of each submit input field information
$first_name = ucwords($_POST["first_name"]);
$last_name = ucwords($_POST["last_name"]);
?>
PHP Tutorials
Assuming short tags are enabled:
$firstName = 'Text to go into the form';
<input type="text" name="first_name" value="<?=ucwords($firstName)?>" />
Otherwise as you stated
<input type="text" name="first_name" value="<?php echo ucwords($firstName); ?>" />
Assuming you wanted to do it without a page refresh, you need to use Javascript. Simplest way would be to add an onkeyup event to the input field and simulate PHP's ucwords functions, which would look something like...
function ucwords(str) {
return (str + '').replace(/^([a-z])|\s+([a-z])/g, function ($1) {
return $1.toUpperCase();
});
}
Edit: In response to your edit, if you want to get the value they sent with ucwords applied, all you need to do is $newVal = ucwords($_POST['fieldName']);
How do I show a message from the php action script of a form?
The form is a user login with these fields.
<div id="register_user_box" class="inline_form" style="position: absolute; top: 20px; right: 10px; <br/>
<span id="user_msg"></span><br/>
<form action="register_user.php" method="post">
<input type="hidden" name="id" id="id" value="add" />
<input type="hidden" name="edit_user" id="edit_user" value="y" />
<table cellspacing="0px"> <tr><td>Username:</td></tr><tr><td>
<input type="text" name="uname" size="30" value="" class="inline_input"/></td> </tr> <tr><td>Email:</td></tr><tr><td>
<input type="text" name="uemail" size="30" value="" class="inline_input"/></td> </tr> <tr><td>Password:</td></tr><tr><td>
<input type="password" name="upass" size="30" class="inline_input"/></td> </tr> <tr><td>Confirm Password:</td></tr><tr> <td>
<input type="password" name="cpass" size="30" class="inline_input"/></td></tr> </table></td></tr> </table> <p>
<input class="button" type="submit" name="register" value="Register" style="float:right;"/></p>
</form>
</div>
The php script register_user.php checks the if the passwords match and shows an error message if they don't. The script checks all the other fields and prints a message if necessary.
<?php
$messages = array( 'usr_cred_req' => 'Must specify username, email, password.',
'usr_name_bad' => 'Bad username selection. Select a different usrename.',
'usr_name_exists' => 'Username selected already exists. Select a different username.',
'usr_email_bad' => 'Bad email selection. Select a different email.',
'usr_email_exists' => 'Email selected already exists. Select a different email.',
'usr_pass_notmached' => 'Passwords do not match. Type passwords again.',
'usr_not_added' => 'User not added.',
'usr_not_updated' => 'User not updated.',
'usr_added' => 'User added.'
);
$username = trim($_REQUEST['uname']);
$email = trim($_REQUEST['uemail']);
$password = md5(trim($_REQUEST['upass']));
$copasswd = md5(trim($_REQUEST['cpass']));
if ( $password != $copasswd ) { echo '<script> $("#usr_msg").html("'.$messages['usr_pass_notmached'].'"); </script>'; return;}
?>
The error message isn't shown and the browser leaves the page. I'd like the browser to stay on the page and add the error message to the span user_msg.
If you don't want the browser to leave the page when the form is submitted, then you will have to use AJAX to submit the form in the background to communicate with the server and then update the container with the error message (or something different on success).
Alternatively, have the PHP form post to itself, check the error messages before you output your HTML and if there was an error, insert the error message in the form markup in the desired location and re-populate the form with all of the values that were originally submitted.
http://jquery.malsup.com/form/
Here's a good jQuery AJAX form plugin. This will prevent page refresh upon submission.
Hope this helps.
Why are you echoing a JS script to display the error message? The way you have it written out it won't display a little popup, you just having it filling the span. A better way to do it is something like this:
if ( $password != $copasswd ) {
$display_msg = $messages['usr_pass_notmached']
}
Then in your HTML do this:
<span><?php echo $display_msg?></span>
If the variable is empty then nothing is displayed. If you do this for all the fields, then you can ensure all the information from the form is returned on error, whether the actual field IS the error or not, preventing the user from having to retype all the information again. Have the form do a $_SERVER['PHP_SELF'] to ensure it reloads the same page
I would build the PHP functionality (which can't be turned off by the user) and ensure your form works properly 100% (or close to that) of the time. Then, once you have that script working, add your JS funcionality to compliment your existing code.
What I do in mine, is I build an extra array, in this case $display_msg and I run a check of all the input fields. If a field fails, I add that to the array, $display_msg['password'] then I move on to the next field. Once all the fields have been check, I check if the $display_msg variable is empty or not. If it's not empty, then I have it fill all the span next to the input boxes with red letters explaining the error. This will print out ALL of the errors at the same time, instead of one at a time while it works it's way down the form. Next to each input I have a span with the given variable name, in this instance <?php echo $display_msg['password']?>, then next to the username, <?php echo $display_msg['username']?> and so on. Hope this is clear enough and helps.
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'] : ''; ?>" />