Dynamically enable and disable DIV via MySQL - php

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 -->

Related

Can't echo data from phpmyadmin

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!

How to validate a form in php?

I know how to validate a form in JavaScript, but not in php.
Here is my code:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Cafeteria Ordering System</title>
<style type="text/css">
#import "cafeteriastyle.css";
</style>
</head>
<body>
<?php
if(isset($_POST['btnSubmit']))
{
//2nd page
}
else
{
?>
<form name="form1" method="post">
<table width="500" border="0" align="center" class="TableBorder">
<tbody>
<tr>
<td colspan="2" align="center" class="TableTitle TableHeadingFill">Cafeteria Ordering System</td>
</tr>
<tr>
<td width="250" align="right"><p>Customer ID</p></td>
<td><input type="text" name="txtID"></td>
</tr>
<tr>
<td align="right"><p>Num. Of Items Order</p></td>
<td><input type="text" name="txtItems"></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" name="btnSubmit"></td>
</tr>
</tbody>
</table>
</form>
<?php
}
?>
</body>
</html>
I have a form call "form1", inside the form1, I have 2 textfield.
When the Submit button is clicked, I want to perform a form validation check, to make sure the both textfield is filled, and jump to the 2nd page. If textfield is empty, display a alert message and stay on the same page.
I know how to do it with JavaScript, for example:
<script language="javascript" type="text/javascript">
function formValidation()
{
if(form1.elements["Name"].value.trim() == "")
{
alert("Please enter the name");
form1.elements["Name"].select();
return false;
}
return true;
}
</script>
and just need to add onSubmit="return formValidation" into the form tag like:
<form name="form1" method="post" onSubmit="return formValidation()"> then it will working probably. But how to do that with php instead of JS?
<?php
if(isset($_POST['btnSubmit']))
{
$txnid=trim($_POST['txtID']);
$txtItems=trim($_POST['txtItems']);
if(!empty($txnid) && !empty($txtItems))
{
//2nd page
}
else
{
echo 'Both Fields are Required.';
}
}
else
{
?>
<form name="form1" method="post">
<table width="500" border="0" align="center" class="TableBorder">
<tbody>
<tr>
<td colspan="2" align="center" class="TableTitle TableHeadingFill">Cafeteria Ordering System</td>
</tr>
<tr>
<td width="250" align="right"><p>Customer ID</p></td>
<td><input type="text" name="txtID"></td>
</tr>
<tr>
<td align="right"><p>Num. Of Items Order</p></td>
<td><input type="text" name="txtItems"></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" name="btnSubmit"></td>
</tr>
</tbody>
Use zebra form http://stefangabos.ro/php-libraries/zebra-form/
it is the best
will do both php and js validation
Use this check with jquery it might be help you
function formValidation()
{
if($("input[name='name']").trim() == "")
{
alert("Please enter the name");
$("input[name='name']").focus();
return false;
}
return true;
}
Try this...
function formValidation()
{
if($("input[name='name']").val().trim() == "")
{
alert("Please Enter The Name");
return false;
}
return true;
}

Unable to upload image to the database through PHP

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

Firefox does not submit my form

I have a php application that fetches the requests from mysql database and displays them for further approval. The form is fetched from send_req.php and is displayed inside the div on showrequests.php. This is the code for send_req.php
<table style="border:0;border-color:transparent">
<tr style="background-color:lightblue">
<td>Product ID</td>
<td>Name</td>
<td>Quantity</td>
<td><input type="checkbox" name="selectAll" /></td>
<td>Authorized Quantity</td>
</tr>
<form method="post" action="send_req.php">
<?php
$reqNum = $_POST['rId'];
echo "<h3>Request # $reqNum</h3>";
$showReqs = mysql_query("Select * from request where request_number='".$reqNum."' and status=0");
while($resultA = mysql_fetch_array($showReqs))
{
$rBy = $resultA['requested_by'];
$rTime = $resultA['request_time'];
$rId = $resultA['id'];
$pId = $resultA['product_id'];
$getPrName = mysql_query("select name from products where id='$pId'");
$prN = mysql_fetch_array($getPrName);
$prName = $prN['name'];
$rQuantity = $resultA['requested_quantity'];
$status = $resultA['status'];
?>
<tr>
<input type="hidden" name="rId[]" value="<?php echo $rId; ?>"/>
<td style="background-color:orange"><input type="text" name="prId[]" value="<?php echo $pId; ?>" readonly="readonly" style="border:0px"/></td>
<td style="background-color:orange"><input type="text" name="prName[]" value="<?php echo $prName; ?>" readonly="readonly" style="border:0px"/></td>
<td style="background-color:orange"><input type="text" name="quantity[]" value="<?php echo $rQuantity; ?>" readonly="readonly" style="border:0px"/></td>
<td style="background-color:orange"></td>
<td><input type="text" name="pQuantity[]" /></td>
</tr>
<?php }
?>
<tr>
<td></td>
<td></td>
<td></td>
<input type="hidden" name="rNum" value="<?php echo $reqNum; ?>" />
<td></td>
<td><input type="submit" name="submitReq" value="Send" id="submit_req" style="backgroundColor:Transparent;border:0;color:blue;width:100;"/></td>
</tr>
</form>
</table>
<?php
echo "Requested By:$rBy at ".substr($rTime,11,18)." ".substr($rTime,0,10);
?>
This is the showrequests.php page
<html>
<head>
<script type="text/javascript">
function getRequest(ob)
{
var id = ob.id;
if(window.XMLHttpRequest)
{
ajaxOb = new XMLHttpRequest();
}
else if(window.ActiveXObject)
{
ajaxOb = new ActiveXObject("Microsoft.XMLHTTP");
}
ajaxOb.open("POST", "send_req.php");
ajaxOb.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
ajaxOb.send("rId=" + id);
ajaxOb.onreadystatechange = function()
{
if(ajaxOb.readyState == 4)
{
if(ajaxOb.status == 200)
{
document.getElementById("showTable").innerHTML = ajaxOb.responseText;
}
}
}
}
</script>
</head>
<body>
<?php
$mysql_con = mysql_connect("localhost","root","") or die("Could not connect ".mysql_error());
$mysql_db = mysql_select_db("cart",$mysql_con) or die("Unable to select db ".mysql_error());
echo "<h2 align='center'>Pending Requests</h2>";
$showReq = mysql_query("Select distinct(request_number) as rNums from request where status=0");
?>
<div style="float:left;margin-right:15px;">
<br/>
<?php
while($result = mysql_fetch_array($showReq))
{
$rNum = $result['rNums'];
?>
<input type="button" name="fetchReq" id="<?php echo $rNum; ?>" value="<?php echo "Request # $rNum"; ?>" style="margin-bottom:5px;backgroundColor:Transparent;border:0;color:blue;width:100;text-Decoration:underline" onclick="getRequest(this)"/>
<?php
echo "<br/>";
}
?>
</div>
<div id="showTable" style="float: left">
</div>
</body>
</html>
My problem now is that everything works fine in chrome and IE but the form is not submitted when i click the submit button in firefox. I am using firefox 20.0.1. Update: I have removed the html,head and body tags from send_req.php
still not working
form is not allowed inside table. Please see also
Form inside a table
Regards,
Michael
Reminder : the structure of an HTML document is :
<!-- No div before html tag -->
<!DOCTYPE html> <!-- Doctype for HTML5 ; use whatever doctype you need -->
<html>
<head>
</head>
<!-- No div before body tag -->
<body>
<!-- Divs only belongs here -->
</body>
</html>
<!-- No div after html tag -->
If you don't follow this basic structure, you're forcing the browser to interpret your invalid code (+ quirks mode when you don't provide a doctype).
Some browser guess well what you tried to do, others don't, as Firefox might.
Please use a HTML validator as W3's validator to check your syntax.

How to integrate (validate) recapcha in submit page

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:&nbsp&nbsp</label><br>
<input type="text" name="name" id="name" />
<p><label for="email">Email: (bice sakriven)&nbsp&nbsp</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:&nbsp&nbsp</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.

Categories