how do I verify this value? - php

entering total value of two numbers in a text box to prevent spam
<?php
$rand = rand(2,9);
$rand1 = rand(2,9);
echo $rand." + ".$rand1;
?>
<span class="stred">*</span>
</label>
</td>
<td>
<div class="input-container">
<input name="randm" class="intext" id="county" type="text" />
</div>
How do I verify this value of both in a POST method??

There is nothing to verify in your code. You cannot compare the received value, because you did not keep the originals. You throw away $rand and $rand1 in the snippet that you have shown.
You need to keep them in the session (don't forget session_start() beforehand) like so:
$_SESSION["rand"] = $rand + $rand1;
Then you might be able to do this when you receive the form:
if (strlen($_POST["randm"]) && ($_POST["randm"] == $_SESSION["rand"])) {
$_SESSION["rand"] = ""; // unset afterwards to prevent replays

I would use a CAPTCHA instead. With math problems, you still have to display the equation for users to solve, which opens the door for a spammer to write a script to parse the operands from your HTML, solve the math problem, and submit a POST request containing the correct answer. Automating such a script would allow for the continuous misuse of your form, a scenario which is actually not as unlikely or difficult to accomplish as one might think.
reCATCHA is a good option should you choose to go the CAPTCHA route.

Related

Cooldown on Post in PHP

I have a really basic PHP chat system. Only thing post do is adding a line with $user and $message to log.html.
But users can spam with holding enter or pressing enter multiple times. And that causes lag in website.
I want to make a cooldown system for like 0.3 seconds. If it's in cooldown, don't let user post or disable the input for 0.3 seconds.
How can I make this?
Here, my code :
index.php contains 2 things. "log.html" and these codes
<form name="message" action="">
<div class="input-group dropup" id="bottom">
<input type="usermsg" type="text" id="usermsg" maxlength="65" autocomplete="off" class="form-control" placeholder="Type your message here.">
<span class="input-group-btn">
<button class="btn btn-success" type="submit" name"submitmsg" id="submitmsg">Send</button>
</span>
</div>
</form>
And the post.php contains these codes
<?
session_start();
if(isset($_SESSION['name'])){
$text = $_POST['text'];
$sp = fopen("player_log.html", 'a');
fwrite($sp, "<div class='msgln'>[" .date("Y-m-d"). "-".date("g:i A"). " | " .$_SERVER['REMOTE_ADDR']."] <b>".$_SESSION['name']."</b>: ".stripslashes(htmlspecialchars($text))."<br></div>");
fclose($sp);
// SOME str_replace CODES FOR EMOTICONS, BANNED TEXTS ETC..
$fp = fopen("log.html", 'a');
fwrite($fp, "<div class='msgln' style='color: #BDBDBD;'><b style='color: #FFBF00;'>[Player] ".$_SESSION['name'].":</b> ".$finaltext."<br></div>");
fclose($fp);
}
?>
You could try using the setTimeout() function in JavaScript. When enter is pressed, disable the user from entering another message (I can't comment on how to do this, as you have posted none of your code). Then use the setTimeout() function to enable the input after x amount of seconds (below shows an alert after 3 seconds):
setTimeout(function(){
alert("Hello");
}, 3000);
If you want more help, expand on your question and show us some code.
Having read through the code you have posted, it could be worth doing what others have suggested - check if the content is empty and don't post it. However, this still won't stop users spamming with one letter replies. If you want to users from quickly entering messages and posting them, I believe the timeout would work best. If you want to only stop users from holding down enter, checking for empty messages would probably be better. The best solution (in my eyes) would be to use both techniques as it would stop users from quickly spamming and stop users just entering blank messages.
Disabling the input is not a good solution. It will disrupt the user experience and users gonna hate you for that.
A better approach would be to do nothing if the message is empty or contains spaces or banned characters only.
When your Users enters a message and you recieve it, just add a timestamp to a session variable. When the User sends a message again, check the timestamp in the session, with the current timestamp.
http://php.net/manual/de/datetime.gettimestamp.php
Change this
$text = $_POST['text'];
To this
$text = $_POST['text'] || exit();
This way if a user posts nothing, nothing happens.

How to set a value of input type after it was created

I have a basic question which I cant find an answer to.
i have an input text
I want to change the value by1 every time i click the button.
so, when I make a new soldier, i want it to be shown in the soldiers count.
I started programming in PhP recently.
In Java, command Im looking for would be some setText or something like that.
Here's the basic idea:
You specifically mentioned PHP so I'll give you a PHP example:
This is at the top of every page you want the form on...
<?php
session_start();
if(!isset($_SESSION['soldiers']))
$_SESSION['soldiers'] = 0;
include('form_process.php');
Then in form_process.php:
<?php
if(isset($_POST['soldiers']) && is_numeric($_POST['soldiers']))
{
if($_POST['soldiers'] == $_SESSION['soldiers'])
$_SESSION['soldiers'] ++;
else
$_SESSION['soldiers'] = $_POST['soldiers'];
}
?>
<form id="soldiers" action="" method="post">
<input type="text" name="soldiers" value="<?php echo $_SESSION['soldiers']; ?>">
<input type="submit" name="submit" value="submit">
</form>
I would do this in html and jquery personally, but you asked for PHP so here you go.
Why use sessions? Cause you said the form is on every page so you need to maintain a constant number throughout the session. Better to use a database so the number is constant across all people who may be viewing the site, but you didn't specify that in your question.
I myself don't know what value something like this could be in the state it is in. To me it sounds like you wanted a javascript type way to just update the html of an element on click, which makes a little more sense than incrementing an input value the user can just manually overwrite to begin with. But hey, the beauty of programming is it never needs to make sense to anybody per say, so long as you get whatever you want out of it.

need some help to add some captcha contact form

Hi I'm new to PHP and I would like some help please.
I 've created a contact form and i would like to add some captcha. I have created some gif images, that have numbers with some noise added on, and named the code_01.gif for no1, code_02.gif for no2 etc etc. I have put some of them on my form, staticly, for display purposes like this:
<img src="images/code_01.gif" />
<img src="images/code_07.gif" />
<img src="images/code_01.gif" />
<img src="images/code_08.gif" />
<img src="images/code_03.gif" />
<img src="images/code_07.gif" />
<input name="captcha" type="text" id="captcha" />
I would like to add some functionality to display randomly the image codes every time and also check to see if the input matches with the 6 digits that displayed.
Any help would be appreciated.
Simple PHP Captcha
This is one of the easiest CAPTCHA scripts you will ever use. While it doesn’t obscure the text, it will serve its purpose well for many people who need a low-level CAPTCHA solution. This script requires little-to-no setup. The only dependency is the PHP GD library.
It can be as simple as this to use, but it is also configurable:
<?php
session_start();
include("captcha.php");
$_SESSION['captcha'] = captcha();
echo '<img src="' . $_SESSION['captcha']['image_src'] . '" alt="CAPTCHA" />';
?>
Demo: http://labs.abeautifulsite.net/simple-php-captcha/
You can also use this: Securimage
Securimage is an open-source free PHP CAPTCHA script for generating complex images and CAPTCHA codes to protect forms from spam and abuse. It can be easily added into existing forms on your website to provide protection from spam bots. It can run on most any webserver as long as you have PHP installed, and GD support within PHP. Securimage does everything from generating the CAPTCHA images to validating the typed code. Audible codes can be streamed to the browser with Flash for the vision impaired.
Here is a simple math captha type thing I found long ago.
Advantages:
- No Images so less bandwidth usage.
- No external dependency.
FLOW PROCESS
In form.php:
Select one random number $n1
Select another random number $n2
Compute $n1 & $n2 with various math oprations and store it as $result, so that the resulant number is unpredicatble & unaligned with $n1+$n2
Echo "What is $n1 + $n2?"
Ask user to input the answer of question asked in step 4.
Add $result as hidden value in the form.
On submit, the $_POST values are processed by check.php.
In check.php:
If $_POST["answer"] is set, store it in $answer
Compute the $answer in same manner as it was computed in step 3 of form.php
Now, if $answer is equal to $_POST["result"], it is verified that User is Human.
Keep in mind that $answer is answer submitted by user & $result is our result after doing math operations on the $answer.
CODE:
File:form.php
<?php
$n1 = rand(1,15);
$n2 = rand(1,15);
//start making our result unpredictable & non-aligned with hidden value
$result = $n1+$n2;
$result = ($result*3)-2;
$result = ($result+4)*5;
$question="what is $n1 + $n2?";
?>
<form method="post" action="check.php">
<?php echo $question.PHP_EOL; ?>
<input name="answer" type="text"><br />
<input type="hidden" name="result" value="<?php echo $result; ?>">
</form>
File:check.php
<?php
if(isset($_POST["answer")){
$answer = $_POST["answer"];
// start doing same math on $answer
$answer = ($answer*3)-2;
$answer = ($answer+4)*5;
if($answer == $_POST["result"]{
// echo Hurray, you are Human..
// Do anything here..
}else{
echo "Wrong Answer";
}
Logic Implementation at http://codepad.org/2MtULNhZ
The key is in making the encoding & decoding formula harder. So that somebody looking at hidden form value result and Question should not find out the relation in between both of them.

CAPTCHA checking fail no matter i input correctly

I am using secureImage which is a simple way to implement captcha,
i follow the guideline there to add the code, however, the checking is always invalid even i have input the correct value
It is the website of that plugin, within ten lines of code:
And this is my code:
in html form
<img id="captcha" src="http://www.phpcaptcha.org/securimage3/securimage_show.php?0.6905195268336684" alt="CAPTCHA Image">
<input type="text" class="required" name="captcha_code" size="10" maxlength="6">
in verification php
include_once '../plugin/securimage/securimage.php';
$securimage = new Securimage();
if ($securimage->check($_POST['captcha_code']) == false) {
die ("<div class='alert alert-success'><strong>The security code entered was incorrect.</strong><br /><br />Please go <a href='javascript:history.go(-1)'>back</a> and try again.</div>");
}
I have checked the post value, that is exactly what i have inputted. I would like to know which data the plugin used to compare with my input, however, i can not do this by echo the $secureimage
Thank you
To compare the randomly generated image with the code entered by a user a valid session is required. Please check this quick start guide and read the section about putting session_start() on top of your PHP script.
If you are too lazy to code, maybe you can try at http://www.google.com/recaptcha. It's widely used, I think it is better than the secureimage. You can get a php implementation at this site. I am if sorry if I don't answer your questions directly, this was because mr.GolezTrol suggested to not to use it.

php secure comment logic?

Ok, this might be obvious but its not clicking quite yet. I am creating a forum/blog esque app.
I grab the posts from the database rather securely but commenting is beginning to be a little more difficult. (I could just be paranoid, right?).
How do I add a comment without exposing the id of the parent message? (like in a hidden form field or query string, or something).
I guess I am a bit paranoid that someone might go into the code with firebug or something and change the hidden form field value to something else before submitting. I guess I would have to make sure the user has permission to comment to that particular post/category?
Things to note :
The user is already logged in.
Its not a public post
I would recommend that you setup your database like so:
Comments
---------
id
encodedID
authorID
parentID
message
Then, for the form field have two hidden values, one will be the encodedID, and the second will be a hash that you make. I would recommend the hash to be:
<?php
$hash = sha1(md5($encodedID . $userID . $_SERVER['REMOTE_ADDR'] . "abc1234"));
?>
Then, when the user submits the form, validate that the hash is valid for the specific encodedID and user. Here is a brief code write up:
<?php
if(isset($_POST['submit']))
{
//Get the variables and all and sanitize the input of 'message'
if(sha1(md5($_POST['value1']. $userID . $_SERVER['REMOTE_ADDR'] . "abc1234")) == $_POST['value2'])
{
//User is valid.
}
else
{
//Invalid user.
//Document this.
}
}
$value1 = $encodedID; //Grab this from your database
$value2 = sha1(md5($value1 . $userID . $_SERVER['REMOTE_ADDR'] . "abc1234"));
?>
<form method="post" action="comment.php">
<input type="text" name="message" />
<input type="hidden" name="value1" value="<?php echo $value1; ?>" />
<input type="hidden" name="value2" value="<?php echo $value2; ?>" />
<input type="submit" name="submit" value="Comment" />
</form>
Edit: Just a small tip, but I would recommend that you change value1 and value2 to something abstract, don't call it encodedID or anything like that, just so that it confuses any users that will attempt to try and break it.
And yes md5 and sha1 are not completely secure, but for this case it will work since you want to be able to process the comments fast and efficiently.
That might be an overkill but if you really want to hide the post_id of the current message then you should consider using session. So instead of using something like this on your form:
<form action="/postcomment.php" method="post" >
<input name="post_id" type="hidden" value="123" />
<textarea name="message"></textarea>
</form>
Reduce it to something like this:
<?php $_SESSION['post_id'] = '123'; ?>
<form action="/postcomment.php" method="post" >
<textarea name="message"></textarea>
</form>
Of course this is "yucky" coding but at least you get the idea.
Oh, don't forget to validate EVERYTHING on postcomment.php. Also escape ALL string input values and make sure all numeric inouts are numbers indeed (multiply them by one?).
[EDIT: Due to insistent public demand, may I, if you please, amend the aforementioned:]
Instead of:
<?php $_SESSION['post_id'] = '123'; ?>
Generate a form id:
<?php $_SESSION['form_id'] = $_SESSION['user_id'].'_'.md5(time()); ?>
Then generate the unique post_id:
<?php $_SESSION[$_SESSION['form_id'].'_post_id'] = '123'; ?>
After submitting get the post_id:
<?php $post_id = $_SESSION[$_SESSION['form_id'].'_post_id']; ?>
you could assign the form an "id" as a hidden field and create a database table to track form ids and their associated post ids, that way when the form gets submitted you could check the post id in the db without ever sending it to the client based on the form id that is returned with the post
You're asking the wrong question here: instead of being concerned about the user getting some internal ID that means nothing outside your application, your primary concern should be about keeping them from doing anything unpleasant with it.
Imagine I just started sending POST requests to add a comment for every ID between 1 and 10,000. I'm sure to hit a real post sooner or later.
Rule #1 about writing secure web applications: Don't trust the user.
In other words, yes, you should check to make sure that they have permission to comment when you receive the results back from the from.

Categories