I have a form on my website that takes input from a text area and processes it one way if it is empty (strlen = 0) and another if it has text in it.
Here is part of the form:
<form name='contact' action='contact.php' method='post'>
...
Message*<br />
<textarea name='msg' rows='10' cols='70' maxlength='2048'><?php echo $msg ?></textarea><br />
...
<input type='submit' value='Send!' id='subby' name='fatk' style='height:60px; width:300px;' />
</form>
Now the PHP code:
$msg = isset($_POST['msg'])?safeString($_POST['msg']):'';
$msg = substr($msg,0,2048);
if (strlen($msg) == 0)
echo "<h1>Test failed</h1>";
else { ... }
Here's the safestring(str) method:
function safeString($str) {
htmlentities($str);
htmlspecialchars($str);
}
Every time I submit the form, no matter how much or how little I put in the msg textarea, it always says it's empty (by echoing TEST FAILED). Also, do you know anything else I should add to my safestring() function to make my forms more secure?
You are not returning anything from safeString.
Apart from that, what safeString does is redundant (htmlentities is a superset of htmlspecialchars, and the latter does the job of protecting against XSS).
Finally, you should really not be doing this sanitization when accepting input but only when you are producing output.
Put toghether, your code should look more like
$msg = isset($_POST['msg']) ? $_POST['msg'] :'';
if ($msg == '')
echo "<h1>Test failed</h1>";
else {
echo "Received value: ".htmlspecialchars($msg);
}
You should also definitely specify the input's encoding (see third parameter of htmlspecialchars).
Related
I want to use PHP to check if $_POST["pass"] is set, and do something if it's not, and do something else if it is.... But I can't get it working, I'm sure my logic is wrong.
I have a php code that looks something like this...
if (!isset($_POST["pass"])) {
...some form with an input type text here...
if (...wrote the wrong thing in input type text...) {
echo "something is wrong....";
}
else {
$pass_var = "Pass";
$pass_var = $_POST["pass"];
}
}
else {
echo "This thing is working...";
}
If I type the right thing in my input type text, I wan't to get to "This thing is working", and if not I wan't to echo "something is wrong....".
It works almost fine, except that if I type the right thing in my form, I never get to "This thing is working...".
The page just does nothing..
I'm sure it's the
$pass_var = "Pass";
$pass_var = $_POST["pass"];
that I'm doing wrong.
I know that I could set this up in another way to make it work, but I have a large script that is set up like this, and I really want it to work...
You test in the form against the $_POST NOT being set (See the !). You want however the post to be set!
if(isset($_POST["pass"]))
{
print_r($_POST); // basic debugging -> Test the post array
echo "The form was submitted";
// ...some form with an input type text here...
if(...wrote the wrong thing in input type text...)
{
echo "something is wrong with the input....";
}
else
{
// Valid user input, process form
echo "Valid input byy the user";
$pass_var = "Pass";
$pass_var = $_POST["pass"];
}
}
else
{
echo "The form was not submitted...";
}
You can use the empty() function of php
if(!empty($_POST['pass'])){
// do something
}else{
// do something else
}
Hope this will work for you .
Make sure you have "method='POST'" in your html form else $_POST isn't accessible in php, and logic was a bit screwy, try this?
e.g.
if (!isset($_POST["pass"])) {
//no POST so echo form
echo "<form action='".$_SERVER['PHP_SELF']."' method='POST'>
<input type='text' name='txtInput' />
<input type='submit' name='pass' />
</form>";
} elseif (isset($_POST["pass"])) {
//have POST check txtInput for "right thing"
if ($_POST["txtInput"] == "wrong thing") {
echo "something is wrong....";
} elseif ($_POST["txtInput"] == "right thing") {
//$pass_var = "Pass";
$pass_var = $_POST["pass"];
echo "This thing is working...";
}
}
Well, if (!isset($_POST["pass"])) means if $_POST["pass"] is not set, so you might want to remove the '!' which stands for not.
I am trying to wrap up this contact/quote form which has same page validation but external processing. I have set up a variable to go in the form action and the variable/url changes from the same page to the processing page when the form validates. However, it is taking two clicks on the submit button to process the form after all the required fields have been filled in: All the required fields will be filled in, I click submit, the page reloads with the saved data variables and then when I hit submit agin, it finally goes through, sending the email and loading the thankyou page. I have searched the posts here and tried multiple things but have not found a solution. I am definitely not a php expert, still a newbie so this may not be the best way to accomplish this but I'd appreciate any ideas on how to finish this up. Here is what I have:
<?php
....
if (empty($Name) && empty($Company) && empty($Address1) && empty($City) && empty($State) && empty($Phone))
{
echo '<p class="tan">The fields marked with an * are required.</p>';
$Process = 'samepageurl';
}
/*else if (empty($Name) || is_numeric($Name))
{
echo '<p class="tan"><b>Please enter your name.</b></p>';
}*/
else if (empty($Company) || is_numeric($Company))
{
echo '<p class="tan"><b>Please enter your company name.</b></p>';
$Process = 'samepageurl';
}
else if (empty($Address1) || is_numeric($Address1))
{
echo '<p class="tan"><b>Please enter your address.</b></p>';
$Process = 'samepageurl';
}
else if (empty($City) || is_numeric($City))
{
echo '<p class="tan"><b>Please enter your city.</b></p>';
$Process = 'samepageurl';
}
else if (empty($State) || is_numeric($State))
{
echo '<p class="tan"><b>Please enter your state.</b></p>';
$Process = 'samepageurl';
}
else if (empty($Phone) || ctype_alpha($Phone))
{
echo '<p class="tan"><b>Please enter your phone number.</b></p>';
$Process = 'samepageurl';
}
else if (strlen($Phone) < 10 || strlen($Phone) > 12 || ctype_alpha($Phone) || ctype_space($Phone))
{
echo '<p class="tan"><b>Please enter a phone number with an area code.</b></p>';
$Process = 'samepageurl';
}
else if (isset($Name) && isset($Company) && isset($Address1) && isset($City) && isset($State) && isset($Phone))
{
$Process = 'processingurl';
}
?>
<form action="<?php echo $Process; ?>" method="post" class="print" >
<p><input type="hidden" name="recipient" value="responses#url.com"/>
<input type="hidden" name="subject" value="Web Site Response"/>
<input type="hidden" name="redirect" value="thankyou.html"/></p>
... form fields ...
</form>
Thank you in advance!
First check for missing variables, then extract and validate the variables, then serve content based on them.
<?php
function verifyPostContains(&$req) {
global $_POST;
$missing = array();
foreach($req as $var => $_) {
if(!isset($_POST[$var])) {
$missing[] = $var;
}
}
return $missing;
}
$requirements = array('name'=>'','city'=>'','state'=>'',...);
$missing = verifyPostContains($requirements);
if(count($missing)>0) {
$content = formErrorReport($missing);
sendHeaders();
echo $content;
exit();
}
// extract, making sure to sanitize
$name = sanitize($_POST["name"]);
...
$errorHtml = array();
// validate by reference. Effectively call testName($name).
if(failsValidation($name, "testName")) {
$errorHtml [] = generateError(NAME_ERROR, $name);
} else { $requirements["name"] = $name; }
if(failsValidation($city, "testCity")) {
$errorHtml [] = generateError(CITY_ERROR, $city);
} else { $requirements["city"] = $name; }
...
if(count($errorHTML)>0) {
generateErrorPage($requirements, $missing, $errorHTML);
} else { processForm($requirements); }
?>
this code assumes you have functions to do the various bits that need to be done, and has some string constants for generating error HTML.
As a newcomer you may want to google for some tutorials that explain doing form processing using PHP at the server, and JavaScript at the client. If you find a tutorial that gives you code that echos errors while it's testing the data, such as you code does, move along. It's not a good tutorial. If you find one that stops after it finds one error, move along too. If you find one that tells you to make sure the values are right in JavaScript, and then says "we already validated this at the client so we use the values directly in PHP", move along, too. Look for a tutorial that explains:
ensuring there's data in all the form fields, using JavaScript, so the submit button is disabled until there's data for all the fields.
ensuring the data matches your criteria, in PHP, so that people who just POST to your server without ever using your page don't get away with injecting all manner of fun stuff they weren't supposed to be able to do
you generate a page with all the errors explained, if there are any, and the form repopulated with the wrong data, but highlighted as wrong
you process the post request if there are no errors.
(Bonus points if the tutorial explains that a POST request is not required to actually ever generate page content as a response, other than a header that indicates whether or not the POST call was accepted or rejected.)
I have coded some alerting system.
But let's not look at the system itself, Let's look at how will the system know that the system really did sent the alert/error to the browsing user.
I have made something so when you randomly go to ?alert=name, without doing any error, it will say 'No errors'.
But if the system makes you go to ?alert=name, it will echo the error.
How I handle posts
function postComment() {
if (!empty($_POST['name']) || !empty($_POST['comment'])) {
$comment = mysql_real_escape_string(htmlentities($_POST['comment']));
$guest = mysql_real_escape_string(htmlentities($_POST['name']));
}
$guestId = 1;
if (empty($guest)) {
$alert = 1;
return header('location: index.php?alert=name');
}
if (empty($comment)) {
$alert = 2;
return header('location: index.php?alert=comment');
}
if (!isset($_COOKIE['alreadyPosted'])) {
mysql_query("INSERT INTO `comments` (`comment_guest`, `guest_id`, `comment`, `comment_date`, `comment_time`) VALUES ('$guest', '$guestId', '$comment', CURDATE(), CURTIME())") or die(mysql_error());
header('Location: index.php?action=sucess');
setcookie(alreadyPosted, $cookieId+1, time() + 60);
} else {
$alert = 3;
header('location: index.php?alert=delay');
}
}
As you see, to check if user really getting that error, I will set $alert to whatever error number it is.
And to check if hes getting the error I will use this:
if (isset($_GET['alert']) == 'name') {
if ($alert == 1) {
echo 'hai';
} else {
echo 'No errors';
}
}
You will probably wonder why I am doing it this way.., well because I use 1 function for post, and my post function goes under the form, and i want the alerts to display up to the form.
Problem:
The variable either doesn't get set to the number that it is supposed to when running the function,
or.. something is blocking it from it.. I don't know..
My guess: Because the check for errors is located up to the postComment function before the variables even get set?
<?php
if (isset($_GET['alert']) == 'name') {
if ($alert == 1) {
echo 'hai';
} else {
echo 'No errors';
}
}
?>
<form action="index.php" method="POST">
<input type="text" name="name" placeholder="Your name here" class="field">
<textarea class="textarea" name="comment" placeholder="Your comment here..."></textarea>
<input type="submit" name="send" class="blue_button" value="Post Comment">
</form><input type="submit" name="" id="margin" class="blue_button" value="See all messages">
<br />
<?php
//Show the comments
showComments();
if (isset($_POST['send'])) {
postComment();
}
if (isset($_GET['delete']) == "comment"){
deleteComment();
}
echo '<br />';
?>
If it is, what is the solution?
Thanks!
Please don't start with the story about mysql_ function, I understood & I will use PDO instead, but I am using mysql_ at the moment for testing purposes
The problem is that you're redirecting on an error, and so the $alert variable does not get carried over.
To fix the problem add the alert type to the $_GET parameters:
function postComment()
{
// ...
if (empty($guest))
{
header('location: index.php?alert=name&alert_type=1');
exit;
}
// ...
}
And then when you check for the error:
if (isset($_GET['alert']) && 'name' == $_GET['alert'])
{
if (isset($_GET['alert_type']) && '1' == $_GET['alert_type'])
{
echo 'hai';
}
else
{
echo 'No errors';
}
}
Note also that I fixed the error here:
isset($_GET['alert']) == 'name'
That doesn't do what I think you think it does. What you want is:
isset($_GET['alert']) && 'name' == $_GET['alert']
(Excuse the order of the comparison; I prefer to have variables on the right for comparisons as it will cause a parse error if you miss a = -- much better than having it run but not do what you expect)
if you are a newbie, you better consider using client side scripting (viz javascript) for validation as using server side validation will simple make the process longer. but as you are facing problems, this might give you the solution.
as you are redirecting the page to index.php?alert=name', so $alert is never set initially when the page loads itself. when you call the function postcomment(), $alert is initiated but immediately destroyed when the system redirects. And as $alert never holds a value when you randomly visit the page, it shows no error.
Ok I have this code
a script in my head.
function checkForm(e) {
if (e.keyCode == 13) {
$('#de').hide()
$.post('search.php', { name : search.searchinput.value() }, function(output) {
$('#searchpage').html(output).show();
});
}
}
and this is the html part:
<form name="search" id="searchbox">
<input name="searchinput" value="search item here..." type="text" id="inputbox" onkeydown="checkForm(event);" onclick="clickclear(this, 'search item here...')" onblur="clickrecall(this,'search item here...')"/><input id="submit" value="" OnClick="checkForm(event);" type="submit"/>
</form>
<div id="searchpage"></div>
and this the php file where the script will pass the data into.
<?
$name= $_POST['name'];
$con=mysql_connect("localhost", "root", "");
if(!$con)
{
die ('could not connect' . mysql_error());
}
mysql_select_db("juliver", $con);
$result = mysql_query("SELECT * FROM items WHERE title='$name' OR description='$name' OR type='$name'");
$vv = "";
while($row = mysql_fetch_array($result))
{
$vv .= "<div id='itemdiv2' class='gradient'>";
$vv .= "<div id='imgc'>".'<img src="Images/media/'.$row['name'].'" />'."<br/>";
$vv .= "<a href='#?w=700' id='".$row['id']."' rel='popup' class='poplight'>View full</a>"."</div>";
$vv .= "<div id='pdiva'>"."<p id='ittitle'>".$row['title']."</p>";
$vv .= "<p id='itdes'>".$row['description']."</p>";
$vv .= "<a href='".$row['link']."'>".$row['link']."</a>";
$vv .= "</div>"."</div>";
}
echo $vv;
mysql_close($con);
?>
here is the sceneraio, a user put a whatever text on the textbox name:'searchinput' and so whenever the user pressed the enter key the function checkForm(e) will execute and pass the data from the input field name:'searchinput' into the php file and then that php file will process the data into the mysql and see if the data that the script has pass into the php file is match to the mysql records and then if ever it match then the php file will pass that data back into the script and then the script will output the data to the #searchpage div.
Problem:
"all are not working" and the onclick function on the go button are not working"
please help, im stuck on this. thank you in advance.
First of all, there is a website called Jsfiddle. Paste your codes in the website and then paste the URL here. It makes your post a lot more readable.
Now, here if you are using jQuery, then why are you relying on onkeydown and onclick events? Its better to use jQuery's live function.
I have changed your code. Have a look at here. You can use live function for other events like onclick,onfocus,onblur,etc. It makes your HTML code much more cleaner and readable.
Consider using load instead of post (And remove the form tag or change input to textarea or else hitting enter will submit your form)
$('#inputbox').keypress(function(event){
var keycode = (event.keyCode ? event.keyCode : event.which);
if(keycode == '13')
{
$('div#searchpage').load('search.php',{name: $(this).val()});
}
});
you have to stop the form from submitting the data, use something like
onsubmit="return (checkForm(e))"
and double check for syntax errors, for example you have missed a Semicolon at this line
$('#de').hide()
How can I make PHP print an error inline instead of changing the entire page?
I'd like it to target #errors and fill that instead of changing everything.
The code I'm currently using is die ("Incorrect username or password.");
I'm very new to PHP so sorry if this is a pretty easy thing to do.
Put the error in a variable where you do your logic and print its contents in #errors. For example:
if (username_is_incorrect()) $error = 'Incorrect username or password.';
And in the HTML
<?php if (isset($error)):?><div id="errors"><?=$error?></div><?php endif;?>
There are 2 ways of doing it.
A real inline method is not entirely PHP-based, as it cannot be used without JavaScript and AJAX calls.
Note the irritating disadvantage of this method: you will need to re-check every field again upon receiving form data finally.
Another one will reload your page but it will be the same page with all the form fields, entered data and also freshly generated error messages. This is called POST/Redirect/GET pattern
here is a short example
<?
if ($_SERVER['REQUEST_METHOD']=='POST') {
$err = array();
//performing all validations and raising corresponding errors
if (empty($_POST['name']) $err[] = "Username field is required";
if (empty($_POST['text']) $err[] = "Comments field is required";
if (!$err) {
// if no errors - saving data
// and then redirect:
header("Location: ".$_SERVER['PHP_SELF']);
exit;
} else {
// all field values should be escaped according to HTML standard
foreach ($_POST as $key => $val) {
$form[$key] = htmlspecialchars($val);
}
} else {
$form['name'] = $form['comments'] = '';
}
include 'form.tpl.php';
?>
while in the form.tpl.php file you have your form fields, entered values and conditional output of error messages
<? if ($err): ?>
<? foreach($err as $e): ?>
<div class="err"><?=$e?></div>
<? endforeach ?>
<? endif ?>
<form>
<input type="text" name="name" value="<?=$form['name']?>">
<textarea name="comments"><?=$form['comments']?></textarea>
<input type="submit">
</form>