I'm using simple ajax commenting system and i dont now how to integrate recaptcha in submit page!
AJAX COMMENT.PHP
<?php
// Error reporting:
error_reporting(E_ALL^E_NOTICE);
include "connect.php";
include "comment.class.php";
/*
/ Select all the comments and populate the $comments array with objects
*/
$id = empty($_GET['id'])?0:$_GET['id'];
$comments = array();
$result = mysql_query("SELECT * FROM comments where url='$id' ORDER BY id desc");
while($row = mysql_fetch_assoc($result))
{
$comments[] = new Comment($row);
}
?>
<table width="800" border="0" class="komentar" cellpadding="0" cellspacing="0">
<tr>
<td width="480">
<div id="addCommentContainer" style="width:500px; overflow-x:hidden;">
</div>
<div id="main" style="width:500px; overflow-x:hidden;">
<?php
/*
/ Output the comments one by one:
*/
foreach($comments as $c){
echo $c->markup();
}
?>
</div>
</td>
<td valign="top" width="320">
<table width="300" border="0" cellpadding="0" cellspacing="0">
<tr>
<td height="16" background="commentfg.png" style="background-repeat:no-repeat;">
</td>
</tr>
<tr>
<td height="20" background="commentfs.png">
<form id="addCommentForm" method="post" action="">
<div style="margin-left:15px; color:white;">
<label for="name">Vase ime:  </label><br>
<input type="text" name="name" id="name" />
<p><label for="email">Email: (bice sakriven)  </label><br>
<input type="text" name="email" id="email" /></p>
<input type="hidden" name="url" id="url" value="<?php $id = empty($_GET['id'])?0:$_GET['id']; echo $id;?>"/>
<label for="body">Unesite komentar:  </label><br>
<textarea name="body" id="body" cols="30" rows="5" onKeyDown="limitText(this.form.body,this.form.countdown,200);"
onKeyUp="limitText(this.form.body,this.form.countdown,200);"></textarea><br><br>
Broj preostalih znakova:(max 200):<input readonly type="text" name="countdown" size="3" value="200">
<br>
<script type="text/javascript"
src="http://www.google.com/recaptcha/api/challenge?k=6LeQc8MSAAAAAMGe16dslbxCRu3Frs_265JhH88j">
</script>
<noscript>
<iframe src="http://www.google.com/recaptcha/api/noscript?k=6LeQc8MSAAAAAMGe16dslbxCRu3Frs_265JhH88j"
height="300" width="500" frameborder="0"></iframe><br>
<textarea name="recaptcha_challenge_field" rows="3" cols="40">
</textarea>
<input type="hidden" name="recaptcha_response_field"
value="manual_challenge">
</noscript>
<br>
<input type="submit" id="submit" value="Potvrdi" />
</div>
</form>
</td>
</tr>
<tr>
<td height="16" background="commentfd.png" style="background-repeat:no-repeat;">
</td>
</tr>
</table>
</td>
</tr>
</table>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="script.js"></script>
COMMENT.CLASS.php
<?php
class Comment
{
private $data = array();
public function __construct($row)
{
/*
/ The constructor
*/
$this->data = $row;
}
public function markup()
{
/*
/ This method outputs the XHTML markup of the comment
*/
// Setting up an alias, so we don't have to write $this->data every time:
$d = &$this->data;
$link_open = '';
$link_close = '';
// Converting the time to a UNIX timestamp:
$d['dt'] = strtotime($d['dt']);
// Needed for the default gravatar image:
$url = 'http://'.dirname($_SERVER['SERVER_NAME'].$_SERVER["REQUEST_URI"]).'/img/default_avatar.png';
return '
<div style="width:500px; overflow-x:hidden;">
<table width="500" >
<tr>
<td valign="top" width="100" height="120" background="avatar.png" style="background-repeat:no-repeat;" align="center">
<div class="avatar" style="width:100px; overflow-x:hidden; margin-top:10px; ">
'.$link_open.'
<img src="http://www.gravatar.com/avatar/'.md5($d['email']).'?size=50&default='.urlencode($url).'" />
'.$link_close.'
</div>
<div style="width:80px; height:40px; overflow:hidden;">
<font color="#47a5db">'.$link_open.$d['name'].$link_close.'</font>
</div>
</td>
<td width="400" valign="top">
<table width="400" border="0" cellpadding="0" cellspacing="0">
<tr>
<td height="20" valign="bottom" background="commentg.png" style="background-repeat:no-repeat;">
<div class="date" title="Added at '.date('H:i \o\n d M Y',$d['dt']).'" style="margin-left:10px;">
<font color="silver" size="-1">'.date('d M Y',$d['dt']).'</font>
</div>
</td>
</tr>
<tr>
<td background="comments.png" style="background-repeat:repeat-y;">
<div style="width:350px; overflow-x:hidden; margin-top:0px; margin-left:10px;">
<p><font color="white"><b>'.$d['body'].'</b></font></p>
</div>
</td>
</tr>
<tr>
<td height="20" background="commentd.png" style="background-repeat:no-repeat;">
</td>
</tr>
</table>
</td>
</tr>
</table>
</div>
';
}
public static function validate(&$arr)
{
/*
/ This method is used to validate the data sent via AJAX.
/
/ It return true/false depending on whether the data is valid, and populates
/ the $arr array passed as a paremter (notice the ampersand above) with
/ either the valid input data, or the error messages.
*/
$errors = array();
$data = array();
// Using the filter_input function introduced in PHP 5.2.0
if(!($data['email'] = filter_input(INPUT_POST,'email',FILTER_VALIDATE_EMAIL)))
{
$errors['email'] = 'Unesite validan Email!';
}
if(!($data['url'] = filter_input(INPUT_POST,'url',FILTER_CALLBACK,array('options'=>'Comment::validate_text'))))
{
// If the URL field was not populated with a valid URL,
// act as if no URL was entered at all:
$errors['url'] = 'Please enter a url.';
}
// Using the filter with a custom callback function:
if(!($data['body'] = filter_input(INPUT_POST,'body',FILTER_CALLBACK,array('options'=>'Comment::validate_text'))))
{
$errors['body'] = 'Niste uneli komentar!';
}
if(!($data['name'] = filter_input(INPUT_POST,'name',FILTER_CALLBACK,array('options'=>'Comment::validate_text'))))
{
$errors['name'] = 'Niste uneli ime!';
}
if(!empty($errors)){
// If there are errors, copy the $errors array to $arr:
$arr = $errors;
return false;
}
// If the data is valid, sanitize all the data and copy it to $arr:
foreach($data as $k=>$v){
$arr[$k] = mysql_real_escape_string($v);
}
// Ensure that the email is lower case:
$arr['email'] = strtolower(trim($arr['email']));
return true;
}
private static function validate_text($str)
{
/*
/ This method is used internally as a FILTER_CALLBACK
*/
if(mb_strlen($str,'utf8')<1)
return false;
// Encode all html special characters (<, >, ", & .. etc) and convert
// the new line characters to <br> tags:
$str = nl2br(htmlspecialchars($str));
// Remove the new line characters that are left
$str = str_replace(array(chr(10),chr(13)),'',$str);
return $str;
}
}
?>
SUBMIT.PHP
<?php
// Error reporting:
error_reporting(E_ALL^E_NOTICE);
include "connect.php";
include "comment.class.php";
/*
/ This array is going to be populated with either
/ the data that was sent to the script, or the
/ error messages.
/*/
$arr = array();
$validates = Comment::validate($arr);
if($validates)
{
/* Everything is OK, insert to database: */
mysql_query(" INSERT INTO comments(name,url,email,body)
VALUES (
'".$arr['name']."',
'".$arr['url']."',
'".$arr['email']."',
'".$arr['body']."'
)");
$arr['dt'] = date('r',time());
$arr['id'] = mysql_insert_id();
/*
/ The data in $arr is escaped for the mysql query,
/ but we need the unescaped variables, so we apply,
/ stripslashes to all the elements in the array:
/*/
$arr = array_map('stripslashes',$arr);
$insertedComment = new Comment($arr);
/* Outputting the markup of the just-inserted comment: */
echo json_encode(array('status'=>1,'html'=>$insertedComment->markup()));
}
else
{
/* Outputtng the error messages */
echo '{"status":0,"errors":'.json_encode($arr).'}';
}
?>
Generally
Call captcha script on your comment (submit) page. It sets value to session variable (e.g. $_SESSION["captcha"]).
Put text input in your submit form to get user's answer on captcha (if it's not provided with captcha script).
In submit script check if session value matches user's input.
Related
Am was already created form like this and working perfect but on last two forms not working, it displays warning-Undefined variable: reg_no and cost. Am trying to follow algorithm as previous forms but nothing happen. My goal is to update inserted data and here is my form
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Edit invoice</title>
<link rel="stylesheet" href="box_style.css" />
</head>
<body>
<?php
include ("db_con.php");
if(isset($_GET['edit_invoice'])){
$edit_i_id = $_GET['edit_invoice'];
$select_invoice = "select * from invoice where i_id='$edit_i_id'";
$run_query = mysqli_query($con, $select_invoice);
while ($row_invoice=mysqli_fetch_array($run_query)){
$i_id = $row_invoice['i_id'];
$reg_no = $row_invoice['reg_no'];
$cost = $row_invoice['cost'];
}
}
?>
<div class='form'>
<form action="" method="post" enctype="multipart/form-data" >
<table width="745" align="center" border="2">
<p style="text-align: center;"><strong><span style="text-decoration: underline;">EDIT INVOICE:</span></strong></p>
<tr>
<td align="right" bgcolor="#dbe5f1"><strong>Registration Number:</strong></td>
<td><input type="text" name="reg_no" id="reg_no" size="35" class="text" placeholder="Registration Number" value="<?php echo $reg_no; ?>" required=""/></td>
</tr>
<tr>
<td align="right" bgcolor="#dbe5f1"><strong>Cost(Tshs):</strong></td>
<td><input type="text" name="cost" id="cost" size="35" class="text" placeholder="Cost" value="<?php echo $cost; ?>" required=""/></td>
</tr>
<tr>
<td colspan="6" align="center" bgcolor="#dbe5f1" ><input type="submit" name="update" class="submit-button" value="SAVE CHANGES"></td>
</tr>
</table>
</form>
</div>
</body>
</html>
Remove while loop from your php code since update is for one record based on id
The code will be as :
if(isset($_GET['edit_invoice'])){
$edit_i_id = $_GET['edit_invoice'];
$select_invoice = "select * from invoice where i_id='$edit_i_id'";
$run_query = mysqli_query($con, $select_invoice);
$row_invoice = mysqli_fetch_array($run_query);
$i_id = $row_invoice['i_id'];
$reg_no = $row_invoice['reg_no'];
$cost = $row_invoice['cost'];
}
if isset($_GET['edit_invoice']) is false, your $reg_no is not present in later script (where you want to echo it).
Put $reg_no above your isset($_GET...) check and set it null or empty string.
$reg_no = null;
if (isset($_GET['edit_invoice'])) {
// your code...
}
Edit: Do the same for $cost and $i_id ;)
PLEASE consider Tom Uddings comment with SQL injections!
At present I have set 4 variables, the values of which are then stored into mysql. This works fine. However, I don't want to set the values but write a line of code that takes these values from my form (on the same page). I have set the form method to POST and added specialchars to help security. Can someone pretty please show me one or two lines of code so I don't have to write ="John Doe". Please remember that I am very new all of this
<?php
// Connect to the Database
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "topsecretDontTell";
$dbname = "gaming";
$connection = mysqli_connect($dbhost,$dbuser,$dbpass,$dbname);
// Show error if connection fails
if(mysqli_connect_errno()){
die("Database connection failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno() .")"
);
}
?>
<?php
// ordertbl
$customer_name = "John Doe";
$game_id = 3;
$reservation_start = "2015-01-05";
$requested_days = 1;
// removes single quotes (escapes strings)
$customer_name = mysqli_real_escape_string($connection, $customer_name);
//add into ordertbl
$query = "INSERT INTO ordertbl (customer_name,game_id,reservation_start,requested_days) VALUES ('{$customer_name}',{$game_id},'{$reservation_start}', {$requested_days})";
//Run query and test if there was a query error
$result = mysqli_query($connection, $query);
if (!$result) {
die("Database query failed.");
}
?>
<?php
//determine the name of the game via its id using a function
function GameTitle ($game_id){
$message = "";
if ($gameid ==1){
$message = "Fantasy World";
}
else if ($gameid ==2){
$message = "Sir Wags A Lot";
}
else if ($gameid ==3){
$message = "Take a Path";
}
else if ($gameid ==4){
$message = "River Clean Up";
}
else if ($gameid ==5){
$message = "PinBall";
}
else if ($gameid ==6){
$message = "Ghost girl";
}
else if ($gameid ==7){
$message = "Dress up";
}
else if ($gameid ==8){
$message = "Where is my hat?";
}
else {
$message = "Invalid ID";
}
return $message;
}
?>
</body>
</html>
<!--Link to the style sheet-->
<link href="styles.css" rel="stylesheet" type="text/css">
</head>
<!--Create Header (logo, title and navigation bar)-->
<body>
<div id='main'>
<div id='titleImage'><img title='Home' src='images/GLLogo.png' width='700' height='190' alt='Games Library Title' /></div>
<div id='menu-wrapper'>
<div id='menu'>
<ul>
<li><a href='index.html'>Home</a></li>
<li class='current_page_item'><a href='#'>Reservations</a></li>
</ul>
</div>
</div>
<!--Make the form-->
<div class="form">
<h1>Reservations</h1>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<table width="755" border="3" cellpadding="6">
<tr>
<td width="195" align="right" bgcolor="#FF0000"><label for="customer_name">Name:</label></td>
<td width="370"><input name="customer_name" autofocus type="text" id="customer_name" size="35" maxlength="90" required autocomplete="off" /></td>
</tr>
<tr>
<td align="right" bgcolor="#FF0000"><label for="game_id">Game's ID:</label></td>
<td><input name="game_id" type="number" id="game_id" size="35" maxlength="50" min="1" /></td>
</tr>
<tr>
<td width="195" align="right" bgcolor="#FF0000"><button onClick="GameTitle(); return false">Search</button></td>
<td><input name="Result" type="text" id="demo" size="35" maxlength="50" /></td>
</tr>
<tr>
<td align="right" bgcolor="#FF0000"><label for="Loan">Number of Days you wish to borrow the Game</label></td>
<td><select name="requested_days" id="requested_days">
<option selected="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select></td>
</tr>
<tr> <!--put date into value field to get a calendar-->
<td align="right" bgcolor="#FF0000"><label for="reservation">Reservation Date:</label></td>
<td><input id="reservation_start" input name="reservation_start" type="" value="" placeholder="YYYY/MM/DD" pattern="(?:19|20)[0-9]{2}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-9])|(?:(?!02)(?:0[1-9]|1[0-2])-(?:30))|(?:(?:0[13578]|1[02])-31))" title="The date should be in the exact format: YYYY-MM-DD with leading zeros where necessary"/>
</tr>
<tr>
<td align="right" bgcolor="#FF0000"><label for="mysearch2">Enter your search string here : </label></td>
<td><input {background-colour: #E5F5EF;} id="mysearch2" type="search" placeholder="search"size="35" maxlength="50"/>
</tr>
<tr>
<td align="right" bgcolor="#FF0000"><input type="reset" name="Reset" id="button" value="Reset Form" /></td>
<td><input type="submit" name="button2" id="button2" value="Submit Form" /></td>
</tr>
</table>
</form>
</div>
</div>
</body>
</html>
<?php
// get rid of data in cache and close
mysqli_close($connection);
?>
Use the following, taking the POST variable from your form's <input name="customer_name"... element:
$customer_name=stripslashes($_POST['customer_name']);
$customer_name=mysqli_real_escape_string($connection,$_POST['customer_name']);
which will allow for names containing apostrophes like John O'Reilly.
Plus, you have function GameTitle ($game_id) therefore you most likely meant to use function GameTitle ($gameid)
You should use $_POST. In that array are post data. For example:
$customer_name = $_POST['name'];
I'm trying to upload an image through php and store it in another folder of my project. I made sure that all the permissions are set. Previously,It worked fine but now I'm getting the message "not inserted!". My folder structure is as follows
I have 3 folders in my project(Admin,images and includes) at an equal level not as siblings
Below posted is my code.
<?php
session_start();
if(!$_SESSION['admin_username'])
{
header("location:login.php");
}
?>
<html>
<head>
<title>insert your comments here.</title>
<link rel = "stylesheet" href="admin_style.css">
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.0/themes/smoothness/jquery-
ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.0/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<style>
#resizable
{
width: 150px;
height: 150px;
padding: 0.5em;
}
#resizable h3
{
text-align: center;
margin: 0;
}
</style>
<script>
$(function() {
$( "#cname").resizable();
$("#postauthor").resizable();
$("#postkeywords").resizable();
$("#postcontent").resizable();
});
</script>
</head>
<body>
<div class = "header">
<h1>WELCOME TO THE ADMIN PANEL </h1>
</div>
<div class = "main">
<h1 align="center">this is where you can write your content</h1>
<form action = "insert_posts.php" method="post" class = "cmxform"
enctype="multipart/form-data" id = "posts">
<fieldset>
<table width = "600" align = "center" border="10">
<tr>
<h1 align="center">insert your posts here </h1>
</tr>
<tr>
<!--<label for="cname">post_title (required, at least 2 characters)</label>-->
<td align="center">post_title</td>
<td><input type = "text" size="30" name ="posttitle" id = 'cname' minlength =
'2' required/></td>
</tr>
<tr>
<td align="center">post_date </td>
<td><input type="text" size="30" name="postdate" id= 'datepicker' required/>
</td>
</tr>
<tr>
<td align="center">post_author</td>
<td><input type="text" size="30" name="postauthor" id='postauthor' required/>
</td>
</tr>
<tr>
<td align="center">post_image</td>
<td><input type= "file" name="postimage" required/></td>
</tr>
<tr>
<td align="center">post_keywords</td>
<td><input type="text" size="30" name="postkeywords" id = "postkeywords"
required/></td>
</tr>
<tr>
<td align="center">post_content</td>
<td><textarea cols="20" rows="20" name = "postcontent" id = "postcontent"
required/></textarea></td>
</tr>
<tr>
<td colspan="5" align="center"><input type="submit" value="submit" name =
"submit" /></td>
</tr>
</table>
</fieldset>
</form>
<script>
$("#posts").validate();
</script>
<script>
$(function() {
$( "#datepicker" ).datepicker();
});
</script>
<script>
$(function())
{
$("#datepicker").validate();
}
</script>
<?php
include("../includes/connect.php");
?>
<?php
if(isset($_POST['submit']))
{
$post_title = $_POST['posttitle'];
$post_date = explode('/',$_POST['postdate']);
$new_date = $post_date[2].'-'.$post_date[0].'-'.$post_date[1];
$post_author = $_POST['postauthor'];
$post_keywords = $_POST['postkeywords'];
$post_content = $_POST['postcontent'];
$post_image = $_FILES['postimage']['name'];
$image_tmp = $_FILES['postimage']['tmp_name'];
if(move_uploaded_file($_FILES['postimage']['tmp_name'],'../images/'.$post_image))
{
echo "inserted";
}
else
{
echo "not inserted";
}
?>
</div>
<div class = "side">
<h3>this is side bar</h3>
<div class = "small_side">
<h2><a href = "insert_posts.php"><input type = "button" value = "insertposts">
</a></h2>
<h2><input type = "button" value="logout"></h2>
<h2><a href = "view_posts.php"><input type = "button" value="view posts"
height="50"></a></h2>
<h2><a href = "remove_posts.php"><input type = "button" value="remove_posts">
</a></h2>
</div>
</div>
<div class = "footer">
<h3>this is the footer</h3>
</div>
</body>
</html>
Try printing - var_dump() - the $_FILES array, to check if anything was posted or you had an error in the client side.
In your script, before the next line:
if(move_uploaded_file($_FILES['postimage']['tmp_name'],'../images/'.$post_image))
Add one line with the following code:
var_dump($_FILES);
Run the script, and you will get a printed version of what does the array contains at that point. Then, check there if the file looks like it was correctly received (check if tmp_name and name looks good).
If these parameters looks good, it must be a permissions problem (Or the disk is full). Make sure that apache has Write permissions in the /images/ folder
I was trying to create this login form to validate on the same page. it should hide the form once the login is validated. I have been testing is, but its not showing any error.
When i click on the submit button, it just refreshes the page.
<table width="800" border="0" align="center" cellpadding="0" cellspacing="0">
<tr>
<td><?php
$DisplayForm = TRUE;
$errors = 0;
if(isset($_POST['loginForm'])){
include("dbconnect.php");
if($DBConnect !== FALSE){
$SQLstring = "SELECT userid, first_name, last_name FROM users WHERE username ='".
$_POST['uname']. "' and password = '".md5($_POST['pass'])."'";
$DisplayForm = FALSE;
$QueryResult = #mysql_query($SQLstring, $DBConnect);
echo mysql_error();
if (mysql_num_rows($QueryResult)=== 0){
echo "<p>The email address/password " .
" combination is not valid.</p>\n";
++$errors;
$DisplayForm = TRUE;
}
else
{
$DisplayForm = FALSE;
}
}
}
if ($DisplayForm)
{?>
<form id="form1" name="loginForm" method="post" action="index.php">
<table width="800" border="0" align="center" cellpadding="0" cellspacing="0">
<tr>
<td width="93" bgcolor="#DACFAF"><strong> Username:</strong></td>
<td width="149" bgcolor="#DACFAF"><label for="textfield"></label>
<input type="text" name="uname" id="textfield" /></td>
<td width="76" bgcolor="#DACFAF"><strong>Password:</strong></td>
<td width="150" bgcolor="#DACFAF"><label for="textfield2"></label>
<input type="password" name="pass" id="pass" /></td>
<td width="196" bgcolor="#DACFAF"><input type="image" name="login" src="images/login.jpg" /> </td>
<td width="68" bgcolor="#DACFAF"> </td>
<td width="68" bgcolor="#DACFAF"><strong>Register</strong> </td>
</tr>
</table>
</form>
<?php }
else {
$Row = mysql_fetch_assoc($QueryResult);
$userID = $Row['userid'];
$userName = $Row['first_name']. " ". $Row['last_name'];
echo "<p>Welcome back, $userName!</p>\n";
}
?> </td>
</tr>
</table>
You don't have a submit button.
Add the following to your form :
<input type="submit" name="formSubmit" />
Then you can check in your first isset-line: isset($_POST['uname'] && $_POST['pass']);
You could not apply isset on <form>. Try to apply isset on input field
<?php
if(isset($_POST['uname'] && isset($_POST['pass'])) {
// .. foo
}
?>
Moreover, your form is never submitted. Add <input type="submit" value="Register" />
To check if something's been posted, you should instead add a hidden input field:
<input type="hidden" name="wasSubmitted" value="true">
Then check isset($_POST['wasSubmitted']), or $_POST['submitted'] == 'true'.
Only fields are contained in the $_POST[] superglobal.
Last night I was trying to figure out how I can how I can dynamically enable and disable span#txtCaptchaDiv on my contact form at the very bottom, above the submit button.
So I added a new field to MySQL, called captcha where I wanted to 1 to show and 0 to hide
So if I add 1 to field captcha the following code will show on my form.php
<label for="code">Write code below > <span id="txtCaptchaDiv" style="color:#F00"></span><!-- this is where the script will place the generated code -->
<input type="hidden" id="txtCaptcha" /></label><!-- this is where the script will place a copy of the code for validation: this is a hidden field -->
<input type="text" name="txtInput" id="txtInput" size="30" />
If I add 0 to field captcha the captcha area will be blank on my form.php.
Can you guy help me out please?
here is my index.php code I currently have:
<?php
require_once("/config/database.php");
$con = mysql_connect($config["db_server"],$config["db_user"],$config["db_pass"]);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Email FORM</title>
</head>
<body>
<div style="width: 550px; text-align: center;">
<span style="filter:alpha(opacity=60); opacity:.6; padding-left: 10px;"><br />
<?php
$data = mysql_query("SELECT * FROM formrelated")
or die(mysql_error());
while($info = mysql_fetch_array( $data ))
Print " ".$info['welcomemsg'] . "";
?>
</span></div>
<form id="form1" name="form1" method="post" action="submit.php" onsubmit="return checkform(this);">
<table width="454" border="1" align="center" cellpadding="0" cellspacing="0">
<tr>
<td width="123">Name</td>
<td width="325">
<input name="name" type="text" />
</td>
</tr>
<tr>
<td height="21">Address</td>
<td><input name="adress" type="text" /></td>
</tr>
<tr>
<td height="21"> </td>
<td><input name="address2" type="text" /></td>
</tr>
<tr>
<td height="21">Email</td>
<td><input name="email" type="text" /></td>
</tr>
<tr>
<td height="21">Tel</td>
<td><input name="email" type="text" /></td>
</tr>
</table>
<!--- captcha code here--->
<center>
<table width="454" height="122" border="0" cellspacing="0" cellpadding="0" background="reCAPbg.png">
<tr>
<td height="73" colspan="2" align="center" valign="middle"><label for="code"><span id="txtCaptchaDiv" style="color:#333; font-size:18px;"></span><!-- this is where the script will place the generated code -->
<input type="hidden" id="txtCaptcha" /></label></td>
<td width="136" rowspan="2"> </td>
</tr>
<tr>
<td width="145"> type the code here:</td>
<td width="173" height="47" align="center"><input type="text" name="txtInput" id="txtInput" size="20" /></td>
</tr>
</table>
</center>
<!--- captcha code ends here--->
<input name="Submit" type="button" value="submit" />
</form>
<script type="text/javascript">
//Generates the captcha function
var a = Math.ceil(Math.random() * 9)+ '';
var b = Math.ceil(Math.random() * 9)+ '';
var c = Math.ceil(Math.random() * 9)+ '';
var d = Math.ceil(Math.random() * 9)+ '';
var e = Math.ceil(Math.random() * 9)+ '';
var code = a + b + c + d + e;
document.getElementById("txtCaptcha").value = code;
document.getElementById("txtCaptchaDiv").innerHTML = code;
</script>
<script type="text/javascript">
function checkform(theform){
var why = "";
if(theform.txtInput.value == ""){
why += "- Security code should not be empty.\n";
}
if(theform.txtInput.value != ""){
if(ValidCaptcha(theform.txtInput.value) == false){
why += "- Security code did not match.\n";
}
}
if(why != ""){
alert(why);
return false;
}
}
// Validate the Entered input aganist the generated security code function
function ValidCaptcha(){
var str1 = removeSpaces(document.getElementById('txtCaptcha').value);
var str2 = removeSpaces(document.getElementById('txtInput').value);
if (str1 == str2){
return true;
}else{
return false;
}
}
// Remove the spaces from the entered and generated code
function removeSpaces(string){
return string.split(' ').join('');
}
</script>
</body>
</html>
This will work for you... enjoy!
<?PHP
$query = mysql_query("SELECT captcha FROM formrelated WHERE id = '1'");
while ($row = mysql_fetch_assoc($query)) {
$captchathis = $row['captcha'];
if ($captchathis == "1") {
echo "YOUR HTML CODE HERE";
}
else {
echo "BLANK";
}
}
?>
Try it like this
<?PHP
if($mysqlResult['captcha'] === 1)
{
echo $myHtml;
}
?>
Where $mysqlResult is an array with the result from the query, $mysqlResult['captcha']is the value of the row captcha from your query and $myHtml is that HTML code you just showed on your answer.
Good luck! ;)
Reffer to
http://php.net/manual/en/
EDIT:
http://www.php.net/manual/en/language.types.array.php ( Array type on the manual )
http://www.php.net/manual/en/control-structures.if.php ( If control structure on the manual )
http://www.php.net/manual/en/ref.mysql.php ( MySQL native functions. deprecated. Preffer MySQLi )
http://www.php.net/manual/en/book.mysqli.php ( MySQLi extension )
http://www.php.net/manual/en/book.pdo.php ( PDO native php class )
Another answer to explain the basic construct of IF logic.
Suppose i have some condition i want to meet to do something; in this case, the following logic
SHOW my form with the basic inputs
IF condition 'captcha = 1' is met, SHOW input2 (captcha)
SHOW rest of the HTML
it would be like this in PHP
<?PHP
echo $myFormWithBasicInputs;
if($captcha === 1)
{
echo $input2;
}
echo $restOfHTML;
?>
In your case, $myFormWithBasicInput and $restOfHTML is already outputed as HTML. All you want to do is inject an PHP code in it to check if some condition is matched. It will be like this
<html>
<!-- MY FORM WITH BASIC INPUTS -->
<?PHP
$captcha = $mySQLresult['captchaRow'];
if($captcha === 1)
{
?>
<!-- CAPTCHA INPUT HERE -->
<?PHP
}
?>
<!-- REST OF HTML -->
</html>
be aware that this is an workaround with example code.
<?PHP
$mysql_query = "SELECT captcha FROM formrelated";
$captcha = $mySQLresult['captchaRow'];
if($captcha === 1)
{
?>
<!--- CODE---->
<table width="454" height="122" border="0" cellspacing="0" cellpadding="0" background="reCAPbg.png">
<tr>
<td height="73" colspan="2" align="center" valign="middle"><label for="code"><span id="txtCaptchaDiv" style="color:#333; font-size:18px;"></span><!-- this is where the script will place the generated code -->
<input type="hidden" id="txtCaptcha" /></label></td>
<td width="136" rowspan="2"> </td>
</tr>
<tr>
<td width="145"> type the code here:</td>
<td width="173" height="47" align="center"><input type="text" name="txtInput" id="txtInput" size="20" /></td>
</tr>
</table>
<?PHP
}
?>
<!-- REST OF HTML -->