I am trying to add a CAPTCHA option to a specific page on a website. The validation code for the page is written in Javascript, and the PHP CAPTCHA documentation (http://www.phpcaptcha.org/documentation/quickstart-guide/) is given strictly in PHP. I've managed to add the CAPTCHA box to the page and everything else up until where the code verifies the user's CAPTCHA entry. I am having trouble merging the two because:
a) they are written in different languages
b) my knowledge in PHP/Javascript is very basic
Here is a snippet of the page's original validation code:
function validate(formData, jqForm, options){
// # Valid?
valid = false;
// # Validate Contact Form
var errs = new Array();
// # Contact Name
if($('#ContactName').val() == ''){
errs.push(['#ContactName', 'Enter your name.']);
} else if(label = $('#ContactNameLabel label.error-message')){
label.fadeOut();
}
I want to repeat the same process except with the user's CAPTCHA entry. The following code is given in the PHP CAPTCHA documentation:
include_once $_SERVER['DOCUMENT_ROOT'] . '/securimage/securimage.php';
$securimage = new Securimage();
and
if ($securimage->check($_POST['captcha_code']) == false) {
// the code was incorrect
// you should handle the error so that the form processor doesn't continue
// or you can use the following code if there is no validation or you do not know how
echo "The security code entered was incorrect.<br /><br />";
echo "Please go <a href='javascript:history.go(-1)'>back</a> and try again.";
exit;
}
The code can be found, along with instructions, in the link given above. My question is: how can I implement the given PHP code inside the Javascript function that I have? To my understanding, it is possible to embed PHP inside Javascript as long as the forum is written using PHP (and I can confirm that the website I'm working on is built using CakePHP) - I am just lost with the syntax/how to go about executing this (if it is possible).
If anyone could offer me a helping hand that would be greatly appreciated! Thank you in advance.
You can write PHP within JavaScript if the JavaScript is in the View (as opposed to being in a .js file)
Example:
<?php
$message = "Hello World";
?>
<script>
alert("<?php echo $message; ?>");
</script>
You can't do that as PHP is a server-side language and Javascript is a client-side one. By the time your browser sees the page, all the PHP processing has finished on the server and all that's left is client-side rendering of the page. You will need to validate the CAPTCHA on the server-side.
Related
i have a custom website, no CMS, and this website uses Smarty. The website allow users to register and uses an old image captcha system.
To disallow bots registrations, i will implement new Google No Captcha Recaptcha plugin, ( more info here: https://www.google.com/recaptcha/ ).
So i decided to follow this tutorial: https://webdesign.tutsplus.com/tutorials/how-to-integrate-no-captcha-recaptcha-in-your-website--cms-23024
I have no problem in first steps: register on Google and obtain Site Key and Secret Key.
Also no problem in following steps: insert JavaScript API and div box in register.tpl smarty template file .
My problem is in the final steps, send to Google response so it can verify it.
This was no problem in normal website to put php code in register.php normal php page.
But on Smarty Template, so in register.tpl, it gives me fatal errors, also if i use {php}{/php} special tags
<?php
// grab recaptcha library
require_once "recaptchalib.php";
// your secret key
$secret = "0000000000000000000000000000000000";
// empty response
$response = null;
// check our secret key
$reCaptcha = new ReCaptcha($secret);
// if submitted check response
if ($_POST["g-recaptcha-response"]) {
$response = $reCaptcha->verifyResponse(
$_SERVER["REMOTE_ADDR"],
$_POST["g-recaptcha-response"]
);
}
?>
And this:
<?php
if ($response != null && $response->success) {
echo "Hi " . $_POST["name"] . " (" . $_POST["email"] . "), thanks for submitting the form!";
} else {
?>
<?php } ?>
I think the solution is to put this code in register.php page and import it in register.tpl page, but i am a beginner, can you please transform this code for me ?
I am sure this code will be useful for many users around the web.
php
require_once ('recaptchalib.php');
$mypublickey = "456723345";
$smarty->assign("captcha", recaptcha_get_html($mypublickey));
tpl
{$captcha}
http://devcodepro.com/view/22/8/reCaptcha-with-smarty
I Have one registration and payment page. program flow is like registration > confirmation > payment. After validation and calculation in registration page need to go to confirmation page.
My code is
<?php
ob_start();
session_start();
include("header.php");
include("ini.php");
date_default_timezone_set('Asia/Brunei');
header('Cache-Control: max-age=900');
if (isset($_POST['submit'])) {
$error = 0;
//validations
if ($error <= 0) {
//do some calculation
header('location:confirm.php');
}
}
<?php
ob_flush();
?>
Control entered in to if ($error <= 0) clause, but stay on the registration page.
I tried many ways like
header('location:confirm.php', true, 302);
instead of
header('location:confirm.php');
removed
ob_start() and ob_flush()
add exit() after header()
then it goes to blank page.
Also try to use
echo '<script type="text/javascript">';
echo 'window.location.href="confirm.php";';
echo '</script>';
Then the control goes to confirmation page but url seems to be as registration.php
But header('location:confirm.php'); is working fine in my local server. Anybody please help me to resolve this issue.. Is there any alternate way for header(). Looking forward to you guys.. Thanks
Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include, or require, functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file.
Also try to change header('Location:confirm.php');
(Note L is capital since its work in your local server may be problem with strict php type try this once)
$host = $_SERVER['HTTP_HOST'];
$uri = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
$extra = 'confirm.php';
header("Location: http://$host$uri/$extra");
use ob_end_flush() at the end. This should work like charm.
i had the same issues for years but today i discovered that u don't have to have any html or blank space before the header word .Try it out
I am using a plugin userfrosting to manage users.
The PHP side of the app checks if the user is currently logged in.
The javascript side of the app checks what the permission of the user is.
EG.
<?php
if (isUserLoggedIn()){
?>
<script>
loadCurrentUserPermission();
</script>
<?php
}
?>
Now that's fine and dandy, but now I want to implement some user access restrictions in my PHP files. Can I use such a method inside of a php function? Because I don't want to escape the PHP and check for every action.
The next option would be to store it in a variable, but how can I escape a variable assignment midway to the outcome of a < script > ?
$userPermission;
if (isUserLoggedIn()){
$userPermission = (
?>
<script type="text/javascript">
userLoadPermissions();
</script>
<?php
);
}
?>
Finally what if I use jquery to store the permission level in a PHP session ID? is that safe? Can someone easily modify their own level?
What's wrong with echoing the js?
<?php
if (isUserLoggedIn()){
echo "<script>loadCurrentUserPermission();</script>";
// more php
?>
Edit: Oh, I see. Javascript, being server-side, will be loaded after the PHP, so it's not simple (or even possible) to have PHP, then JS, then more PHP execute on the same page. You could consider calling the rest of the PHP from somewhere else using an AJAX request but that might not be practical for all of your pages.
just wondering what the best way to go about having both javascript and PHP validation.
So, currently I have js validation for just an empty field and that then send the data to the PHP page.
What can I do for e.g.
if ($_POST['username'] == '') {
die();
}
I want to have PHP validation for more security and also for people with js turned off.
I could set a session on fail, and then check next to the field if there is a session set and then on true echo out a empty field message?
But then how do I stop that working when js is enabled etc.
Thanks for any help.
yes you need serverside validation also... I do it (most of the time) like so...
$errors= array();
$username=$_POST['username'];
if ($username == '') {
$errors[]='username can not be empty!' ;
}
after all the validation stuff (you can and have to do more validation) you could check if there are errors set...
if (empty($errors)) {
//your code when there are no errors
}
if there are errors you could echo them to the user.
if (!empty($errors)) {
foreach($errors as $err){
echo $err;
}
}
also don't forget to mysql_real_escape_string() your posted data if you plan to save it in a database.
What I'm trying to do is read a specific line from a webpage from inside of my PHP application. This is my experimental setup thus far:
<?php
$url = "http://www.some-web-site.com";
$file_contents = file_get_contents($url);
$findme = 'text to be found';
$pos = strpos($file_contents, $findme);
if ($pos == false) {
echo "The string '$findme' was not found in the string";
} else {
echo "The string '$findme' was found in the string";
echo " and exists at position $pos";
}
?>
The "if" statements contain echo operators for now, this will change to database operators later on, the current setup is to test functionality.
Basically the problem is, with using this method any java on the page is returned as script. What I need is the text that the script is supposed to render inside the browser. Is there any way to do this within PHP?
What I'm ultimately trying to achieve is updating stock from within an ecommerce site via reading the stock level from the site's supplier. The supplier does not use RSS feeds for this.
cURL does not have a javascript parser. as such, if the content you are trying to read is placed in the page via Javascript after initial page render, then it will not be accesible via cURL.
The result of the script is supposed executed and return back to your script.
PHP doesn't support any feature about web browser itself.
I suggest you try to learn about "web crawler" and "webbrowsers" which are included in .NET framework ( not PHP )
so that you can use the exec() command in php to call it.
try to find out the example code of web crawler and web browsers on codeproject.com
hope it works.
You can get the entire web page as a file like this:
function get_data($url)
{
$ch = curl_init();
$timeout = 5;
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$returned_content = get_data('http://example.com/page.htm');
$my_file = 'file.htm';
$handle = fopen($my_file, 'w') or die('Cannot open file: '.$my_file);
fwrite($handle, $returned_content);
Then I suppose you can use a class such as explained in this link below as a guide to separate the javascript from the html (its in the head tags usually). for linked(imported) .js files you would have to repeat the function for those urls, and also for linked/imported css. You can also grab images if you need to save them as files.
http://www.digeratimarketing.co.uk/2008/12/16/curl-page-scraping-script/