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.
Related
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 trying to track the fields that are left blank on my website form when it is submitted.
The form I am using is used by my sales agents, and since I do not immediately see the submitted info before the sales agent has a chance to modify the submitted information, I am looking to see if they are filling out all of the info on the site instead of adding in more info later in the CRM. This will help me to optimize the form for their use. Currently the form is written using HTML, PHP, jQuery and AJAX.
I have not tried anything yet, as I do not even know where to begin with this. I have not seen it done before.
Let me know if you need to see the markup or if this question needs more clarification. Feel free to point me in the direction of a tutorial if that is easiest.
Thanks for the help!
That is what PHP empty() is for:
if (empty(trim($_POST['some_field']))
{
// Nothing was supplied.
}
So, you could create an array of 'required' fields like this:
$required = array('this', 'that', 'the', 'other');
...and then loop through them:
$errors = false;
foreach ($required as $field)
{
$field_value = isset($_POST[$field]) ? trim($_POST[$field]) : null;
if (empty($field_value))
{
$errors[] = 'The "' . $field . '" field was not submitted.';
}
}
if ($errors)
{
// Do something now that you know there are missing fields.
// Here, we're sending an email...
$subject = 'These fields were not filled out';
$body = 'The following errors occurred: ' . implode(', ', $errors);
mail('email#example.com', $subject, $body);
}
I think that you want to know the way how to check and validate the form information before submit. And as you said that you use jQuery, so I advise that there are 2 solutions to solve the problem at least.
1, write the validate script by yourself.
you can use the following script to check the form data before submit.
jQuery(form).submit(function(){
// Here you can validate your form data
// and if the data are incorrect,
// you can return false, and the form submission will be cancelled
});
2, use the jQuery Validation plugin.
The plugin can be got from http://jqueryvalidation.org/, and you can import it with the following script.
<script type="text/script" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.0/jquery.validate.js"></script>
And then, you only need to add some special attribute in your form.
For example, if you add "required" of your input field, which means the field must be filled with the characters.
<form>
<input type="text" name="username" required />
</form>
And then, write the following script to notify the plugin to validate the form before submission.
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery("form").validate();
});
</script>
You can check in both PHP or JS. If you want to do this server side so you can save this information simply check the POST results of the form.
if (trim($_POST['myField'])=="") {
//not filled out. if you have default values, check for it in the if above too.
mail('your#email.com', 'Subject', 'Your body.');
}
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.
I have a piece of code for checking if a "user already exists" in my database and i was told that the code is outdated as get_magic_quotes_gpc no longer works and my username variable is not sanitized .
I tried to update the code but not sure if its ok :
Original :
if (!get_magic_quotes_gpc()) {
$_POST['username'] = addslashes($_POST['username']);
}
$usercheck = $_POST['username'];
$check = mysql_query("SELECT username FROM users WHERE username = '$usercheck'")
or die(mysql_error());
$check2 = mysql_num_rows($check);
if ($check2 != 0) {
die('Sorry, the username '.$_POST['username'].' is already in use.');
}
UPDATED :
// i already have a jquery validation that checks it is a word (\w+) before submitting
$usercheck = $_POST['username'];
$sanitizeduser= filter_var($usercheck, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW);
$check = mysqli_query("SELECT EXISTS(SELECT 1 FROM users WHERE username = $sanitizeduser)"
if ($check != 0) {
die('Sorry, the username '.$_POST['username'].' is already in use.');
}
I also want to check it first with jquery before submitting the form - i already have a jquery code for testing valid name , email etc.. but i don;t know how to include that php code inside of it since i have to access the db.
parts of my jquery code : ( i'm using this script : http://jqueryvalidation.org/)
names: function(value, element) {
return this.optional(element) || /^\w+$/.test(value);
},
if it returns true - i get a valid message ,
returns false - get a custom message
Full Jquery code :
file 1 : http://jsfiddle.net/EjSbd/1/ (script.js)
file 2 : http://jsfiddle.net/qM4Uz/1/ (jquery.validate.js)
Use mysql_real_escape_string() function for server side.
Javascript is fine for client side and user can disable javascript from the browser so at that time javascript validation will not work. So dont rely on only javascript validation. Use server side escaping also to filter the user data.
Use mysql_real_escape_string.
And dont rely on any javascript preventing anything,
attackers wont even use a browser to attack you.
I have encountered a huge error for an idea I came up with. So I am working on a project, on my main website and we needed to put up a being worked on page, yadayda but I wanted to add the functionality of letting the user send us their email , but after we received that data a pop dialog would show.. But this doesn't work as I would like for it to.
So what I need help with, is actually the PHP and the JavaScript event to make it acknowledge that the message and email was sent, then show the dialog box. Does anyone know how to do this? Or maybe at least how to make a dialog show after a user did something, like entered information rather then just clicking a button? If anyone can help I would ridiculously appreciate it!
If you use jQuery, you can make an AJAX call to your serverside script and use the success callback to initiate the dialog on the client side.
$.ajax({
url: 'ajax/test.php',
data: { name: "WeLikeThePandaz", email: "panda#gmail.com" },
success: function(response) {
if (response.status == "OK"){
// Show dialog
}else{
// Let the user know there were errors
alert(response.error);
}
}
},'json');
Here is the relevant documentation for using the $.ajax method -
http://api.jquery.com/jQuery.ajax/
Your server side PHP code in ajax/test.php can then decipher the data that was sent and assemble a json object to be returned to the jQuery -
<?php
$err= '';
$name = sanitizeString($_POST['name']);
$email = sanitizeString($_POST['email']);
// note the sanitization of the strings before we insert them - always make sure
// to sanitize your data before insertion into your database.
// Insert data into database.
$result = mysql_query('INSERT INTO `user_table` VALUES...');
if (!$result) {
$status = "FAIL";
$err = mysql_error();
}else{
$status = "OK";
}
echo json_encode(array('error'=>$err,'status'=>$status)); // send the response
exit();
?>