PHP - Google Recaptcha "use Of Undefined Constant .."
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. Similar TutorialsI am pretty sure I defined these, by making it something like $blah="blah" and `blah` = ' {$blah}' So why am I getting these errors = Notice: Use of undefined constant petid - assumed 'petid' in /home/vhosts/foggyjungle.6te.net/viewpet_forum.php on line 38 Notice: Use of undefined constant adopter - assumed 'adopter' in /home/vhosts/foggyjungle.6te.net/viewpet_forum.php on line 41 Notice: Undefined variable: fulldate in /home/vhosts/foggyjungle.6te.net/viewpet_forum.php on line 44 Fatal error: Call to undefined function showpet_forum() in /home/vhosts/foggyjungle.6te.net/viewpet_forum.php on line 45 $time = mysql_query("SELECT * FROM `pets_adopted`"); $date = mysql_fetch_array($time); $fulldate = "$date[fulldate]"; $halfdate = "$date[halfdate]"; function check(){ $pid = mysql_real_escape_string($_GET['id']); $result = mysql_query("SELECT * FROM `pets_adopted` WHERE `id` = '{$pid}'"); while($row = mysql_fetch_array($result, MYSQL_ASSOC)) { $results = mysql_query("SELECT * FROM `pets_list` WHERE `id` = '{$row[petid]}'"); $pet = mysql_fetch_array($results); $results2 = mysql_query("SELECT * FROM `users` WHERE `id` = '{$row[adopter]}'"); $usercc = mysql_fetch_array($results2); There's the snippet. Thank you for any help. I am just really lost.
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 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
Hello How can i add google recaptcha to this code https://github.com/Tutorialwork/Tutorials/blob/master/PHP Rechtesystem/addnews.php 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 hi, I have just used teh pagination from this site: http://papermashup.com/easy-php-pagination/ all is working ok apart from I get an error: Notice: Use of undefined constant num - assumed 'num' in D:\retroandvintage.co.uk\wwwroot\default.php on line 207 line 207: Code: [Select] $total_pages = $total_pages[num]; Please help? here is my site: http://www.retroandvintage.co.uk/default.php?page=5 Howdy Fairly new to the whole php scene made some php code which works, but i get the error Notice: Use of undefined constant Yes - assumed 'Yes' in C:\Program Files\EasyPHP-5.3.3\www\htdocs\top.php on line 26, line 26 is the first line code, kind of lost and would appreciate an explanation on how to fix this if possible thanks! Code: [Select] <?php if ($players['Banned'] == Yes){ echo $players['name'] ?> (BANNED) <?php } else {?> <a href="profile.php?id=<?php echo $players['id'] ?>"><?php echo $players['name'] ?> I am having a problem with some php code that runs on a landing page that queries a database for the content needed to display on the template page from the keywords passed in the url. My issue is that when I tried to add some php code to the template page it reads it fails and returns Notice: Use of undefined constant tdbd_name - assumed 'tdbd_name' in /var/www/ppcindex.php on line 147 Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in /var/www/ppcindex.php on line 150 If anyone could point me in the right direction it would be much appreciated. Here is the code from the landing page php <?php // template variables - PLEASE CHANGE error_reporting(E_ALL); ini_set('display_errors','On'); define("TEMPLATE_NAME","ppcindexcontent.php"); // your page templates define("FULL_PATH","/var/www/speedppc/"); // true path to your speedPPC install directory define("MAX_ROWS",1); // maximum display rows for CSV data - we recommend no more the 100 records if(!isset($_GET["CSVID"])){ define("CSVID", "18"); // CSVID of your csv file. leave blank if passing csvid in the url (See README.txt) } else { define("CSVID", $_GET[csvid], true); } define("REPLACECHAR", '-'); // this is the replacement character for the custom function replace() // include files include(FULL_PATH."config.php"); include(FULL_PATH."common.php"); // variables passed in URL $csvkeyword = $_GET['csvkeyword']; $seed = $_GET['seed']; $expansion = $_GET['expansion']; $final = $_GET['final']; // connect to DB $dbhandle = dbconnect($host, $user, $pass, $db); // functions function replaceTokens($passedContent) { global $csvkeyword, $seed, $expansion, $final; $tokens = array("[%csvkeyword%]", "[%seed%]", "[%expansion%]", "[%final%]", "[%Csvkeyword%]", "[%Seed%]", "[%Expansion%]", "[%Final%]"); $tokenValues = array(rs($csvkeyword), rs($seed), rs($expansion), rs($final), uc(rs($csvkeyword)), uc(rs($seed)), uc(rs($expansion)), uc(rs($final))); $replacedContent = str_replace($tokens, $tokenValues, $passedContent); return $replacedContent; } function stripUndefinedTokens($passedContent) { $patterns = '/\[%.*?(%\]|\]|%)/'; $result = preg_replace($patterns, '', $passedContent); return $result; } function changeCase($passedContent) { $patterns = '/\$.*?\]/'; $string = $passedContent; preg_match_all($patterns, $string, $matches); $uniqueMatches = array_unique($matches[0]); foreach($uniqueMatches as $key => $value) { if(substr($value, 13, 1) == strtoupper(substr($value, 13, 1))) { $string = str_replace($value, '".ucwords('.strtolower($value).')."', $string); } } return $string; } function replaceChar($passedContent) { $string = $passedContent; $patterns = '/replace\(.*?\)/'; preg_match_all($patterns, $string, $matches); $replaceChar = '-'; foreach($matches[0] as $key => $value) { $valueReplaced = str_replace(' ', REPLACECHAR, $value); $string = str_replace($value, $valueReplaced, $string); } $replace = array("replace(", ")"); //$string = str_replace($replace, '', $string); return $string; } function rs($passWord) { return str_replace('-', ' ', $passWord); } function uc($passWord) { return ucfirst($passWord); } // get CSV table Information $sql = "SELECT * FROM tabledb_details WHERE tdbd_id = '".CSVID."'"; $result = mysql_query($sql); $row = mysql_fetch_assoc($result); // replace '-' in keyword with space and also use keyword with '-' in it incase it is part of the word $keywordsArray = explode(",", $csvkeyword); $i = 0; foreach($keywordsArray as $key => $value) { $keywords[$i] = $value; $i++; $position = strpos($value, '-'); if($position !== false){ $keywords[$i] = str_replace("-", " ", $value); $i++; } } // CSV fields to search keyword occurence in $keywordFields = explode("|", $row[tdbd_search_fields]); $sqlKeyword = ' ('; foreach($keywords as $key => $value) { $sqlKeyword .= "("; foreach($keywordFields as $keyField => $valueField) { $sqlKeyword .= "`" . $valueField . "` REGEXP '( |^)".$value."( |s|[\.]|$)' OR "; } $sqlKeyword = substr($sqlKeyword, 0, -4); $sqlKeyword .= ") OR "; } $sqlKeyword = substr($sqlKeyword, 0, -4).')'; // set the default sql 'where' section if the keyword is not defined in url if($csvkeyword == '' || !isset($csvkeyword)) { $sqlKeyword = '1'; } // start template Display Output ob_start(); include(TEMPLATE_NAME); $output = ob_get_contents(); ob_end_clean(); // get the position of the loop template $loopStart = strpos($output,"[start_csv_loop]"); $loopEnd = strpos($output,"[end_csv_loop]"); // get the loop template layout $loopTemplate = substr($output, ($loopStart+16), ($loopEnd-($loopStart+16))); // get content before loop template $preContent = stripslashes(stripUndefinedTokens(addslashes(replaceTokens(substr($output, 0, $loopStart))))); // get content after loop template $postContent = stripslashes(stripUndefinedTokens(addslashes(replaceTokens(substr($output, $loopEnd+14))))); // output pre content eval("\$preContent = \"$preContent\";"); print_r( replaceChar($preContent) ); $sqlSearch = "SELECT * FROM ".$row[tdbd_name]." WHERE ".$sqlKeyword." LIMIT ".MAX_ROWS; $resultSearch = mysql_query($sqlSearch); while($displayrows = mysql_fetch_assoc($resultSearch)) { $display = replaceTokens($loopTemplate); $display = str_replace('\\', '[backslash]', $display); $display = str_replace('[%', '$displayrows[', $display); $display = addslashes(str_replace('%]', ']', $display)); $display = replaceTokens($display); $display = changeCase($display); eval("\$display = \"$display\";"); $display = stripslashes($display); $display = str_replace('[backslash]', '\\', $display); $display = replaceChar($display); print_r( $display ); } // output post content eval("\$postContent = \"$postContent\";"); print_r( replaceChar($postContent) ); ?> And here is part of the template (ppcindexcontent.php) the above code is reading. <div style=" float:right; width: 300px; height: 0px; margin-top:-20px ; margin-bottom:0px"> <p style=" font-size:16px; text-align: center; line-height:1; color:#0391D1;"> <?php error_reporting(E_ALL); ini_set('display_errors','On'); $mySQLServer = "xxxxxx"; $mySQLUser = "xxxxxxxx"; $mySQLPass = "xxxxxxxxx"; $mySQLDB = "xxxxxxxxxxx"; $SQLToday = date("m/d/y") . "<br />"; $SQLsevendays = mktime(0,0,0,date("n"),date("j")-7,date("Y")); $SQLsevenname = (date("l", $SQLsevendays)); $SQLsevennumber = (date("jS", $SQLsevendays)); $dbhandle = mssql_connect($mySQLServer, $mySQLUser, $mySQLPass) or die("Couldn't connect to SQL Server on $myServer"); $selected = mssql_select_db($mySQLDB, $dbhandle) or die("Couldn't open database $myDB"); $query = "WEB_ApproveHistory @State='CA', @Days=5, @Records=8"; $data = mssql_query($query); $result = array(); while ($row = mssql_fetch_object($data)) : $result[] = $row; $returnedresults = (97*($row->TotalApprovals)) ; endwhile; $englishreturnedresults = number_format($returnedresults); echo 'In just the last week since ' . $SQLsevenname . ' the ' . $SQLsevennumber . ' xx '; echo $englishreturnedresults; echo ' to People Just Like you In California. <br><br>Here are just a few people who' ; echo '<ul class="BulletCheck">'; mssql_next_result($data); while ($row = mssql_fetch_object($data)) : $result[] = $row; echo '<li>' . ' ' . $row->FirstName . ' From '. $row->City . ', ' . $row->State .' PreApproved On ' .$row->ApprovedDate . '</li>'; endwhile; mssql_close($dbhandle); ?> </div> Code: [Select] $entrantQuery = "SELECT entrantID FROM entrants WHERE Game = $idT"; $entrantResult = mysql_query(entrantQuery); $entrantRow = mysql_fetch_row(entrantResult); I have these at the start of my php (after getting $idT), but I get the error Notice: Use of undefined constant entrantQuery - assumed 'entrantQuery' in C:\Entrants.php on line .. Notice: Use of undefined constant entrantResult - assumed 'entrantResult' in C:\www\Entrants.php on line.. Ive used this code lots of times before, what am I missing? They are variables that I am defining! I get an undefined constant error message. Am I using the variable correctly? Should I use an echo to output the variable as text? Added by <?php ${displayName}; ?> 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 all, In my server at present php4 is running. upto now it is working fine.Suddenly it is showing lot of errors like Use of undefined constant or Undefined variable:. While trying in Google and all i came to know that the variable should be initialized and bounded by quotes.I checked in 1 file and it worked fine. But my coding is 99% completed and to change in every file is not an easy thing.Can anybody help regarding this Please? Here i'm having 1 more problem also which suffering me for a long time. I'm having one login form in this.That user session is working properly in Chrome but not in Mozilla.Even in Chrome once i try to logoff and relogin again it is behaving like in Mozilla. anybody please help me regarding these 2 issues.Thanks in advance.
im getting these errors Notice: Use of undefined constant QUERY_STRING - assumed 'QUERY_STRING' in C:\xampps\htdocs\skyline\admin\other.php on line 36 and
<?php
$sql = "SELECT * FROM other "; 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". I've followed every piece of advice (quotes, no quotes, $...) and nothing works. Here is the snippet of code that's generating the error. This woks fine in PHP 5, but I have to upgrade to 7. Warning if for line 71, which corresponds to where query3 starts.
if($numRows == 0) { Earlier in code, I define this: $numRows = mysql_num_rows($r); Thanks in advance for any help you can lend. Edited February 7 by PoetHello!
First of all, i would like to thank everyone in this community as this is where i post most of the problems that i can no longer fix on my own. and everytime i do, i get all the help i need and with a 100% success rate.
Anyway, i am following a tutorial, however the tutorial is based on a MAC environment and i am working on windows. I think this is a problem with the DIRECTORY_SEPARATOR but i might be wrong.
I am getting this error message "Notice: Use of undefined constant LIB_PATH - assumed 'LIB_PATH' in C:\wamp\www\beyond_basics_photogallery\includes\database.php on line 2"
i will just post the code that is relevant to this error. here is the code for database.php: (config.php is in the same folder with database.php)
require_once(LIB_PATH.DS."config.php");and this is my initialize.php where i initialized my DIRECTORY_SEPARATOR. this is also located in the same folder with database.php <?php // Define the core paths // Define them as absolute paths to make sure that require_once works as expected defined('DS') ? null : define('DS', DIRECTORY_SEPARATOR); defined('SITE_ROOT') ? null : define('SITE_ROOT', DS.'wamp'.DS.'www'.DS.'beyond_basics_photogallery'); defined('LIB_PATH') ? null : define('LIB_PATH', SITE_ROOT.DS.'includes'); // load config file first require_once(LIB_PATH.DS.'config.php'); // load basic functions next so that everything after can use them require_once(LIB_PATH.DS.'functions.php'); // load core objects require_once(LIB_PATH.DS.'session.php'); require_once(LIB_PATH.DS.'database.php'); // load database-related classes require_once(LIB_PATH.DS.'user.php'); ?>and this is the path to my project folder: C:\wamp\www\beyond_basics_photogallery I have tried everything i could but i am completely lost as to what is causing this. could it be the SITE_ROOT statement? i appreciate any help. thanks! cant understand this error as i seemed to have it defined in my config file...... helpppp Notice: Use of undefined constant TBL_MEMBERS - assumed 'TBL_MEMBERS' in /export/SOI-50/students/m2009/abhr428/web/WebIbs/Member.class.php on line 32 Query failed: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'abhr428.TBL_MEMBERS' doesn't exist Code: [Select] <?php define('DB_DSN','mysql:host=vega.soi.city.ac.uk;dbname=abhr428' ); define( "DB_USERNAME", "abhr428" ); define( "DB_PASSWORD", "" ); define( "PAGE_SIZE", 5 ); define( "TBL_MEMBERS", "members" ); define( "TBL_ACCESS_LOG", "accessLog" ); ?> members.class.php <?php require_once "DataObject.class.php"; class Member extends DataObject { protected $data = array( "id" => "", "username" => "", "password" => "", "firstName" => "", "lastName" => "", "joinDate" => "", "gender" => "", "favoriteGenre" => "", "emailAddress" => "", "otherInterests" => "" ); private $_genres = array( "crime" => "Crime", "horror" => "Horror", "thriller" => "Thriller", "romance" => "Romance", "sciFi" => "Sci-Fi", "adventure" => "Adventure", "nonFiction" => "Non-Fiction" ); public static function getMembers( $startRow, $numRows, $order ) { $conn = parent::connect(); $sql = "SELECT SQL_CALC_FOUND_ROWS * FROM " . TBL_MEMBERS . " ORDER BY $order LIMIT :startRow, :numRows"; try { $st = $conn->prepare( $sql ); $st->bindValue( ":startRow", $startRow, PDO::PARAM_INT ); $st->bindValue( ":numRows", $numRows, PDO::PARAM_INT ); $st->execute(); $members = array(); foreach ( $st->fetchAll() as $row ) { $members[] = new Member( $row ); } $st = $conn->query( "SELECT found_rows() AS totalRows" ); $row = $st->fetch(); parent::disconnect( $conn ); return array( $members, $row["totalRows"] ); } catch ( PDOException $e ) { parent::disconnect( $conn ); die( "Query failed: " . $e->getMessage() ); } } public static function getMember( $id ) { $conn = parent::connect(); $sql = "SELECT * FROM " . TBL_MEMBERS . " WHERE id = :id"; try { $st = $conn->prepare( $sql ); $st->bindValue( ":id", $id, PDO::PARAM_INT ); $st->execute(); $row = $st->fetch(); parent::disconnect( $conn ); if ( $row ) return new Member( $row ); } catch ( PDOException $e ) { parent::disconnect( $conn ); die( "Query failed: " . $e->getMessage() ); } } public function getGenderString() { return ( $this->data["gender"] == "f" ) ? "Female" : "Male"; } public function getFavoriteGenreString() { return ( $this->_genres[$this->data["favoriteGenre"]] ); } } ?> Hi All, I am using PHP 5.3 and storing php session data to the database using session.set_save_handler callbacks. I see that the write method, strangely treats the Class constant as undefined. All the other methods seem to work fine with the class constant. Any reason why this would happen? Please see code below. I get an error "Use of undefined constant db_table in Sessions.php in line". This seems to be happening only with the write api. Can someone please help? Thanks class Sessions { //var $life_time; var $id; var $data; const db_table = 'php_mysql_session'; function PHPSessions() { // Read the maxlifetime setting from PHP //$this->life_time = get_cfg_var("session.gc_maxlifetime"); $this->id = session_id(); $this->data = ''; // Register this object as the session handler session_set_save_handler( array( &$this, "_open" ), array( &$this, "_close" ), array( &$this, "_read" ), array( &$this, "_write" ), array( &$this, "_destroy") , array( &$this, "_gc" ) ); } function _open () // open the session. { Zend_Log::log("opening connection"); global $_sess_db; Zend_Log::log("session db ".$_sess_db); if ($_sess_db = mysql_connect(DB_HOST_READ, DB_USER, DB_PASS)) { return mysql_select_db('TEST_SESSION', $_sess_db); } // If there is a failure return false return FALSE; } // open function _close () // close the db connection here { global $_sess_db; return mysql_close($_sess_db); } // close function _read ($id) // read any data for this session. { global $_sess_db; Zend_Log::log("Session db ".$_sess_db); //$id = mysql_real_escape_string(session_id()); Zend_Log::log("Session Id :" .$id); $sql = "SELECT * FROM ". self::db_table ." WHERE session_id = '$id'"; Zend_Log::log("SQL IS : ".$sql); $data = ''; $result = mysql_query($sql); $a = mysql_num_rows($result); Zend_Log::log("Record count ".$a); if($a > 0) { Zend_Log::log("Record Exists!"); $row = mysql_fetch_assoc($result); $data = $row['session_data']; Zend_Log::log("Fetching session Data ".$data); return $data; } else { Zend_Log::log("No Data ".$data); return ''; } } function _write ($id, $data) // write session data to the database. { global $_sess_db; $newid = mysql_real_escape_string($id); $newdata = mysql_real_escape_string($data); $sql = "REPLACE ". self::db_table ." (session_id,user_id,session_data,date_created) VALUES('$newid', '$userid', '$newdata', 'NOW()')"; $rs = mysql_query($sql); return TRUE; } // write function _destroy ($id) // destroy the specified session. { Zend_Log::log("Destroy method "); return TRUE; } // destroy function _gc ($max_lifetime) // perform garbage collection. { Zend_Log::log("GC Method"); return TRUE; } // gc function _destruct () // ensure session data is written out before classes are destroyed // (see http://bugs.php.net/bug.php?id=33772 for details) { @session_write_close(); } // __destruct // **************************************************************************** } // end class Notice: Use of undefined constant DB_DSN - assumed 'DB_DSN' in /export/SOI-50/students/m2009/abhr428/web/WebIbs/DataObject.class.php on line 32 dataobject.class.php can understand this problem has it got anything to with the config.php file which contains is this the reason for the above error or is it something else in the dataobjects.php below config.php <?php define( "DB_DSN", mysql:dbname=abhr428 ); define( "DB_USERNAME","" ); define( "DB_PASSWORD", "040010722" ); define( "PAGE_SIZE", 5 ); define( "TBL_users", "users" ); define( "TBL_accesslog", "accesslog" ); ?> dataobject.class.php <?php require_once "config.php"; abstract class DataObject { protected $data = array(); public function __construct( $data ) { foreach ( $data as $key => $value ) { if ( array_key_exists( $key, $this->data )) $this->data[$key] = $value; } } public function getValue( $field ) { if ( array_key_exists( $field, $this->data )) { return $this->data[$field]; } else { die( "field not found" ); } } public function getValueEncoded( $field ) { return htmlspecialchars( $this->getValue( $field )); } protected function connect() { try { $conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD ); $Conn->setAttribute( PDO::ATTR_PERSISTENT, true ); $conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION ); } catch ( PDOException $e) { die( "connection failed: " . $e->getMessage() ); } return $conn; } protected function disconnect( $conn ) { $conn = ""; } } ?> I have just re-installed Xampp and suddenly my sites are now displaying lots of: Notice: Use of undefined constant name - assumed 'name' in ... Notice: Use of undefined constant price - assumed 'price' in ... this is an example of the line its refering too: $defineProducts[1001] = array(name=>'This is a product', price=>123); |