Jump to content

Moorcam

Members
  • Posts

    245
  • Joined

  • Last visited

About Moorcam

  • Birthday 02/12/1971

Contact Methods

  • Website URL
    https://www.moorcam.com.au

Profile Information

  • Gender
    Male
  • Location
    Victoria, Australia
  • Interests
    Coding, driving large heavy vehicles.
  • Age
    53

Recent Profile Visitors

4,720 profile views

Moorcam's Achievements

Advanced Member

Advanced Member (4/5)

5

Reputation

12

Community Answers

  1. 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.
  2. 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.
  3. 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!'; ?>
  4. 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
  5. 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.
  6. 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/
  7. 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.
  8. 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>'
  9. 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>
  10. 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
  11. Provide the code you are using so we can have a look. The more information you provide the better chance someone can help.
  12. 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(); } ?>
  13. Further to the last post, I am also getting this: An error occurred: JSON Decode Error: Syntax error
  14. 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.
  15. 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.
×
×
  • 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.