Double URL error on php - php

I'm having trouble trying to make work a php. Here's the code:
<?php
$host = "localhost";
$user = "ff";
$pass = "ff";
$db = "ff";
$login = mysqli_connect ($host,$user,$pass,$db);
if (!$login) die ("Connection Error to Database <br/>". mysqli_error());
$username = $_POST["username"];
$password = $_POST["password"];
$result = mysqli_query($login, "SELECT * FROM users WHERE username = '$username'");
if($row = mysqli_fetch_array($result))
{
if($row["password"] == $password)
{
session_start();
$_SESSION['username'] = $username;
header("Location: ../index.php");
}
else
{
?>
<script>
alert("Wrong password");
location.href = "../login.html";
</script>
<?
}
}
else
{
?>
<script>
alert("Wrong username");
location.href = "../login.html";
</script>
<?
}
mysqli_free_result($result);
mysqli_close();
?>
Using localhost there isn't any error, but uploading to my server appears something like:
"The website detected an error in http://****/php/validate.php http://****/php/validate.php. blablabla"
The php try to connect to a double URL (sorry for my bad english).
What am I doing wrong?

It's highly likely that on your production server it doesn't allow you to use shorttags (<?) like you are using in the areas where you're outputting Javascript. Your local server probably allows these so you wouldn't have noticed.
You should probably use a header redirect here too with a message attached or in the session, and output that message on another page, but that's another issue.
Change <? to <?php to make sure.

Related

session_start() causing problems

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.

how to call a function $_SESSION[usr]->logout() inside <a>

I have a class named User which has a function named logout(). I create an instance of this class in index.php and i pass it's value to $_SESSION[usr] before i call memberspage.php . In memberspage.php i have a link named logout which when clicked i want the logout() function to run and also send the user to index.php. For this purpose i've done something like this.
Log out
I know that -> causes the problem but i don't know how to fix it. thnx for your time.
The following code worked for me
Log out
but there is a problem. If i go to the page(memberspage.php) where the above code is and i press the back arrow (not logout link) the logOut() function will still be used(the session is destroyed and i will have to log in again to access memberpage.php) . I don't get it because i thought that the only way to call the logOut() function was to click on Log out link.
If $_SESSION[usr]->logout() is working for you as you said in your comment. I don't know how.
But here is just for calling a php function inside anchor tag.It's totally depend on your function response.
<?php
function usr(){
return "abc";
}
?>
Log out
First i suggest that you change your use of session you can create a page for example session.php where all your session is place, it can also be the re directory page of your login page.
like this one named login.php
create in your form make action redirect to session.php
i also suggest that all your php codes of login are inside the session.php then make this one.
<?php
session_start();
$host = "localhost";
$uname = "root";
$pass = "";
$db = "mydb;
//database connection
$conn = mysqli_connect($host, $uname, $pass, $db);
mysqli_select_db($conn, $db);
if(!$conn){
die("Connection failed: " . mysqli_connect_error());
}
if(isset($_POST['username'])){
$username = $_POST['username'];
$password = $_POST['password'];
$username = stripslashes($username);
$password = stripslashes($password);
//$username = mysqli_real_escape_string($username);
//$password = mysqli_real_escape_string($password);
$sql = "SELECT * FROM table WHERE username = '" .$username. "' AND password = '".$password."' LIMIT 1";
$res = mysqli_query($conn, $sql);
if(mysqli_num_rows($res) > 0){
if($data = mysqli_fetch_assoc($res))
{
$_SESSION['type'] = $data['type'];
if(isset($_SESSION["login_user"]))
{
if($data['type'] == 'admin'){
header('location: admin.php');
}
else if($data['type'] == 'customer'){
header('location: customerhome.php');
}//header('location: uservalidation.php');
}
}
}
else{
//header('location: #');
echo '<script>';
echo 'alert("Invalid no?")';
echo '</script>';
header('location: logind.php');
}
}
?>
then create another page which is logout.php
put this code inside:
<?php
session_start();
header('location: index.php');
session_destroy();
?>
then save put the a link your page for logout.php
Add file logout.php and put into them your logout implementation:
<?php
header('Content-Type: application/json');
$_SESSION[usr]->logout();
echo json_encode(['message' => 'ok']);
And call this file with AJAX:
<script>
function logout() {
$.ajax({
url: '/logout.php'
}).then(function (res) {
window.location.href = '/';
});
}
</script>
Log out

PHP login got Too Many Redirect Loop error

Please help me. I got this error everytime I tried to login. - "This webpage has a redirect loop ERR_TOO_MANY_REDIRECTS"
Please help me and I'll appreciate your help very much. thanks.
This is my index.php
<?php
include('login.php'); // Includes Login Script
?>
This is my login.php
<?php
session_start();
$error = "";
if (isset($_POST['submit'])) {
if (empty($_POST['email']) || empty($_POST['password'])) {
$error = "Username or Password is invalid";
} else {
// Define $username and $password
$usernameLogin = $_POST['email'];
$passwordLogin = $_POST['password'];
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = mysql_connect("localhost", "apple", "Apple318992");
// To protect MySQL injection for Security purpose
$username = stripslashes($usernameLogin);
$password = stripslashes($passwordLogin);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
// Selecting Database
$db = mysql_select_db("TS", $connection);
// SQL query to fetch information of registerd users and finds user match.
$query = mysql_query("select * from Users where password='$password' AND email='$usernameLogin'", $connection);
$rows = mysql_num_rows($query);
if ($rows == 1) {
$_SESSION['login_user'] = $usernameLogin; // Initializing Session
} else {
$error = "Username or Password is invalid";
}
}
}
if (isset($_SESSION["login_user"])) {
header("Location:timesheets.php");
}
?>
This is my session.php
<?php
include ('DBConnect.php');
session_start(); // Starting Session
// Storing Session
$user_check = $_SESSION['login_user'];
// SQL Query To Fetch Complete Information Of User
$ses_sql = mysql_query("select email from Users where email='$user_check'", $conn);
$row = mysql_fetch_assoc($ses_sql);
$login_session = $row['email'];
if (!isset($login_session)) {
mysql_close($conn); // Closing Connection
header('Location: index.php'); // Redirecting To Home Page
}
?>
instead of : header('Location: index.php');
try to do it with javascript :
echo '< script> document.location.href="index.php"< /script>';
In your session.php you have to destroy the session because it might be set still but without that the query can find a existing user?
To unset sessions do this:
unset(); for all the session variables unset($_SESSION['login_user']); for a specific session
Please put that before redirecting to index.php.
Otherwise I don't know how to help you sorry.
Also do you have php error / debug enabled? Normally session_start(); should be at very first line in your php file if I am correct, or it throws error.

PHP Login Form is misbehaving

There is an error in my php login script, but i have been unable to find it. can you explain to me how to debug this simple error.
here is my script:
session_start();
include("connect.php");
$kullanici = $_POST["user"];
$kullanici_sor = mysql_query("SELECT * FROM admin where isim = '{$user}'") or die (mysql_error)();
$admin = mysql_fetch_array($user_ask);
if($_POST["user"] == "" and $_POST["pass"] == "")
{
echo "Cannot empty fields.Please tyr again!";
}else{
if(isset($_POST["user"]))
{
if($_POST["user"]== $admin['name'] and ($_POST["pass"] == $admin['pass'])){
$_SESSION["enter"] = true;
$_SESSION["name"] =$_POST["user"];
$_SESSION["pass"] =$_POST["pass"];
header("Location: panel.php");
exit();
}else{
echo"Wrong pass or username";
header("refresh:2; url=index.php");
}
}
You should probably change your line:
$admin = mysql_fetch_array($user_ask);
info
$admin = mysql_fetch_array($kullanici_sor);
But your code is vulnerable to SQL injection. You should use prepared statements via PDO and not mysql. You should also at the beginning of your code (after <?php add:
error_reporting(E_ALL);
ini_set('display_errors','1');
when you are testing your script. On production it should be set to:
error_reporting(0);
ini_set('display_errors','0');
EDIT And of course as someone mentioned in comment you should never put your password into session!
$kullanici_sor = mysql_query("SELECT * FROM admin where isim = '{$user}'") or die (mysql_error)();
$admin = mysql_fetch_array($kullanici_sor);

PHP register form not connecting to database

I have a simple user registration form and external connection script with some strange results.
The page register.php shows the form fine, however seems to display my entire connection string before the form?
It then throws up errors in relation to my connection variable '$dbcon' (I have commented the line at which this happens) Here is my register.php code:
<?php
session_start();
require "connect.php";
if (isset($_SESSION['username'])){
header("location: members.php");
}
if (isset($_POST['submit']))
{
$user = $_POST['user'];
$pass = $_POST['pass'];
$rpass = $_POST['rpass'];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
if ($user == "" || $pass == "" || $rpass == "")
{
echo "Please fill all fields";
}
else
{
if ($pass != $rpass)
{
echo "Passwords do not match";
}
else
{
//This is where the errors are found
$query = mysqli_query($dbcon, "SELECT * FROM users WHERE username = '$user' ") or die ("Cannot query table");
$row = mysqli_num_rows($query);
if($row == 1)
{
echo "This username is already taken";
}
else
{
$add = mysqli_query($dbcon, "INSERT INTO users (id, firstname, lastname, username, password, admin) VALUES
(null, '$fname', '$lname', '$user', '$pass', '$admin') ") or die ("Cant insert data");
echo "Successfully added user!";
}
}
}
}
?>
And here is my connection file 'connect.php' (the $dbcon string is the one that prints out??)
$server = 'localhost';
$user = 'root';
$pass = '';
$dbname = 'bodgett';
$dbcon = mysqli_connect($server, $user, $pass, $dbname)or die("Can not connect to Server.");
Specifically, the error is 'Notice: Undefined variable: dbcon in C:\webserver...\register2.php'
Can anyone suggest why is doesn't recognize this variable?
Probably a wrong filename (maybe file isn't called connect.php) OR wrong file extension? (html instead of .php)
I just copied all your code, and it works for me. Aswell I don't see php start and closing Tags.
I agree with #Xatenev. Also, you may want to consider using PDO for your database interactions, it's the most secure way. I found this very helpful: http://code.tutsplus.com/tutorials/why-you-should-be-using-phps-pdo-for-database-access--net-12059
Sorry if this seems irrelevant, just trying to help.
The connection file 'connect.php' is not enclosed within tags, hence not usable and explains why the text was simply printing out at the top of the page.
Check if mysqli extension is enabled
the code that generates $dbcon is inside a class or inside some function?
If yes, maybe you need to return or call it properly.

Categories