PHP - Implementing Recaptcha
Can someone help me please?....
I'm using this Code: [Select] <form name="form1" method="post" action="create-b.php" enctype="application/x-www-form-urlencoded" style="margin:0px"> <input name="name" value="Anonymous" type="text" MAXLENGTH="15" style="position:absolute;width:650px;left:67px;top:142px;z-index:4"> <input name="subject" value="(No subject)" MAXLENGTH="15" type="text" style="position:absolute;width:650px;left:67px;top:166px;z-index:5"> <textarea name="body" MAXLENGTH="255" type="text" style="position:absolute;left:67px;top:191px;width:650px;height:98px;z-index:6"></textarea> <div id="captcha" style="position:absolute; overflow:hidden; left:10px; top:296px; z-index:8"> <input name="submit" type="submit" value="Create thread" style="position:absolute;left:614px;top:291px;z-index:7"> <?php require_once('captc/recaptchalib.php'); $publickey = "**************************************"; echo recaptcha_get_html($publickey); ?> </form>On the HTML side and this require_once('captc/recaptchalib.php'); $privatekey = "************************"; $resp = recaptcha_check_answer ($privatekey, $_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]); if (!$resp->is_valid) { // What happens when the CAPTCHA was entered incorrectly die ("<font color='red'><font size='12'><strong><center>The verification code you entered appears to be incorrect!"); } else { CONTENT CONTENT CONTENT CONTENT CONTENT ETC But it always returns "The verification code you entered appears to be incorrect!" Any idea what I'm doing wrong?... Similar TutorialsHallo allenmaal,
Weet iemand de moeilijkheidsgraad van deze captcha code. Note! Ik heb een reden waarom ik geen reCaptcha v3 wil gebruiken..
I have a webpage which has the following: WEBPAGE <form method="post" action="http://www.xxxx.nz/Scripts/xxxxemail.php" enctype="multipart/form-data"> <div> <input type="hidden" name="redirect" value="http://xxxxxxx.net.nz/xxxxyou.php" /></div> <form> <table border="1"> <tr><td>Company Name (required)</td><td><input type="text" name="Business" /></td></tr> <tr><td>Email Address (required)</td><td><input type="text" name="Email" /></td></tr> <tr><td>Wish To Sign Up For ?</td><td><select size="1" name="xxxxxxx"> <option value="No">No</option> <option value="Yes">Yes</option> xxxxxx xxxxxx xxxxxx <input type="submit" value="Submit for Quote" /></td></tr> xxxxemail.php <?php require '/home/xxxxxz/Includes/connect.php'; /* Assign all variables passed from the form */ $business = mysql_real_escape_string($_POST['Business']); xxxxxx xxxxxx /* Sending email with information to us */ $to = "kerryxxxxx"; $subject = "xxxxx"; $random_hash = md5(date('r', time())); $headers = 'From: xxxxxxx'; $headers .= "\r\nContent-Type: multipart/alternative; boundary=\"PHP-alt-".$random_hash."\""; ob_start(); ?> --PHP-alt-<?php echo $random_hash; ?> Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: 7bit <!-- Email Content --> <? include '/home/xxxxxx/Includes/laqcquote.inc'; ?> <!-- End of Email Content --> --PHP-alt-<?php echo $random_hash; ?>-- <?php $html = ob_get_contents(); ob_end_clean(); $body = $html; mail($to, $subject, $body, $headers); /* Once Complete return to............*/ header("Location: https://xxxxxxxxxxxxxxxxxxx/qxxxxxyou.php"); ?> if I want to add the recaptcha and have it verify what do i need to do? I have code via recaptcha and it says used a verify.php. If I do that i do not have the web page going through to where I can get the data via email and it does not give me an error message. Can anyone help? This is all new to me and I am struggling to see where I put the recaptcha and to make it work if right and not work if wrong Hello How can i add google recaptcha to this code https://github.com/Tutorialwork/Tutorials/blob/master/PHP Rechtesystem/addnews.php I've tried two separate captcha options, Securimage and reCaptcha, which is the one I currently have on my page. I got the same error with each code: Quote Warning: Cannot modify header information - headers already sent by (output started at /home/jwrbloom/public_html/metroindybasketball.com/form/dbenter.php:20) in /home/jwrbloom/public_html/metroindybasketball.com/form/dbenter.php on line 101 It's a conflict with the code that moves my User to the 'next step'. Here is the code: (scroll down toward the bottom, just before the email fields) <?php require_once('/home/jwrbloom/public_html/metroindybasketball.com/recaptcha/recaptchalib.php'); $privatekey = "6LetxbwSAAAAAMP2q1q5F5S_tiEcu1sH1_dM3DTl "; $resp = recaptcha_check_answer ($privatekey, $_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]); if (!$resp->is_valid) { // What happens when the CAPTCHA was entered incorrectly die ("The reCAPTCHA wasn't entered correctly. Go back and try it again." . "(reCAPTCHA said: " . $resp->error . ")"); } else { // Your code here to handle a successful verification } ?> <?php /* connect to database */ if(!$con = mysql_connect("localhost","######","######")) { die("Could not connect to database: ".mysql_error()); } mysql_select_db("######_wpMIB", $con); $nameFirst = $_POST['nameFirst']; $nameLast = $_POST['nameLast']; $email = $_POST['email']; $addressHome = $_POST['addressHome']; $cityHome = $_POST['cityHome']; $stateHome = $_POST['stateHome']; $zipHome = $_POST['zipHome']; $phoneHome = $_POST['phoneHome']; $phoneMobile = $_POST['phoneMobile']; $school = $_POST['school']; $grade = $_POST['grade']; $coachSchool = $_POST['coachSchool']; $feet = $_POST['feet']; $inches = $_POST['inches']; /* search for existing row */ $sql = "SELECT id FROM fallLeague10 WHERE nameFirst='".mysql_real_escape_string($nameFirst)."' AND nameLast='".mysql_real_escape_string($nameLast)."' AND school='".mysql_real_escape_string($school)."'"; if(!$result = mysql_query($sql)) { die(mysql_error()."<br />Query: ".$sql); } if(mysql_num_rows($result)) { $row = mysql_fetch_assoc($result); /* update existing row */ $sql = "UPDATE fallLeague10 SET confirm='y', email='".mysql_real_escape_string($email)."', addressHome='".mysql_real_escape_string($addressHome)."', cityHome='".mysql_real_escape_string($cityHome)."', stateHome='".mysql_real_escape_string($stateHome)."', zipHome='".mysql_real_escape_string($zipHome)."', phoneHome='".mysql_real_escape_string($phoneHome)."', phoneMobile='".mysql_real_escape_string($phoneMobile)."', coachSchool='".mysql_real_escape_string($coachSchool)."', feet='".mysql_real_escape_string($feet)."', inches='".mysql_real_escape_string($inches)."' WHERE id='".$row['id']."'"; if(!$result = mysql_query($sql)) { die(mysql_error()."<br />Query: ".$sql); } } else { /* insert new row */ $sql = "INSERT INTO fallLeague10 SET confirm='y', nameFirst='".mysql_real_escape_string($nameFirst)."', nameLast='".mysql_real_escape_string($nameLast)."', email='".mysql_real_escape_string($email)."', addressHome='".mysql_real_escape_string($addressHome)."', cityHome='".mysql_real_escape_string($cityHome)."', stateHome='".mysql_real_escape_string($stateHome)."', zipHome='".mysql_real_escape_string($zipHome)."', phoneHome='".mysql_real_escape_string($phoneHome)."', phoneMobile='".mysql_real_escape_string($phoneMobile)."', school='".mysql_real_escape_string($school)."', grade='".mysql_real_escape_string($grade)."', coachSchool='".mysql_real_escape_string($coachSchool)."', feet='".mysql_real_escape_string($feet)."', inches='".mysql_real_escape_string($inches)."'"; if(!$result = mysql_query($sql)) { die(mysql_error()."<br />Query: ".$sql); } } /* redirect user HERE IS WHERE I AM HAVING MY ERROR */ header("Location:/fall-league/payment"); //exit(); ?> <?php // The message $message = $_POST['nameFirst'] . " " . $_POST['nameLast'] ." has entered the fall league.\n"; $message .= $_POST['feet'] . "'" . $_POST['inches'] ."\", " . $_POST['grade'] . "; " . $_POST['school'] ."\n"; $message .= $_POST['email']; // In case any of our lines are larger than 70 characters, we should use wordwrap() $message = wordwrap($message, 70); $headers = 'From: ' . $_POST['nameFirst'] . " " . $_POST['nameLast'] . " " . $_POST['email']; // Send mail('basketball@metroindybasketball.com', '2010 Fall League Registration', $message, $headers); ?> I have been running Google ReCaptcha v2 on 4 different sites for a very long time without any problem. They were all working fine. Not sure when as I was just recently made aware it, but none of them work anymore ??? Did google change something or is it because I updated php?? The problem is in the response - no matter what I try, I cannot verify that I am human. This is the response code:
[\code] For some reason I am no longer getting a successful response. Any help would be greatly appreciated Thanx
I am still fairly new to using phpmailer and it works but I have been asked to google recaptcha v2 checkbox into their contact form but unsure how to do that within the phpmailer code, below is what I currently have <?php // PHPMailer classes into the global namespace use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\Exception; // Base files require 'PHPMailer/src/Exception.php'; require 'PHPMailer/src/PHPMailer.php'; require 'PHPMailer/src/SMTP.php'; // create object of PHPMailer class with boolean parameter which sets/unsets exception. $mail = new PHPMailer(true); try { //$mail->isSMTP(); // using SMTP protocol $mail->Host = 'hostname'; // SMTP host as gmail $mail->SMTPAuth = true; // enable smtp authentication $mail->Username = 'emailaddress'; // sender gmail host $mail->Password = 'emailpassword'; // sender gmail host password $mail->SMTPSecure = 'ssl'; // for encrypted connection $mail->Port = 587; // port for SMTP $mail->setFrom('emailaddress', "Business Name"); // sender's email and name $mail->addAddress('emailaddress', "Business Name"); // receiver's email and name $mail->Subject = 'New Website Enquiry'; $mail->Body = "A new website enquiry has been made. The enquiry information is below" . "\r\n\r\n" . "Name: " . $_POST["name"] . "\r\n" . "Email: " . $_POST["email"] . "\r\n" . "Subject: " . $_POST["subjectline"] . "\r\n" . "Message: " . $_POST["message"]; $mail->send(); header('Location:enquiry-confirmation.php'); } catch (Exception $e) { // handle error. echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo; } ?>
I have been getting a lot of bots spamming this script, and need to add captcha to it. I am new to php and was wondering if someone would help me with this issue. Below is the script, and I really would appreciate the help. Code: [Select] <?php include "admin/conf.php"; $setting1="SELECT * FROM ".$prefix."settings"; $setting2=mysql_query($setting1) or die("Sorry, Could not select sites table"); $setting=mysql_fetch_array($setting2); include "lang/$setting[lang]/main.php"; print "<title>$lang_reg1</title>"; print "<link rel='stylesheet' href='skin/$setting[style]/style.css' type='text/css'>"; print "<body bgcolor='#FFFFFF'>"; print "<table cellpadding='0' cellspacing='0' align='center' class='outtable'><tr><td>"; /*----------------- Bread ------------------*/ print "<br /><table><tr><td width='100%'><a href='index.php'>$setting[title]</a> > $lang_reg4</td></tr></table><br />"; /*----------------- Bread End ------------------*/ print "<table cellpadding='0' cellspacing='0' align='center' width='100%'><tr><td valign='middle'><img src='skin/$setting[style]/images/pen.gif' style='vertical-align: middle;'></td> <td valign='middle'>$lang_reg1</td></tr></table>"; print "<table cellspacing='0' cellpadding='0' width='100%' align='center'><tr> <td><img src='skin/$setting[style]/images/cat_left_shadow.gif' style='vertical-align: middle;'></td> <td><img src='skin/$setting[style]/images/cat_left.gif' style='vertical-align: middle;'></td> <td class='tilecat' width='100%'><img src='skin/$setting[style]/images/tile_back.gif' style='vertical-align: middle;'></td> <td><img src='skin/$setting[style]/images/cat_right.gif' style='vertical-align: middle;'></td><td><img src='skin/$setting[style]/images/cat_right_shadow.gif' style='vertical-align: middle;'></td> </tr></table>"; print "<table cellspacing='0' cellpadding='0' width='100%' align='center'><tr> <td class='shadowL'><img src='skin/$setting[style]/images/left_shadow.gif' style='vertical-align: middle;'></td> <td width='100%'>"; print "<form name='topsite' action='source/reguser.php' method='post' onSubmit='return check_it();'>"; print "<table cellspacing='0' cellpadding='2' align='center' class='maintable'>"; print "<tr><td colspan='2' class='titlemedium' style='padding: 3px;' align='center'>$lang_reg4</td></tr>"; print "<tr><td class='tileshadow' colspan='2' align='center'><img src='skin/$setting[style]/images/spacer.gif' width='1' height='3' alt='' /></td></tr>"; print "<tr class='row5'><td nowrap valign='top'>$lang_reg5</td>"; print "<td><input type='text' name='topsiteuser' size='60'></td></tr>"; print "<tr class='row5'><td valign='top'>$lang_reg6</td>"; print "<td><input type='password' name='password' size='60'></td></tr>"; print "<tr class='row5'><td valign='top'>$lang_reg7</td>"; print "<td><input type='text' name='email' size='60'></td></tr>"; print "<tr class='row5'><td valign='top'>$lang_reg8</td>"; print "<td><input type='text' name='title' size='60'></td></tr>"; print "<tr class='row5'><td valign='top'>$lang_reg9</td>"; print "<td><input type='text' name='url' size='60' value=''></td></tr>"; print "<tr class='row5'><td valign='top'>$lang_reg10</td>"; print "<td><input type='text' name='button' size='60' value=''> <a href=\"javascript:void(window.open('http://www.imageshack.us/iframe.php?txtcolor=111111&type=blank&size=30','','height=100,width=275,left=0,top=0,toolbar=0,scrollbars=0'))\" target=\"_self\"><font face=\"Arial\" size=\"1\">UPLOAD HERE</font></a></td></tr>"; $selects="SELECT * FROM ".$prefix."categories where 1"; $selects2=mysql_query($selects) or die("Sorry, Could not select"); $selects3=mysql_fetch_array($selects2); if($selects3[ID]<1) {print"";}else { print "<tr class='row5'><td valign='top'>$lang_reg11</td>"; $selectcategory="SELECT * FROM ".$prefix."categories"; $selectcategory2=mysql_query($selectcategory) or die("Sorry, Could not select category"); print "<td><select name='catname'>"; $selectcategory="SELECT * FROM ".$prefix."categories"; $selectcategory2=mysql_query($selectcategory) or die("Sorry, Could not select category"); while($selectcategory3=mysql_fetch_array($selectcategory2)) {print "<option>$selectcategory3[catname]</option>";} print "</select></td></tr>";} print "<tr class='row5'><td width='40%' valign='top'>$lang_reg13<br>$lang_reg12</td>"; print "<td width='60%' ><textarea name='description' rows='5' cols='50'></textarea></td></tr>"; print "</table><br /><br />"; print "</td> <td class='shadowR'><img src='skin/$setting[style]/images/right_shadow.gif' style='vertical-align: middle;'></td> </tr></table>"; print"<table cellspacing='0' cellpadding='0' width='100%' align='center'><tr> <td><img src='skin/$setting[style]/images/mainfoot_left_shadow.gif' style='vertical-align: middle;'></td> <td><img src='skin/$setting[style]/images/mainfoot_left.gif' style='vertical-align: middle;'></td> <td class='footer' width='100%'><img src='skin/$setting[style]/images/mainfoot.gif' style='vertical-align: middle;'></td> <td><img src='skin/$setting[style]/images/mainfoot_right.gif' style='vertical-align: middle;'></td><td><img src='skin/$setting[style]/images/mainfoot_right_shadow.gif' style='vertical-align: middle;'></td> </tr></table><br />"; print "<table cellspacing='0' cellpadding='0' width='100%' align='center'><tr> <td><img src='skin/$setting[style]/images/cat_left_shadow.gif' style='vertical-align: middle;'></td> <td><img src='skin/$setting[style]/images/cat_left.gif' style='vertical-align: middle;'></td> <td class='tilecat' width='100%'><img src='skin/$setting[style]/images/tile_back.gif' style='vertical-align: middle;'></td> <td><img src='skin/$setting[style]/images/cat_right.gif' style='vertical-align: middle;'></td><td><img src='skin/$setting[style]/images/cat_right_shadow.gif' style='vertical-align: middle;'></td> </tr></table>"; print "<table cellspacing='0' cellpadding='0' width='100%' align='center'><tr> <td class='shadowL'><img src='skin/$setting[style]/images/left_shadow.gif' style='vertical-align: middle;'></td> <td width='100%'>"; print "<table cellspacing='0' cellpadding='2' align='center' class='maintable'>"; print "<tr><td class='titlemedium' style='padding: 3px;' align='center'>$lang_rul</td></tr>"; print "<tr><td class='tileshadow' align='center'><img src='skin/$setting[style]/images/spacer.gif' width='1' height='3' alt='' /></td></tr>"; print "<tr class='row5'><td nowrap valign='top' align='center'><textarea cols='60' rows='10'>$setting[rules]</textarea></td></tr>"; Print"<tr><td class='subs' colspan='2' align='center'><input type='submit' name='submit' value='$lang_agree'></td></tr></table></form>"; print "</td> <td class='shadowR'><img src='skin/$setting[style]/images/right_shadow.gif' style='vertical-align: middle;'></td> </tr></table>"; print"<table cellspacing='0' cellpadding='0' width='100%' align='center'><tr> <td><img src='skin/$setting[style]/images/mainfoot_left_shadow.gif' style='vertical-align: middle;'></td> <td><img src='skin/$setting[style]/images/mainfoot_left.gif' style='vertical-align: middle;'></td> <td class='footer' width='100%'><img src='skin/$setting[style]/images/mainfoot.gif' style='vertical-align: middle;'></td> <td><img src='skin/$setting[style]/images/mainfoot_right.gif' style='vertical-align: middle;'></td><td><img src='skin/$setting[style]/images/mainfoot_right_shadow.gif' style='vertical-align: middle;'></td> </tr></table><br />"; print "<table width='100%' border='0' cellspacing='0' cellpadding='0'> <tr><td colspan='$cols' nowrap style='padding: 3px;' id='runtime' ><div><span><center>$setting[magic]</center></span></div></td></tr></table>"; print "</td></tr></table>"; ?> I'm implementing google's reCAPTCHA V2. It works almost perfectly except for the following error located in the recaptchalib.php:
Notice: Use of undefined constant success - assumed 'success' in (script location)
https://github.com/g...ecaptchalib.php
Anyone got an idea how to fix this?
Edited by tork, 28 November 2014 - 04:24 PM. Why am I getting that error on Google reCAPTCHA V2 response? Hello, it's my first time posting here and I'm not good with such stuff as the one I'm posting right now I have been trying to solve this issue for 2 days by now so I could use some help lol This error "Please solve the captcha." is showing even if the captcha is verified so it's showing in the both cases (verified/unverified). Thanks in advance.
<?php require_once 'db/setting.php'; require_once 'db/odbc.php'; session_start(); error_reporting(0); if (isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == 1) || isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') { $protocol = 'https://'; } else { $protocol = 'http://'; } $currentDomain = $protocol.$_SERVER[HTTP_HOST]; $API["secret_key"] = "xx"; $API["api_key"] = "xx"; $API["callback"] = $currentDomain."/vote-reward-tok.php?return={RETURNEDCODE}"; $API["API_Domain"] = "http://api.top-kal.com"; $secretKey = 'xxx'; $captcha = $_POST['g-recaptcha-response']; $ip = $_SERVER['REMOTE_ADDR']; $responseData=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secretKey."&responseData=".$captcha."&remoteip=".$ip); $responseKeys = json_decode($responseData,true); $config["db_username"] = "sa"; $config["db_password"] = "********"; $config["db_database_account"] = "kal_auth"; $config["db_database_player"] = "kal_db"; $config["db_server"] = "NAME\SQLEXPRESS"; $config["db_driver"] = "SQL Server"; $config["Reward_Name"] = "Vote Coin"; $config["MinLvl_Require"] = 30; $config["Reward_Index"] = 447; $config["Reward_Amount"] = 10; $config["Reward_Bound"] = false;
function insertRewards($account_unique_id){ global $config; $connect = odbc_connect('Driver={'.$config["db_driver"].'};Server='.$config["db_server"].';Database='.$config["db_database_player"].';', $config['db_username'] ,$config['db_password']); if(!$connect) return false; $query = odbc_exec($connect,"SELECT Top 1 [IID] FROM [Item] Where [IID] < 1 order by IID Desc"); if(!$query) return false; $data = odbc_fetch_array($query); if($data && !empty($data) && isset($data["IID"])) odbc_exec($connect,"INSERT INTO [Item] ([PID],[IID],[Index],[Prefix],[Info],[Num])VALUES ($account_unique_id,".($data["IID"]+1).",".$config["Reward_Index"].",0,".(16+($config["Reward_Bound"] ? 128 : 0)).",".$config["Reward_Amount"].")"); } function checkCharacters($accountUID){ global $config; $connect = odbc_connect('Driver={'.$config["db_driver"].'};Server='.$config["db_server"].';Database='.$config["db_database_player"].';', $config['db_username'] ,$config['db_password']); if(!$connect) return array("error" => "failed to connect to database players."); $query = odbc_exec($connect,"SELECT [Level] FROM [Player] WHERE [UID] = $accountUID ORDER BY [Level] DESC"); if(!$query) return array("error" => "failed to find characters in this account id."); while($r = odbc_fetch_array($query)){ if($r["Level"] >= $config["MinLvl_Require"]) return array("success" => $accountUID); } return array("error" => "You should have one character at least higher than level : ".$config["MinLvl_Require"]." to vote."); } function checkAccount($accountID){ global $config; $connect = odbc_connect('Driver={'.$config["db_driver"].'};Server='.$config["db_server"].';Database='.$config["db_database_account"].';', $config['db_username'] ,$config['db_password']); if(!$connect) return array("error" => "failed to connect to database accounts."); $query = odbc_exec($connect,"SELECT TOP 1 [UID] FROM [Login] WHERE [ID] = '$accountID'"); if(!$query) return array("error" => "this account id not exists."); $data = odbc_fetch_array($query); if(!$data || empty($data) || !isset($data["UID"])) return array("error" => "this account id not exists."); if($config["MinLvl_Require"] > 0) return checkCharacters($data["UID"]); return array("success" => $data["UID"]); } >> Submitting Function $response = array("error" => false , "success" => false , 'redirect' => false); function post_content($query){ $query_array = array();foreach( $query as $key => $key_value )$query_array[] = urlencode( $key ) . '=' . urlencode( $key_value );return implode( '&', $query_array ); } global $API; $opts = array('http' => array('method' => 'POST',"header" => "Content-type: application/x-www-form-urlencoded\r\nAuthorization:".base64_encode($API["api_key"].":".$API["secret_key"])."\r\n", "content" => post_content($content)));return stream_context_create($opts); } function submit(){ global $API; if(empty($captcha) || $captcha == '' || !isset($captcha)) return array( "error" => "Please solve the captcha."); if (empty($_POST['account']) || !ctype_alnum($_POST['account'])) return array( "error" => "Invalid account id."); $checkAccount = checkAccount($_POST['account']); if (isset($checkAccount["error"])) return array("error" => $checkAccount["error"]); if (isset($checkAccount["success"])){ $account_unique_id = (isset($_SESSION['kal_id'])) ? $_SESSION['kal_id'] : $checkAccount["success"]; $result = json_decode(file_get_contents($API["API_Domain"] . '/api/generate/vote-rewards-token', false, postParams(array('callback' => $API["callback"],'account_unique_id' => $account_unique_id ))) , true); { echo '<br><center><h3>Please wait...</h3></center>'; } if (!empty($result)){ if (isset($result["response"])){ if (isset($result["response"]["error"])) return array("error" => $result["response"]["error"]); elseif (isset($result["response"]["success"])) return array("redirect" => '<script type="text/javascript">setTimeout(function () { window.location.href = "'.$result["response"]["success"].'";}, 500)</script>'); } } } } if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['account'])){ $response = submit(); if (isset($response['redirect']) && $response['redirect']){ echo $response['redirect']; die; } }elseif (isset($_GET['return'])){ $result = json_decode(file_get_contents($API["API_Domain"] . '/api/verify/vote-rewards-token', false, postParams(array('returned_code' => $_GET['return']))) , true); if (!empty($result)){ if (isset($result["response"])){ if (isset($result["response"]["error"])) $response['error'] = $result["response"]["error"]; elseif (isset($result["response"]["success"])){ insertRewards($result["response"]["account_unique_id"]); $response['success'] = '<b>Thank you, Your vote has been recorded and the server rank will be updated soon.<b><br />You will receive your rewards in storage of your account.<p>Your next vote in : <b>' . $result["response"]["NextVote"] . '</b></p>'; } } } } ?>
<head> <title>Vote Rewards - <?php echo $config['serverName']; ?></title> <link rel="shortcut icon" href=images/favicon.png"> <link rel="stylesheet" href="css/vote.css"> <link rel="stylesheet" href="css/fontawesome.css"> <link rel="stylesheet" href="css/fontawesomeall.css"> <script src='https://www.google.com/recaptcha/api.js'></script> </head> <body> <form class="vote-form" method="post"> <noscript><div class="isa_error">Javascript is not enabled in your browser! Please enable it or change your browser.</div></noscript> <?php if(isset($response['error']) && $response['error']){ ?><div class="isa_error"> <?php echo $response['error'] ;?> </div> <?php } ?> <?php if(isset($response['success']) && $response['success']){ ?><div class="isa_success"> <?php echo $response['success'] ;?> </div> <?php }else{ ?> <label> <span>Account ID :</span> <input type="text" name="account" maxlength="20" <?php echo (isset($_SESSION['kal_username'])) ? 'readonly value="'.$_SESSION['kal_username'].'"' : ""; ?>" /> </label> <div class="g-recaptcha" style="margin:0 auto;" data-sitekey="xxx" data-theme="dark"></div> <label class="label_btn"> <input type="submit" class="button" value="Vote" /> </label> <?php } ?> </form> <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script> </body> </html> Edited October 13, 2019 by requinix we don't do markdown. please use the Code <> button for code I cannot redirect to other page even I enter correct information and recaptcha in activation form. Anyone who can check what going wrong in my activation script?
Here is my php activation check script:
<?php I am a php newbie and with help from someone on this forum managed to get my php form working. I am now trying to add recaptcha 3 but can't get it to work. I have added my code to this post and would appreciate some pointers. <?php /* This is the Header PHP file */ ?> <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content="My Name"> <title>My Title</title> <!--Bootstrap Core CSS--> <link href="assets/css/bootstrap.min.css" rel="stylesheet"> <!--Font Awresome Icons--> <link href="https://fonts.googleapis.com/css?family=Open+Sans:400,600&display=swap" rel="stylesheet"> <!--Google Fonts--> <link href="assets/css/fontawesome/css/all.min.css" rel="stylesheet"> <!--Adobe Typekit Fonts--> <link href="https://use.typekit.net/jtf1geg.css" rel="stylesheet"> <!--Custom CSS--> <link href="assets/css/custom.css" rel="stylesheet"> <!--Favicon--> <link rel="icon" type="image/png" sizes="32x32" href="assets/img/MyFavicon32WhiteAlt.png"> <!--Google reCaptcha--> <script src="https://www.google.com/recaptcha/api.js"></script> <script> function onSubmit(token) { document.getElementById("contact-form").submit(); } </script> </head> <body> <!--HEADER--> <header class="site-header"> <!--Navbar--> <nav class="navbar"> <!-- Navbar brand --> <div class="navbar-brand"> <img src="assets/img/myLogo.png" id="wd-logo" alt="My Logo"> </div> <!-- Linking Menu Text to Collapse Button --> <div class="menu-button"> <button class="navbar-toggler button" type="button" data-toggle="collapse" data-target="#navbarSupportedContent20" aria-controls="navbarSupportedContent20" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-text">Menu</span> </button> <!-- Collapse Button --> <button class="navbar-toggler button animated-icon" type="button" data-toggle="collapse" data-target="#navbarSupportedContent20" aria-controls="navbarSupportedContent20" aria-expanded="false" aria-label="Toggle navigation"> <span></span> <span></span> <span></span> </button> <!-- Collapse Button End --> </div> <!-- Linking Menu Text to Collapse Button End --> <!-- Collapsible content --> <div class="collapse navbar-collapse" id="navbarSupportedContent20"> <!-- Links --> <ul class="navbar-nav"> <li class="nav-item"> <a class="nav-link" href="index.php">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="contact.php">About</a> </li> <li class="nav-item"> <a class="nav-link" href="contact.php">Services</a> </li> <li class="nav-item"> <a class="nav-link" href="contact.php">Our Work</a> </li> <li class="nav-item active"> <a class="nav-link" href="contact.php">Contact<span class="sr-only">(current)</span></a> </li> </ul> <!-- Links End --> </div> <!-- Collapsible Content End --> </nav> <!--Navbar End--> </header> <!--Header End--> <hr> <!--Content--> <section class="main"> <?php // This is the contact form // Message Vars $msg = ''; $msgClass = ''; // Check to see if the form has been submitted if(filter_has_var(INPUT_POST, 'submit')) { // Input Data Variables $firstname = htmlspecialchars($_POST['firstname']); $lastname = htmlspecialchars($_POST['lastname']); $phonenumber = htmlspecialchars($_POST['phonenumber']); $email = htmlspecialchars($_POST['email']); $dropdown = htmlspecialchars($_POST['selectdropdown']); $message = htmlspecialchars($_POST['message']); $checkbox = htmlspecialchars($_POST['checkbox'] ?? 0); // Check required fields if(!empty($firstname) && !empty($lastname) && !empty($phonenumber) && !empty($email) && !empty($dropdown) && !empty($message) && !empty($checkbox)) { // If passed, check email address if(filter_var($email, FILTER_VALIDATE_EMAIL) === false) { // If failed, Email address is not valid $msg = 'Please use a valid email address'; $msgClass = 'alert-danger'; } else { // Recipient email address and information to be sent to them $toEmail = 'hello@example.co.uk'; $subject = 'Contact Request from Website'; $body = '<h2>Contact Request</h2> <h4>Name</h4><p>'.$firstname. ' '.$lastname.'</p> <h4>Phone Number</h4><p>'.$phonenumber.'</p> <h4>Email Address</h4><p>'.$email.'</p> <h4>Subject</h4><p>'.$dropdown.'</p> <h4>Message</h4><p>'.$message.'</p>'; // Email Headers $headers = "MIME-VERSION: 1.0" ."\r\n"; $headers .="Content-Type:text/html;charset=UTF-8" ."\r\n"; // Additional Headers $headers .= "From: " .$firstname. "".$lastname." <".$email.">" ."\r\n"; $recaptcha_url = "https://www.google.com/recaptcha/api/siteverify"; $recaptcha_secret ="secrettoken"; $recaptcha_response = $_POST['g-recaptcha-response']; $recaptcha = file_get_contents($recaptcha_url . '?secret=' . $recaptcha_secret . '&response=' . $recaptcha_response); $recaptcha = json_decode($recaptcha, true); if($recaptcha['success'] == 1 AND $recaptcha['score'] >= 0.5 AND $recaptcha['action'] == "submit") { if(mail($toEmail, $subject, $body, $headers)) { // Message Sent $msg = 'Verfication successful, your message has been sent'; $msgClass = 'alert-success'; } else { // Message failed $msg = 'Your message has NOT been sent'; $msgClass = 'alert-danger'; } } } } else { // Failed $msg = 'Please fill in all fields'; $msgClass = 'alert-danger'; } } ?> <div class="container clearfix content-container"> <h1 class="section-title">Contact Us</h1> <p>If you have any questions about the services we provide or would like to chat about a new website project, please get in touch using any of the options below. We would love to hear from you!</p> <!--Contact Page Row--> <div class="row"> <div class="col-lg-6 contact-details"> <div class="row"> <div class="col-lg-12"> <img src="assets/img/contact-us.jpg" class="img-responsive d-block contact-image" alt="Contact Us Image"> </div> </div> <div class="row"> <div class="col-lg-12 contact-name"> <span class="d-inline-block contact-inline-block"><i class="fas fa-user fa-2x"> </i></span> <span class="d-inline-block"><p class="contact-details">me</p></span> </div> </div> <div class="row"> <div class="col-lg-12 contact-phone"> <span class="d-inline-block contact-inline-block"><a href="tel:01234 567890"><i class="fas fa-mobile-alt fa-2x"></i></a></span> <span class="d-inline-block"><a href="tel:01234 567890"><p class="contact-details">01234 567890</a></p></span> </div> </div> <div class="row"> <div class="col-lg-12 contact-email"> <span class="d-inline-block contact-inline-block"><a href="mailhandler.php"><i class="fas fa-envelope-square fa-2x"></i></a></span> <span class="d-inline-block"><a href="mailhandler.php"><p class="contact-details">hello@wexample.co.uk</a></p></span> </div> </div> <div class="row"> <div class="col-lg-12 contact-fb"> <span class="d-inline-block contact-inline-block"><a href="https://www.facebook.com/example/" target="_blank"><i class="fab fa-facebook-square fa-2x"></a></i></span> <span class="d-inline-block"><a href="https://www.facebook.com/example/" target="_blank"><p class="contact-details">@example</a></p></span> </div> </div> </div> <!--Contact Form--> <div class="col-lg-6 contact-form d-block"> <?php if($msg != ''): ?> <div class="alert <?php echo $msgClass; ?>"><?php echo $msg; ?></div> <?php endif;?> <form method="post" action="contact.php" role="form" id="contact-form"> <div class=" row form-group"> <div class="col-lg-6"> <label for="firstnameid">First name<span class="asterisk"> *</span></label> <input type="text" name="firstname" class="form-control mb-3" id="firstnameid"> </div> <div class="col-lg-6"> <label for="lastnameid">Last name<span class="asterisk"> *</span></label> <input type="text" name="lastname" class="form-control mb-3" id="lastnameid"> </div> </div> <div class="row form-group"> <div class="col-lg-6"> <label for="phonenumber">Phone number<span class="asterisk"> *</span></label> <input type="tel" name="phonenumber" class="form-control mb-3" id="phonenumberid"> </div> <div class="col-lg-6"> <label for="emailid">Email address<span class="asterisk"> *</span></label> <input type="email" name="email" class="form-control mb-3" id="emailid"> </div> </div> <div class="row form-group"> <div class="col-lg-12"> <label for="subjectid">How can we help<span class="asterisk"> *</span></label> <select class="form-control mb-3" name="selectdropdown" id="subjectid"> <option value="">Please choose an option</option> <option value="I would like to discuss a project">I would like to discuss a project</option> <option value="Existing Web 2 Digital client enquiry">Existing client enquiry</option> <option value="General enquiry">General enquiry</option> </select> </div> </div> <div class="row form-group"> <div class="col-lg-12"> <label for="messageid">Tell us a little bit more<span class="asterisk"> *</span></label> <textarea name="message" class="form-control mb-3" id="messageid" rows="6"></textarea> </div> </div> <div class="row form-group"> <div class="col-lg-12"> <p><span class="asterisk"> *</span> indicates required field</p> </div> </div> <div class="row form-group"> <div class="col-lg-12 form-check"> <input type="checkbox" name="checkbox" class="form-check-input" id="formcheckid"> <label for="formcheckid" class=form-check-label mb-3>By checking this tickbox you have confirmed that we can collect the information in this form for the purposes outlined in our <a href="privacypolicy.php">privacy policy.</a></label> </div> </div> <div class="row form-group"> <div class="col-lg-12"> <button type="submit" name="submit" class="btn btn-primary mt-4 g-recaptcha" data-sitekey="sitetoken" data-callback='onSubmit' data-action='submit'>Send Message </button> </div> </div> </form> </div> <!--Contact Form End--> </div> <!--Contact Page Row End--> </div> <!--Container end--> <?php echo file_get_contents('footer.php'); ?>
Hi guys, I'm having problems integrating Recaptcha into an existing form. I want it all to process on the same page. I took a look on Google and found a pre-existing script which does what I want but I'm still having trouble integrating it with what I already have, form fields and the recaptcha validate seperately. Here's my script so far: before the <html> tag: Code: [Select] <?php session_start(); ?> <?php // DEMO to use reCAPTCHA library on a form // // courtesy Spectrum Nashville // http://www.spectrum-nashville.com // // provide the Public Key and Private Key for your account he define( API_PUBLIC_KEY, '6LeNt84SAAAAAAH0Et-eJpNeuYO-kRXgrpcXML36' ); define( API_PRIVATE_KEY, '6LeNt84SAAAAAMlGWZUEHqFHncRyvaYbI5YdE8BY' ); // // once the keys have been provided above, this demo should work without any further changes to the code below // // include the recaptcha library file here // require_once('recaptchalib.php'); // // the $validated variable will switch to true in the code below if a valid CAPTCHA is submitted (see code below). // do not change this. // $validated = false; ?> <?php //If the form is submitted if(isset($_POST['submit'])) { //Check to make sure that the name field is not empty if(trim($_POST['name']) == '') { $hasError = true; } else { $name = trim($_POST['name']); } //Check to make sure sure that a valid email address is submitted if(trim($_POST['email']) == '') { $hasError = true; } else if (!eregi("^[A-Z0-9._%-]+@[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email']))) { $hasError = true; } else { $email = trim($_POST['email']); } //Check to make sure comments were entered if(trim($_POST['comment']) == '') { $hasError = true; } else { if(function_exists('stripslashes')) { $comment = stripslashes(trim($_POST['comment'])); } else { $comment = trim($_POST['comment']); } } //If there is no error, send the email if(!isset($hasError)) { $emailTo = 'eevansrange@gmail.com'; //Put your own email address here $subject = "Feedback from TEST FORM"; $body = "Name: $name \n\nEmail: $email \n\nSubject: $subject \n\nComments:\n $comment"; // $body = "Enquiry type: $enquiry \n\nName: $name \n\nEmail: $email \n\nSubject: $subject \n\nComments:\n $comments"; $headers = 'From: My Site <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email; mail($emailTo, $subject, $body, $headers); $emailSent = true; } } ?> Within body tag: Code: [Select] <!-- RECAPTCHA START --> <script> // example of using JavaScript variable to provide "theme" control // of the reCAPTCHA element. This entire <script> block is optional. var RecaptchaOptions = { theme : 'blackglass', tabindex : 2 }; </script> <!-- RECAPTCHA END --> <section id="form"> <h2 class="blue">CONTACT ME</h2> <div id="form-holder"> <p class="form-instructions">Need some work doing? Have a comment? Post them below and I'll get back to you asap!</p> <?php if(isset($hasError)) { //If errors are found ?> <p class="errors">Please check you've filled out the fields correctly.</p> <?php } ?> <?php if(isset($emailSent) && $emailSent == true) { //If email is sent ?> <p class="success">Thank you <strong><?php echo $name;?></strong>, your email has been sent.</p> <?php } ?> <?php // see the form below and look for the hidden input named 'validate' to see how this works. This is a nice flag to // indicate to us that the validation should be attempted. The first time a user browses to this page, there will be // no 'validate' variable in the $_POST[] array, so no validation is attempted and no error message will be generated. // // do not change any of this code. // if( $_POST['validate'] === 'yes' ) { $response = recaptcha_check_answer( API_PRIVATE_KEY, $_SERVER['REMOTE_ADDR'], $_POST['recaptcha_challenge_field'], $_POST['recaptcha_response_field'] ); if( ! $response->is_valid ) { // // captcha failed -- display the error message // // change this to whatever message you want to display. you could even perform other form validations // and display messages about other required fields, etc., here if you want. // use the CSS in the <head> section above to determine how your error message "box" will appear. // echo '<div id="recaptcha_error_box">The reCAPTCHA failed with this message: '.$response->error.'<br />Please try again.</div>'; // by default now, let the flow-of-control fall back into the <form> below so the user can try again } else { // set $validated to true so we know later in our document not to show the form again // don't change this. $validated = true; // // YOUR CODE HERE.... // // at this point, th form was submitted with valid reCAPTCHA, so go do whatever you wanted to do. // for the demo, we'll just echo back the values from the form. // // you could also send an email message, add or update database records, etc. // ?> <?php } /* end if( ! is_valid ) */ } /* end if($_POST['validate']==='yes') */ ?> <?php if( ! $validated ) { ?> <form class="cmxform" id="commentForm" method="post" border="0" action="<?php echo $_SERVER['PHP_SELF']; ?>#form"><!-- added #form so on submit the page anchors to the form div rather than taking you back to the top of the page --> <?php require_once('recaptchalib.php'); $publickey = "6LeNt84SAAAAAAH0Et-eJpNeuYO-kRXgrpcXML36"; // you got this from the signup page echo recaptcha_get_html($publickey); ?> <!--<input type="submit" />--> <br /> <label class="required" for="name" title="Enter your name"><span>Name</span><input type="text" id="name" name="name" size="50" class="required" value="<?php echo stripslashes(htmlentities($_POST['your_name'])); ?>" /></label> <label class="required" for="email" title="Enter your email"><span>Email</span><input type="text" id="email" name="email" size="50" class="required" value="<?php echo stripslashes(htmlentities($_POST['your_email'])); ?>" /></label> <label class="required" for="comment" title="Enter your comments" size="50" value="<?php echo stripslashes(htmlentities($_POST['comment'])); ?>"> <span>Comments</span><textarea name="comment" rows="5" cols="50" class="required"></textarea> </label> <!-- CAPTCHA START --> <?php echo recaptcha_get_html(API_PUBLIC_KEY); ?> <!-- CAPTCHA END --> <input type="hidden" name="validate" value="yes" /> <!--<input type="submit" value="Try It" />--> <label for="submit" class="nocontent"><input class="submit" type="submit" name="submit" value="Try It" title="Send form" />Items marked <img src="images/required-2.png" width="12" height="12" alt="required field" /> are required fields</label> <!-- need to include the name tag =submit above for the form to process and send the email --> <!-- class="nocontent" - commmented out of above label --> </form> <?php } /* end if( ! $validated ) */ ?> </div> </section> <!-- client-side validation --> <script type="text/javascript"> jQuery(function(){ // Grab each form element jQuery("label[title]").each(function(){ jQuery(this).append("<div class=\"infopop\">"); titletext = jQuery(this).attr("title"); jQuery(this).removeAttr("title"); jQuery(".infopop",this).css({opacity:0}).html(titletext); jQuery("input",this).focus(function(){ // Mouseover doFocus(this); }).blur(function(){ // MouseOut doBlur(this); }); /* ADDED TO show errors for textarea */ jQuery("textarea",this).focus(function(){ // Mouseover doFocus(this); }).blur(function(){ // MouseOut doBlur(this); }); }); }); function doFocus(obj) { jQuery(obj).addClass("active").parents("label").addClass("active").find(".infopop").animate({opacity:1,left:492},500); } function doBlur(obj) { if (validate(obj)) { isGood(obj); } } function reportErr(obj, message) { jQuery(obj).addClass("error").parents("label").removeClass("isgood").addClass("required").addClass("error").find(".infopop").html(message).addClass("errorpop").animate({opacity:1,left:492},500); } function isGood(obj) { jQuery(obj).removeClass("error").removeClass("active").parents("label").addClass("isgood").removeClass("error").removeClass("active").find(".infopop").removeClass("errorpop").animate({opacity:0,left:513},500); } function validate(obj) { mask = jQuery.extend({textfieldmask: /^[a-z\.\s-]{5,}$/i,emailmask: /^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/i,commentsboxmask: /^[a-z\.\s-]{5,}$/i}); errmsg = jQuery.extend({textfielderr:"5 or more letters",emailerr:"Invalid address",matcherr: "Must match",commenterr: "5 or more letters"}); var masktouse = null; var mustmatch = null; switch(obj.name) { case "name": masktouse="textfieldmask"; errtouse="textfielderr"; break; case "email": masktouse="emailmask"; errtouse="emailerr"; break; case "comment": masktouse="commentsboxmask"; errtouse="commenterr"; break; } // Check that the element is a required field before validating against it. if(jQuery(obj).parents("label").hasClass("required") && masktouse) { // Set up a quick way of accessing the object we're validating pointer = jQuery(obj); // Test the value of the field against the Regular Expression if (mask[masktouse].test(pointer.val())) { // The field validated successfully! // Check to see if the field needs to match another field in the form if (mustmatch) { // It does need to match, so grab the object it needs to match matchobj = jQuery("#"+mustmatch); if (matchobj.val()!='' && matchobj.val()!=pointer.val()) { // The fields don't match, so report an error on both of them reportErr(obj,errmsg["matcherr"]); reportErr(matchobj,errmsg["matcherr"]); } else { // Either the fields match, or the other field hasn't been completed yet // If the other field has been completed, call the isGood function to clear any error message showing if (matchobj.val()!='') { isGood(matchobj);} return true; } } else { // No match is required, so return true - validation passed! return true; } } else { // The field failed to validate against the Regular Expression reportErr(obj,errmsg[errtouse]); return false; } } else { // This isn't a required field, so we won't validate it against anything return true; } } </script> Any help would be much appreciated MK I implemented google's reCAPTCHA V2 on http:// on the remote apache shared server and it worked 100%. I then changed the protocol to my shared server SSL using the same PHP script as the non-SSL script. The older version of reCaptcha had an SSL 'false' to 'true' SSL parameter, whereas I can't find one for V2. I had to use htaccess to redirect the example.com to the shared SSL server https://serverid.net/example/ which works perfectly without recCAPTCHA. I incorporated reCAPTCHA V2 and the error message where the reCAPTCHA image should be shows "ERROR: Invalid domain for site key". Hi All, Prob very simple but here goes. I've a form on a page, which needs a recaptcha field, due to design constraints however, it won't fit. I therefore need it so you fill in the form, click submit, a new window appears with the recaptcha field and a confirmation button. Once you click confirm, the form is processed and the email sent. What's the best way to do this please? The form script has the PHP to handle the emailing side. So I want to implement the concept of "entitlements" on my website for articles, but am unsure of the most efficient way to code things. @Barand looked at and was okay with my table structure, but my question deal with PHP... Here is a basic ERD of the relevant tables... MEMBER >|-------||- MEMBERSHIP_PLAN -||-------|< MEMBESHIP_PLAN_VERSION -||-------|< ENTTLEMENT >0-------||- ARTICLE
Up until now, the user would click on an Article link, and my "article.php" script would grab the Category, Sub-Category and Article slug from the URL, and go look for the particular instance of the Article in MySQL. But now I want to control who can see what - that is only Members at a certain paid level can see "premium" content.
Here are my tables...
MEMBERSHIP_PLAN - id - name
MEMBERSHIP_PLAN_VERSION - id - plan_id - version_no - start_date - end_date
ENTITLEMENT - id - plan_id - version_id -article_id
ARTICLE - id - slug - title - body
And here is how I am thinking of approaching things, but would appreciate your thoughts...
- Member clicks on a link to the article: "How to use Indexes to Tune MySQL" - article.php loads and grabs the category/Sub-Category/Slug from the URL **new** - call getMembershipPlan( ) which grabs memberID from $_SESSION, queries MySQL , and returns "Membership Plan" - call getMembershipPlanVersion( ) which takes the Member's "Membership Plan", queries MySQL, and returns current/latest version - call getArticleEntitlement( ) which takes "Membership Plan", "Membership Plan Version" and "Article Slug", queries MySQL, and returns TRUE if this member is "entitled" to view the chosen Article **end of new** - Take "Category", "Sub-Category' and "Article Slug", query MySQL, and return Article and related metadata - Populate Article on page, OR display error: "This article is only available to Premium Members..."
What do you think about this approach?
Is it a sin to have 3 PHP functions and make 3 calls to MySQL? (This relates to my last thread asking about how much to store in my SESSION variable.
Edited February 18, 2020 by SaranacLake I am trying to write a PHP script that implements the MD5 algorithm just so that I can better understand MD5's inner-workings. For those of you already familiar with how MD5 works, could you help me figure out why my script is not producing the correct output? <?php $string = ""; $a = "01100111010001010010001100000001"; // 0x67452301 $b = "11101111110011011010101110001001"; // 0xEFCDAB89 $c = "10011000101110101101110011111110"; // 0x98BADCFE $d = "00010000001100100101010001110110"; // 0x10325476 $aa = $a; $bb = $b; $cc = $c; $dd = $d; // PADDED BINARY FOR NULL STRING, I.E.: "" $binary_md5 = "10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"; $binary_md5_words = strlen($binary_md5) / 32; // SPLIT BINARY INTO 16 32-BIT WORDS for($i = 1; $i <= $binary_md5_words; $i++) { $m[] = substr($binary_md5, ($i - 1) * 32, 32); } // GENERATE T-VALUES for($i = 0; $i < 64; $i++) { $T[] = Pad(decbin(floor(4294967296 * abs(sin($i+1)))), 32); } /* // PRINT THE M[K] ARRAY echo "<h1>m[k] Array</h1><br>"; print_r($m); echo "<br><br>"; // PRINT THE T[t] ARRAY echo "<h1>T[t] Array</h1><br>"; print_r($T); echo "<br><br>"; // TEST ANDxy echo "<h1>Test ANDxy</h1><br>"; echo "$m[0]<br>$T[0]<br>"; echo ANDxy($m[0], $T[0]); echo "<br><br>"; // TEST ORxy echo "<h1>Test ORxy</h1><br>"; echo "$m[0]<br>$T[0]<br>"; echo ORxy($m[0], $T[0]); echo "<br><br>"; // TEST ADDxy echo "<h1>Test ADDxy</h1><br>"; echo "$m[0]<br>$T[0]<br>"; echo ADDxy($m[0], $T[0]); echo "<br><br>"; // TEST XORxy echo "<h1>Test XORxy</h1><br>"; echo "$m[0]<br>$T[0]<br>"; echo XORxy($m[0], $T[0]); echo "<br><br>"; // TEST NOTx echo "<h1>Test NOTx</h1><br>"; echo "$m[0]<br>"; echo NOTx($m[0]); echo "<br><br>"; // TEST SHIFTleft echo "<h1>Test SHIFTleft</h1><br>"; echo "$m[0]<br>"; echo SHIFTleft($m[0], 1); echo "<br><br>"; // TEST F echo "<h1>Test F</h1><br>"; echo "X = $m[0]<br>Y = $m[1]<br>Z = $m[2]<br>F = "; echo F($m[0], $m[1], $m[2]); $step1 = ANDxy($m[0], $m[1]); $step2 = ANDxy(NOTx($m[0]), $m[2]); $step3 = ORxy($step1, $step2); echo "<br>F = $step3"; echo "<br><br>"; // TEST H echo "<h1>Test H</h1><br>"; echo "X = $m[0]<br>Y = $m[1]<br>Z = $m[2]<br>F = "; echo H($m[0], $m[1], $m[2]); echo "<br><br>"; */ // ROUND 1 $a = ff($a, $b, $c, $d, $m, 0, 7, $T[0]); $d = ff($d, $a, $b, $c, $m, 1, 12, $T[1]); $c = ff($c, $d, $a, $b, $m, 2, 17, $T[2]); $b = ff($b, $c, $d, $a, $m, 3, 22, $T[3]); $a = ff($a, $b, $c, $d, $m, 4, 7, $T[4]); $d = ff($d, $a, $b, $c, $m, 5, 12, $T[5]); $c = ff($c, $d, $a, $b, $m, 6, 17, $T[6]); $b = ff($b, $c, $d, $a, $m, 7, 22, $T[7]); $a = ff($a, $b, $c, $d, $m, 8, 7, $T[8]); $d = ff($d, $a, $b, $c, $m, 9, 12, $T[9]); $c = ff($c, $d, $a, $b, $m, 10, 17, $T[10]); $b = ff($b, $c, $d, $a, $m, 11, 22, $T[11]); $a = ff($a, $b, $c, $d, $m, 12, 17, $T[12]); $d = ff($d, $a, $b, $c, $m, 13, 12, $T[13]); $c = ff($c, $d, $a, $b, $m, 14, 17, $T[14]); $b = ff($b, $c, $d, $a, $m, 15, 22, $T[15]); // ROUND 2 $a = gg($a, $b, $c, $d, $m, 1, 5, $T[16]); $d = gg($d, $a, $b, $c, $m, 6, 9, $T[17]); $c = gg($c, $d, $a, $b, $m, 11, 14, $T[18]); $b = gg($b, $c, $d, $a, $m, 0, 20, $T[19]); $a = gg($a, $b, $c, $d, $m, 5, 5, $T[20]); $d = gg($d, $a, $b, $c, $m, 10, 9, $T[21]); $c = gg($c, $d, $a, $b, $m, 15, 14, $T[22]); $b = gg($b, $c, $d, $a, $m, 4, 20, $T[23]); $a = gg($a, $b, $c, $d, $m, 9, 5, $T[24]); $d = gg($d, $a, $b, $c, $m, 14, 9, $T[25]); $c = gg($c, $d, $a, $b, $m, 3, 14, $T[26]); $b = gg($b, $c, $d, $a, $m, 8, 20, $T[27]); $a = gg($a, $b, $c, $d, $m, 13, 5, $T[28]); $d = gg($d, $a, $b, $c, $m, 2, 9, $T[29]); $c = gg($c, $d, $a, $b, $m, 7, 14, $T[30]); $b = gg($b, $c, $d, $a, $m, 12, 20, $T[31]); // ROUND 3 $a = hh($a, $b, $c, $d, $m, 5, 4, $T[32]); $d = hh($d, $a, $b, $c, $m, 8, 11, $T[33]); $c = hh($c, $d, $a, $b, $m, 11, 16, $T[34]); $b = hh($b, $c, $d, $a, $m, 14, 23, $T[35]); $a = hh($a, $b, $c, $d, $m, 1, 4, $T[36]); $d = hh($d, $a, $b, $c, $m, 4, 11, $T[37]); $c = hh($c, $d, $a, $b, $m, 7, 16, $T[38]); $b = hh($b, $c, $d, $a, $m, 10, 23, $T[39]); $a = hh($a, $b, $c, $d, $m, 13, 4, $T[40]); $d = hh($d, $a, $b, $c, $m, 0, 11, $T[41]); $c = hh($c, $d, $a, $b, $m, 3, 16, $T[42]); $b = hh($b, $c, $d, $a, $m, 6, 23, $T[43]); $a = hh($a, $b, $c, $d, $m, 9, 4, $T[44]); $d = hh($d, $a, $b, $c, $m, 12, 11, $T[45]); $c = hh($c, $d, $a, $b, $m, 15, 16, $T[46]); $b = hh($b, $c, $d, $a, $m, 2, 23, $T[47]); // ROUND 4 $a = ii($a, $b, $c, $d, $m, 0, 6, $T[48]); $d = ii($d, $a, $b, $c, $m, 7, 10, $T[49]); $c = ii($c, $d, $a, $b, $m, 14, 15, $T[50]); $b = ii($b, $c, $d, $a, $m, 5, 21, $T[51]); $a = ii($a, $b, $c, $d, $m, 12, 6, $T[52]); $d = ii($d, $a, $b, $c, $m, 3, 10, $T[53]); $c = ii($c, $d, $a, $b, $m, 10, 15, $T[54]); $b = ii($b, $c, $d, $a, $m, 1, 21, $T[55]); $a = ii($a, $b, $c, $d, $m, 8, 6, $T[56]); $d = ii($d, $a, $b, $c, $m, 15, 10, $T[57]); $c = ii($c, $d, $a, $b, $m, 6, 15, $T[58]); $b = ii($b, $c, $d, $a, $m, 13, 21, $T[59]); $a = ii($a, $b, $c, $d, $m, 4, 6, $T[60]); $d = ii($d, $a, $b, $c, $m, 11, 10, $T[61]); $c = ii($c, $d, $a, $b, $m, 2, 15, $T[62]); $b = ii($b, $c, $d, $a, $m, 9, 21, $T[63]); $a = ADDxy($a, $aa); $b = ADDxy($b, $bb); $c = ADDxy($c, $cc); $d = ADDxy($d, $dd); // ECHO RESULTS echo "<h1>String</h1><br>"; echo "String: '$string'<br>"; $md5 = md5($string); echo "MD5: $md5<br><br>"; $md5_1 = substr($md5, 0, 8); $md5_2 = substr($md5, 8, 8); $md5_3 = substr($md5, 16, 8); $md5_4 = substr($md5, 24, 8); echo "A = $md5_1<br>B = $md5_2<br>C = $md5_3<br>D = $md5_4<br><br>"; $md5_bin_a = Pad(decbin(hexdec($md5_1)), 32); $md5_bin_b = Pad(decbin(hexdec($md5_2)), 32); $md5_bin_c = Pad(decbin(hexdec($md5_3)), 32); $md5_bin_d = Pad(decbin(hexdec($md5_4)), 32); echo "A = $md5_bin_a<br>B = $md5_bin_b<br>C = $md5_bin_c<br>D = $md5_bin_d<br><br>"; echo "<h1>Results</h1><br>"; echo "A = $a<br>B = $b<br>C = $c<br>D = $d<br><br>"; $a_dec = bindec($a); $b_dec = bindec($b); $c_dec = bindec($c); $d_dec = bindec($d); $a_hex = dechex($a_dec); $b_hex = dechex($b_dec); $c_hex = dechex($c_dec); $d_hex = dechex($d_dec); echo "A = $a_hex<br>B = $b_hex<br>C = $c_hex<br>D = $d_hex<br><br>"; // FUNCTIONS function ff($a, $b, $c, $d, $m, $k, $s, $t) { //a = b + ((a + F(b,c,d) + X[k] + T[i]) <<< s) return ADDxy($b, SHIFTleft(ADDxy(ADDxy(ADDxy($a, F($b, $c, $d)), $m[$k]), $t), $s)); } function gg($a, $b, $c, $d, $m, $k, $s, $t) { //a = b + ((a + G(b,c,d) + X[k] + T[i]) <<< s) return ADDxy($b, SHIFTleft(ADDxy(ADDxy(ADDxy($a, G($b, $c, $d)), $m[$k]), $t), $s)); } function hh($a, $b, $c, $d, $m, $k, $s, $t) { //a = b + ((a + H(b,c,d) + X[k] + T[i]) <<< s) return ADDxy($b, SHIFTleft(ADDxy(ADDxy(ADDxy($a, H($b, $c, $d)), $m[$k]), $t), $s)); } function ii($a, $b, $c, $d, $m, $k, $s, $t) { //a = b + ((a + I(b,c,d) + X[k] + T[i]) <<< s) return ADDxy($b, SHIFTleft(ADDxy(ADDxy(ADDxy($a, I($b, $c, $d)), $m[$k]), $t), $s)); } function F($X, $Y, $Z) { //return ($X & $Y) | ((~$X) & $Z); return ORxy(ANDxy($X, $Y), ANDxy(NOTx($X), $Z)); } function G($X, $Y, $Z) { //return ($X & $Z) | ($Y & (~$Z)); return ORxy(ANDxy($X, $Z), ANDxy($Y, NOTx($Z))); } function H($X, $Y, $Z) { //return $X ^ $Y ^ $Z; return XORxy(XORxy($X, $Y), $Z); } function I($X, $Y, $Z) { //return $Y ^ ($X | (~$Z)); return XORxy($Y, ORxy($X, NOTx($Z))); } function Pad($binary, $pad_length) { $pad_length = $pad_length - strlen($binary); for($i = 0; $i < $pad_length; $i++) { $padding .= '0'; } return $padding . $binary; } function mod($val, $div) { $r = $val - (floor($val/$div)*$div); return $r; } function ANDxy($x, $y) { $x_dec = bindec($x); $y_dec = bindec($y); $result = $x_dec & $y_dec; $result = Pad(decbin($result), strlen($x)); return $result; } function ORxy($x, $y) { $x_dec = bindec($x); $y_dec = bindec($y); $result = $x_dec | $y_dec; $result = Pad(decbin($result), strlen($x)); return $result; } function ADDxy($x, $y) { $x_dec = bindec($x); $y_dec = bindec($y); $result = mod($x_dec + $y_dec, pow(2, 32)); $result = Pad(decbin($result), strlen($x)); return $result; } function XORxy($x, $y) { $x_dec = bindec($x); $y_dec = bindec($y); $result = $x_dec ^ $y_dec; $result = Pad(decbin($result), strlen($x)); return $result; } function NOTx($x) { $x_dec = bindec($x); $result = ~$x_dec; $result = Pad(decbin($result), strlen($x)); return $result; } function SHIFTleft($x, $y) { $x_dec = bindec($x); $result = $x_dec << $y; $result = Pad(decbin($result), strlen($x)); return $result; } function SHIFTright($x, $y) { $x_dec = bindec($x); $result = $x_dec >> $y; $result = Pad(decbin($result), strlen($x)); return $result; } ?> This topic has been moved to Other Libraries and Frameworks. http://www.phpfreaks.com/forums/index.php?topic=358005.0 Hello. Through MySQL, I created a database using the following code: Code: [Select] create database auth; use auth; create table authorized_users ( name varchar(20), password varchar(40), primary key (name) ); insert into authorized_users values ( 'username', 'password' ); insert into authorized_users values ( 'testuser', sha1('password') ); grant select on auth.* to 'webauth' identified by 'webauth'; flush privileges; Then I used the following code to set up a simple log in page. Code: [Select] <?php $name = $_POST['name']; $password = $_POST['password']; if ((!isset($name)) || (!isset($password))) { //Visitor needs to enter a name and password ?> <h1>Please Log In</h1> <p>This page is secret.</p> <form method="post" action="secretdb.php"> <p>Username: <input type="text" name="name"></p> <p>Password: <input type="password" name="password"></p> <p><input type="submit" name="submit" value="Log In"></p> </form> <?php } else { // connect to mysql $mysql = mysqli_connect("localhost", "webauth", "webauth"); if(!$mysql) { echo "Cannot connect to database."; exit; } // select the appropriate database $selected = mysqli_select_db($mysql, "auth"); if(!$selected) { echo "Cannot select database."; exit; } // query the database to see if there is a record which matches $query = "select count(*) from authorized_users where name = '".$name."' and password = sha1('".$password."')"; $result = mysqli_query($mysql, $query); if(!$result) { echo "Cannot run query."; exit; } $row = mysqli_fetch_row($result); $count = $row[0]; if ($count > 0) { // visitor's name and password combination are correct echo "<h1>Here it is!</h1> <p>I bet you are glad you can see this secret page.</p>"; } else { // visitor's name and password combination are not correct echo "<h1>Go Away!</h1> <p>You are not authorized to use this resource.</p>"; } } ?> When I open up this page, above "Please Log In", I get this error: Notice: Undefined index: name in C:\xampp\htdocs\learning\secretdb.php on line 2 Notice: Undefined index: password in C:\xampp\htdocs\learning\secretdb.php on line 3 Moreover, when I type in an authorized username and password, I get another error: Warning: mysqli_connect() [function.mysqli-connect]: (28000/1045): Access denied for user 'webauth'@'localhost' (using password: YES) in C:\xampp\htdocs\learning\secretdb.php on line 19 Cannot connect to database. Does anyone know what I'm doing wrong? I'm fairly new to PHP and MySQL and I'm pretty stuck. Thanks. I registered a few days ago for help on this thread but didn't post again on it now because it has been marked answered and I thought I'd better not bump it. I received help in a way that has been the most encouraging since I began my calendar project. I'm wondering, though, if you would help me understand why I'm not successful at implementing the advice to the point that events are inserting into my calendar.
My testing database has only one table: events and in events, only two columns (other than id): "startdt" and "description". This is a screenshot of how the table's columns are set upL
screenshot.jpg 37.21KB
0 downloads
This is a screenshot of the table content:
screenshot2.jpg 9.35KB
0 downloads
This is my code with the edits added from the support thread:
<?PHP $var = mysql_real_escape_string($_GET['startdt, description']); $con=mysql_connect("localhost","user","password"); // Check connection if (mysql_connect_error()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } //select a database to work with $selected = mysql_select_db("mydatabase_",$con) or die("Could not select mydatabase_"); //execute the SQL query and return records $result = mysql_query("SELECT information FROM events WHERE value='$startdt', 'description'"); //fetch tha data from the database while ($row = mysql_fetch_array($result)) { echo $row{'startdt, description'}; } //close the connection mysql_close($con); ?> <!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" /> <link rel="stylesheet" href="css/master.css" type="text/css" media="all"> <meta http-equiv="Content-Type" content="text/html" /> <title>Yet Another Test</title> </head> <body> <?php $currMonth = isset($_GET['month']) ? $_GET['month'] : date('n'); $currYear = isset($_GET['year']) ? $_GET['year'] : date('Y'); $today = (($currYear == date('Y')) && ($currMonth == date('n'))) ? date('j') : 0; $prevMonth = $currMonth==1 ? 12 : $currMonth-1; $nextMonth = $currMonth==12? 1 : $currMonth+1; $prevYear = $currMonth==1 ? $currYear-1 : $currYear; $nextYear = $currMonth==12? $currYear+1 : $currYear; $day1 = mktime(0,0,0,$currMonth,1,$currYear); $dim = date('t', $day1); $dayN = mktime(0,0,0,$currMonth,$dim,$currYear); $dow1 = (date('w',$day1)+0) % 7; $dowN = (date('w',$dayN)+0) % 7; $calHead = date('F Y',$day1); echo <<<EOT <div class="calwrapper"> <div class="caltitle"><h1>Calendar</h1></div> <div class="container"> <div class="fnl first"></div> <div class="adjust"></div> <div class="fnl last"></div> </div> <div class="caldisplay"> <table cellspacing="0"> <tr> <td class="hd"><a class="cal_button" href="$_SERVER[PHP_SELF]?year=$prevYear&month=$prevMonth"> Prev </a></td> <td colspan="5" class="adjust">$calHead</td> <td class="hd"><a class="cal_button" href="$_SERVER[PHP_SELF]?year=$nextYear&month=$nextMonth"> Next </a></td> </tr> <tr> <th class="we">Sun</th> <th class="wd">Mon</th> <th class="wd">Tue</th> <th class="wd">Wed</th> <th class="wd">Thu</th> <th class="wd">Fri</th> <th class="we">Sat</th> </tr> <tr> EOT; for ($d=0;$d<$dow1;$d++) echo "<td class=\"hd\"> </td>"; $c = $dow1; for ($d=1; $d<=$dim; $d++, $c++) { if ($c%7==0) echo "</tr><tr>"; $cl = ($c%7==5) || ($c%7==6) ? 'we' : 'wd'; $st = ($d == $today) ? "style='padding: 0px;'" : ''; echo "<td class=\"$cl\" $st>\n"; echo "$d" ; echo "</td>\n"; } while ($c++ % 7 != 0) echo '<td class=\"hd\"> </td>'; echo "</tr></table>\n"; echo '</div></div>'; // calander entries. Use the date as the key (in YYYY/MM/DD format) $entries = array( '2014/8/16' => array( 'Event', ), ); for ($d=1; $d<=$dim; $d++, $c++) { if ($c%7==0) echo "</tr><tr>"; $cl = ($c%7==5) || ($c%7==6) ? 'we' : 'wd'; $st = ($d == $today) ? "style='padding: 0px;'" : ''; echo "<td class=\"$cl\" $st>\n"; echo "$d" ; echo "</td>\n"; } // construct the date, this will be used to check to if the key exists in the $entries array $dateKey = "$currYear/$currMonth/$d"; // check if the key exists in the $entries array if(array_key_exists($dateKey, $entries)) { // for each event, list it in a seperate tool tip foreach($entries[$dateKey] as $entry) { echo '<div class="has-tooltip"> Event <span class="tooltip">'.$entry.'</span> </div>'; } } ?> </body> </html>I am not getting any errors in the PHP Code Checker (although I am receiving the notice that these functions are now deprecated): mysql_close() mysql_connect() mysql_fetch_array() mysql_query() mysql_real_escape_string() mysql_select_db() When I upload my page to the server, everything seems fine, except that no information is added to the table. When I check the page source, I see this: <!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" /> <link rel="stylesheet" href="css/master.css" type="text/css" media="all"> <meta http-equiv="Content-Type" content="text/html" /> <title>Yet Another Test</title> </head> <body> <div class="calwrapper"> <div class="caltitle"><h1>Calendar</h1></div> <div class="container"> <div class="fnl first"></div> <div class="adjust"></div> <div class="fnl last"></div> </div> <div class="caldisplay"> <table cellspacing="0"> <tr> <td class="hd"><a class="cal_button" href="/1cal/calendar.php?year=2014&month=7"> Prev </a></td> <td colspan="5" class="adjust">August 2014</td> <td class="hd"><a class="cal_button" href="/1cal/calendar.php?year=2014&month=9"> Next </a></td> </tr> <tr> <th class="we">Sun</th> <th class="wd">Mon</th> <th class="wd">Tue</th> <th class="wd">Wed</th> <th class="wd">Thu</th> <th class="wd">Fri</th> <th class="we">Sat</th> </tr> <tr><!--DEBUG: year=$currYear and month=$currMonth<hr/--><td class="hd"> </td><td class="hd"> </td><td class="hd"> </td><td class="hd"> </td><td class="hd"> </td><td class="we" > 1</td> <td class="we" > 2</td> </tr><tr><td class="wd" > 3</td> <td class="wd" > 4</td> <td class="wd" > 5</td> <td class="wd" > 6</td> <td class="wd" > 7</td> <td class="we" > 8</td> <td class="we" > 9</td> </tr><tr><td class="wd" > 10</td> <td class="wd" > 11</td> <td class="wd" > 12</td> <td class="wd" > 13</td> <td class="wd" > 14</td> <td class="we" style='padding: 0px;'> 15</td> <td class="we" > 16</td> </tr><tr><td class="wd" > 17</td> <td class="wd" > 18</td> <td class="wd" > 19</td> <td class="wd" > 20</td> <td class="wd" > 21</td> <td class="we" > 22</td> <td class="we" > 23</td> </tr><tr><td class="wd" > 24</td> <td class="wd" > 25</td> <td class="wd" > 26</td> <td class="wd" > 27</td> <td class="wd" > 28</td> <td class="we" > 29</td> <td class="we" > 30</td> </tr><tr><td class="wd" > 31</td> <td class=\"hd\"> </td><td class=\"hd\"> </td><td class=\"hd\"> </td><td class=\"hd\"> </td><td class=\"hd\"> </td><td class=\"hd\"> </td></tr></table> </div></div></body> </html>I don't have an understanding of what the Debug is telling me although I note the number "1" within the tag and find that interesting because on those occasions, earlier today, when the file upload would result in a white page, viewing the page source would reveal nothing but the numeral "1" in the upper left top. Are the deprecated functions enough to cause the event not to insert into the calendar? I'd appreciate any help in sorting why I'm not succeeding. As you see so often around here, I'm not a coder. I'm just forced into a position to have to fend for myself, as of late, and so I'm trying to learn what I can. Thank you for any help. Edited by Izzy-B, 15 August 2014 - 07:24 PM. |