-
Posts
253 -
Joined
-
Last visited
Everything posted by Moorcam
-
I have had a good look through your code and made a few minor changes for better readability, simplicity and understanding. There is so much code in yours when there is really no need for it. I have added some Javascript (as mentioned above) that calculates the total on price changes. I have also made the total field read only to prevent it being changed. You can change that easy in the HTML. Hope it helps. Look through it and learn from it. <!DOCTYPE html> <?php $con = mysqli_connect("localhost", "root", "", "receipt"); $data["product"] = []; $sql = "SELECT * FROM feedetails"; $res = $con->query($sql); if ($res->num_rows > 0) { while ($row = $res->fetch_assoc()) { $data["product"][] = $row; } } if (!$res) { trigger_error('Invalid query: ' . $con->error); } ?> <html> <head> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"> <script src="https://code.jquery.com/jquery-3.6.1.min.js"></script> <style> html { counter-reset: rows; } tr { counter-increment: rows; } tbody td { border: 1px dotted grey; padding: 0.25rem; } tbody tr td:first-of-type::before { content: counter(rows); display: table-cell; } tfoot td { background: grey; padding: 0.5rem; color: white; } </style> </head> <body> <div class="container mt-5"> <div class="row"> <div class="col-md-12"> <table class='table table-bordered'> <tbody id='table'> <tr class='crow'> <td style='width:150px;'></td> <td style='width:350px;'> <select class="form-control pid" required name="pid[]"> <option value='' price='0'>Select</option> <?php foreach ($data["product"] as $row): ?> <option value='<?= $row["fid"] ?>' price='<?= $row["famount"] ?>'><?= $row["fdescription"] ?></option> <?php endforeach; ?> </select> </td> <td> <input type="text" name="price[]" class="form-control price" required> </td> <td> <input data-action='remove' type='button' value='Remove' class='btn btn-link btn-xs rmv' required /> </td> </tr> </tbody> <tfoot> <tr> <td><input data-action='add' type='button' class='btn btn-link add' value='+Add Row' /></td> <td colspan='2' class='text-right'>Total</td> <td><input type='text' name='grand_total' class='form-control' required readonly /></td> </tr> </tfoot> </table> </div> </div> </div> <script> const d = document; const total = d.querySelector('input[name="grand_total"]'); d.addEventListener('click', e => { if (e.target.classList.contains('btn-link') && e.target.dataset.action === 'add') { let tbody = d.querySelector('tbody#table'); let tr = tbody.querySelector('tr:first-of-type'); let clone = tr.cloneNode(true); clone.querySelector('input[name="price[]"]').value = ''; tbody.appendChild(clone); } if (e.target.classList.contains('btn-link') && e.target.dataset.action === 'remove') { if (d.querySelectorAll('tbody#table tr').length > 1) { let value = e.target.closest('tr').querySelector('input[name="price[]"]').value; d.querySelector('tbody#table').removeChild(e.target.closest('tr')); total.value -= parseFloat(value); } } }); d.addEventListener('keyup', e => { let col = d.querySelectorAll('input[name="price[]"]'); total.value = [...col].map(n => n.value > 0 ? n.value : 0).reduce((a, b) => parseFloat(a) + parseFloat(b), 0); }); $("body").on("change", ".pid", function() { var p = $(this).find(":selected").attr("price"); $(this).closest("tr").find(".price").val(p); }); </script> </body> </html>
-
Examples of php scripting projects without laravel?
Moorcam replied to oslon's topic in PHP Coding Help
Here's one simple script that fetches news from a news website. #!/bin/bash # Define the URL of the local news channel NEWS_URL="https://www.localnewschannel.com" # Fetch the HTML content of the news page HTML_CONTENT=$(curl -s "$NEWS_URL") # Extract the headlines using grep and sed HEADLINES=$(echo "$HTML_CONTENT" | grep -oP '(?<=<h2 class="headline">).*?(?=</h2>)') # Display the headlines echo "Latest News Headlines:" echo "$HEADLINES" There's an idea. -
Help Needed with Fetching and Updating Vehicle Data Using API
Moorcam replied to GaneshNaiknavre's topic in PHP Coding Help
The script checks if the mileage and location data are valid before attempting to update the database. If either of these checks fails, the update will be skipped. // Update the database if data is valid if ($api_miles > 0 && $latitude !== null && $longitude !== null) { $update_query = "UPDATE created_jobs SET run_km = IFNULL(run_km, 0) + ?, current_km = IFNULL(current_km, 0) + ?, latitude = ?, longitude = ? WHERE vehicle_no = ?"; $stmt = $mysqli->prepare($update_query); if ($stmt) { $stmt->bind_param("ddsss", $api_miles, $api_miles, $latitude, $longitude, $vehicle_no); if (!$stmt->execute()) { error_log("Failed to execute statement for vehicle_no {$vehicle_no}: " . $stmt->error); } else { error_log("Updated vehicle_no: {$vehicle_no} | KM Added: {$api_miles} | Lat: {$latitude} | Lng: {$longitude}"); } } else { error_log("Failed to prepare statement for vehicle_no {$vehicle_no}: " . $mysqli->error); } } else { error_log("Skipping update for vehicle_no {$vehicle_no} due to invalid data."); } See if that helps. -
This is so funny. The fact that you can't even follow forum rules and requirements when posting indicates the lazy sod that you are. If you want to learn, there is a great community of developers here who will teach you. But, at least show some effort. You don't even put your code into formatted "Code" when posting, making it almost impossible to read.
-
Ok, After more research the issue was with these two lines: $pickupLocations, // Now properly initialized $dropLocations, // Now properly initialized These two variables are connected to a json_encode function. And, since json_encode returns a value rather than a variable, it cannot be passed by reference. So, the fix was to predefine the json_encode and pass them then into the bind as follows: // Prepare JSON encoded variables $pickupLocation = json_encode($charterData['pickup_location']); $dropLocation = json_encode($charterData['drop_location']); // Bind parameters $stmt->bind_param("ssssssssssssssi", $charterData['chtr_name'], $charterData['chtr_description'], $charterData['start_date'], $charterData['end_date'], $charterData['depot_start'], $charterData['depot_finish'], $charterData['driver'], $charterData['fleet_number'], $charterData['updated_by'], $charterData['customer_name'], $pickupLocation, $dropLocation, $charterData['pickup_time'], $charterData['return_time'], $charterId ); Hope this may help others in the future.
-
Hi guys, I have the following code, which does work. The two problematic parts are pickup_location and drop_location. When I click Save the data is saved to the database and those two are saved to an array with multiple locations. However, opening err_log, I get the following for each one: Only variables should be passed by reference <?php // Include Header file which contains required credentials include_once('includes/header.php'); // Initialize variables $charterData = [ 'chtr_name' => '', 'chtr_description' => '', 'start_date' => '', 'end_date' => '', 'depot_start' => '', 'depot_finish' => '', 'driver' => '', 'fleet_number' => '', 'updated_by' => '', 'customer_name' => '', 'pickup_location' => [], 'drop_location' => [], 'pickup_time' => '', 'return_time' => '' ]; try { // Fetch current charter details $charterId = (int)$_GET['chtr_id']; // Assuming the charter ID is passed via the URL $fetchStmt = $conn->prepare("SELECT chtr_name, chtr_description, start_date, end_date, depot_start, depot_finish, driver, fleet_number, updated_by, customer_name, pickup_location, drop_location, pickup_time, return_time FROM charters WHERE chtr_id = ?"); $fetchStmt->bind_param("i", $charterId); $fetchStmt->execute(); // Initialize variables $pickupLocations = null; // or an appropriate default value $dropLocations = null; // or an appropriate default value $fetchStmt->bind_result( $charterData['chtr_name'], $charterData['chtr_description'], $charterData['start_date'], $charterData['end_date'], $charterData['depot_start'], $charterData['depot_finish'], $charterData['driver'], $charterData['fleet_number'], $charterData['updated_by'], $charterData['customer_name'], $pickupLocations, // Now properly initialized $dropLocations, // Now properly initialized $charterData['pickup_time'], $charterData['return_time'] ); $fetchStmt->fetch(); $fetchStmt->close(); // Convert pickup and drop locations from JSON to array $charterData['pickup_location'] = json_decode($pickupLocations, true) ?: []; $charterData['drop_location'] = json_decode($dropLocations, true) ?: []; // Check if the form is submitted if ($_SERVER["REQUEST_METHOD"] === "POST") { // User data foreach ($charterData as $key => $value) { if ($key === 'pickup_location' || $key === 'drop_location') { $charterData[$key] = array_filter(array_map('htmlspecialchars', $_POST[$key] ?? [])); } else { $charterData[$key] = htmlspecialchars(trim($_POST[$key] ?? '')); } } // Prepare an SQL statement for updating the charter $stmt = $conn->prepare("UPDATE charters SET chtr_name = ?, chtr_description = ?, start_date = ?, end_date = ?, depot_start = ?, depot_finish = ?, driver = ?, fleet_number = ?, updated_by = ?, customer_name = ?, pickup_location = ?, drop_location = ?, pickup_time = ?, return_time = ? WHERE chtr_id = ?"); // Bind parameters $stmt->bind_param("ssssssssssssssi", $charterData['chtr_name'], $charterData['chtr_description'], $charterData['start_date'], $charterData['end_date'], $charterData['depot_start'], $charterData['depot_finish'], $charterData['driver'], $charterData['fleet_number'], $charterData['updated_by'], $charterData['customer_name'], json_encode($charterData['pickup_location']), json_encode($charterData['drop_location']), $charterData['pickup_time'], $charterData['return_time'], $charterId ); // Execute the statement if (!$stmt->execute()) { throw new Exception("Error: " . $stmt->error); } echo '<script type="text/javascript"> Swal.fire({ icon: "success", title: "Great Job!", text: "Be proud! Charter has been updated successfully!", showConfirmButton: false, timer: 2500, footer: "Powered by NerfCMS" }); </script>'; } } catch (Exception $e) { $ErrMsg = $e->getMessage(); } ?> Can anyone please guide me in the right direction?
-
They usually go in the top of the php file where you want to use them. For example, if you want them in index.php, you open index.php and paste them at the top: <?php // index.php require_once 'path/to/PhpPresentation/src/PhpPresentation/Autoloader.php'; \PhpOffice\PhpPresentation\Autoloader::register(); require_once 'path/to/PhpOffice/Common/src/Common/Autoloader.php'; \PhpOffice\Common\Autoloader::register(); // and whatever after that ?> Just change the paths to reflect the file locations.
-
If contacting support or getting support from a hosting company appears to be an issue, I would definitely be looking elsewhere. If you are paying for hosting, I would be expecting 24 hour tech support to be included.
-
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.