403 Forbidden error in PHP Login - javascript

Whenever I click the submit button of my login, I'm taken to a blank page which has the texts "403 Forbidden", I feel that this may be due to the URL of my login page as it is "mywebsite.com8:8888/login/" and is hosted on a different port (I'm using Tornado web server).
HTML
<form method="POST">
<fieldset id="inputs">
<input name="username" id="username" required>
<input name="password" id="password" type="password" name="Password" placeholder="Password" required>
</fieldset>
<fieldset id="actions">
<input type="submit" id="submit" value="Log in" name="submit">
<label><input type="checkbox" checked="checked"> Keep me signed in</label>
</fieldset>
</form> <div id="container"></div>
PHP
<?php header('Access-Control-Allow-Origin: *'); ?>
<?php
if (isset($_POST['submit'])){
session_start();
error_reporting(0);
$username = $_POST['username'];
$password = md5($_POST['password']);
$connection = mysql_connect("localhost", "moot", "lmlkmklmklmkl"); // Establishing Connection with Server
$db = mysql_select_db("snamr", $connection); // Selecting Database from Server
$sql="SELECT * FROM accs WHERE name='$username' and password='$password'";
$result=mysql_query($sql);
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
$check = mysql_query("SELECT active FROM accs WHERE name = '$username'");
while($rows=mysql_fetch_assoc($check)){
$active = $rows['active'];
}
// If result matched $myusername and $mypassword, table row must be 1 row
if($count!=1){
echo "Wrong Username or Password";
}
elseif ($active == 0) {
echo "Your account isn't active!";
}
else {
$_SESSION['username'] = $username;
}
$time = time();
$setLogged= mysql_query("UPDATE accs SET loginstatus = '$time' WHERE name = '$username'") or die(mysql_error());
}
}
?>
JAVASCRIPT WHICH LOADS THE PHP INTO HTML (good reasons for this)
<script type="text/javascript">
$(document).ready(function(){
$("#container").load('http://mywebsite.com/sname/signing.php');
});
</script>
The login form along with the PHP works with all other files on my default port but when I take the code to my files hosted on port 8888 things go wrong. Hence why I think the main issue may be in the domain.
Any solutions?

Related

Showing success message on a redirected page

There's two pages: one is index.php and another is add-name.php . add-name.php has a form which takes a name and after a successful submission, it redirects to index.php page where all the names is shown.
I was wondering how can I show a message that the name has been added on index.php page after add-name.php page redirects to index.php page when it's submitted.
add-name.php
<?php
if ($_SERVER["REQUEST_METHOD"] === "POST"){
$name = $_POST["name"];
addName($name); // this addName function saves the name to a
file called names.txt and index.php page
uses this file to access all the names
header("Location: index.php");
}
?>
<form action="add-name.php" method="POST">
<label for="name">Name:</label>
<input type="text" name="name" id="name">
<input type="submit" name="submitButton" value="Save">
</form>
Use session
add-name.php
<?php
if ($_SERVER["REQUEST_METHOD"] === "POST"){
$name = $_POST["name"];
// addName($name);
session_start();
$_SESSION["name"] = "added";
header("Location: index.php");
exit();
}
?>
<form action="add-name.php" method="POST">
<label for="name">Name:</label>
<input type="text" name="name" id="name">
<input type="submit" name="submitButton" value="Save">
</form>
index.php
<?php
session_start();
if (isset($_SESSION["name"]) && $_SESSION["name"] === "added") {
echo "name added";
unset($_SESSION["name"]);
} else {
echo "just called";
}
# ...

PHP redirecting to wrong URL when trying logging in with a form [duplicate]

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.

PHP in JavaScript brokes all scripts

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.

i can not add informations to my table at mysql. i use javascript to show an information message and it doesnot do anything then

this is my php code to add to my database. dbConfic.php is my connection to database. I have tried it for the others page i made and it works fine.
<?php
session_start();
if(isset($_POST['Send'])) {
include('dbConfig.php');
$date=$_POST['lname'];
$comm=$_POST['fname'];
$username1=$_POST['address'];
$id1=$_POST['costname'];
$sql="INSERT INTO damage (damageid, damagetype, description,damagedate,damagecost)
VALUES (NULL,'$date', '$comm', '$username1','$id1')";
if ($sql){
echo "Insert successful";
} else {
echo "Insert failed.";
}
}
my form is in the same page: and have 4 text fields and 2 buttons. For the button send i use javascript at the seperate js document. My js works fine and shows the message i want but the information dont add to database.
<p>type of damage:<input type="text" name="lname" size="60">
<br>
description:<input type="text" name="fname" size="60">
<br>
Date of record damage:<input type="text" name="address" size="60">
<br>
Estimated cost<input type="text" name="costname" size="60">
<br>
<input type="button" name="Send" value="send" onclick="respond();">
<input type="reset" value="reset">
</p>
</form>
This IF statement will always result in true
$sql="INSERT INTO damage (damageid, damagetype, description,damagedate,damagecost)
VALUES (NULL,'$date', '$comm', '$username1','$id1')";
if ($sql){
echo "Insert successful";
} else {
echo "Insert failed.";
}
I think what you're trying to do is
$db = new PDO("mysql:host=localhost;dbname=test", $user, $pass);
$query = $db->prepare($sql);
$result = $query->execute();
if ($result) {
// success
}
else {
// fail
}
You want to test the result of running your query, not testing the $sql string itself.

Redirect happens before form data is processed

What i'm trying to do here is to sends an email to a salesperson notifying them that their client has viewed a google docs presentation.
The query's Num=val is a serial number that I use to get the actual google doc's url out of a database and stuff it into a form.
My problem is that the page redirects before the data is retrieved, and ends up going to the default for the site, nitrofill.com.index
The gdform.php file has the header redirect, which works fine if I don't try to process the form when the page loads. Heres the code:
<?php
$sn=$_GET['num'];
echo $sn;
mysql_connect($hostname,$username, $password) OR DIE ('Unable to connect to database! Please try again later.');
mysql_select_db($dbname);
$selectSQL = "select * from `Presentations` where `serialnum` ='" . $sn ."'" ;
$result = mysql_query($selectSQL) or die(mysql_error());
$row = mysql_fetch_array($result, MYSQL_BOTH);
?>
<script type="text/javascript">
function myfunc () {
var frm = document.getElementById("notice");
frm.submit();
}
window.onload = myfunc;
</script>
<title>Nitrofill Document</title></head>
<body>
<form id="notice" action="http://m3sglobal.com/gdform.php" method="post">
<input type="hidden" name="subject" value="<?php echo (urldecode($row['recipient'])) . " has viewed the document you sent them."; ?>" />
<input type="hidden" name="redirect" value="<?php echo ((urldecode($row['docurl']))); ?>"/>
<label>Email:</label><input type="text" name="email" value="<?php echo (urldecode($row['tracker'])); ?>"/>
<label>Comments:</label><textarea name="comments" cols="40" rows="5">
Document Viewed:<?php echo ((urldecode($row['docurl']))); ?>
When Accessed:<?php echo ((urldecode($row['last_accessed']))); ?>
</textarea>
<input type="submit" name="submit"/>
</form>
The gdform.php does the redirect like this:
while (list ($key, $val) = each ($query_vars)) {
fputs($fp,"<GDFORM_VARIABLE NAME=$key START>\n");
fputs($fp,"$val\n");
fputs($fp,"<GDFORM_VARIABLE NAME=$key END>\n");
if ($key == "redirect") { $landing_page = $val;}
}
fclose($fp);
if ($landing_page != ""){
header("Location: " . $landing_page);
} else {
header("Location: http://".$_SERVER["HTTP_HOST"]."/");
}
Thanks for looking!
Code in HTML is executed top-down. You're submitting as soon as you get to that block of JavaScript, which is before you even render the form on the page.
Move your JS code to the bottom of the page, or execute it after the DOM is ready.

Categories

Resources