Jump to content

Recommended Posts

Please can some one help me. We have upgraded php and not i cant get the php page to correctly redirect the user to the login page if the user has not logged in and the get it to redirect to the index page. So the form sequence is as follows. User connects to index page, user clicks on link to add or delete data in mysql database, page must redirect to login page if user has not logged in, once logged in login page must redirect to add or delete page depending on the link clicked on. Addins and deleting data to the mysql database table works fine.

 

Below is the add,php page.

 

<?php

 

ini_set('display_errors', 1);

ini_set('display_startup_errors', 1);

error_reporting(E_ALL);

 

session_start(); //start session.

if(!isset($_GET['name'])){//added this to check if name is sent

include('database.php');

if (!isset($_SESSION["user.id"]) && $_SESSION["user.id"] !="")

{

}

else{

  header("Location: login.php");

}

 

if($_POST['action'])

{

 

include('email.php');

  $address="";

  $name=$_POST['name'];

  $extension=$_POST['extension'];

  $department=$_POST['department'];

  $phone=$_POST['phone'];

  $email=$_POST['email'];

 

$sql = "INSERT INTO users (ID, Name, Email, Extension, Phone, Department) VALUES (NULL, '$name', '$email', '$extension', '$phone', '$department')";

 

 

if ($conn->query($sql) === TRUE)

echo "New record added";

else

echo "Error: " . $sql . "<br>" . $conn->error;

$conn->close();

 }

 

?>

 

<style type="text/css">

<!--

form { font-family: "Courier New", Courier, mono}

body { font-family: "Times New Roman", Times, serif}

-->

</style>

 

 

<center><form action="" method="POST">

Name:<br><input type="text" name="name" required

pattern=".*[ ].*" title="Please enter Name and Surname."

><br />

Email:<br><input type="text" name="email" required placeholder="@alpinemotors.co.za"

pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$" title="Must be a valid email address, eg: user@mail.co.za"

><br />

Extension:<br><input type="text" name="extension" required pattern="^\d{4}( \/ \d{4})?$" title="Please Enter the Extension Number"><br />

Phone:<br><input type="text" name="phone" pattern="^\d{3} \d{3} \d{4}$" title="Please enter a valid Cellphone Number, eg. 083 511 9213"><br />

Department:<br> <select name ="department">

  <option value="ADMIN">ADMIN</option>

  <option value="FINANCIAL MANAGER">FINANCIAL MANAGER</option>

  <option value="AFTER-SALES DIRECTOR">AFTER-SALES DIRECTOR</option>

  <option value="ALPINE SALES DIRECTOR">ALPINE SALES DIRECTOR</option>

  <option value="DEALER PRINCIPAL">DEALER PRINCIPAL</option>

  <option value="AUTO ARMOUR/AUTO ENHANCE - FITMENT CENTRE (Smash and Grab)">AUTO ARMOUR/AUTO ENHANCE - FITMENT CENTRE (Smash and Grab)</option>

  <option value="BANDIT">BANDIT</option>

  <option value="BIDTRACK">BIDTRACK</option>

  <option value="WORKSHOP BOOKINGS">WORKSHOP BOOKINGS</option>

  <option value="CLEANERS">CLEANERS</option>

  <option value="COMMERCIAL SALES DIRECTOR">COMMERCIAL SALES DIRECTOR</option>

  <option value="WORKSHOP WASHBAY">WORKSHOP WASHBAY</option>

  <option value="FINANCE AND INSURANCE OFFICE">FINANCE AND INSURANCE OFFICE</option>

  <option value="FINANCE AND INSURANCE MANAGER">FINANCE AND INSURANCE MANAGER</option>

  <option value="IT DEPARTMENT">IT DEPARTMENT</option>

  <option value="MARKETING DIRECTOR">MARKETING DIRECTOR</option>

  <option value="MARKETING DEPARTMENT">MARKETING DEPARTMENT</option>

  <option value="MASTER CARS SALES">MASTER CARS SALES</option>

  <option value="MASTER CARS SALES MANAGER">MASTER CARS SALES MANAGER</option>

  <option value="PREP DEPARTMENT">PREP DEPARMENT</option>

  <option value="NUMBER PLATES">NUMBER PLATES</option>

  <option value="PANELBEATER - EASIFIX - CAR CARE">PANELBEATER - EASIFIX - CAR CARE</option>

  <option value="PARTS MANAGER">PARTS MANAGER</option>

  <option value="PARTS">PARTS</option>

  <option value="PARTS DISPATCH">PARTS DISPATCH</option>

  <option value="PARTS TELESALES">PARTS TELESALES</option>

  <option value="TRADE SALES MANAGER">TRADE SALES MANAGER</option>

  <option value="WASHBAY">WASHBAY</option>

  <option value="MASTER CARS PREP AND ORDERS">MASTER CARS PREP AND ORDERS</option>

  <option value="NEW CARS ADMIN AND STOCK CONTROL">NEW CARS ADMIN AND STOCK CONTROL</option>

  <option value="NEW CARS SHOWROOM">NEW CARS SHOWROOM</option>

  <option value="NEW CARS SALES MANAGER">NEW CARS SALES MANAGER</option>

  <option value="WORKSHOP SERVICE ADVISORS">WORKSHOP SERVICE ADVISORS</option>

  <option value="WORKSHOP">WORKSHOP</option>

  <option value="WORKSHOP FOREMEN">WORKSHOP FOREMEN</option>

  <option value="WAREHOUSE">WAREHOUSE</option>

  <option value="WARRANTY & CLAIMS">WARRANTY & CLAIMS</option>

  <option value="WORKSHOP DRIVERS">WORKSHOP DRIVERS</option>

  <option value="WORKSHOP MANAGER">WORKSHOP MANAGER</option>

  </select>

<br />

<br><input type="submit" name="action" value="Submit">

<input type="reset" value="Reset">

</form>

<a href="index.php">Extension List</a>

</center>

</html>

}

 

Below is the login.php

 

  <?php

 

ini_set('display_errors', 1);

ini_set('display_startup_errors', 1);

error_reporting(E_ALL);

 

  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 $username and $password

  $username = $_POST['username'];

  $password = $_POST['password'];

  // mysqli_connect() function opens a new connection to the MySQL server.

  $conn = mysqli_connect("localhost", "root", "Pr1v@cY", "T-List_VW");

  // SQL query to fetch information of registerd users and finds user match.

  $query = "SELECT * from UserName where userName=? AND pass=? LIMIT 1";

  // To protect MySQL injection for Security purpose

  $stmt = $conn->prepare($query);

  $stmt->bind_param("ss", $username, $password);

  $stmt->execute();

  $stmt->bind_result($username, $password);

  $stmt->store_result();

  if($stmt->fetch()) //fetching the contents of the row {

  $_SESSION['login_user'] = $username; // Initializing Session

  header("location: index.php"); // Redirecting To Profile Page

  }

  mysqli_close($conn); // Closing Connection

  }

  ?>

 

  <!DOCTYPE html>

  <html>

  <head>

  <title>Login Form in PHP with Session</title>

  <link href="style.css" rel="stylesheet" type="text/css">

  </head>

  <body>

  <div id="login">

  <h2>Login Form</h2>

  <form action="" method="post">

  <label>UserName :</label>

  <input id="name" name="username" placeholder="username" type="text">

  <label>Password :</label>

  <input id="password" name="password" placeholder="**********" type="password"><br><br>

  <input name="submit" type="submit" value=" Login ">

  <span><?php echo $error; ?></span>

  </form>

  </div>

  </body>

  </html>

 

 

 

Link to comment
https://forums.phpfreaks.com/topic/309426-page-redirector-php7/
Share on other sites

19 minutes ago, ManieE said:

Not sure what this means...

It means you posted this in multiple forums and someone already took the time in another forum to answer you so we are not going to waste more experts time answering something that has already been answered.

  • Like 1
10 hours ago, benanamen said:

It means you posted this in multiple forums and someone already took the time in another forum to answer you so we are not going to waste more experts time answering something that has already been answered.

Hi Yes i have posted it here and on phphelp.com hoping to get a response from either forum. They also did not help with the code, they only gave me a lot of info to read witch i'm very grateful for and will definitely read, but for now im pressed for time to get this fixed. I was hoping that one of the experts here could help me as i'm no expert.  I have already spend 4 nights trying to fix the redirect code and have not been able to do so.

If some one can help me out i will be very grateful.

Hope to your from some one.....

 

4 minutes ago, ManieE said:

a lot of info to read witch i'm very grateful for and will definitely read

Your time might have been better spent reading on the first night and fixing on the second. Sounds like you want us to do it for you rather than give help.

If you want people to look at your code then format it so it is clear, by virtue of its indentations, where your various control blocks start and end. (BTW, our first if() {…} block has no end)

Put your code in a code block, either with code tags or use the <> button in the toolbar.

Thanks @Barand for pointing me i the right direction. It's my first time on this forum.

Below is the old code that use to work fine on php5.x


<?php
error_reporting(0);
 session_start();
if (!isset($_SESSION['CheckLogin'])) { header("Location: login.php"); }
include('database.php');

if($_POST['action'])
{

include('email.php');
  $address="";
  $name=$_POST['name'];
  $extension=$_POST['extension'];
  $department=$_POST['department'];
  $phone=$_POST['phone'];
  $email=$_POST['email'];

$query="INSERT INTO users (ID, Name, Email, Extension, Phone, Department) VALUES (NULL, '$name', '$email', '$extension', '$phone', '$department')";
  $rez=mysql_query($query);

header("Location: index.php");

 }
?>

Then the upgrade to php7 happened and the task was dumped into my lap to fix as the previous guy is no more with the company. So i did read a few pages abut php and had a look at some samples and this is what i have at the moment but its not working correctly. I have done searches on the errors that was displayed in the browser and have read up on them as well. So i'm asking for help, please.

So i got to this and it still did not work...

<?php

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

header("Location: index.php");
include('database.php');

if($_POST['action'])
{

include('email.php');
  $address="";
  $name=$_POST['name'];
  $extension=$_POST['extension'];
  $department=$_POST['department'];
  $phone=$_POST['phone'];
  $email=$_POST['email'];

$sql = "INSERT INTO users (ID, Name, Email, Extension, Phone, Department) VALUES (NULL, '$name', '$email', '$extension', '$phone', '$department')";


if ($conn->query($sql) === TRUE)
echo "New record added";
else
echo "Error: " . $sql . "<br>" . $conn->error;
$conn->close();
 }

?>

So after digging some more i got to this and im stuck here...... The below code redirects me to the login page and i can login and then i get redirected back to the index page, then i click on add again and i go back to the loign page, but im suppose to go to the add php page.

<?php

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start(); //start session.
if(!isset($_GET['name'])){//added this to check if name is sent
include('database.php');
if (!isset($_SESSION["user.id"]) && $_SESSION["user.id"] !="")
{
}
else{
    header("Location: login.php");
}

if($_POST['action'])
{

include('email.php');
  $address="";
  $name=$_POST['name'];
  $extension=$_POST['extension'];
  $department=$_POST['department'];
  $phone=$_POST['phone'];
  $email=$_POST['email'];

$sql = "INSERT INTO users (ID, Name, Email, Extension, Phone, Department) VALUES (NULL, '$name', '$email', '$extension', '$phone', '$department')";


if ($conn->query($sql) === TRUE)
echo "New record added";
else
echo "Error: " . $sql . "<br>" . $conn->error;
$conn->close();
 }
}
?>

So to me it looks like this part is not being read.

if (!isset($_SESSION["user.id"]) && $_SESSION["user.id"] !="")

 

7 minutes ago, ManieE said:

if (!isset($_SESSION['CheckLogin'])) { header("Location: login.php"); }

 

8 minutes ago, ManieE said:

if (!isset($_SESSION["user.id"]) && $_SESSION["user.id"] !="")

There seems to be some discrepancy with exactly what session variable to check.

You need to exit after a redirect to prevent the rest of the code from executing EG In that first line above.

Your main problem is trying to use mysql_ functions with v7.0+ (they no longer exist). Had you not turned off the error reporting with error_reporting(0) it might have told you.

Use mysqli_ or PDO (better than mysqli).

Use prepared queries instead of putting user data directly into the query to prevent SQL injection.

54 minutes ago, Barand said:

 

There seems to be some discrepancy with exactly what session variable to check.

You need to exit after a redirect to prevent the rest of the code from executing EG In that first line above.

Your main problem is trying to use mysql_ functions with v7.0+ (they no longer exist). Had you not turned off the error reporting with error_reporting(0) it might have told you.

Use mysqli_ or PDO (better than mysqli).

Use prepared queries instead of putting user data directly into the query to prevent SQL injection.

Hi Barand, the first piece of code was the old code that use to work with php5.x, that was just to show you what it use to look like. All mysql functions has been changed to mysqli functions, so i don't have a problem adding or removing items from the mysql database  or to read any information from the mysql database, its just the redirect function i have a problem with.

So i made some changes.

This code does not take me to the add page it just brings me to a blank page HTTP 500 (website cannot be displayed.

<?php

// To display any coding errors on the page
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start(); //start session.
include('database.php');
if(!isset($_SESSION['username'] && $_SESSION['username'] !="")){   // To check if the user has logged in
    header("Location: login.php"); // To redirect to login page if user has not logged in
   exit();   // To skip the login page and exit if the user has logged in
}

/?>

This code keeps bringing me back to the login page .

<?php

// To display any coding errors on the page
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start(); //start session.
include('database.php');
if(!isset($_SESSION['username'])){   // To check if the user has logged in
    header("Location: login.php"); // To redirect to login page if user has not logged in
   exit();   // To skip the login page and exit if the user has logged in
}

/?>
2 minutes ago, ManieE said:

ini_set('display_errors', 1);

ini_set('display_startup_errors', 1);

error_reporting(E_ALL);

Set those in your php.ini file, not in the code. If you have any startup errors the code won't execute. If it won't execute it can't set those values.

7 minutes ago, ManieE said:

if(!isset($_SESSION['username'] && $_SESSION['username'] !="")){ // To check if the user has logged in

Try changing that to

if(!isset($_SESSION['username'] || $_SESSION['username'] =="")){   // To check if the user has logged in

Have you checked that the session value is being set on login?

8 minutes ago, Barand said:

Have you checked that the session value is being set on login?

Im not sure how to achieve that. I added the echo statement in but did not get any output text.

session_start(); //start session.
if(!isset($_SESSION['username'] ==0)){   // To check if the user has logged in
        echo $_SESSION['username']
    header("Location: index.php");} // To redirect to login page if user has not logged in
else{ header("Location: Login.php");}

 

Ok so i think i'm making progress.

The below code will give me the login page but wont take me further after i have logged in.

session_start(); //start session.
if (!isset($_SESSION["username"]) && $_SESSION["username"] ==0) {   // To check if the user has logged in
    header("Location: login.php"); // To redirect to login page if user has not logged in
}

if i change it to this it does not ask for login and takes me to the add php page.

session_start(); //start session.
if (!isset($_SESSION["username"]) && $_SESSION["username"] ==1) {   // To check if the user has logged in
    header("Location: login.php"); // To redirect to login page if user has not logged in
}

This is my login page script. I completely forgot to add that in this post as well.

    <?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 $username and $password
    $username = $_POST['username'];
    $password = $_POST['password'];
    // mysqli_connect() function opens a new connection to the MySQL server.
    $conn = mysqli_connect("localhost", "root", "db-password", "db-name");
    // SQL query to fetch information of registerd users and finds user match.
    $query = "SELECT * from UserName where userName=? AND pass=? LIMIT 1";
    // To protect MySQL injection for Security purpose
    $stmt = $conn->prepare($query);
    $stmt->bind_param("ss", $username, $password);
    $stmt->execute();
    $stmt->bind_result($username, $password);
    $stmt->store_result();
    if($stmt->fetch()) //fetching the contents of the row {
    $_SESSION['login_user'] = $username; // Initializing Session
    header("location: index.php"); // Redirecting To Profile Page
    }
    mysqli_close($conn); // Closing Connection
    }
    ?>

 

On 10/29/2019 at 6:20 PM, benanamen said:

OP,  you were handed a complete properly coded example on the other forum by a gracious expert. Why are you still messing around with this bad code?

Hi

Yes i saw that and i DO appreciate it, i also replied and said that all the database connections on all the php pages was in mysqli and not pdo, so i have figure out how to go by changing all of that to pdo.  I did say this on the other forum.

 

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.