So I have index.php has my default page. It works fine on xampp. So I uploaded my whole site to 1&1 (my domain/hosting provider) and when I try to go to my domain I get an empty alert with no message and a completely blank page.
I changed the name of the file to index.html and the webpage loaded just fine. So I know it must be something with the .php extention or my code up top.
I also added a file called .htaccess and it contains only:
DirectoryIndex index.php
Here is my php code at the top of index.php (replaced sensitive infow with *s):
<?php
//Connect to a database
$host_name = "******.db.1and1.com";
$database = "db****";
$user_name = "dbo******";
$password = "***z.0**";
$connect = mysqli_connect($host_name, $user_name, $password, $database);
// echo("nice job");
//Take the values from the html form and assign them to variables
$ID = $_POST['name'];
$userpassword = $_POST['password'];
//If no passsowrd entered then go straight to index.php
echo "<script type='text/javascript'>alert($userpassword);</script>";
if ($userpassword == null) {
header("Location: http://localhost:82/index3.php");
die();
}
//Check to see if the password matches the hashes
if (md5($userpassword) === '******************'
or md5($userpassword) === '***********'
or md5($userpassword) === '****************'
or md5($userpassword) === '**************')
{
//Add the visitor name to our list
mysqli_query($connect, "INSERT INTO `WebsiteVisitors` (`Name`) VALUES ('$ID')") or die("Error in INSERT: ".mysqli_error($connect));
// echo "You have entered the correct password, congrats.";
// Start the session so they can access other pages
session_start();
$_SESSION['loggedIn'] = true;
// Redirect them to rest of site
header("Location: http://localhost:82/home.php");
die();
}
else {
header("Refresh: 0; url=index2.php");
echo "<script type='text/javascript'>alert(\"Wrong Password. Check your invitation card.\");</script>";
}
?>
Since $_POST request comes only after submitting form in your case, you need to only execute the username and password checks if $_POST["name"] and $_POST["password"] exists.
So give an if statement if(isset($_POST['name']) && isset($_POST['password'])) before using and manipulating $_POST variables. Alson session_start() should be given at top of your script.
Below is your complete code including the check
<?php
session_start();
// session start should be at top of your script
error_reporting(E_ERROR); // reports only errors
//Connect to a database
$host_name = "******.db.1and1.com";
$database = "db****";
$user_name = "dbo******";
$password = "***z.0**";
$connect = mysqli_connect($host_name, $user_name, $password, $database);
// $_POST request comes only when form is submitted in your case. So check for $_POST['name'] and $_POST['password']
if(isset($_POST['name']) && isset($_POST['password']))
{
$ID = $_POST['name'];
$userpassword = $_POST['password'];
//If no passsowrd entered then go straight to index.php
if ($userpassword == null)
{
echo "<script type='text/javascript'>alert("Empty Password");</script>";
header("Location: http://localhost:82/index3.php");
die();
}
//Check to see if the password matches the hashes
if (md5($userpassword) === '******************'
or md5($userpassword) === '***********'
or md5($userpassword) === '****************'
or md5($userpassword) === '**************')
{
//Add the visitor name to our list
mysqli_query($connect, "INSERT INTO `WebsiteVisitors` (`Name`) VALUES ('$ID')") or die("Error in INSERT: ".mysqli_error($connect));
$_SESSION['loggedIn'] = true;
// Redirect them to rest of site
header("Location: http://localhost:82/home.php");
die();
}
else
{
echo "<script type='text/javascript'>alert(\"Wrong Password. Check your invitation card.\");</script>";
header("Refresh: 0; url=index2.php");
}
}
?>
Related
I'm making a login system. Everything works, but when i use a email (username) in the login that is not in the database it will go to the URL with filename and then just the form data (email and password). I need to set the header with an error so i can say that login was failed. Does anyone see the problem?
<?php
ob_start();
if (isset($_REQUEST['password'])) {
require 'connect.php';
$password = $_REQUEST['password'];
$mail = $_REQUEST['email'];
if (empty($mail) || empty($password)) {
header('location: ../login.php?error=empty');
exit();
} else {
$sql = "SELECT * FROM account WHERE email = ?;";
$stmt = mysqli_stmt_init($connect);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../login.php?error=sqlError");
exit();
} else {
mysqli_stmt_bind_param($stmt, "s", $mail);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
if ($row = mysqli_fetch_assoc($result)) {
$passwordCheck = password_verify($password, $row['wachtwoord']);
if ($passwordCheck == false) {
header("Location: ../login.php?error=passwordWrong");
exit();
} elseif ($passwordCheck == true) {
session_start();
$_SESSION['userId'] = $row['account_id'];
$_SESSION['username'] = $row['gebruikersnaam'];
header("Location: ../index.php?login=succes");
exit();
}
} else {
header("Location login.php?error=noUser");
exit();
}
}
}
} else {
header("Location: ../login.php?error=");
exit();
}
Since your login form is working.
Let me ask you:
Is Your form action using get method or post method?.
Remember when you send a form with GET method to backend eg to a php file, all the form parameters are seen in the url okay.
So You can check this below.
1.) Ensure that your form is using Post method eg method="POST"
2). Why are you using $_REQUEST[..]. in php
its better you used $_POST method for http request coming from form inputs
Something like
if(isset($_POST['submit'])){
require 'connect.php';
$password = $_POST['password'];
$mail = $_POST['email'];
OR
if (isset($_POST['password'])) {
require 'connect.php';
$password = $_POST['password'];
$mail = $_POST['email'];
Note: The variables in $_REQUEST are provided to the script via the GET, POST, and COOKIE input mechanisms and
therefore could be modified by the remote user and cannot be trusted. Therefore proper validation and sanitization should be
done on both front and backend.
see php manual warnings
Finally,
If any of this suggestion does not work for you, you can then upload also all your form fields and I will get it working for you. Thank You
I am having problems with my code. This is a login/register script I've made by following a tutorial.
The problem I have is that I want the script to echo "logged in" ONLY when the user has entered correct login details, and yet it still echoes "logged in" even if I don't enter any login details. I checked it and if I delete the "session_start()" function, it doesn't do the same thing, but it still doesn't give me access to the session when I want to login.
This is the init.php file, used to initiate the connection with the database and define some other functions:
<?php
session_start();
require 'database/connect.php';
require 'functions/general.php';
require 'functions/users.php';
$errors = array();
?>
This is the connect.php file, used to connect to the database :
<?php
$connect_error = 'Sorry, we are experiencing connection issues. This will be solved as soon as possible.';
$con=mysqli_connect("localhost","root","","lr") or die ($connect_error);
mysqli_select_db($con,'lr') or die($connect_error);
mysqli_close($con);
?>
The general.php file is not important for this question.
This is the users.php file, where I keep some other functions.
function user_id_from_username ($username){
$username = sanitise($username);
$mysqli = new mysqli("localhost", "root", "", "lr");
$query = "SELECT * FROM users";
$result = $mysqli->query($query);
while($row=$result->fetch_row()){
if ($row[1]==$username){ //username == $username
return $row[0];//user_id;
}
}
}
function login ($username, $password){
$user_id= user_id_from_username($username);
$mysqli = new mysqli("localhost", "root", "", "lr");
$username = sanitise($username);
$password =md5 ($password);
$query = "SELECT * FROM users";
$result = $mysqli -> query($query);
while ($row =$result -> fetch_row()){
if($row[1]==$username && $row[2]==$password){
return TRUE;
}else {
return FALSE;
}
}
}
This is the file that calls the login function, presented above:
<?php
include 'core/init.php';
if (empty($_POST) === false) {
$username = $_POST['username'];
$password = $_POST['password'];
if (empty($username) ===TRUE || empty ($password) === TRUE) {
$errors[]='You need to enter a username and password!';
} else if (user_exists($username) ===FALSE) {
$errors[]="We can't find that username, have you registered?";
} else if (user_active($username)===FALSE){
$errors[]="You have not activated your account!";
} else{
$login = login($username, $password);
session_start();
if ($login ==false) {
$errors[] ='That username/password combination is incorrect!';
}else if ($login==true) {
//set the user session
$_SESSION['username'] = $login;
//redirect user to homepage
header('Location: index.php');
exit();
}
}
if ($errors){
print_r($errors);
}
}
?>
And now the index.php file, in which I have the if statement that echoes 'logged in' even if I am not logged in :
<?php
if (empty($_SESSION['username'])) {
echo 'not logged_in';
}else {
echo 'logged in';
}
?>
Now I think the problem is located somewhere either in the users.php, login.php or in the index.php file. I presented all of the files so you could get an idea of what I am trying to achieve. This code is spread over so many files because I have functions and interfaces that I have included and I want to be able to reuse the code, so I am using includes.
For you to get a better idea, if my files did not help you enough, I will leave the Youtube link of the tutorial I am following :
https://www.youtube.com/watch?v=JUk2e8oqOvI&list=PLE134D877783367C7&index=7#t=6.296979
Thank you,
Waiting for your answer,
Best regards,
If you don't use $_GET requests to include the pages, you need to put session_start() on top of each file where you are using the $_SESSION variable otherwise you can't use the sessions.
<?php
session_start();
// Rest of your script
I hope this will help you.
I have created a website lately with a group of students, but were having some troubles.
We created the website in php 5.4 on a localhost and it worked perfectly.
But now we wanted to get the site online and the webhosting is using a different version of php(5.6).
So now the session does not start.
It redirects us to the homepage, but we are not logged in.
We were thinking that it was because of the version of php, since it did work at first.
<?php
include_once 'connect.php';
session_start();// Starting Session
// Storing Session
$user_check=$_SESSION['gebruiker'];
// SQL Query To Fetch Complete Information Of User
$ses_sql="select email_adres from gebruiker where email_adres='".$user_check".'";
$row = mysqli_fetch_assoc($ses_sql);
$login_session =$row['username'];
if(!isset($login_session)){
header('Location: login.php'); // Redirecting To Home Page
}
else{
header('Location: acountgegevens.php');
}
?>
<?php
include_once 'connect.php';
function logincheck(){
if(isset($_POST['submit'])){
$error = 0;
// declare variables
$email = null;
$password = null;
// check if email address has been set
if (isset($_POST['email_adres']) &&
!empty($_POST['email_adres'])) {
$email = addslashes($_POST['email_adres']);
}
// check if password has been set
if (isset($_POST['password']) && !empty($_POST['password'])) {
$password = md5($_POST['password']);
}
if ($email == null || $password == null) {
$error = 1;
}
// query database for user credentials
$db = new PDO('**');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$statement = $db->prepare("SELECT *
FROM gebruiker
WHERE email_adres = :email
AND wachtwoord = :password
LIMIT 1");
$statement->execute(array(':email' => $email, ':password' => $password));
$result = $statement->fetch(PDO::FETCH_OBJ);
if (!$result) {
$error = 1;
} else {
session_start();
$_SESSION['gebruiker'] = $email;
var_dump($_SESSION);
?>
<script>location.href='index.php'</script>
<?php
}
return $error;
}
}
?>
These two files are included, but we cant figure it out.
Could someone help?
I would hazzard a guess that your connect.php has not been changed to match the hosting companies host/user/password and therefore is outputting an error message.
This of course means that session_start() , which was placed after the connect.php and therefore after your script has attempted to send something to the browser, will not work.
You are only seeing the result of the failed session_start() but I would check the connect.php is configured correctly for its new hosting location
I have a PHP login page that works perfectly locally, but when in server always come out with "Invalid Username or Password". I tried it in two different servers and the result was the same.
login.php
session_start(); // Starting Session
$error = ''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
if (empty($_POST['username']) || empty($_POST['password']))
{
$error = "Username or Password is invalid";
}
else
{
// Define $username1 and $password1
$username1 = $_POST['username'];
$password1 = $_POST['password'];
include_once ('lib/db.php');
$connection = new mysqli($servername, $username, $password, $dbname);
$username1 = stripslashes($username1);
$password1 = stripslashes($password1);
$username1 = mysql_real_escape_string($username1);
$password1 = mysql_real_escape_string($password1);
// SQL query to fetch information of registerd users and finds user match.
$query = "select * from login where PASSWORD='$password1' AND USERNAME='$username1'";
$result = $connection->query($query);
$rows = mysqli_num_rows($result);
if ($rows == 1)
{
$_SESSION['user']=$username1; // Initializing Session
$_SESSION['pppv'] = 10;
header("Location: logged-in.php"); // Redirecting To Other Page
}
else
{
$error = "Username or Password is invalid";
}
}
}
EDIT
Try printing the query after submission gives me this:
Local:
select * from login where PASSWORD='test' AND USERNAME='test'
Server:
select * from login where PASSWORD='' AND USERNAME=''
Use isset($_POST['username']) ||isset($_POST['password'])instead of empty($_POST['username']) || empty($_POST['password']).
Read this to know the difference between isset and empty.
There's no context, but check these things:
Does your database contain the same credentials as local?
Does your requested page return http status such as 200? If it's 404, there's something wrong with your path's. If it's 500, there's an internal error (right permissions set?)
Did you check your log files?
Did you clear your browser cookies and history?
Did you print the full query (including filled parameters) to the window and did you execute this query in your database management tool? And did you get result?
I wrote custom login script for users to login to the main control page. I found out that even when users are not login they can still visit the main control of which I want someone to help me to write a restrict access to page().
Please look through my php login script and based on that code help me write the restrict access to the main control page. assume that my main crontrol page is: cecontrolpage.php
I know we use $_SESSION to that but I have little idea of it.
this is my login.php code which is working fine:
<?php
Session_start();
$Email = $_POST["email"];
$Password = $_POST["password"];
$cn = "localhost";
$db_username = "root";
$pas = "***";
$db_name = "cemembers";
//Open a connection to a MySQL Server
if ($Email && $Password) {
$connect = mysqli_connect($cn, $db_username, $pas, $db_name) or die("Could not connect to database");
//sending MySqli query
$query = mysqli_query($connect, "SELECT * FROM users WHERE Email= '$Email'");
$numrows = mysqli_num_rows($query);
//After PHP declaration we are going to create index file[form]
if ($numrows !== 0) {
while ($row = mysqli_fetch_array($query)) {
$dbEmail = $row["Email"];
$dbPassword = $row["Password"];
}
if ($Email == $dbEmail && $Password == $dbPassword) {
header("location:ce membership birthday system control_pannel.php");
#$_SESSION("Email") == $Email;
} else
header("location:index.php?login_attempt=1");
} else
header("location:index.php?login_attempt=2");
} else
header("Location:index.php?login_attempt=0");
?>
please can someone help me write the php code to restrict access to cecontrol.php ??
Please STEP by STEP with php comments on each part.
First you need to check if the user is logged in:
you do that by checking if the session has been set.
//Check if the user is logged in
function userlogged_in()
{
return(isset($_SESSION['userid']))?true:false;
}
Then you need to redirect the user to a page that says the access to is not authorised, they need to be logged in to view that page:
You do this by checking if the userlogged_in function returned a true or false
function user_restricted()
{
if (userlogged_in()=== false)
{
header('Location: permission.php ');
exit();
}
}
Then you need to call the user_restricted() function on each page, just after starting the session.
First you have to save user values in session after authentication from database like
$_SESSION['username'] = "name"; $_SESSION['user_id'] = 1;
function check_session() {
session_start();
if ($_SESSION['user_id']=='')
{
// redirect to login
}
}
On every page that you want to restrict access you can call check_session().