davidd07 Posted March 29, 2023 Share Posted March 29, 2023 (edited) I have been trying to create a registration and log-in page, the registration works well but the log-in page is having an issue. When submitting the first username and password work, but the issue happens on the "fopen('accounts.txt', 'a+');". <?php session_start(); session_unset(); // input fields validation if ($_SERVER["REQUEST_METHOD"] == "POST") { echo "Your username is " . $_POST['username'] . "<br>"; echo "You password is " . $_POST['password'] ; $passwordCompare = ""; $username = $_POST["username"]; $password = $_POST["password"]; if ($_POST['username'] == "" ) { // not defined if (empty($_POST['username'])) { $msg = "Username missing"; echo $msg . "Username missing"; } else { // check if name only contains letters and whitespace if (!preg_match("/^[a-zA-Z ]*$/", input_data($_POST['username']))) { $msg = "Only alphabets and white space are allowed"; echo $msg . "mathing this "; } echo $msg . "Username missing is just dumb"; } } elseif ($_POST['password'] == "") { // not defined if (empty($_POST['password'])) { $msg = "Pass missing"; } else { // check if name only contains letters and whitespace if (!preg_match("/^[a-zA-Z ]*$/", input_data($_POST['password']))) { $msg = "Only alphabets and white space are allowed"; } } } else { // THE MAIN ISSUE HERE $passwordCompare = ""; $username = $_POST["username"]; $password = $_POST["password"]; $myfile = fopen('accounts.txt', 'a+'); $contents = file_get_contents($myfile); $lines = explode("\n", $contents); $userfound = 'N'; for ($i=0; $i < count($lines)-1; $i++) { $fields = explode(" ", $lines[$i]); if ($fields[0] == $username) { $passwordCompare = $fields[1]; $userfound = 'Y'; } } if ($password == $passwordCompare) { // Redirect to the next webpage $_SESSION['uid'] = $username; header("location: admin.php"); exit; } else { if ($userfound == 'Y') { $msg = ' Password incorrect !'; } else { $msg = ' Username not found !'; } } } } // trim, stripslashes and htmlspecialchars function input_data($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } ?> <form method="post" action="<?php echo $_SERVER["PHP_SELF"]; ?>"> <div> <label for="username">Username:</label> <input type="text" id="username" name="username"> </div> <div> <label for="password">Password:</label> <input type="password" id="password" name="password"> </div> <div> <input type="submit" name="submit" value="Login"> </div> </form> Edited March 29, 2023 by davidd07 Quote Link to comment https://forums.phpfreaks.com/topic/316065-php-and-text-txt/ Share on other sites More sharing options...
gw1500se Posted March 29, 2023 Share Posted March 29, 2023 Probably the wrong approach. That information should be secured in a database. Google examples of PHP log in pages. Quote Link to comment https://forums.phpfreaks.com/topic/316065-php-and-text-txt/#findComment-1606942 Share on other sites More sharing options...
Strider64 Posted March 29, 2023 Share Posted March 29, 2023 (edited) Here's a simple login (not tested) that might get you started? $dsn = 'mysql:host=localhost;dbname=database'; $username = 'username'; $password = 'password'; try { $pdo = new PDO($dsn, $username, $password); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $stmt = $pdo->prepare("SELECT id, hashed_password FROM users WHERE username = :username LIMIT 1"); $stmt->execute(array(':username' => $username)); if ($stmt->rowCount() == 1) { $user = $stmt->fetch(PDO::FETCH_ASSOC); if (password_verify($password, $user['hashed_password'])) { session_start(); unset($password); session_regenerate_id(); $_SESSION['last_login'] = time(); $_SESSION['id'] = $user['id']; header("Location: admin.php"); exit(); } } $error[] = 'Invalid username or password.'; } catch (PDOException $e) { die('Error: ' . $e->getMessage()); } That reads it in and the following writes the user's username and password $username = 'exampleuser'; $password = 'secretpassword'; // Hash the password using the default algorithm (currently bcrypt) $hashed_password = password_hash($password, PASSWORD_DEFAULT); // Connect to the MySQL database using PDO $dsn = 'mysql:host=localhost;dbname=database'; $username = 'username'; $password = 'password'; try { $pdo = new PDO($dsn, $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Prepare an SQL statement to insert the username and hashed password into the users table $stmt = $pdo->prepare("INSERT INTO users (username, hashed_password) VALUES (:username, :hashed_password)"); $stmt->bindParam(':username', $username); $stmt->bindParam(':hashed_password', $hashed_password); // Execute the statement $stmt->execute(); echo "New record created successfully"; } catch (PDOException $e) { echo "Error: " . $e->getMessage(); } and I even throw in the SQL for a MYSQL database table CREATE TABLE users ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, username VARCHAR(30) NOT NULL UNIQUE, hashed_password VARCHAR(255) NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); Edited March 29, 2023 by Strider64 Quote Link to comment https://forums.phpfreaks.com/topic/316065-php-and-text-txt/#findComment-1606943 Share on other sites More sharing options...
davidd07 Posted March 29, 2023 Author Share Posted March 29, 2023 (edited) Yes I know. The main issue is not to use sql but just to use txt instead with fopen('accounts.txt', 'a+'), and that is the main issue of running the 3rd part. Quote 1/ username -works 2/ password - works 3/ fopen... does not work login.txt Edited March 29, 2023 by davidd07 Quote Link to comment https://forums.phpfreaks.com/topic/316065-php-and-text-txt/#findComment-1606945 Share on other sites More sharing options...
maxxd Posted March 29, 2023 Share Posted March 29, 2023 (edited) I'm assuming this is a classroom assignment because doing it this way is not the best idea but you say it's a requirement. That having been said, fopen() throws a warning on failure. What message are you seeing? If you're not seeing anything then either the logic flaw is elsewhere in the code or you don't have error reporting enabled. Speaking of logic errors, your regex against password and/or username only runs if those values equal "" but aren't empty, which can't happen. stripslashes() and htmlentities() are output functions, and what if a password legitimately ends or starts with a space? If it is a classroom assignment, I commend you on your use of exit after the redirect. Edited March 29, 2023 by maxxd Quote Link to comment https://forums.phpfreaks.com/topic/316065-php-and-text-txt/#findComment-1606946 Share on other sites More sharing options...
davidd07 Posted March 30, 2023 Author Share Posted March 30, 2023 I'm on the mac console and don't get any errors Quote Link to comment https://forums.phpfreaks.com/topic/316065-php-and-text-txt/#findComment-1606947 Share on other sites More sharing options...
Solution kicken Posted March 30, 2023 Solution Share Posted March 30, 2023 7 hours ago, davidd07 said: $myfile = fopen('accounts.txt', 'a+'); $contents = file_get_contents($myfile); This is wrong. fopen returns a resource, but file_get_contents wants a filename. This should be triggering a warning and/or error for you (depending on PHP version), something like: Quote Fatal error: Uncaught TypeError: file_get_contents(): Argument #1 ($filename) must be of type string, resource given or Warning: file_get_contents() expects parameter 1 to be a valid path, resource given if you cannot see that warning/error in your output or in PHP's error logs then you need to adjust your error reporting settings for your installation. If you want to use file_get_contents to read a file, then you don't fopen it first, you just call file_get_contents. $contents = file_get_contents('accounts.txt'); If you want to fopen the file (for example, so you can lock it) then you need to read the data using fread, fgets, stream_get_contents, or similar. Quote Link to comment https://forums.phpfreaks.com/topic/316065-php-and-text-txt/#findComment-1606948 Share on other sites More sharing options...
davidd07 Posted March 31, 2023 Author Share Posted March 31, 2023 Thanks you so much Gurus, that worked well. Quote Link to comment https://forums.phpfreaks.com/topic/316065-php-and-text-txt/#findComment-1606977 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.