Jump to content

Strider64

Members
  • Posts

    466
  • Joined

  • Last visited

  • Days Won

    12

Everything posted by Strider64

  1. Ever since AI I have seen tech forums like this one become very quiet which isn't surprising.
  2. I didn't create a Model, but a trait though maybe it will give you some ideas? <?php // NavigationMenuTrait.php namespace clearwebconcepts; use function htmlspecialchars; use function hash_equals; trait NavigationMenuTrait { public function regular_navigation(): void { $navItems = [ 'Home' => 'index.php', 'About' => 'about.php', 'Puzzle' => 'puzzle.php', 'Portfolio' => 'portfolio.php', 'Contact' => 'contact.php' ]; // Check if the user is logged in $isLoggedIn = isset($_COOKIE['login_token']) && isset($_SESSION['login_token']) && hash_equals($_SESSION['login_token'], $_COOKIE['login_token']); if ($isLoggedIn) { unset($navItems['Home']); // Remove 'Home' from the navigation menu // Add 'Dashboard' to the start of the navigation menu $navItems = array('Dashboard' => 'dashboard.php') + $navItems; } else { $navItems['Login'] = 'login.php'; // Add 'Login' to the navigation menu } $navLinks = []; foreach ($navItems as $title => $path) { $href = $this->generateHref($path); $safeTitle = htmlspecialchars($title, ENT_QUOTES, 'UTF-8'); $navLinks[] = "<a href=\"{$href}\">{$safeTitle}</a>"; } // Check if the user is logged in if ($isLoggedIn) { $navLinks[] = '<a href="logout.php">Logout</a>'; // Add 'Logout' to the end of the navigation menu } echo implode('', $navLinks); } public function showAdminNavigation(): void { $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' ? 'https://' : 'http://'; $host = $_SERVER['HTTP_HOST']; // Define your base path here $base_path = ($host === 'localhost:8888') ? '/clearwebconcepts' : ''; $base_url = $protocol . $host . $base_path; $adminItems = [ 'Create Entry' => $base_url . '/create_cms.php', 'Edit Entry' => $base_url . '/edit_cms.php', 'Add to Portfolio' => $base_url . '/new_portfolio.php', 'Edit Portfolio Page' => $base_url . '/edit_portfolio.php', 'Add Jigsaw' => $base_url . '/add_to_puzzle.php', 'Edit Jigsaw' => $base_url . '/edit_puzzle.php', 'Service Form' => $base_url . '/service_form.php' ]; echo '<div class="admin-navigation">'; foreach ($adminItems as $adminTitle => $adminPath) { $adminSafeTitle = htmlspecialchars($adminTitle, ENT_QUOTES, 'UTF-8'); echo "<a href=\"{$adminPath}\">{$adminSafeTitle}</a>"; } echo '</div>'; } private function generateHref(string $path): string { $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' ? 'https://' : 'http://'; $host = $_SERVER['HTTP_HOST']; // Define your base path here $base_path = ($host === 'localhost:8888') ? '/clearwebconcepts' : ''; $base_url = $protocol . $host . $base_path; // Build the URL first, then validate it $url = $base_url . '/' . $path; $sanitized_url = filter_var($url, FILTER_SANITIZE_URL); $valid_url = filter_var($sanitized_url, FILTER_VALIDATE_URL); if ($valid_url === false) { die('Invalid URL'); } return $valid_url; } }
  3. I create a simple error log for my own use and it comes in handy in debugging without the user knowing about it. I even created a simple error handler to sort the errors. class ErrorHandler implements ErrorHandlerInterface { public function handleException(Throwable $e): void { if ($e instanceof PDOException) { error_log('PDO Error: ' . $e->getMessage()); } elseif ($e instanceof JsonException) { error_log('JSON Error: ' . $e->getMessage()); } else { error_log('General Error: ' . $e->getMessage()); } } } and in my configuration file // Set the path for the error log file ini_set('error_log', __DIR__ . '/error_log/error_log_file.log'); this is the most import. part errors isn't seen by the public.
  4. Here's my query -> $sql = 'SELECT * FROM '. $this->table . ' WHERE page =:page AND category =:category ORDER BY id DESC, date_added DESC LIMIT :perPage OFFSET :blogOffset'; it might help?
  5. That sure seems like a strange way in doing pagination. In my opinion the data should be come from a database table and broken down to something like the following -> // Grab the current page the user is on if (isset($_GET['page']) && !empty($_GET['page'])) { $current_page = urldecode($_GET['page']); } else { $current_page = 1; } $per_page = 2; // Total number of records to be displayed: // Grab Total Pages $total_pages = $cms->total_pages($total_count, $per_page); /* Grab the offset (page) location from using the offset method */ /* $per_page * ($current_page - 1) */ $offset = $cms->offset($per_page, $current_page); // Figure out the Links that you want the display to look like $links = new Links($current_page, $per_page, $total_count, $category); // Finally grab the records that are actually going to be displayed on the page $records = $cms->page($per_page, $offset, 'cms', $category); that way all you have to do is format. the HTML using CSS -> <main class="main_container" itemprop="mainContentOfPage"> <?php foreach ($records as $record) { $imagePath = htmlspecialchars($record['image_path'], ENT_QUOTES, 'UTF-8'); $heading = htmlspecialchars($record['heading'], ENT_QUOTES, 'UTF-8'); $content = htmlspecialchars($record['content'], ENT_QUOTES, 'UTF-8'); echo '<div class="image-header">'; echo '<img src="' . $imagePath . '" title="' . $heading . '" alt="' . $heading . '">'; echo '</div>'; echo '<h1>' . $heading . '</h1>'; echo '<p>' . nl2br($content) . '</p>'; echo '<br><hr><br>'; } ?> </main> The above is just an example, but if you breakdown the HTML/Code in smaller sections it's easier to read & debug. There are a lot of good pagination tutorials online.
  6. First get the PDO connection out of the function as that will cause you nothing but headaches. Here's an example of a generic PDO connection -> <?php $host = '127.0.0.1'; // or your database host $db = 'your_database_name'; $user = 'your_database_username'; $pass = 'your_database_password'; $charset = 'utf8mb4'; $dsn = "mysql:host=$host;dbname=$db;charset=$charset"; $options = [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_EMULATE_PREPARES => false, ]; try { $pdo = new PDO($dsn, $user, $pass, $options); // Use $pdo to perform database operations } catch (\PDOException $e) { throw new \PDOException($e->getMessage(), (int)$e->getCode()); } ?> I would put this in a configuration file maybe name it config.php file? My example would entail explaining OOP, so maybe someone else will do a better example for you. But here is how I do it -> $sql = "SELECT id, password FROM admins WHERE username =:username LIMIT 1"; $user = $this->retrieve_credentials($sql, $username); if ($user && password_verify($password, $user['password'])) { session_regenerate_id(); // prevent session fixation attacks $_SESSION['user_id'] = $user['id']; return true; } return false; and little more code protected function retrieve_credentials(string $sql, string $username): ?array { $stmt = $this->pdo->prepare($sql); $stmt->execute(['username' => $username]); $result = $stmt->fetch(PDO::FETCH_ASSOC); return $result !== false ? $result : null; }
  7. Studying design patterns such as MVC (Model-View-Controller) and Active Record Design has enhanced my understanding of Object-Oriented Programming (OOP). Although many prefer Model-View-Controller, I found Active Record Design more helpful in solidifying my grasp of OOP. One constant with OOP is that there's always something new to learn, and there's always someone with a deeper understanding of it. I believe that beginners often find the structure of Object-Oriented Programming (OOP) challenging. Here's an example from some code on my website to illustrate this. -> // Display Record(s) by Pagination public function page($perPage, $offset, $page = "index", $category = "general"): array { $sql = 'SELECT * FROM '. $this->table . ' WHERE page =:page AND category =:category ORDER BY id ASC, date_added DESC LIMIT :perPage OFFSET :blogOffset'; $stmt = $this->pdo->prepare($sql); // Prepare the query: $stmt->execute(['page' => $page, 'perPage' => $perPage, 'category' => $category, 'blogOffset' => $offset]); // Execute the query with the supplied data: return $stmt->fetchAll(PDO::FETCH_ASSOC); } Initially, I would mix up my code by writing `$sql` and `$this->sql`, which made things confusing for me. However, everyone has their unique journey in learning Object-Oriented Programming (OOP). By coding in this manner, I'm able to more clearly identify key OOP components, such as recognizing `$this->pdo` and understanding that `$stmt->fetchAll(PDO::FETCH_ASSOC)` is an example of object-oriented code.
  8. My approach would be to divide the content into three files, although it's feasible to combine everything into a single file. Nonetheless, I'd still make an effort to keep the code and HTML distinct and separate as much as possible. Client's search page - example clients.php (form to search) JavaScript file - example clients.js PHP search results file - example client_results.php Here's an example of what I'm trying to express: My HTML form (edit_cms.php): <div class="search-form-container"> <form id="searchForm"> <div class="input-group"> <label for="heading">Heading:</label> <select class="select-css" id="heading" name="heading"> <option value="" disabled selected>Select Heading</option> <?php foreach ($records as $record) { echo '<option value="' . $record['heading'] . '">' . $record['heading'] . '</option>'; } ?> </select> </div> <div class="input-group"> <label for="searchTerm">Search Product Content:</label> <input type="text" placeholder="Search Content" id="searchTerm" class="input-field" autofocus required> </div> <button class="search_button" type="submit">Search</button> </form> </div> A little bit of my JavaScript code (edit_cms.js): async function displayRecord(searchTerm = null, selectedHeading = null) { const requestData = {}; if(searchTerm !== null) requestData.searchTerm = searchTerm; if(selectedHeading !== null) requestData.heading = selectedHeading; try { const response = await fetch("search_cms_records.php", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify(requestData), }); const data = await response.json(); console.log(data); // Add this line if (data.message) { resultInput.value = ''; resultInput.placeholder = data.message; } else if (data.error) { console.error(data.error); } else { const row = data[0]; console.log(row); idInput.value = row.id; image_for_edit_record.src = row.thumb_path; image_for_edit_record.alt = row.heading; category.value = row.category; category.textContent = `${row.category.charAt(0).toUpperCase()}${row.category.slice(1)}`; heading.value = row.heading; content.value = row.content; resizeTextarea(content); } } catch (error) { console.error("Error:", error); } } and my PHP file with a little bit of the code that gets the results (search_cms_records.php): // Get the request body and decode it as JSON. $request = json_decode(file_get_contents('php://input'), true); // Extract the search term and heading from the request, if they exist. $searchTerm = $request['searchTerm'] ?? null; $heading = $request['heading'] ?? null; // If a search term was provided, use a full-text search on the 'content' field. // Before this can work, you'll need to make sure your content column is indexed for full-text searching. // You can do this with the following SQL command: // Example: // ALTER TABLE cms ADD FULLTEXT(content); if($searchTerm !== null) { $sql = "SELECT * FROM cms WHERE MATCH(content) AGAINST(:searchTerm IN NATURAL LANGUAGE MODE) LIMIT 1"; $stmt = $pdo->prepare($sql); $stmt->bindValue(':searchTerm', $searchTerm); // If a heading was provided, search for exact matches on the 'heading' field. } else if($heading !== null) { $sql = "SELECT * FROM cms WHERE heading = :heading LIMIT 1"; $stmt = $pdo->prepare($sql); $stmt->bindValue(':heading', $heading); // If neither a search term nor a heading was provided, throw an exception. } else { throw new Exception("No valid search term or heading provided"); } // Execute the prepared statement. $stmt->execute(); // Fetch the results and handle them as needed. $results = $stmt->fetchAll(PDO::FETCH_ASSOC); // If results were found, return them to the client as JSON. if ($results) { echo json_encode($results); } else { echo json_encode(['message' => 'No results found.']); } My argument is that debugging becomes simpler when most of the code is organized and separated as much as possible within its respective programming language.
  9. I personally find it better to have the configuration file outside the root directory require_once __DIR__ . '/../config/config.php'; // Goes one up from the root / directory
  10. Instead of using `if` statements you should be using `functions`, plus PHP has a great way of doing pagination (The following is just an example of what I'm talking about) -> // Display Record(s) by Pagination public function page($perPage, $offset, $page = "index", $category = "general"): array { $sql = 'SELECT * FROM '. $this->table . ' WHERE page =:page AND category =:category ORDER BY id ASC, date_added DESC LIMIT :perPage OFFSET :blogOffset'; $stmt = $this->pdo->prepare($sql); // Prepare the query: $stmt->execute(['page' => $page, 'perPage' => $perPage, 'category' => $category, 'blogOffset' => $offset]); // Execute the query with the supplied data: return $stmt->fetchAll(PDO::FETCH_ASSOC); } I would look into pagination tutorials as that will save you a lot headaches.
  11. I would studied up on using CSS Grids, CSS Flexbox and media queries for responsive that way you can control the any page layout.
  12. You might want to check that your CSS is the same on both servers and that is correct. For example if you have `display:none;` the image won't show. Ensure that the file permissions for the image are set correctly. The web server should have read access to the image file. If you're using an Apache web server, check your .htaccess file and server configuration for any rules that might be affecting image loading.
  13. I'd also point out that you aren't using prepared statements. I'd recommend learning PDO over mysqli. Additionally, you seem to rely heavily on sessions when ideally, only the user's ID should be stored in them and maybe a token.
  14. // Import the arrayOfObjects from the data module. const arrayOfObjects = require("./data"); // Iterate through each object in the arrayOfObjects. for (const obj of arrayOfObjects) { // Log the id and name properties of the current object to the console. console.log(`ID: ${obj.id}, Name: ${obj.name}`); } For the data module that contains the array of objects: // Define an array of objects with properties id and name. const arrayOfObjects = [ { "id": 1, "name": "bla bla" }, // Object with id 1 and name 'bla bla' { "id": 2, "name": "bla bla bla" } // Object with id 2 and name 'bla bla bla' ]; // Export the arrayOfObjects so it can be imported and used in other modules. module.exports = arrayOfObjects;
  15. If you are `editing` the data anywhere else and that data isn't clean then you will have to look at that code as well. I hope I'm making sense.
  16. You don't need a registration form/page as all you have to do is hash your password that you want to use. That's what I do when I develop my website(s).
  17. Here's a good website that helped me with composer when I first started out using it. https://devdojo.com/bobbyiliev/use-composer-like-a-pro-the-dependency-manager-for-php It might not help you with this project, but it'll give you a better understanding on how to use it.
  18. You need to do something like this -> // Add an event listener to the edit form's submit event editForm.addEventListener("submit", async function (event) { // Prevent the default form submit behavior event.preventDefault(); // Create a FormData object from the edit form const formData = new FormData(editForm); //console.log("form data", formData); // Send a POST request to the edit_update_blog.php endpoint with the form data const response = await fetch("edit_update_blog.php", { method: "POST", body: formData, }); // Check if the request was successful if (response.ok) { const result = await response.json(); console.log(result); // If the response has a "success" property and its value is true, clear the form if (result.success) { resultInput.value = ''; // Clear the current value of the search input field resultInput.placeholder = "New Search"; // Set the placeholder to `New Search` image_for_edit_record.src = ""; image_for_edit_record.alt = ""; editForm.reset(); // Resetting the edit form searchForm.reset(); // Resetting the search form // Reset select box to default (first) option const selectBox = document.querySelector('select[name="heading"]'); selectBox.selectedIndex = 0; } } else { console.error( "Error submitting the form:", response.status, response.statusText ); // Handle error response } }); also using `console.log` helps in debugging, plus your `sql_connection.php` is expecting back json data back.
  19. Sure, I just do something like this echo "<pre>" . print_r($results, 1) . "</pre>"; It's a great way to debug also.
  20. /* ----- Upload File / Image ----- */ function uploadFile(uid) { const url = 'process.php'; const form = document.querySelector('form'); form.onsubmit = function(e) { e.preventDefault(); const files = document.querySelector('[type=file]').files; const formData = new FormData(); for (let i = 0; i < files.length; i++) { let file = files[i]; formData.append('files[]', file); formData.append('uploadid', uid); } fetch(url, { method: 'POST', body: formData }).then(response => { return response.text(); }).then(data => { console.log(data); }); }; return; } Instead of using the addEventListener method for the form submission, you can directly bind the function to the form's onsubmit?
  21. Personally, if I were writing a chess game I would use JavaScript and Canvas not PHP for the main coding part of the game.
  22. I just wanted to add that when I took a course in web design one of the things to do is keep the form simple as possible. I'm assuming all that data is coming from a form? If that case I would simplify it down a bit as most visitors will leave that website if they see a HTML form that l large. An example of what I'm talking about. <form class="registerStyle" action="register.php" method="post"> <input id="secret" type="hidden" name="user[secret]" value=""> <div id="qr-code-container" class="d-none"> <img id="qr-code-image" src="" alt="QR Code"> <p id="qr-code-info">Scan QR Code for 2FA</p> </div> <div class="first"> <label for="first_name">First Name</label> <input id="first_name" type="text" name="user[first_name]" value="" tabindex="2" required> </div> <div class="last"> <label for="last_name">Last Name</label> <input id="last_name" type="text" name="user[last_name]" value="" tabindex="3" required> </div> <div class="screenName"> <label class="text_username" for="username">Username <span class="error"> is unavailable!</span> </label> <input id="username" class="io_username" type="text" name="user[username]" value="" tabindex="4" required> </div> <div class="telephone"> <label for="phone">Phone (Optional)</label> <input id="phone" type="tel" name="user[phone]" value="" placeholder="555-555-5555" pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}" tabindex="5"> </div> <div class="emailStyle"> <label class="emailLabel" for="email">Email <span class="emailError"> is invalid</span> </label> <input id="email" type="email" name="user[email]" value="" tabindex="1" autofocus required> </div> <div class="password1"> <label for="passwordBox">Password</label> <input class="passwordBox1" id="passwordBox" type="password" name="user[password]" value="" tabindex="6" required> <label for="passwordVisibility">Show Passwords (private computer)</label> <input class="passwordBtn1" id="passwordVisibility" type="checkbox" tabindex="7"> </div> <div class="password2"> <label for="redoPassword">ReEnter Password</label> <input class="passwordBox2" id="redoPassword" type="password" name="user[comfirm_password]" value="" tabindex="8" required> </div> <div class="birthday"> <label for="birthday">Birthday (optional)</label> <input id="birthday" type="date" name="user[birthday]" value="1970-01-01" tabindex="9"> </div> <div class="submitForm"> <button class="submitBtn" id="submitForm" type="submit" name="submit" value="enter" tabindex="10"> Submit </button> </div> </form> or at least pull the data in easier -> Example: $user = $_POST['user'];
  23. My suggestion is to use composer https://getcomposer.org/ as it will save you a lot a headaches and you don't have to reinvent the wheel. Then you can just do something like the following -> <?php // Include the configuration file and autoload file from the composer. require_once __DIR__ . '/../config/config.php'; require_once "vendor/autoload.php"; // Import the ErrorHandler and Database classes from the PhotoTech namespace. use brainwave\{ ErrorHandler, Database, Links, ImageContentManager, LoginRepository as Login }; // Instantiate the ErrorHandler class $errorHandler = new ErrorHandler(); // Set the exception handler to use the handleException method from the ErrorHandler instance set_exception_handler([$errorHandler, 'handleException']); // Create a new instance of the Database class $database = new Database(); // Create a PDO instance using the Database class's method $pdo = $database->createPDO(); $login = new Login($pdo); if ($login->check_login_token()) { header('location: dashboard.php'); exit(); } $cms = new ImageContentManager($pdo); a sample class -> <?php // ErrorHandler.php namespace brainwave; use PDOException; use Throwable; use JsonException; class ErrorHandler implements ErrorHandlerInterface { public function handleException(Throwable $e): void { if ($e instanceof PDOException) { error_log('PDO Error: ' . $e->getMessage()); } elseif ($e instanceof JsonException) { error_log('JSON Error: ' . $e->getMessage()); } else { error_log('General Error: ' . $e->getMessage()); } } } I would also check out namespace for PHP classes.
  24. This is taken from my website project -> $file_ext = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION)); $extensions = array("jpeg", "jpg", "png"); if (in_array($file_ext, $extensions, true) === false) { $errors[] = "extension not allowed, please choose a JPEG or PNG file."; } /* * If no errors save ALL the information to the * database table. */ if (empty($errors) === true) { // Code that does it.... } I know my variable naming isn't exact, but it should give you a basic way in doing it. I have the GitHub repository -> https://github.com/Strider64/brain-wave-blitz/blob/master/create_cms.php feel free to look around.
×
×
  • 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.