Jump to content

Help with PHP Login Scripts


ameharhughes

Recommended Posts

Hi everyone,

 

first i want to say thanks in advance, i have spend 3 days looking for a solution to my problem, ive had some luck but no more, so here is my problem.

 

I have index.php with a login script, i click login and it goes checklogin.php, that works fine, if its write it goes to upload.php and if it wrong its says wrong username and password.

 

My question is how do i get it to go back to index.php if the uname and pword were wrong?

Also if i type http://eprasheed/home/upload.php into my browser i dont need to login, how do i stop this?

 

again thanks in advance

Link to comment
Share on other sites

I would have the page post back to itself. In other words you would have your php script at the top of the page:

 


<?php

if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
      //Do your login code here

      $username = "user";
      $password = "password";

      if ($username != $password)
      {
           $message = "Wrong username/password";
      }
      else
      {
           header('Location: main.php');
      }
}

?>

<html>
<head>
<title>login page</title>

</head>
<body>
<form method='POST' action="<?= $_SERVER['PHP_SELF'] ?>">
<input type="text" name="username" />
<input type="password" name="password" />
<input type="submit" value="login" />
</form>
</body>
</html>

Link to comment
Share on other sites

<?php
$username = "user";
$password = "password";

if($username!=$password){
header('Location: login.php');
exit;
}else{
header('Location: main.php');
exit;
}

?>

 

Not trying to criticize here, but in your script your basically saying ...

 

if username is not equal to password, redirect to login.php..... in your experience, when is username and password EVER equal?? In all the login systems I have created, this statement would redirect to the login page EVERY SINGLE TIME... even if the user is legitimately logged in.

 

Is this login system using sessions for the login data? If it uses a session, then you would simply check for the presence of that var.

 

Assuming it is $_SESSION['loggedIn'] as the session var,

 

<?php

if(isset($_SESSION['loggedIn']))
{
    // redirect to allowed page, or let user continue
}
else
{
   // user is not properly logged in, redirect to login.php
  header('Location:login.php');
}
?>

 

The code given above is trying to validate the user and ensure the credentials are correct. This is typically done with a database or flat-file database.

 

Your looking for something that works after the validation is done. You need to see if they have been validated yet or not, so you would typically look for a particular session var, or look in a database and see if their session is set there.... depending on how the system is set up.

 

Hope that helps...

 

Nate

Link to comment
Share on other sites

sorry guys, its still not working, maybe my code is just all togther, i have files, main_login, checklogin, and upload, all php files, i have put them below;MAIN_LOGIN

<style type="text/css">

<!--

body {

  background-color: #b8d0dc;

}

.style3 {

  font-size: 48px;

  font-weight: bold;

}

.style2 {  font-size: 10px;

  color: #999999;

}

-->

</style>

<p> </p>

<p align="center"><span class="style3">:: EPRasheed LTD ::</span></p>

<p> </p>

<table width="300" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#b8d0dc">

<tr>

<form name="form1" method="post" action="checklogin.php">

<td>

<table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">

<tr>

<td colspan="3" bgcolor="#b8d0dc"><strong>Member Login </strong></td>

</tr>

<tr>

<td width="78" bgcolor="#b8d0dc">Username</td>

<td width="6" bgcolor="#b8d0dc">:</td>

<td width="294" bgcolor="#b8d0dc"><input name="myusername" type="text" id="myusername"></td>

</tr>

<tr>

<td bgcolor="#b8d0dc">Password</td>

<td bgcolor="#b8d0dc">:</td>

<td bgcolor="#b8d0dc"><input name="mypassword" type="password" id="mypassword"></td>

</tr>

<tr>

<td bgcolor="#b8d0dc"> </td>

<td bgcolor="#b8d0dc"> </td>

<td bgcolor="#b8d0dc"><input type="submit" name="Submit" value="Login"></td>

</tr>

</table>

</td>

</form>

</tr>

</table>

<p> </p>

<p align="center"><span class="style2">Powered by <a href="http://www.eprasheed.com/">EPR File Sharing Server </a><br />

Copyright © 2009 EPRasheed.</span></p>

 

 

and there the CHECKLOGIN.PHP

<?php

$host="localhost";

$username="******";

$password="*******";

$db_name="users";

$tbl_name="members";

 

 

mysql_connect("$host", "$username", "$password")or die("cannot connect");

mysql_select_db("$db_name")or die("cannot select DB");

 

$myusername=$_POST['myusername'];

$mypassword=$_POST['mypassword'];

 

$myusername = stripslashes($myusername);

$mypassword = stripslashes($mypassword);

$myusername = mysql_real_escape_string($myusername);

$mypassword = mysql_real_escape_string($mypassword);

 

$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'";

$result=mysql_query($sql);

 

$count=mysql_num_rows($result);

 

if($count==1){

 

session_register("myusername");

session_register("mypassword");

header("location:upload.php");

}

else {

echo "Wrong Username or Password";

}

?>

 

and finally UPLOAD.PHP

<?

  include("uploader.php");

?>

<?php

 

if(isset($_SESSION['loggedIn']))

{

   

}

else

{

 

  header('Location:main_login.php');

}

?>

 

<? global $user; ?>

<style type="text/css">

<!--

body {

  background-color: #b8d0dc;

}

a:link {

  color: #000000;

}

a:visited {

  color: #000000;

}

a:hover {

  color: #000000;

}

a:active {

  color: #000000;

}

.style1 {  font-size: 10px;

  color: #999999;

}

-->

</style><title>:: EPR File Sharing Server ::</title>

      <p align="center"><strong><span style="background: #fff; color: #000"><? if($_REQUEST["message"] == "") echo "Upload a file below."; else echo $_REQUEST["message"]?></span></strong><br />Hello, please use the bar below to upload your files.</p>

    <form action="upload.php" enctype="multipart/form-data" id="upload" method="post">

        <p align="center"><input id="userfile" name="userfile" size="45" type="file" />

          <input name="upload" type="submit" value="Upload File" />

          <br />

          <br />

        </p>

 

        <p>Allowed file extensions: <strong><?=$file_extensions_list?></strong></p>

 

        <p>Maximum file size: <strong><?=$maximum_file_size?> bytes 100 Meg</strong></p>

 

        <p>Deleting files is currently: <strong><?=$status?></strong></p>

 

        <p>Powered by <strong>:: <a href="http://eprasheed.com" title="Uploader">Eprasheed LTD</a> ::</strong></p>

</form>

 

      <p><strong>Uploaded Files</strong></p>

      <table style="border: 2px dotted #000; width: 100%">

  <? if($uploaded_files == "") echo "      <tr>

            <td colspan=\"2\" style=\"background: #fff; color: #000; text-align: center\"><br /><strong>There are no uploaded files.</strong><br /><br /></td>

        </tr>

  "; else echo $uploaded_files ?>

  </table>

      <p> </p>

      <p align="center"><span class="style1"><br />

Powered by <a href="http://www.eprasheed.com/">EPR File Sharing Server </a><br />

Copyright © 2009 EPRasheed.</span></p>

 

oh there is uploader.php (obvisously im uploading and this is the control file)i dont this is will effect anything but ill give it anyway

 

<?

 

  set_time_limit(0);

  ini_set("upload_max_filesize","100M");

  ini_set("post_max_size","100M");

  ini_set("max_execution_time","300");

  ini_set("max_input_time","300");

  ini_set("memory_limit","300M");

 

 

 

  $allow_file_deletion = true;

 

  $file_extensions = array(".doc", ".gif", ".htm", ".html", ".jpg", ".pdf", ".png", ".zip", ".txt");

 

  $file_extensions_list = ".doc, .gif, .htm, .html, .jpg, .pdf, .png, .zip, .txt";

 

  $max_length = 128;

 

  $maximum_file_size = "104857600";

 

  $upload_log_file = "upload_log.txt";

 

  $folder_directory = "http://".$_SERVER["HTTP_HOST"].dirname($_SERVER["PHP_SELF"]);

  $message = "";

  $set_chmod = 777;

  $site_uri = "http://".$_SERVER["HTTP_HOST"].$_SERVER["PHP_SELF"];

  $upload_directory = "files/";

  $upload_uri = $folder_directory."/files/";

 

  if($allow_file_deletion == true) $status = "enabled";

  else $status = "disabled";

 

  if($_REQUEST["delete"] && $allow_file_deletion) {

  $resource = fopen($upload_log_file,"a");

  fwrite($resource,date("F d, Y / h:i:sa")." - ".$_REQUEST["delete"]." deleted by ".$_SERVER["REMOTE_ADDR"]."\n");

  fclose($resource);

 

  if(strpos($_REQUEST["delete"],"/.") > 0);

  elseif(strpos($_REQUEST["delete"],$upload_directory) === false);

  elseif(substr($_REQUEST["delete"],0,6) == $upload_directory) {

  unlink($_REQUEST["delete"]);

  $message = "File has been deleted.";

  header("Location: $site_uri?message=$message");

  }

  }

 

  elseif($_FILES["userfile"]) {

  $resource = fopen($upload_log_file,"a");

  fwrite($resource,date("F d, Y / h:i:sa")." - ".$_FILES["userfile"]["name"]." "

  .$_FILES["userfile"]["type"]." uploaded by ".$_SERVER["REMOTE_ADDR"]."\n");

  fclose($resource);

 

  $file_type = $_FILES["userfile"]["type"];

  $file_name = $_FILES["userfile"]["name"];

  $file_ext = strtolower(substr($file_name,strrpos($file_name,".")));

  @chmod($upload_uri."".$file_name, 0755);

  if($_FILES["userfile"]["size"] > $maximum_file_size) {

  $message = "ERROR: File size cannot be over ".$maximum_file_size." bytes.";

  }

 

  elseif($file_name == "") $message = "ERROR: Please select a file to upload.";

  elseif(strlen($file_name > $max_length)) $message = "ERROR: The maximum length for a file name is ".$max_length." characters.";

  elseif(!preg_match("/^[A-Z0-9_.\- ]+$/i",$file_name)) $message = "ERROR: Your file name contains invalid characters.";

  elseif(!in_array($file_ext, $file_extensions)) $message = "ERROR: <ins>$file_ext</ins> is not an allowed file extension.";

  else $message = upload_file($upload_directory, $upload_uri);

  header("Location: $site_uri?message=$message");

  }

 

  elseif(!$_FILES["userfile"]);

  else $message = "ERROR: Invalid file specified.";

 

  $open = opendir($upload_directory);

  $uploaded_files = "";

  while($file = readdir($open)) {

  if(!is_dir($file) && !is_link($file)) {

  $uploaded_files .= "      <tr>

            <td style=\"background: #fff; color: #000; text-align: left; width: 70%\"><a href=\"$upload_directory$file\" title=\"$file (".filesize($upload_directory.$file)." bytes)\">".$file."</a> (".filesize($upload_directory.$file)." bytes)</td>";

  if($allow_file_deletion)

  $uploaded_files .= "

            <td style=\"background: #fff; color: #000; text-align: right; width: 30%\"><a href=\"?delete=$upload_directory".urlencode($file)."\" title=\"Delete File\">Delete File</a></td>";

  else

  $uploaded_files .= "

            <td style=\"background: #fff; color: #000; text-align: right; width: 30%\"><del><strong>Delete File</strong></del></td>";

  $uploaded_files .= "

        </tr>

        <tr>

            <td colspan=\"2\" style=\"background: #eee; color: #000; text-align: left; text-indent: 20px\">Uploaded <strong>".date("F d, Y / h:ia", filemtime($upload_directory.$file))."</strong></td>";

  $uploaded_files .="

        </tr>

  ";

  }

  }

 

  function upload_file($upload_directory, $upload_uri) {

  $file_name = $_FILES["userfile"]["name"];

  $file_name = str_replace(" ","_",$file_name);

  $file_path = $upload_directory.$file_name;

  $temporary = $_FILES["userfile"]["tmp_name"];

 

  $result = move_uploaded_file($temporary, $file_path);

  if(!chmod($file_path,0777))

  $message = "ERROR: A folder to place the files was not found, or the files need to be CHMODed to 777.";

  else $message = ($result)?"File has been uploaded." : "An error has occurred.";

  return $message;

  }

?>

 

 

thanks in advance every, i really appreciate the advice[/]

Link to comment
Share on other sites

session_register("myusername");
session_register("mypassword");

 

here is the piece that takes care of the registration.....

 

 

I just used loggedIn as an example since I did not know what the actual vars were called.

 

So change 

 

<?php

if(isset($_SESSION['loggedIn']))
{
   
}
else
{

  header('Location:main_login.php');
}
?>

 

to

 

<?php

if(isset($_SESSION['myusername']) && isset($_SESSION['mypassword']))
{
   
}
else
{

  header('Location:main_login.php');
}
?>

 

This should be on any pages that you wish to protect...

 

that should work for ya..

 

*edit* Let's condense it...

 

<?php
   ( isset($_SESSION['myusername']) && isset($_SESSION['mypassword']) ) ? '' : header('Location:main_login.php') ;
?>

 

I think the shorter version will work.. though I have not tested it.

 

 

nate

 

Link to comment
Share on other sites

What was asked by ameharhughes

 

Posted on: Today at 07:09:31 AMPosted by: ameharhughes 

Hi everyone,

 

first i want to say thanks in advance, i have spend 3 days looking for a solution to my problem, ive had some luck but no more, so here is my problem.

 

I have index.php with a login script, i click login and it goes checklogin.php, that works fine, if its write it goes to upload.php and if it wrong its says wrong username and password.

 

My question is how do i get it to go back to index.php if the uname and pword were wrong?

Also if i type http://eprasheed/home/upload.php into my browser i dont need to login, how do i stop this?

 

again thanks in advance

 

and my reply was :

<?php
$username = "user";
$password = "password";

if($username!=$password){
header('Location: login.php');
exit;
}else{
header('Location: main.php');
exit;
}

?>

 

@chronister , @hobeau

 

The example code that I posted was to help the poster understand how to redirect on a failure flag. It is NOT an actual login script for me to worry about its working modalities. There are lots of secure classes and scripts available that will help him acheive that, a simple google search will help him.

 

wht i was addressing is:

 

Posted by: ameharhughes --- My question is how do i get it to go back to index.php if the uname and pword were wrong?

 

And I believe the code I posted is sensible enough to serve the purpose.

 

Edit: Lets not trivialize without actually going through the inherent purpose.

 

Rgds,

Kris

 

 

 

Link to comment
Share on other sites

@l_kris06

 

I now understand you were intending to get a true result everytime (meaning that the 2 are never equal).. and it makes sense to what your trying to accomplish, but I think it could be confusing to folks new to PHP. Remember that others new to this stuff may read it and take what you posted at face value... so try to explain what your attempting to show for the benefit of everyone... Just my opinion. :)

 

the redirect should actually go here... though we did not have this code at the time of the first posts.

 

<?php
if($count==1){

session_register("myusername");
session_register("mypassword");
header("location:upload.php");
}
else {
$message = "Wrong Username or Password";
header('Location:index.php?msg='.$message);
}

?>

 

On index.php, you would then want to display the error message....

 

But when I think about it, if the username and password are wrong, wouldn't you want to re-direct them to the login page again so they can try again?  Again, just my 2 cents.

 

Nate

Link to comment
Share on other sites

@chronister,

 

Maybe people new to programming might take it in its face value.

<?php if($username != $password) {//failed flag , do something}?>

. maybe!! but i see wht u mean though. adding more comments should help. :)

 

Anyways i believe  ameharhughes still is in square 1.

 

@ameharhughes, hope this helps.

 

<?php

$username = "user";
$password = md5("pass");

/*$username and $password are constants, ideally username and password will be fetched from a
user login form page, and when the user presses submit, the entire form will be posted and
you can grab the values by using $_POST.*/


/*I am assuming you have a DB called "users" where you have the username and password stored for each user
and we assume here that the password has a one way encryption(MD5).*/



$query = "select * from users where username = '$username' and password='$password';";
$success = mysql_query($query);

//enforce conditions

$returned = mysql_num_rows($success); /* this will have the number of rows returned by the query,
and the returned number MUST BE 1 for a success condition, failure will result in 0, and any value
greater than 1 indicates a manipulated database */


if($returned == 1){ /*OK, we have a success, the user trying to login is a valid user and can be redirected to
main page. We store his username in session file and during all page traversal we call this session file
to see who is the current user*/

$_SESSION['curUser'] = $username;
header('Location: main.php');
exit;

}elseif($returned == 0){ /*Failure flag, username and password failed validation. 
We store the error message in a session and redirect to the login page, and print
the error which is stored in the $_SESSION['err'] session file */
$_SESSION['err'] = "Username and password failed validation.";
header('Location: login.php');
exit;
}else{

/*query returned more than 1 row, compromised db. Ideally you need to make a file log here and
shut down the website*/

}

?>

 

Link to comment
Share on other sites

i am completely confused, i have a attached the files. is there any chance some one could have a look and make it work, comments by what you did as well would be nice so i can learn where i went wrong.

 

thanks so much in advance.

 

if you like, i can host for free any name for a year if you like, with mysql db if needed.

 

[attachment deleted by admin]

Link to comment
Share on other sites

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.