-
Posts
245 -
Joined
-
Last visited
Everything posted by Moorcam
-
Not sure of a "Setting" in PHP as such but try this: if (password_verify($password, $hashedPassword)) { $_SESSION['user_id'] = $user['id']; $_SESSION['handle'] = $user['user_handle']; echo "Login successful! Welcome, " . htmlspecialchars($username) . "."; } else { echo "Invalid username or password."; } I removed Named Parameters: The password_verify function does not support named parameters in PHP. Therefore, I removed the 'password:' syntax to ensure the code runs correctly.
-
I personally find it pointless moving the files to outside the www or root directory. I just use the following to protect any file from direct browser access: In this example, I will display config.php with database credentials: <?php // config.php if (!defined('ACCESS_GRANTED')) { die('Access denied.'); } $databaseHost = 'localhost'; $databaseUser = 'root'; $databasePassword = 'password'; $databaseName = 'my_database'; function connectToDatabase() { global $databaseHost, $databaseUser, $databasePassword, $databaseName; $connection = new mysqli($databaseHost, $databaseUser, $databasePassword, $databaseName); if ($connection->connect_error) { die('Connection failed: ' . $connection->connect_error); } return $connection; } ?> return $connection; } And, in the file that I want to grant access to: <?php // index.php define('ACCESS_GRANTED', true); include 'config.php'; $connection = connectToDatabase(); echo 'Connected successfully to the database.'; ?> Moving files outside the www for example, is a royal pain in the buttox and requires some file permissions etc. Just my opinion.
-
I know a solution has been established, but just wanted to put my 2c in. Here is what I use to show content based on user roles: <?php $user_id = $_SESSION['user_id']; $stmt = $conn->prepare("SELECT role FROM users WHERE user_id = ?"); $stmt->bind_param("i", $user_id); $stmt->execute(); $stmt->bind_result($role); $stmt->fetch(); $stmt->close(); switch ($role) { case 'Admin': echo 'I am admin'; break; case 'Member': echo 'I am Member'; break; default: echo 'Whatever!'; ?>
-
You need to give is some information as to what the actual issue is. Otherwise nobody can or will help you. Another good tip is to encase your code into the <> tag so it shows like this: <?php // database.php require_once __DIR__ . '/config.php'; // Ensure this path correctly points to config.php /** * Establish a new database connection. * * @return mysqli The MySQLi database connection object. * @throws Exception if the connection fails. */ function db_connect() { // Use MySQLi to connect to the database $connection = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); // Check if the connection was successful if ($connection->connect_error) { error_log("Database connection failed: " . $connection->connect_error); die("Database connection failed. Please check the error log for details."); } // Set the character set to UTF-8 for proper handling of characters if (!$connection->set_charset("utf8mb4")) { error_log("Error setting character set utf8mb4: " . $connection->error); } return $connection; } /** * Close an existing database connection. * * @param mysqli|null $connection The connection object to close. * @return void */ function db_disconnect($connection) { if ($connection instanceof mysqli) { $connection->close(); } } // Establish a connection and store it in the variable $db for use later $db = db_connect(); // You can now use $db for your database queries It makes it easier to read. Also, no need for this: if ($connection instanceof mysqli) { $connection->close(); } PHP automatically closes connections. Okay, your turn
-
Fixed. The issue was with the Javascript: // Unban User function unbanUser(userId) { Swal.fire({ title: 'Are you sure?', text: "You are about to unban this user.", icon: 'warning', showCancelButton: true, confirmButtonText: 'Yes, unban it!', cancelButtonText: 'No, cancel!', }).then((result) => { if (result.isConfirmed) { fetch("includes/unban-user.php", { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: `userId=${encodeURIComponent(userId)}` }) .then(response => handleResponse(response)) .catch(error => { console.error("Error:", error); Swal.fire({ title: 'Error!', text: 'There was an issue unbanning the user.', icon: 'error', confirmButtonText: 'Okay' }); }); } }); } function handleResponse(response) { if (response.ok) { response.text().then(text => { Swal.fire({ title: 'Success!', text: text, icon: 'success', confirmButtonText: 'Okay' }).then(() => { location.reload(); // Reload the page to see the changes }); }); } else { console.error("Error: " + response.statusText); Swal.fire({ title: 'Error!', text: 'There was an issue unbanning the user.', icon: 'error', confirmButtonText: 'Okay' }); } } I was missing this part: function handleResponse(response) { if (response.ok) { response.text().then(text => { Swal.fire({ title: 'Success!', text: text, icon: 'success', confirmButtonText: 'Okay' }).then(() => { location.reload(); // Reload the page to see the changes }); }); } else { console.error("Error: " + response.statusText); Swal.fire({ title: 'Error!', text: 'There was an issue unbanning the user.', icon: 'error', confirmButtonText: 'Okay' }); } } Thanks for your help regardless. Always appreciated.
-
For sweetalert to work, it replaces the alert part with Swal.fire So like so: <script>alert("Normal JS Alert");</script> <script>Swal.fire("Are you sure?","You are about to unban this user","warning");</script> See attached image Reference: https://sweetalert.js.org/
-
Here is mac_gyver's code converted to mysqli with prepared statements: <?php // Initialize the MySQLi connection $mysqli = new mysqli("localhost", "username", "password", "database"); // Check for connection errors if ($mysqli->connect_error) { die("Connection failed: " . $mysqli->connect_error); } $where_terms = []; $params = []; $types = ''; // Conditionally add the lorry term if ($lorry != 'all') { $where_terms[] = 'lorry = ?'; $params[] = $lorry; $types .= 's'; // Assuming lorry is a string } // Add the date_created term $where_terms[] = 'date_created BETWEEN ? AND ?'; $params[] = $date_start; $params[] = $date_end; $types .= 'ss'; // Assuming date_start and date_end are strings $where = implode(' AND ', $where_terms); // Build the query $sql = "SELECT * FROM `sales` WHERE $where ORDER BY date_created DESC"; // Prepare the statement $stmt = $mysqli->prepare($sql); // Check for preparation errors if ($stmt === false) { die("MySQLi prepare error: " . $mysqli->error); } // Bind parameters $stmt->bind_param($types, ...$params); // Execute the statement if (!$stmt->execute()) { die("MySQLi execute error: " . $stmt->error); } // Fetch the data $result = $stmt->get_result(); $sales_data = $result->fetch_all(MYSQLI_ASSOC); // Check if there is data to display if (empty($sales_data)) { echo "No data to display."; } else { foreach ($sales_data as $sale) { // Output the data (customize as needed) echo "Sale ID: " . $sale['id'] . "<br>"; // Add more fields as necessary } } ?> Hope this helps.
-
I know. It's not meant to. It's meant to show a Sweetalert, hence the Swal.fire instead of alert. Problem is, it IS showing a normal JS alert on this line: echo '<script>Swal.fire("Success", "User has been unbanned.", "success");</script>'; But, the JS Alert has this in it: '<script>Swal.fire("Success", "User has been unbanned.", "success");</script>'
-
Try this: <select name="lorry" id="lorry" class="custom-select select-2"> <option value="all">All Lorries</option> <?php // Establishing a connection to the database $mysqli = new mysqli('localhost', 'username', 'password', 'database'); // Checking for connection errors if ($mysqli->connect_error) { die("Connection failed: " . $mysqli->connect_error); } // Preparing the SQL query to fetch lorries $sql = "SELECT id, lorry FROM lorries"; $result = $mysqli->query($sql); // Checking if the query returned any results if ($result && $result->num_rows > 0) { // Fetching and displaying each lorry while ($row = $result->fetch_assoc()) { $selected = (isset($_GET['lorry']) && $row['lorry'] == $_GET['lorry']) ? 'selected' : ''; echo "<option value=\"{$row['lorry']}\" $selected>{$row['lorry']}</option>"; } } else { echo "<option value=\"none\">No Lorries Available</option>"; } // Closing the database connection $mysqli->close(); ?> </select>
-
Hi guys, I have this issue. It works fine in another piece of php code as in where I ban a user, it will show sweetalert to confirm and when I click unban this user, it will ask me in a nice sweetalert if I am sure. When I click Yes, the user ban gets lifted and then disaster strikes. It shows a normal js alert with html code inside. Here is the code that is used to lift the ban: <?php include_once('config.php'); // Function to unban a user function unbanUser($userId) { global $conn; // Prepare the SQL statement securely $stmt = $conn->prepare("UPDATE users SET status = ? WHERE user_id = ?"); $status = 'Active'; $stmt->bind_param("si", $status, $userId); // Execute the statement and handle the result if ($stmt->execute()) { echo '<script>Swal.fire("Success", "User has been unbanned.", "success");</script>'; } else { echo '<script>Swal.fire("Error", "Error removing user ban: ' . htmlspecialchars($stmt->error) . '", "error");</script>'; } $stmt->close(); } // Check if the request is made via POST and validate user input if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['userId'])) { $userId = filter_input(INPUT_POST, 'userId', FILTER_VALIDATE_INT); if ($userId !== false) { unbanUser($userId); } else { echo '<script>Swal.fire("Invalid Input", "Invalid user ID.", "warning");</script>'; } } ?> Just confirming, I do have Sweetalert script included in the header (because it needs to be before any execution). <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script> If anyone can work this out I would appreciate it. Thank you
-
How to Get Updated Page Height After Hiding an Element?
Moorcam replied to emmanuelkatto24's topic in Javascript Help
Provide the code you are using so we can have a look. The more information you provide the better chance someone can help. -
Ok, it now works. I changed the domains.php file to the following: <?php // domains.php // Array of domains $domains = [ "example.com", "example.org", "example.net", "example.edu" ]; // Set the content type to application/json header('Content-Type: application/json'); // Encode the array to JSON and output it echo json_encode($domains); ?> Changed the domains to be encased in double quotes rather than single quotes and also set the type to application/json Although it will not work in localhost because of local certificate errors, it does work in a live server environment. Thank you both for your help. It's appreciated. So, for anyone wanting this, here is the rest of the code: <?php // This script checks if the current domain is in the allowed domains list. // Function to fetch domains from the external PHP file function fetchDomains($url) { $ch = curl_init(); // Set cURL options curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Execute cURL request $response = curl_exec($ch); // Error handling for cURL if (curl_errno($ch)) { throw new Exception('cURL Error: ' . curl_error($ch)); } curl_close($ch); // Decode the JSON response $domains = json_decode($response, true); // Error handling for JSON decoding if (json_last_error() !== JSON_ERROR_NONE) { throw new Exception('JSON Decode Error: ' . json_last_error_msg()); } return $domains; } // Main execution try { $url = 'https://www.site.com/domains.php'; // Replace with the actual URL of the external PHP file $domains = fetchDomains($url); // Get the current domain $currentDomain = $_SERVER['HTTP_HOST']; // Check if the current domain is in the fetched array if (!in_array($currentDomain, $domains)) { echo "Your domain, ($currentDomain) is not on the list."; } } catch (Exception $e) { // Handle exceptions echo "An error occurred: " . $e->getMessage(); } ?>
-
Further to the last post, I am also getting this: An error occurred: JSON Decode Error: Syntax error
-
Ok it's weird. Have directly accessed the file in a browser and get the array of domains. However, when I access via the script, I now get: [24-Oct-2024 11:35:34 Australia/Melbourne] PHP Warning: in_array() expects parameter 2 to be array, null given in includes/header.php on line 76 I have also rewritten the code to add error and exception handling: // This script checks if the current domain is in the allowed domains list. // Function to fetch valid domains from the external file function fetchValidDomains($url) { $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Execute cURL request and handle potential errors $response = curl_exec($ch); if ($response === false) { throw new Exception('cURL Error: ' . curl_error($ch)); } curl_close($ch); // Decode the JSON response and handle potential errors $domains = json_decode($response, true); if (json_last_error() !== JSON_ERROR_NONE) { throw new Exception('JSON Decode Error: ' . json_last_error_msg()); } return $domains; } try { // Get the current domain $currentDomain = $_SERVER['HTTP_HOST']; // URL of the external PHP file $externalFileUrl = 'http://www.site.com/domains.php'; // Fetch valid domains $validDomains = fetchValidDomains($externalFileUrl); // Check if the current domain is in the valid domains array if (!in_array($currentDomain, $validDomains)) { throw new Exception('Error: The current domain is not authorized.'); } // If the domain is valid echo 'The current domain is authorized.'; } catch (Exception $e) { // Handle exceptions and display error message echo 'An error occurred: ' . $e->getMessage(); } I'm at a loss.
-
domains.php: <?php // allowed_domains.php // Prevent direct access if (basename($_SERVER['PHP_SELF']) === basename(__FILE__)) { die('Access denied.'); } // Array of allowed domains $allowed_domains = [ 'example.com', 'test.com', 'mywebsite.org' ]; // Return the allowed domains as a JSON encoded string echo json_encode($allowed_domains); ?> site.php // This script checks if the current domain is in the allowed domains list. // Function to fetch allowed domains function fetchAllowedDomains($url) { $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); if (curl_errno($ch)) { throw new Exception('CURL Error: ' . curl_error($ch)); } curl_close($ch); return json_decode($response, true); } try { // URL of the external PHP file $url = 'https://www.site.com/domains.php'; // Fetch allowed domains $allowed_domains = fetchAllowedDomains($url); // Get the current domain $current_domain = $_SERVER['HTTP_HOST']; // Check if the current domain is in the allowed domains if (!in_array($current_domain, $allowed_domains)) { throw new Exception('Error: The current domain (' . $current_domain . ') is not allowed.'); } echo 'Domain check passed. Current domain is allowed.'; } catch (Exception $licenseMsg) { // Handle exceptions echo $licenseMsg->getMessage(); } Error: [24-Oct-2024 02:04:42 Australia/Melbourne] PHP Warning: in_array() expects parameter 2 to be array, null given in includes/header.php on line 83 Thanks guys. Your help is appreciated.
-
Using var_dump I get 301 error "Permanently Moved"
-
Hello folks, I am trying to create a script that will check the current domain, compare it with an array of domains that are stored externally in domains.php. If we have a match, great. If not, show an error. I am using CURL because of the vulnerabilities used using allow_url_include() so don't want to use that. Here is domains.php <?php // domains.php // Prevent direct access if (basename($_SERVER['PHP_SELF']) === basename(__FILE__)) { die('Access denied.'); } // Array of allowed domain names $domains_content = [ 'test1.com', 'test.com', 'mywebsite.org' ]; ?> Here is the function for checking: // This script checks if the current domain is in the allowed domains list. // Function to fetch the external PHP file using CURL function fetchDomains($url) { $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); if (curl_errno($ch)) { throw new Exception('CURL Error: ' . curl_error($ch)); } curl_close($ch); return $response; } try { // URL of the external PHP file $url = 'https://www.domain/domains.php'; // Replace with the actual URL // Fetch the domains $domains_content = fetchDomains($url); // Evaluate the fetched content to get the array eval('?>' . $domains_content); // Get the current domain $current_domain = $_SERVER['HTTP_HOST']; // Check if the current domain is in the allowed domains if (!in_array($current_domain, $domains_content)) { throw new Exception('Error: The current domain "' . $current_domain . '" is not allowed.'); } echo 'Domain check passed. Current domain: ' . $current_domain; } catch (Exception $e) { // Handle exceptions and display error message echo 'An error occurred: ' . $e->getMessage(); } I haven't included the actual domain I am checking for privacy reasons but you get the drift. Here is the error I am getting: [24-Oct-2024 00:04:58 Australia/Melbourne] PHP Warning: in_array() expects parameter 2 to be array, string given in includes/header.php on line 85 Here is that line: if (!in_array($current_domain, $domains_content)) { throw new Exception('Error: The current domain "' . $current_domain . '" is not allowed.'); } If anyone can help resolve this I would appreciate it. The domain the script is hosted on is actually listed in the array.
-
Sanjeev Mansotra Short Intro to Community - Core Educator
Moorcam replied to sanjeevmansotra's topic in Introductions
Welcome to the community -
Thank you. You are all right. I will get onto this. Not hard to do. Still a bit of a learning curve with prepared statements etc. but getting there
- 10 replies
-
- php
- prepared statements
-
(and 2 more)
Tagged with:
-
Thank you kind sir. I will look more into all this. The reason there are two separate logins is because there are two separate panels. One for staff and one for members. I know I could do something like: if($_SESSION['role'] == 'admin'){ header("location: index.php"); }elseif($_SESSION['role'] = ='member'){ header("location: members.php"); } Thanks for the input. Always appreciated.
- 10 replies
-
- php
- prepared statements
-
(and 2 more)
Tagged with:
-
Barand, Remember when I joined here first and I made it clear that I am an old Irish fart? Well, today defines exactly what I meant by that. I was updating the table "users" and should have been updating the table "staff". // Prepare the SQL statement to update the user's login status $stmt = $conn->prepare("UPDATE staff SET is_logged_in = 0 WHERE user_id = ?"); $stmt->bind_param("i", $userId); // Execute the statement if ($stmt->execute()) { // Destroy the session session_unset(); session_destroy(); redirectToLogin(); } else { echo "Error updating user status: " . $stmt->error; } // Close the statement $stmt->close(); } I will now go to bed as it is 12:53 on Sunday morning here. Maybe I just need sleep thing? Good night
- 10 replies
-
- php
- prepared statements
-
(and 2 more)
Tagged with:
-
I have that set globally in config.php // CHECK FOR ERRORS ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL);
- 10 replies
-
- php
- prepared statements
-
(and 2 more)
Tagged with:
-
Hi mate, Thanks for the reply. Have changed it to the following as you mentioned. Still the same: <?php session_start(); // Start the session // Include database connection require_once('includes/config.php'); // Check if user is logged in if (!empty($_SESSION['user_id'])) { logoutUser($conn, $_SESSION['user_id']); } else { redirectToLogin(); } // Close the database connection $conn->close(); /** * Logs out the user by updating their login status and destroying the session. * * @param mysqli $conn The database connection. * @param int $user_id The ID of the user to log out. */ function logoutUser($conn, $user_id) { // Prepare statement to update user login status $stmt = $conn->prepare("UPDATE users SET is_logged_in = 0 WHERE user_id = ?"); $stmt->bind_param("i", $_SESSION['user_id']); // Execute the statement if ($stmt->execute()) { // Destroy the session session_unset(); session_destroy(); redirectToLogin(); } else { echo "Error updating user status: " . $stmt->error; } // Close the statement $stmt->close(); } /** * Redirects the user to the login page. */ function redirectToLogin() { header("Location: login.php"); exit(); } ?> I was binding because I just find it safer to do that when inserting or updating in particular.
- 10 replies
-
- php
- prepared statements
-
(and 2 more)
Tagged with:
-
Darshan Hiranandani Newbie Introduction
Moorcam replied to darshanhiranandani23's topic in Introductions
Welcome -
Hi guys, I have the following logout code, which works just fine, as in it logs the user out and kills the session etc. However, there is one part that is not working and that is updating the database to change the is_logged_in to set to 0 rather than 1, which is set upon login. <?php session_start(); // Start the session // Include database connection require_once('includes/config.php'); // Check if user is logged in if (!empty($_SESSION['user_id'])) { logoutUser($conn, $_SESSION['user_id']); } else { redirectToLogin(); } // Close the database connection $conn->close(); /** * Logs out the user by updating their login status and destroying the session. * * @param mysqli $conn The database connection. * @param int $user_id The ID of the user to log out. */ function logoutUser($conn, $user_id) { // Prepare statement to update user login status $stmt = $conn->prepare("UPDATE users SET is_logged_in = ? WHERE user_id = ?"); $is_logged_in = '0'; // Set user status to logged out $stmt->bind_param("si", $is_logged_in, $user_id); // Execute the statement if ($stmt->execute()) { // Destroy the session session_unset(); session_destroy(); redirectToLogin(); } else { echo "Error updating user status: " . $stmt->error; } // Close the statement $stmt->close(); } /** * Redirects the user to the login page. */ function redirectToLogin() { header("Location: login.php"); exit(); } ?> If anyone can help that would be great. Thanks
- 10 replies
-
- php
- prepared statements
-
(and 2 more)
Tagged with: