PHP Code:
$dom = new DOMDocument;
$headtitle = "Register";
$errors = array();
if(isset($_POST['register'])){
$username = preg_replace('/[^A-Za-z]/', '', $_POST['username']);
$name = $_POST['name'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$password = $_POST['password'];
$c_password = $_POST['c_password'];
$birthday = $_POST['birthday'];
$country = $_POST['country'];
$gender = $_POST['gender'];
$age = $_POST['age'];
$level = $_POST['level'];
$date = $_POST['date'];
if(file_exists('users/' . $username . '.xml')){
$errors[] = ' Username already exists';
}
if($username == ''){
$errors[] = ' Username is missing. Try again.';
}
if($name == ''){
$errors[] = ' Name is missing. Try again.';
}
if($lastname == ''){
$errors[] = ' Lastname is missing. Try again.';
}
if($country == ''){
$errors[] = ' Country is missing. Try again.';
}
if($gender == ''){
$errors[] = ' Gender is missing. Try again.';
}
if($age == ''){
$errors[] = ' Age is missing. Try again.';
}
if($email == ''){
$errors[] = ' Email is missing. Try again.';
}
if($password == '' || $c_password == ''){
$errors[] = ' Passwords are missing. Try again.';
}
if($password != $c_password){
$errors[] = ' Passwords do not match';
}
if(count($errors) == 0){
$xml = new SimpleXMLElement('<user></user>');
$xml->addChild('name', ($name));
$xml->addChild('lastname', ($lastname));
$xml->addChild('password', md5($password));
$xml->addChild('birthday', $birthday);
$xml->addChild('country', $country);
$xml->addChild('gender', $gender);
$xml->addChild('age', $age);
$xml->addChild('email', $email);
$xml->addChild('level', $level);
$xml->addChild('date', $date);
$xml->asXML('users/' . $username . '.xml');
header('Location: index.php');
die;
}
}
Javascript Code:
function vaildate() {
if (document.getElementById('username').value.length <= 4) {
document.getElementById('errors').innerHTML = "Username must me more than 4 words <br />";
return false;
}
return true;
}
Now my problem is, that when I click submit button (that contains name="login" and onclick="vaildate();") he excute only php errors and ignores javascript errors (assuming that id="username" has less than 4 words).
My question is how can I make Javascript & PHP errors work? not only PHP and the system ignores Javascript.
Thank you all..
EDIT:
Also i got this code to echo PHP errors
if(count($errors) > 0){
echo '<font color="red"><ul>';
foreach($errors as $e){
echo '<li>' . $e . '</li>';
}
echo '</ul></font>';
}
Try this:
onclick="return vaildate();"
You need to return the validate function (return the true or false), not just call it.
Your Javascript and PHP you are showing looks fine. What we don't have is the actual markup of the login page. My suspicion is that your markup is not consistent with the code you have in your Javascript.
If you could also try and explain more specifically what you mean by
My question is how can I make Javascript & PHP errors work? not only PHP and the system ignores Javascript.
Have you used a Javascript debugger to see if part your Javascript (maybe elsewhere on the page) is erroring?
Related
I'm looking to create a sign-up page for a large-scale website which means I'm using a lot more layers of validation then I would normally do, given this should be common practice but in this particular case more than any other situation it is imperative.
I've already written most of the code required and formatted it in an order which I believed wouldn't lead to any undefined variable errors, however, upon form submission it doesn't create a new SQL row and doesn't return any errors under the error handling areas of the form validation. In all fairness, the error handling is quite simple at this point and is not a final version, just what I put in place to help me debug and troubleshoot any issues which should arise.
Here's the PHP code, and the snippet of the piss-poor error handling that is supposed to output an error message if an error occurs, to re-state, this error handling isn't final.
$conn = mysqli_connect('localhost', 'root2', '123', 'db');
$signupConditionsMet = "0";
if (isset($_POST["email"]) && isset($_POST["username"]) && isset($_POST["password"]) && isset($_POST["passwordCheck"]) && isset($_POST["birthdate"])) {
$signupConditionsMet = "1";
$birthGood = true;
$passGood = false;
$nameGood = false;
$emailGood = false;
}
$usernameSearch = $conn->prepare("SELECT * FROM users WHERE username = ?");
$userInsertion = $conn->prepare("INSERT INTO users (username, passwd, birthdate, email) VALUES (?,?,?,?)");
$nameErr = $emailErr = $passErr = $birthErr = "";
$name = $email = $pass = $birth = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST["username"];
$email = $_POST["email"];
$pass = $_POST["password"];
$birthdate = $_POST["birthdate"];
$passCheck = $_POST["passwordCheck"];
}
if ($signupConditionsMet === "1"){
function test_input($name) {
if (!preg_match("/^[a-z\d_]{2,15}$/i",$name)) {
$nameErr = "Only letters and white space allowed";
} else {
$nameGood = true;
return $name;
echo "did name ez";
}
}
function test_input2($email){
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
} else {
$emailGood = true;
return $email;
echo "did email ez";
}
}
function test_input3($password){
if (!preg_match("/^[a-z\d_]{2,15}$/",$pass)) {
$passErr = "Invalid password format";
} else if (!preg_match("/^[a-z\d_]{2,15}$/",$passCheck)){
$passErr = "Invalid password check format";
} else if ($_POST["password"] !== $_POST["passwordCheck"]){
$passErr = "Passwords do not match";
} else {
$passwd2 = AES_ENCRYPT($_POST["password"], 'mysecretstring');
$passwdGood = true;
return $passwd2;
echo "did pass ez";
}
}
}
if (($signupConditionsMet === "1") && ($birthGood === true) && ($nameGood === true) && ($passwdGood === true) && ($emailGood === true)) {
if ($usernameSearch->execute(array($_POST['username']))) {
while ($row = $usernameSearch->fetch()) {
if (!empty($row['id'])) {
$creationError = "This username is already taken";
} else {
$userInsertion->bindParam(1, $name);
$userInsertion->bindParam(2, $passwd2);
$userInsertion->bindParam(3, $birthdate);
$userInsertion->bindParam(4, $email);
$userInsertion->execute();
header('Location: userlanding.php');
}
}
}
}
/* PHP inside the HTML to output errors */
<?php if ($signupConditionsMet === "1") { echo "all inputs received"; echo $_SERVER["REQUEST_METHOD"];} else { echo "drats, they weren't all there"; echo $name; echo $email; echo $birthdate; echo $pass; echo $passCheck;}?>
<?php if ($passErr) { echo $passErr;} else if ($nameErr) { echo $nameErr;} else if ($emailErr) { echo $emailErr;} else if ($birthErr) { echo $birthErr;} ?>
Disregarding the previously admitted terrible error handling, I can't seem to wrap my head around why it doesn't work in its current form. It returns (from the client-side reporting) that all inputs were received and there isn't any fatal errors thrown from running the PHP code. In addition, the second client-side code which prints any errors doesn't print anything either, implying that all functions operated correctly, however, the echos at the bottom of the input tests don't echo the strings they've been assigned, implying those didn't work, but there was no errors. Hmm. Perhaps I'm missing something blatantly obvious regarding my syntax but I don't see why it wouldn't work. Any help would be appreciated.
I cannot make the register to work with recaptcha but it work normally without it
<?php
require_once("database.php");
$conn= pdo_con();
ini_set('SMTP','smtp.intnet.mu');
ini_set('smtp_port',25);
ini_set('sendmail_from','admin#example.co.uk');
if(!empty($_POST) || isset($_POST['regis_submit'])){
// Should the code be place here cause I already try it. //
$errors = array();
if (empty($_POST['firstname']) || empty($_POST['regis_username']) || empty($_POST['lastname']) || empty($_POST['inputEmail'])
|| empty($_POST['phone_num']) || empty($_POST["gender"]) || empty($_POST['regis_pass']) || empty($_POST["postal_address"])
|| empty($_POST["DateField"]) ){
$errors[] = 'Value(s) in the form missing, please fill them all out!';
exit();
} else if(!preg_match ('%^[A-Za-zÀàÂâÇçÉéÈèÊêËëÔôÙùÎîÏïÛûÜü\.\' \-]{2,15}$%', $_POST['firstname'])){
$errors['firstname'] = '<p><font color="red">Please enter your first name!</font></p>';
exit();
} else if ( etc...
}
else if (count($errors) > 0) {
foreach($errors as $error) {
echo $error;
}
} else {
$firstname = escape_data($_POST['firstname']);
$username = escape_data($_POST['regis_username']);
$lastname = escape_data($_POST['lastname']);
$email = escape_data($_POST['inputEmail']);
$telephone = escape_data($_POST['phone_num']);
$password = escape_data($_POST['regis_pass']);
$address = escape_data($_POST['postal_address']);
$gender = escape_data($_POST['gender']);
$date = escape_data($_POST['DateField']);
//check if user already exist
$exist = "";
$query = $heidisql->prepare("SELECT user_id as 'exist' FROM users WHERE user_username='$username' OR email_address='$email' ");
$query->execute();
while($userRow = $query->fetch(PDO::FETCH_ASSOC)) {
$exist = $userRow['exist'];
}
if(strlen($exist) > 0){
echo 'Account already exist!';
exit();
} else {
$sql = "";
$stmt = $heidisql->prepare($sql);
$token = bin2hex(random_bytes(20));
$hash = password_hash($password, PASSWORD_BCRYPT);
$stmt->execute(array ( ... ));
my email here
if (mail($to, $subject, $message, $headers)) { // Sending email // email_to, subject, body,email_from
echo 'Thank you for your registration. Check your email, and click on the link to activate your account ';
exit();
} else {
echo'Server failed to sent message, please try again later.';
exit();
}
}
} // END of else statement
exit();
}
debug($errors);
}
WHere exactly should I put the captcha code below into my code... I already try to put it on top but I get an error. Undefined $responseKey or something like that.
$secretKey = "xxxx";
$responseKey = $_POST['g-recaptcha-response'];
$userIP = $_SERVER['REMOTE_ADDR'];
$url = "https://www.google.com/recaptcha/api/siteverify";
$response = file_get_contents($url."?secret=".$secretKey."&response=".$responseKey."&remoteIP=".$userIP);
$data_response = json_decode($response);
if(isset($data_response->success) AND $data_response==true){
} else {
}
The and div are properly place into my form. I just cant pinpoint where the code should be placed exactly.
<?php
$output = NULL;
$ip = $_SERVER['REMOTE_ADDR'];
if (isset($POST['submit'])) {
$username = $mysqli->real_escape_string($_post['username']);
$password = $mysqli->real_escape_string($_post['password']);
$rpassword = $mysqli->real_escape_string($_post['rpassword']);
$email = $mysqli->real_escape_string($_post['email']);
$query = $mysqli->query("SELECT * FROM users WHERE username = '$username'");
if (empty($username) OR empty($password) OR empty($email) or empty($rpassword)) {
$output = "Please fill in all fields!";
} elseif ($query->num_rows != 0) {
$output = "That username is already taken!";
} elseif ($rpassword != $password) {
$output = "Password does not match!";
}
}
?>
Later on in the script, I use this:
<?php
echo $output;
?>
It does not echo, and yes, I have added the mysqli query, but I removed it for the safety of the database. You can also see that it does not echo at the website:
vobern.com
PHP is a case-sensitive Language. There is a difference between $_POST AND $_post. You may also want to take that into consideration. Now why don't you try doing it like below?
<?php
$output = NULL;
$ip = $_SERVER['REMOTE_ADDR'];
if(isset($_POST['submit'])){
// FOR THE VARIABLES BELOW, THERE IS A DIFFERENCE BETWEEN
// $_POST AND $_post (AS YOU WROTE)....
$username = htmlspecialchars(trim($_POST['username']));
$password = htmlspecialchars(trim($_POST['password']));
$rpassword = htmlspecialchars(trim($_POST['rpassword']));
$email = htmlspecialchars(trim($_POST['email']));
$query = $mysqli->query("SELECT * FROM users WHERE username = '$username'");
if (empty($username) || empty($password) || empty($email) || empty($rpassword)){
$output = "Please fill in all fields!";
}elseif($query->num_rows != 0){
$output = "That username is already taken!";
}elseif ($rpassword != $password){
$output = "Password does not match!";
}
}else{
// IF THIS POINT IS REACHED, THEN EVERYTHING SHOULD BE OK
$output = "Login Data is Correct";
}
var_dump($output);
?>
as pointed by DarkBee in comment you have many errors
if(isset($POST['submit'])) replace this with if(isset($_POST['submit']))
All $_post in your code should be $_POST in upper case.
You add one more else to the last
elseif ($rpassword != $password){
$output = "Password does not match!";
}else{
$output = "Valid input!";
}
Here is my code for my index.php page. My header is not working as in not redirecting me to the manage.php page when my users with privs accesses it. The header in my manage.php doesn't work either. I would gladly appreciate anyone's help. I tried re-typing the whole thing again, pasting my instructors code too just to see if maybe it was me that made a mistake but still didn't work, I tried everything :(
<?php
require_once("../req_globals.php");
$error = false;
$message = '';
if(isset($_POST['username']) && isset($_POST['password']))
{
$username = $_POST['username'];
$password = $_POST['password'];
// echo $username;
if(empty($username))
{
$error = true;
$message = $message . "<p>You forgot your username.</p>";
}
if (empty($password))
{
$error = true;
$message = $message . "<p>Do you even password bro?</p>";
}
if($error == false)
{
// echo "working";
$user = mysqli_query($con, "SELECT * FROM users
WHERE username = '" . $username . "'
AND password = '" . $password . "'
LIMIT 1");
$userCount = mysqli_num_rows($user);
$userWorker = mysqli_fetch_assoc($user);
if($userCount < 1)
{
$error = true;
$message = $message . "<p>You don't exist...</p>";
echo $userCount;
}
else
{
if ($userWorker["privs"] == "No")
{
$error = true;
$message = $message . "<p>YOU SHALL NOT PASS!!!</p>";
}
if ($error == false)
{
session_start();
$_SESSION['firstname'] = $userWorker['firstname'];
$_SESSION['privs'] = $userWorker['privs'];
header('Location:ad_manage.php?login=success');
}
}
}
}
?>
header('Location:ad_manage.php?login=success');
exit();
Are you outputting anything before the header is declared? If so, it is not going to work as the headers were already sent.
If no, then try this:
$root = getenv('HTTP_HOST');
header("Location: http://$root/ad_manage.php?login=success");
exit();
I'm having an issue on writing the registration form to the .txt file if a username exist. At the moment, I don't want to write out to the file if a username exist in the user.txt and print out false and if it doesn't exist, continue and write out to the user.txt file.
<?php
if($_POST['submit'])
{
$usernameexist = $_POST['usernameexist'];
$username = $_POST['username'];
$password = $_POST['password'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$dob = $_POST['dob'];
$gender = $_POST['gender'];
$email = $_POST['email'];
$address = $_POST['address'];
$membership = $_POST['membership'];
$creditcard = $_POST['creditcard'];
$cardexpiry = $_POST['cardexpiry'];
$duration = $_POST['duration'];
$name = "/^[A-Za-z]+$/";
$emailaddress = "/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/";
$male_status = 'unchecked';
$female_status = 'unchecked';
// Server side form validation using php.
// Validate username field if empty or not.
if (empty($username)){
$err_username = 'Please enter your username.';
}else{
// Load file and check if username exist
$filename = 'user.txt';
if (file_exists($filename)){
$fp = fopen ('user.txt', 'r');
while ($line = fgetcsv($fp,100,",")) {
if ( ($line[0] == $_POST['username']) ) {
$usernameexist = "Username Exist!";
$err_usernameexist = $usernameexist;
}
}
fclose ($fp);
}
else{
echo '<p> File does not exist! </p>';
}
//$val_username = $username;
}
// Validate password field if empty or not.
if (empty($password)){
$err_password = 'Please enter your password.';
}else{
$val_password = $password;
}
// First Name
if (empty($firstname)){
$err_firstname = 'Please enter your first name.';
}else{
$val_firstname = $firstname;
}
// Last Name
if (empty($lastname)){
$err_lastname = 'Please enter a valid last name.';
}else{
$val_lastname = $lastname;
}
// Gender
if (isset($_POST['submit'])){
$selected_radio = $_POST['gender'];
if($selected_radio == 'Male') {
$male_status = 'checked';
}else if ($selected_radio == 'Female'){
$female_status = 'checked';
}
}
// Email Address
if (!preg_match($emailaddress, $email)){
$err_email = 'Please enter a valid email address.';
}else{
$val_email = $email;
}
if ($_POST['membership'] != 0){
$err_membership = 'Nothing selected!';
}else{
$val_membership = $membership;
}
// Credit Card
if (empty($creditcard)){
$err_creditcard = 'Field is empty, please try again.';
}else{
$val_creditcard = $creditcard;
}
// Card Expiry
if (empty($cardexpiry)){
$err_cardexpiry = 'Field is empty, please try again.';
}else{
$val_cardexpiry = $cardexpiry;
}
// Duration
if (empty($duration)){
$err_duration = 'Field is empty, please try again.';
}else{
$val_duration = $duration;
}
if (!empty($username) && !empty($password) && !empty($firstname)
&& !empty($lastname) && preg_match($emailaddress, $email)
&& ($_GET['membership'] != '0') && !empty($creditcard) && !empty($cardexpiry)
&& !empty($duration)){
$fp = fopen ('user.txt', 'r+');
while ($line = fgetcsv($fp,100,",")){
if($line[0] == $_POST['username']){
$usernameexist = "Username Exist!";
$err_usernameexist = $usernameexist;
echo 'Username EXIST AND WRONG';
}
else{
$output_string = $username. ", "
.$password. ", "
.$firstname. ", "
.$lastname .", "
.$dob .", "
.$gender .", "
.$email .", "
.$address .", "
.$membership .", "
.$creditcard .", "
.$cardexpiry .", "
.$duration ."\n";
$fp = fopen ('user.txt', 'a');
fwrite ($fp, $output_string);
echo "<p> Your Registration was successful! </p>";
}
}fclose($fp);
}
else{
echo 'Please re-check your field as field marked with "*" is required';
}
}
?>
Any help is much appreciate and please excuse my question if it seems too confusing as i am slightly new.
Thanks.
Please forgive apparent criticism but there are a lot of issues with your code and I think it will help if I point out some poor practices first:
Don't keep reassigning variables. Just use them as $_POST['whatever'] there is no advantage in copying them into other memory intensive structures. It obfuscates rather than clarifying your code.
DO NOT EVER store credit card details in a plain text file.
Why are you using a custom CSV data structure? This is what databases are for XML at a pinch.
You test for username existence twice, neither in the right place to fix the problem.
For your answer:
if (!empty($username) && !empty($password) && !empty($firstname)
&& !empty($lastname) && preg_match($emailaddress, $email)
&& ($_GET['membership'] != '0') && !empty($creditcard) && !empty($cardexpiry)
&& !empty($duration)){
$fp = fopen ('user.txt', 'r+');
while ($line = fgetcsv($fp,100,",")){
if($line[0] == $_POST['username']){
$usernameexist = "Username Exist!";
$err_usernameexist = $usernameexist;
echo 'Username EXIST AND WRONG';
}
else{
$output_string = $username. ", "
etc...
Seems to be your problem here. What this says is: "If the data is wrong, check to see if the username exists and if it does, say so, otherwise if the data is correct, post it to the file. [but don't test for username existence first]
Essentially, you are testing for the existence of the username in the wrong place.
Move the username existence check to the other side of the else. You could even (riskily) test for strlen($err_usernameexist)>0 as this will return true if the username exists.
Once again though, this is dangerous code and although it forms an interesting exercise in CSV file manipulation it is not appropriate for the apparent application type it seems to be designed for. It will also break if a user puts a comma in their data.
you could use fputcsv properly by creating an array which is immune to commas though not to quotes:
myarray=array($name,$password,$encryptedcreditcard,$etcetc);
fputcsv($fp,$myarray);
You SHOULD however save the data in mysql where you can at least AES_ENCRYPT your confidential data.
Alternatively, there are plenty of AES classes posted free for PHP. Mysql will handle very large data sets quickly whilst yours just gets slower and slower with time...