When I'm using PHP in JavaScript, then all scripts don't work...
Even if I use php in comment.
<script>
//var variable = <?php echo json_encode($_SESSION['abc']); ?>;
</script>
This comment above destroy all scripts in <script></script> tags.
When I'll delete this line with the comment, then every script will work.
The same thing is when I just want to use PHP in JavaScript (without comment).
Could You help me ?
Here is code which was cut by me (to give You only necessary part of code), please help :) :
<?php
session_start();
if (isset($_POST['login']) && isset($_POST['password']) && isset($_POST['email']))
{
$validation = true;
$firstName = $_SESSION['firstName'];
$lastName = $_SESSION['lastName'];
$street = $_SESSION['street'];
$phone = $_SESSION['phone'];
$login = $_POST['login'];
$password = $_POST['password'];
$email = $_POST['email'];
require_once "connect.php";
mysqli_report(MYSQLI_REPORT_STRICT);
try
{
$connection = new mysqli($host, $db_user, $db_password, $db_name);
if($connection->connect_errno!=0)
{
throw new Exception(mysqli_connect_errno());
}
else
{
if ($validation == true) // when validation process will be successfuly done - i cut validation process
{
if($connection->query("INSERT INTO users values (NULL, '$firstName', '$lastName', '$street', '$phone', '$login', '$password', '$email')"))
{
$_SESSION['abc'] = "done";
//here is also header(location) to login page
}
else
{
throw new Exception($connection->error);
}
}
$connection->close();
}
}
catch(Exception $e)
{
echo '<div class="error">error. sorry, please to register in other term</div>';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<script>
//there are other functions for local/session storage
function deleteSessionData()
{
var variable = "<?php echo $_SESSION['abc']; ?>";
if(variable == "done")
{
sessionStorage.removeItem('firstName');
sessionStorage.removeItem('lastName');
sessionStorage.removeItem('street');
sessionStorage.removeItem('phone');
sessionStorage.removeItem('login');
sessionStorage.removeItem('password');
sessionStorage.removeItem('email');
}
}
</script>
</head>
<body>
<form id="myForm" method="post">
<label for="login">Login: </label>
<input type="text" id="login" name="login">
<label for="password">Password: </label>
<input type="text" id="password" name="password">
<label for="email">E-mail:</label>
<input type="email" id="email" name="email">
<button onclick="java script: document.getElementById('myForm').submit();deleteSessionData();">Register</button>
</form>
</div>
</body>
</html>
you need to comment the php too
//var variable = <?php // echo json_encode($_SESSION['abc']); ?>;
I wouldn't inject PHP into javascript like this without sanitation though.
Related
I am doing email validation for admin registration using JavaScript and save the data to database using PHP. Supposedly, the registration is done only if the email is valid. But when the email evaluates to invalid, the PHP code still run. How do I do it so that when the email is invalid, the PHP won't run.
Below is the PHP code to save data to database:
<?php
include('connection.php');
if(isset($_POST['saveBtn']))
{
$name = $_POST['name'];
$ic = $_POST['ic'];
$email = $_POST['email'];
$pass = $_POST['pass'];
$dob = $_POST['dob'];
$contact = $_POST['contact'];
$gender = $_POST['gender'];
$des = $_POST['des'];
$address = $_POST['address'];
// Check if data exist
$check = "SELECT * FROM admin WHERE admEmail = '".$email."' AND admPassword = '".$pass."'";
if(mysqli_num_rows(mysqli_query($connect,$check)) > 0)
{
?>
<script>
alert('This email and password already registered!');
</script>
<?php
}
else
{
$insert = "INSERT INTO admin (admName, admIC, admEmail, admPassword, admDOB, admContact, admGender, admDesignation, admAddress, admDateJoin) VALUES ('".$name."', '".$ic."', '".$email."', '".$pass."', '".$dob."', '".$contact."', '".$gender."', '".$des."', '".$address."', NOW())";
if(mysqli_query($connect, $insert))
{
?>
<script>
alert('Insertion Successful!');
window.close();
window.opener.location.reload();
</script>
<?php
}
else
{
?>
<script>
alert('Insertion Failed. Try Again!');
</script>
<?php
}
}
}
?>
Below is the JS:
function validateEmail() {
var email = document.addAdminForm.email.value;
var validRegex = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
if (email.match(validRegex))
{
alert("Valid email address!");
return true;
}
else
{
document.getElementById("email_error").innerHTML = "Invalid email";
document.addAdminForm.email.focus();
return false;
}
}
Below is the partial HTML form:
<form class="w-100" name="addAdminForm" method="POST" onsubmit="validateEmail(this)" action="add_admin.php">
<div class="row">
<div class="col form-group">
<!-- <label for="email">Email</label> -->
<input type="text" class="form-control" name="email" placeholder="Email" required>
<span class="error email_error" id="email_error"></span>
</div>
<div class="float-right">
<input type="submit" class="btn button_primary" value="Save" name="saveBtn">
</div>
</form>
I expect PHP run when validation is true
add this:
onsubmit="return validateEmail(this)"
change your JS code to:
var validRegex = /^([a-zA-Z0-9_-])+#([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/;
This question already has an answer here:
Php Redirects to wrong URL when error hanling (Login)
(1 answer)
Closed 3 years ago.
I need some help to solve this problem.
I currently have a website with a database attached with myphpadmin/sql.
I have a register site that redirects users to this url when the registration fields are empty. (http://localhost/register.php?signup=empty)
the problem i am have is that when i try to login on my login page, i want the user to be redirected to this these two url's when an error or empty fields occures. (index.php?login=empty) and (index.php?login=error). and then (index.php?login=success) when the correct credentials have been typed.
The problem is that when i submit the login on my login/index page, i always gets redirected to (index.php?login=empty).
Therefore i think that my fields on the login page are linked to something that aint right?? But i really cant seeem to solve the problem. So any help would be appreciated.
This is my code.
INDEX.php
<?php
session_start();
?>
<!DOCTYPE html <html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="stylesheet.css" />
<title>CSS Login form</title>
</head>
<body>
<div class="login">
<form class=”loginform” action="login.php" method="POST">
<label for="name" style="color: blue;">name</label>
<br>
<input type="text" name="name" id="name" />
<br>
<label for="password">password</label>
<br>
<input type="password" name="password" id="password" />
<br>
<button type="submit" name="submit">Sign in</button>
<!-- <input type="submit" name="submit" value="Sign In"> </form> -->
<input type="button" value="Sign Up" onclick="location.href='register.php';" />
</form>
</div>
</body>
</html>
LOGIN.php
<?php
session_start();
if (isset($_POST['submit'])) {
include 'dbh.inc.php';
$name = mysqli_real_escape_string($conn, $_POST['name']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
//check inputs
if (empty($name) || empty($password)) {
header("Location: ../login.php?login=empty");
exit();
} else {
$sql = "SELECT * FROM users WHERE user_name='$name'";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resulstCheck < 1) {
header("Location: ../index.php?login=error");
exit();
} else {
if ($row = mysqli_fetch_assoc($result)) {
//de-hashing password
$hashedPasswordCheck = password_verify($password, $row['user_password']);
if ($hashedPasswordCheck == false) {
header("Location: ../index.php?login=error");
exit();
} elseif ($hashedPasswordCheck == true) {
//If true log the user in
$_SESSION['u_id'] = $row['user_id'];
$_SESSION['u_name'] = $row['user_name'];
$_SESSION['u_phone'] = $row['user_phone'];
$_SESSION['u_email'] = $row['user_email'];
$_SESSION['u_zip'] = $row['user_zip'];
header("Location: ../index.php?login=success");
exit();
}
}
}
}
} else {
header("Location: ../index.php?login=error");
exit();
}
Register.php
<?php
session_start();
//Check if the user clicked the button,
//to make sure they dont have acces to the code
if (isset($_POST['submit'])) {
include_once 'dbh.inc.php';
$dbServername = "localhost";
$dbUsername = "root";
$dbPassword = "";
$dbName = "loginsystem";
$conn = mysqli_connect($dbServername, $dbUsername, $dbPassword, $dbName);
$name = mysqli_real_escape_string($conn, $_POST['name']);
$phone = mysqli_real_escape_string($conn, $_POST['phone']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$zip = mysqli_real_escape_string($conn, $_POST['zip']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
if (empty($name) || empty($phone) || empty($email) || empty($zip) || empty($password)) {
header("Location: ../register.php?signup=empty");
exit();
} else {
if (
!preg_match("/[\w\s]+/", $name) || !preg_match("/^(\\+)[0-9]{8,30}$/", $phone) ||
!preg_match("/[^#]+#[^#]+\.[^#]+/", $email) || !preg_match("/^[0-9]{4}$/", $zip) ||
!preg_match("/^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9]).{8,}$/", $password)
) {
header("Location: ../register.php?signup=invalid");
exit();
} else {
//Check email
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("Location: ../signup.php?signup=email");
exit();
} else {
$sql = "SELECT * FROM users WHERE user_id='$user_id'";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
header("Location: ../signup.php?signup=usertaken");
exit();
} else {
//Hashing of the Password
$hashedPwd = password_hash($password, PASSWORD_DEFAULT);
//Insert user to database
$sql = "INSERT INTO users (user_name, user_phone, user_email,
user_zip, user_password) VALUES ('$name', '$phone', '$email',
'$zip', '$hashedPwd');";
mysqli_query($conn, $sql);
header("Location: ../signup.php?signup=success");
exit();
}
}
}
}
}
?>
<!DOCTYPE HTML>
<html>
<head></head>
<body>
<form class=”this.html” method="POST">
<label for="name" style="color: blue;">name</label>
<br>
<input type="text" name="name" id="name" />
<br>
<label for="password">password</label>
<br>
<input type="password" name="password" id="password" />
<br>
<label for="phone">phone number</label>
<br>
<input type="text" name="phone" id="phone" />
<br>
<label for="email">email adress</label>
<br>
<input type="text" name="email" id="email" />
<br>
<label for="zip">zip code</label>
<br>
<input type="text" name="zip" id="zip" />
<br>
<button type="submit" name="submit">Sign up</button>
</form>
</body>
</html>
As per your last comment, your connection file location is not correct,
Due to redirections, you cant able to get or show actual issue, after debugging this:
print_r($_POST);
exit;
after this include 'dbh.inc.php'; showing you actual issue,
Issue: your connection file is not located at same directory.
include 'dbh.inc.php';
should be:
include 'includes/dbh.inc.php';
Side note:
Your code is wide open for SQL injection, you can use PDO to prevent with SQL injection.
Some useful links:
Are PDO prepared statements sufficient to prevent SQL injection?
How can I prevent SQL injection in PHP?
Edit:
Regarding session related issue, You have already started your session inside your login.php file, so no need to use in dbh.inc.php
Additionally, remove extra spaces before session_start() otherwise, this will generate an another error.
I have made two pages. I have used php form validation in my first page, i.e., form.php and I have to give action on second page i.e., data_ins.php. Please let me know how will it possible with my coding.
Here are my pages:
form.php
<?php $fnameErr = $lnameErr = "";
$fname = $lname= ""; if($_SERVER["REQUEST_METHOD"] == "POST") {
if(empty($_POST['fname']))
{
$fnameErr = "First Name is required";
}
else
{
$fname= formVal($_POST['fname']);
}
if(empty($_POST['lname']))
{
$lnameErr = "Last Name is required";
}
else
{
$lname= formVal($_POST['lname']);
} }
function formVal($data)
{
$data = trim($data);
$data = stripcslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?> <!DOCTYPE html> <html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
First Name:
<input type="text" name="fname"> <span style="color:red;"><?php echo $fnameErr ?></span> <br>
Last Name:
<input type="text" name="lname"> <span style="color:red;"><?php echo $lnameErr ?></span> <br>
<input type="submit" name="submit">
</form>
</body> </html>
data_ins.php
<?php $conn = mysqli_connect("localhost","root","","test_db");
$sql = "insert into records (FirstName, LastName) values ('$fname', $lname)";
if($result=mysqli_query($conn, $sql))
{
echo "Data Inserted Successfull";
}
else
{
echo "Invalid";
}
mysqli_error($conn); ?>
Personally, I think you may of made it harder than you needed to.
Here is what I'd do with the PHP side:
if (isset($_POST['submit']))
{
if (!empty($_POST['fname']))
{
if (!empty($_POST['lname']))
{
// Add Database insert code here..
} else {
echo "Last name is required";
}
} else {
echo "First name is required";
}
}
As for the form, you don't need to add the PHP self (just add the method) like so:
<form method="POST" action="">
First Name: <input type="text" name="fname"><br>
Last Name: <input type="text" name="lname"><br>
<input type="submit" name="submit">
</form>
Hope this helps more so than your initial idea of doing it.
PLEASE NOTE: I haven't added the $data trim etc in but you'd add these in firstly where // do code note is.
1.change your form like this
`<form method="POST" action="location of your data_ins.php">`
2.in your data_ins.php must have database config code or include it.
3.get your all form value in data_ins.php pass to insert query
<form method="POST" action="">
First Name: <input type="text" name="fname"><br>
Last Name: <input type="text" name="lname"><br>
<input type="submit" name="submit">
</form>
Besides your code, your method (as question is not about it).
To execute other .php file you can use PHP statements:
require
include
include_once
In your case require should be the one to use, like: require 'data_ins.php'; after validation.
I have the following box that contains a sign upform:
<!-- sign up form -->
<div id="cd-signup">
<form class="cd-form" action = "signup.php" > <?php echo "$error" ?>
<p class="fieldset">
<label class="image-replace cd-username" for="signup-username">Username</label>
<input class="full-width has-padding has-border" id="signup-username" type="text" placeholder="Username" name = "user" <?php echo "value='$user'"?>>
</p>
<p class="fieldset">
<label class="image-replace cd-password" for="signup-password">Password</label>
<input name = "pass" class="full-width has-padding has-border" <?php echo "value='$pass'" ?> id="signup-password" type="text" placeholder="Password">
<!-- <span class="cd-error-message">Password must be at least 6 characters long</span> -->
</p>
<p class="fieldset">
<input class="full-width has-padding" type="submit" value="Create account">
</p>
</form>
<!-- more text here -->
<span class="section-nav">
<ul>
<li><a id="signup" class="cd-signup" href="#0">Get Started</a></li>
<li><a id="learnmore" class="cd-learnmore" href="#section2">Learn More</a></li>
</ul>
</span>
<span class="section-nav">
<ul>
<li><a id="signup" class="cd-signup" href="#0">Get Started</a></li>
</ul>
These were implemented as a button shape.
I included at the head of my html file (index.php) the following php code:
<?php
require_once 'functions.php';
require_once 'signup.php';
$userstr = '';
if (isset($_SESSION['user'])) {
$user = $_SESSION['user'];
$loggedin = TRUE;
$userstr = " ($user)";
}
else $loggedin = FALSE;
if ($loggedin) {
header(home.php);
}
else {
?>
signup.php:
session_start();
<?php
$error = $user = $pass = "";
if (isset($_SESSION['user'])) destroySession();
if (isset($_POST['user']))
{
$user = sanitizeString($_POST['user']);
$pass = sanitizeString($_POST['pass']);
if ($user == "" || $pass == "")
$error = "Not all fields were entered<br><br>";
else
{
$result = queryMysql("SELECT * FROM members WHERE user='$user'");
if ($result->num_rows)
$error = "That username already exists<br><br>";
else
{
queryMysql("INSERT INTO members VALUES('$user', '$pass')");
die("<h4>Account created</h4>Please Log in.<br><br>");
}
}
}
?>
functions.php:
<?php
$dbhost = 'localhost'; // Unlikely to require changing
$dbname = 'socialmedia'; // Modify these...
$dbuser = 'root'; // ...variables according
$dbpass = 'mysql'; // ...to your installation
$appname = "Social Media"; // ...and preference
$connection = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if ($connection->connect_error) die($connection->connect_error);
function queryMysql($query)
{
global $connection;
$result = $connection->query($query);
if (!$result) die($connection->error);
return $result;
}
function destroySession()
{
$_SESSION=array();
if (session_id() != "" || isset($_COOKIE[session_name()]))
setcookie(session_name(), '', time()-2592000, '/');
session_destroy();
}
function sanitizeString($var)
{
global $connection;
$var = strip_tags($var);
$var = htmlentities($var);
$var = stripslashes($var);
return $connection->real_escape_string($var);
}
function showProfile($user)
{
if (file_exists("$user.jpg"))
echo "<img src='$user.jpg' style='float:left;'>";
$result = queryMysql("SELECT * FROM profiles WHERE user='$user'");
if ($result->num_rows)
{
$row = $result->fetch_array(MYSQLI_ASSOC);
echo stripslashes($row['text']) . "<br style='clear:left;'><br>";
}
}
?>
The code works perfectly from where I got it (source: Learn Php, MySql, & Javascript), so I decided to apply it to me own website.
However, When I click on the create account button, nothing happens. The database is correctly set along with the appropriate tables (tested on original code) along with the proper Ajax Requests.
I think the problem is somewhere in index.php, maybe something I missed ?
Thank you for your help ! :)
EDIT:
here is the javascript of the button implementation
jQuery(document).ready(function ($) {
var formModal = $('.cd-user-modal'),
formSignup = formModal.find('#cd-signup'),
tabSignup = formModalTab.children('li').eq(1).children('a'),
,
backToLoginLink = formForgotPassword.find('.cd-form-bottom-message a'),
mainNav = $('.main-nav'),
sectionNav = $(".section-nav");
//open modal
mainNav.on('click', function (event) {
$(event.target).is(mainNav) && mainNav.children('ul').toggleClass('is-visible');
});
//open sign-up form
sectionNav.on('click', '.cd-signup', signup_selected);
//open login-form form
mainNav.on('click', '.cd-signin', login_selected);
//close modal
formModal.on('click', function (event) {
if ($(event.target).is(formModal) || $(event.target).is('.cd-close-form')) {
formModal.removeClass('is-visible');
}
});
//close modal when clicking the esc keyboard button
$(document).keyup(function (event) {
if (event.which == '27') {
formModal.removeClass('is-visible');
}
});
//switch from a tab to another
formModalTab.on('click', function (event) {
event.preventDefault();
($(event.target).is(tabLogin)) ? login_selected() : signup_selected();
});
function signup_selected() {
mainNav.children('ul').removeClass('is-visible');
formModal.addClass('is-visible');
formLogin.removeClass('is-selected');
formSignup.addClass('is-selected');
formForgotPassword.removeClass('is-selected');
tabLogin.removeClass('selected');
tabSignup.addClass('selected');
}
Take a look at this line:
<p class="fieldset">
<input class="full-width has-padding" type="submit" value="Create account">
</p>
Your submit button should have a name of user.
<p class="fieldset">
<input class="full-width has-padding" name="user" type="submit" value="Create account">
</p>
So I have an index.php and a r.php. R.php is the registration part. And index.php is the actual form. My question is how can I have errors from r.php be send back to index.php if they exist. So instead of displaying errors on r.php I want them on index.php and prevent the form from advancing.
Here's the index.php
<!DOCTYPE html>
<html>
<body>
<form method="post" action="r.php">
<input type="text" name="name" placeholder="Name">
<input type="submit">
</form>
</body>
Its all very simple. Now here's r.php
<?php
$name = $_POST['name'];
if ($name < 3){
//display error
}
else {
//proceed
}
?>
Should I do this with JS? Or this there a better way.
One way is to use sessions:
<?php session_start(); ?>
<!DOCTYPE html>
<html>
<body>
<?php echo isset($_SESSION['message']) ? $_SESSION['message'] : ''; ?>
<form method="post" action="r.php">
<input type="text" name="name" placeholder="Name">
<input type="submit">
</form>
</body>
<?php
session_start();
unset($_SESSION['message']);
$name = $_POST['name'];
if ($name < 3){ // you probably want strlen($name) < 3
$_SESSION['message'] = 'error';
header('Location: index.php');
exit;
}
else {
//proceed
}
?>
Other than sessions you could redirect back with a query string and use that:
header('Location: index.php?message=' . urlencode('some kind of error');
Then:
<?php echo isset($_GET['message']) ? $_GET['message'] : ''; ?>
Using a single script for this would be easier, just put this all in one file, and check to see if the form has been submitted. If the form has been submitted, you an just include the variables you want straight away.
This is pretty crude, but it gives you an idea of where you can go with this:
<?php
if (isset($_POST['name'])) {
// Begin processing form stuff
$name = $_POST['name'];
// Initialise error variable
$error = null;
if ($name < 3) {
// Display error, for example:
$error = 'Name is less than 3';
} else {
// Proceed
}
}
?>
<!DOCTYPE html>
<html>
<body>
<?php if ( ! empty($error)) { ?>
<p><?php echo $error; ?></p>
<?php } ?>
<form method="post" action="r.php">
<input type="text" name="name" placeholder="Name">
<input type="submit">
</form>
</body>
</html>
<!DOCTYPE html>
<html>
<?php
$msg = '';
if(isset($_GET['e'])
{
$msg = "Error! Input not valid.";
}
?>
<body>
<?php
if($msg!='')
{
echo "<font color='red'>".$msg."</font>";
}
?>
<form method="post" action="r.php">
<input type="text" name="name" placeholder="Name">
<input type="submit">
</form>
</body>
Just pass a variable e using GET request to the index page if an error is found.
<?php
$name = $_POST['name'];
if ($name < 3){
header("Location: index.php?e=error");
}
else {
//proceed
}
?>
GET request will send the variable e using the URL, and if e is found to be having a value, it means there was an error in r.php
Use javascript for simple form validation. In case you require some security stuff or db stuff, you can use session/cookie or use header function to go back.