How can I require a captcha to load a page? - php

I would like a simple PHP captcha script that would require the user so solve a captcha to load the website page. Preferably a captcha that doesn't need a third party such as reCAPTCHA, all done locally.
EDIT: Ended up making a text box to enter the link you would like to protect and it would automatically generate a captcha protected link, and a deletion link to delete the protected link.

You can look at the example here:
https://code.tutsplus.com/tutorials/build-your-own-captcha-and-contact-form-in-php--net-5362
I would also recommend using the timer on your page since bots are becoming better at passing capchas. By timer, I mean time between landing on the page and creating an account/submitting the form.

This is VERY simple. Usually no one is going to put any effort to bypass the captcha unless you have something worth while aka $$$$.
Just post an image with a question. Like What is 345 x 100,000 + 957?
The have an small form with a <input> for them to answer.
You could have any number of images and answers.
$captcha[] = array($answer,$image);
$captcha[] = array($answer,$image);
$captcha[] = array($answer,$image);
Then
$cnt = count($captcha) - 1;
$rec = rand(0,$cnt);
$answer= captcha[$rec][0];
$image = captcha[$rec][1];
echo '<img scr="$image"/>';
echo '<form action="$url" method="post">';
echo '<input type = "text" name="answer" /></form>';
$id = intval(str_replace('.','',$_SERVER['REMOTE_ADDR']));
file_put_contents("$id.txt",$answer);
The in the $url page:
$id = intval(str_replace('.','',$_SERVER['REMOTE_ADDR']));
$answer = intval(file_get_contents("$id.txt"));
unlink("$id.txt");
$pass = false;
if $answer == intval($_POST['answer']){$pass = true;}

Related

Custom easy chat, jquery form submit and auto refresh

I have a small chat application for internal usage, this is light version just for example. I need few things, sorry for asking full source code but I try understand and learn from this example (I need it for few things).
Please find my source code:
<?php
if(isset($_GET['opt']))
{
if($_GET['opt'] == 'write')
{
$entry = $_POST['chat_input'];
$data = fopen("dat.txt","a+");
fwrite($data,"$entry\n");
fclose($data);
}
}
// jQuery auto refresh start
$dat = file_get_contents ("dat.txt");
if($dat == ''){echo 'You do not chat.';}else
{
$number_of_post = substr_count($dat, "\n");
$post = explode ("\n",$dat);
for($i=0 ; $i <= $number_of_post-1 ; $i++)
{
echo 'User x wrote: '.$post[$i].'<br>';
}
}
// jQuery auto refresh end
// jQuery form without refresh start
echo '<form method="post" action="index.php?opt=write">
<p><textarea rows="5" name="chat_input" cols="46"></textarea></p>
<p><input type="submit" value="Submit" name="B1"></p>
</form>';
// jQuery form withour refresh end
?>
I need two things:
- first is auto refresh iframe, when user write new post code must show this
- second is post my form without refresh, just execute action
Thank you very much for help, appreciate this.
To send post without refreshing use AJAX or method POST.
To refresh iframe do as asked here: How to refresh an IFrame using Javascript?
You can refresh iframe every second
setTimeout(function(){/*yourcodehere*/ },1000);

Simple Captcha in PHP with rand()

I'm trying to make a simple captcha in PHP, but it does not work. The query is not currently executing. This is my current code:
<?php
$Random = rand(1, 100);
$Random2 = rand(1,100);
echo "Result: ".$Random." + ".$Random2." ?";
?>
<input type="text" name="r_input"/><br />
$Cap = mysql_real_escape_string($_POST['r_input']);
$Result = $Random+$Random2;
if(isset($_POST['myButton']) and trim($Var) and trim($Var2) and trim($Var3) and $Cap==$Result){
//My Query
}
When you use rand() to generate 2 values, and show those 2 values, and give the form for the user to enter the answer, ...
... the user enters the answer and submits back to the server ...
... the server gets the answer, and then GENERATES 2 NEW VALUES, that don't correspond to the answer given by the user.
Try using session variables to store the generated values in, and match against when the user submits the form!
<?php
session_start();
$captcha_id = 'captcha_' . rand();
$_SESSION['$captcha_id']['val1'] = rand(1,1000);
$_SESSION['$captcha_id']['val2'] = rand(1,1000);
echo "
<form action='' method='post'>
<p>Result: {$_SESSION['$captcha_id']['val1']} + {$_SESSION['$captcha_id']['val2']} = </p>
<input type='hidden' name='captcha_id' value='{$captcha_id}' />
<input type='text' name='captcha_answer' />
<p>?</p>
</form>
";
if (
isset($_POST['captcha_id'])
&& isset($_SESSION[$_POST['captcha_id']])
&& isset($_POST['captcha_answer'])
&& $_SESSION[$_POST['captcha_id']]['val1'] + $_SESSION[$_POST['captcha_id']]['val2'] == intval($_POST['captcha_answer'])
) {
unset($_SESSION[$_POST['captcha_id']]); // don't let this answer be reused anymore.
// do allowed stuff
}
?>
Because $Random and $Random2 have a different value each time.
When you show the form for the first time, they may have the values $Random = 12 and $Random2 = 26. The User sees those, adds them up correctly and types in 38 (which is the correct answer for those two values). The answer is sent to the script again, the values of $Random and $Random2 are generated again (this time as $Random = 23 and $Random2 = 30 which equals 53) and the answer the user has sent is not correct any more.
So you would need to store those values in hidden fields and add these up, instead of the generated ones, like so:
<input type="hidden" name="rand_1" value="<?php echo $Random; ?>">
<input type="hidden" name="rand_2" value="<?php echo $Random2; ?>">
<?php
if ($_POST['rand_1'] + $_POST['rand_2'] == $_POST['r_input']) {
// Query etc.
EDIT: As suggested by #nl-x you should use the Session variables instead of hidden fields to prevent abuse of the captcha:
<?php
$Random = $_SESSION['rand_1'] = rand(1, 100);
$Random2 = $_SESSION['rand_2'] = rand(1,100);
echo "Result: ".$Random." + ".$Random2." ?";
?>
And check those values against the given result afterwards:
<?php
$Cap = mysql_real_escape_string($_POST['r_input']);
$Result = $_SESSION['rand_1'] + $_SESSION['rand_2'];
if ($Result == $Cap) {
// ...
You never re-enter PHP mode after you output your form field:
<input type="text" name="r_input"/><br />
<?php // <----this is missing
$Cap = mysql_real_escape_string($_POST['r_input']);
Pardon me, but you are not making a real captcha. The purpose of the captcha is to distinguish the human from the bots. I would highly suggest you to pick a image database, and randomize a function to call a image. Internally, i would check if the text/description of the image matches with what the user typed.
The only thing you will rand() is what image to load from your image database.
That's a not-healthy way to do it, and there are plenty of better ways to do this. But it's more closer to a captcha than just your current code.
There is also a lot of libraries and engines that can do the job for you.
I'm not a pro at PHP, or even programming at all, but i think you're going to the wrong side - your code won't block any... malicious actions at all, or whatever kind of action that you will try to prevent with the captcha.
Search google for the libraries. PhpCaptcha is one of them. And here is a very simple quickstart guide for phpcaptcha.
Here's a code example, extracted from PHPCaptch that I linked above.
At the desired position in your form, add the following code to display the CAPTCHA image:
<img id="captcha" src="/securimage/securimage_show.php" alt="CAPTCHA Image" />
Next, add the following HTML code to create a text input box:
<input type="text" name="captcha_code" size="10" maxlength="6" />
[ Different Image ]
On the very first line of the form processor, add the following code:
<?php session_start(); ?>
The following php code should be integrated into the script that processes your form and should be placed where error checking is done. It is recommended to place it after any error checking and only attempt to validate the captha code if no other form errors occured. It should also be within tags.
include_once $_SERVER['DOCUMENT_ROOT'] . '/securimage/securimage.php';
$securimage = new Securimage();
This includes the file that contains the Securimage source code and creates a new Securimage object that is responsible for creating, managing and validating captcha codes.
Next we will check to see if the code typed by the user was entered correctly.
if ($securimage->check($_POST['captcha_code']) == false) {
// the code was incorrect
// you should handle the error so that the form processor doesn't continue
// or you can use the following code if there is no validation or you do not know how
echo "The security code entered was incorrect.<br /><br />";
echo "Please go <a href='javascript:history.go(-1)'>back</a> and try again.";
exit;
}
Following the directions above should get Securimage working with minimal effort.
This code is included here as well.
Good luck!

PHP get value from url and pass it to text field

Hi I am a jsf programmer and want to integrate a documents repositary developed using php in my jsf application. So what i am doing is when the user clicks a link from my jsf screen it gets a value for the link pass it to the php url and opens a page where the user can add docs.
I am getting the value from url and displaying it in the page. But what i want is instead of user entering the *number field(please look at the screen shot) the value from URL should pass automatically to the database as number and the number field should be removed . Please look at screen shots.
and the code snippets
<td class="ThRows">*Number</td>
$cellvalue = "";
if ((!isset($_GET["add_fd9"])) && (!isset($_POST["add_fd9"]))) {
$itemvalue = "";
} else {
$itemvalue = qsrequest($_GET["add_fd9");
then
fieldPrompts[_No] = "*Number";
pgitm_No= document.getElementsByName("add_fd9")[0];
I dont understand where to pass the url value
Try it :
$cellvalue = "";
if (!isset($_REQUEST["add_fd9"])) {
$itemvalue = "";
} else {
$itemvalue = qsrequest($_REQUEST["add_fd9"]);
}
Use
$_REQUEST
as
<input type="text" name="text1" value="<?php echo isset($_REQUEST['add_fd9'])?$_REQUEST['add_fd9']:'';?>">

symfony image inside a button?

I'm trying to include an image inside a button using symfony1.4 with this code:
<?php
echo button_to(image_tag('icon.png')."button_name",'url-goes-here');
?>
But the result i get, instead of what i want is a button with "img src=path/to/the/icon.png button_name" as the value of the button. I've google'd it long enought and found nothing, so i'll try asking here.
In other words:
i'd like to find the way to generate html similar to:<button><img src=..>Text</button> but with a symfony url associated in the onclick option
How can i do it to put an image inside a button with symfony? Am i using the helpers wrong?
Thank you for your time!
You are using Symfonys button_to function incorrectly. From the documentation:
string button_to($name, $internal_uri, $options) Creates an
button tag of the given name pointing to a routed URL
As far as I can tell, the button_to function does not allow for image buttons. Instead, you will probably create the button tag yourself and use symfonys routing to output the url.
I finally created my own helper to display this kind of buttons. I know is not very efficient and flexible but works in my case. Here is the code
function image_button_to($img,$name,$uri,$options){
$sfURL = url_for($uri);
$sfIMG = image_tag($img);
if(isset($options['confirm'])){
$confirm_text = $options['confirm'];
$jsFunction = 'if(confirm(\''.$confirm_text.'\')){ return window.location=\''.$sfURL.'\';}else{return false;}';
}else{
$jsFunction = 'window.location="'.$sfURL.'";';
}
$onclick = 'onclick="'.$jsFunction.'"';
if(isset($options['title'])){
$title = 'title=\''.$options['title'].'\' ';
}else{
$title = '';
}
if(isset($options['style'])){
$style = 'style=\''.$options['style'].'\' ';
}else{
$style = '';
}
return '<button type="button" '.$onclick.$title.$style.' >'.$sfIMG." ".$name.'</button>';
}
With this function as helper, in the templates i just have to:
<?php echo image_button_to('image.png',"button_name",'module/actionUri');?>
hope this be useful for someone ;)

Dynamic Text Using JavaScript & PHP?

I'm working on a little project, basically I have some text on my PHP/HTML page that is being echo'ed from a variable ($brief_string).
There is also a back, and continue button which basically subtracts or adds to another variable ($brief_page - which is pulled from my DB). The brief_string changes depending on the brief_page by using if statements. First problem I encounter is that when I hit continue (submit button) it resubmits/refreshes the page, causing my brief_page to reset back to 0.
So I'm thinking maybe I could use JS to hold the info and page variables and control the dynamic text, but then, how would I update my DB with the current page value via JS? Isn't it really easy to manually change/hack these values? I would preferably like my DB to be updated with the page number each time the use presses the back/continue button.
I would just like some advice really as I am a student trying to develop an interactive book like site (that uses a DB to save your current page).
Code:
<?
$brief_info = "brief info goes here";
$brief_page = 0; //< will soon be pulled off DB
if (isset($_GET['brief1Go'])) {
$brief_page = $brief_page + 1;
}
else if (isset($_GET['brief1Back'])) {
$brief_page = $brief_page - 1;
}
$breifController = "
<form action=\"".$_SERVER['PHP_SELF']."\" method=\"POST\">
<input type=\"submit\" name=\"brief1Back\" id=\"brief1Back\" value=\"BACK\" />
</form>
<form action=\"".$_SERVER['PHP_SELF']."\" method=\"POST\">
<input type=\"submit\" name=\"brief1Go\" id=\"brief1Go\" value=\"CONTINUE\" />
</form>";
if($brief_page == 0){
$brief1_info = "<b>Welcome Commander,</b> you are currently viewing the Mission Control Brief page, here you can view all your missions that you need to complete in order to advance through your prestiges. You will need to follow your briefs carefully in order to succeed. <br /><br />
";
}
else if($brief_page == 1){
$brief_info = "Okay, let me show you around the place ...";
}
else if($brief_page == 2){
$brief_info = "brief is on 2";
}
?>
Why not just use get vars entirely?
yes, start at 0 unless $_GET['page'] is set...
$brief_page = 0;
if(isset($_GET['page']))
$brief_page = $_GET['page'];
then only use links to your next and previous pages instead of some weird post thing.
Previous Next
where obviously the page numbers in the previous and next are just echoed from php
$prev = $brief_page - 1;
$next = $brief_page + 1;
The user specific things to store can easily be handled with sesisons, cookies or even other get vars if you want to introduce a horrible security hole. Your choice really.
I would definitely not do this via $_POST though. totally annoying. Go with all full on ajax if you want to do that. At least you won't pester the user with "are you sure you want to resubmit the form data" messages if they choose to refresh the page.

Categories