Jump to content

JacobSeated

Members
  • Posts

    31
  • Joined

  • Last visited

Profile Information

  • Gender
    Male

JacobSeated's Achievements

Member

Member (2/5)

2

Reputation

  1. This is one reason some prefer to use absolute paths when including files, another is that it will be more adaptable than relying on include paths. The idea is that you store the "base path" of your active project/script, which you can then use to work out the paths for the rest of your files — either as a global constant or a variable you pass around as needed. From PHP 5.5 and onwards, the following should work: define('BASE_PATH', rtrim(preg_replace('#[/\\\\]{1,}#', '/', __DIR__), '/') . '/');
  2. Yes thank you. I am working on creating an app that uses a certain API, and did not want to post everything here. I just started coding one-big-file, intending to organize stuff properly later, and I only used unlink for the log file. Because of this problem I ended up organizing it now instead of later, but I realize this way I also avoid spending time on scrolling up and down so much, and it is much easier to debug. What is interesting to me is that the problem just seems to have solved itself, so I am not entirely sure what caused it. But as mentioned, maybe the problem was already fixed, and I just did not notice it because of caching issues. I have spent hours just moving code around, testing, trying a simplified version in a separate file — which did not have the problem. But, the file was deleted, written to, and deleted again — that's for sure — the sleep(10) at the end revealed to me it was happening. I got some idea about what I can test to reproduce the problem: Maybe I was being too optimistic in regards to placing functions and classes at the bottom of my script, only to use/initialize them at the top. I do not normally do that, but it just seemed like a good way to get them "out of my way" until I had better time and energy to organize my code. It was not 🙂 Typically you just spend time scrolling up and down to find things instead of coding.. It could be related to my use of singleton for the logger class, since I do not normally use singleton. I prefer creating everything with dependency injection. This is unlikely though, as I had also tried creating just a global function for the logger, and it had the same problem. Related to opcache, and me not realizing the file was not always updating when I made changes. But, opcache should be disabled in my PHP-FPM config, so again not sure. Related to declaring an object global inside a function. It appeared like the problem went away whenever I removed the global object declaration — but I needed it 😛 So, instead I just moved to DI, which I am now more familiar with using anyway. I am not sure I will try to reproduce it at this point, since I got delayed so much by this. But thanks 🙂
  3. I really would not block traffic from specific IP addresses or regions, but you can do it using Maxmind free GEO-location databases; the problem is you need to update the database occasionally. I wrote a script to do that automatically, and I do actually need it for a cookie consent mechanism. Another option is to compile your own databases, because the data is made available, it is just a bit difficult if you are not used to working with that stuff. Just a few ideas: Check the database for previous spam messages posted by an IP, and reject new messages by known spammers; that would be messages that has been hidden or blocked. You don't just delete the spam, because you might want to analyze it. Check the database for exact match- and variations of messages that has been blocked. If something has been blocked before, there is no reason to allow someone to post it again. Rate-limit your incoming HTTP POST requests on certain URLs I am not sure, but I think fail2ban should be able to do rate limiting. I am only using it for e-mail servers though, since my CMS already has build-in rate-limiting. If you made this 15 years ago, then I would recommend looking into moving it to a custom Wordpress solution. There are plugins to help with rate limiting and other stuff..
  4. Sorry to have troubled you 🙂 I spent several hours trying to fix this issue today, and it now seems the problem just resolved itself. I suspect it was a combination of different issues, one involving me forgetting to clear the obcache while testing. E.g.: opcache_invalidate(__FILE__, true); ini_set('display_errors', '1'); ini_set('display_startup_errors', '1'); error_reporting(E_ALL); I also had a very large file, which I have now split into 1 file per class. I am not sure if that could have caused it. I had quite a few classes located at the bottom of my script. Now everything is also at the top.
  5. I have some code that calls unlink() before calling file_put_contents() with file_append; I expect it to delete the file when the script runs, create a new file for the specific request, and only append data for this current process. BUT, the file seems to be deleted twice when unlink() is called first. Once at the start of the execution, and again when execution ends. Suspecting that a timeout might help, I added two seconds timeout after unlink(). if (file_exists('dev-log.txt')) { unlink('dev-log.txt'); sleep(2); } if(false === file_put_contents('dev-log.txt', $data, FILE_APPEND)) { throw new Exception("Unable to save log"); } I found that if I apply sleep(10) at the end of the script instead, it does in fact write data to the file, but then the file is ultimately deleted again when the script exits, which I find very strange. The same basically happens if I try to truncate the file. I am on PHP 8.0 with PHP8.0-fpm + Apache.
  6. Wordpress websites can be very difficult to optimize. But this depends on what theme you are using. Some theme developers have no idea what they are doing and just load all their CSS in one file, using extremely inefficient selectors. I have a client that asked me to optimize his site, and what I basically established was that little could be done. He is relying on external JavaScript files, such chat widgets, Analytics, and Google Maps. Such things tend to slow down a site a lot. Luckily they typically load asynchronously, so users will not notice it much. The pagespeed tool might still complain about them though. Another thing you really should look into, is the size of your CSS. If you use Divi or similar themes, then the CSS tend to grow extremely large. A good CSS file size is around 10-15kb max. I have seen examples of CSS approaching 1MB in size! Best solution is to stop using Divi and make your own custom-coded designs. I do not know of any good plugins to optimize CSS. They are not "intelligently aware" of the CSS, and that means they might actually make things worse. Autoptimize will just take all of your CSS and combine it into one big file. This is very inefficient, and might cause other problems. Code included in the CSS file should generally only concern stuff that is used sufficiently often, on multiple pages. If you can identify your "essential" (shared) CSS, then you can embedded this in the <head> of your site to speed up the load time. Images will typically not be the hardest thing to optimize, as you can resize and compress those. There are even plugins that will auto-convert to .webp. But, try running your site through Lighthouse in developer tools or PageSpeed Insights, that is how the rest of us try to optimize our pages.
  7. Just a few tips if you are coding vanilla PHP. As others have said, you can create "pretty URLs" with mod_rewrite; But a better way to go about it would be to point all requests to PHP, for non-existent files, since it is much easier to prettify your URLs from PHP than it is with the horrific syntax of .htaccess. Here is an example, for .htaccess: RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^.*$ / [QSA] Then, from your index.php file: $parsed_url = parse_url($_SERVER['REQUEST_URI']); $routes = [ '/^\/(blog)\/([a-z0-1_-]+)$/', '/^\/(forum)\/([a-z0-1_-]+)$/' ]; foreach ($routes as $url_pattern) { if(false === preg_match($url_pattern, $parsed_url['path'], $matches)) { http_response_code(404); echo 'Page not recognised...'; exit(); } // If a requested path matched a pattern, try to call the related feature $requested_feature = $matches[1]; $feature_path = $matches[2]; if (is_callable('feature_'.$requested_feature)) { call_user_func('feature_'.$requested_feature, $feature_path); } else { http_response_code(404); echo 'Page not recognised...'; exit(); } } function feature_blog($feature_path) { http_response_code(200); echo 'Showing the blog'; exit(); } function feature_forum($feature_path) { http_response_code(200); echo 'Showing the forum'; exit(); } This is of course not an ideal way to handle it, but a pretty good starting point. Modern applications also uses templates, again, a pretty good starting point , if you do not use a template engine, would be to store your HTML in heredoc, inside separate .php files: <?php $template = <<<LOADTEMPLATE <!DOCTYPE html> <html lang="en"> <head> <title>{$tpl_content['title']}</title> <link rel="stylesheet" type="text/css" href="/my_css_file.css"> </head> <body> <article> <h1>{$tpl_content['title']}</h1> {$tpl_content['content']} </article> </body> </html> LOADTEMPLATE; // Comment to preserve required "\n" character after heredoc-end delimeter on editor saves You can easily load this file from whatever location you want, and then have it filled out automatically with the contents of the $tpl_content array; just remember to define the array elements to avoid undefined notices. To output the template, and have it filled out with contents, you could do like this: function feature_blog($feature_path) { // Define template content $tpl_content['title'] = 'Hallo World'; $tpl_content['content'] = '<p>Hallo World</p>'; // Include the relevant template, require_once('templates/default.php'); http_response_code(200); echo $template; exit(); } Keep in mind, this is just an example. But you could easily use this as a base for something more mature. A decent system would also allow you to set HTTP response headers, implement caching mechanisms, and allow you to restrict HTTP request methods on a per-feature basis. But, if you used a framework or a CMS like Wordpress, then some of this should automatically be handled.
  8. You do not need a database at all. In fact, it is sometimes faster to not use a database, since it takes extra time to establish a database connection (unless it is hosted on the same server). I already tried this. The code is placed on GitHub under Apache license, maybe you can use it in your project. It only uses build-in features of PHP and gd library. Available here: https://github.com/beamtic/php-photo-gallery The project has not been updated for awhile, but still got some features planned, including a Wordpress plugin.
  9. In my experience, .htaccess (HTTP based authentication) is actually pretty bad, because the htaccess syntax is so exotic that even experienced developers sometimes struggle to figure it out. But, I often use it on client test-sites to easily prevent access and indexing in search engines. For my personal projects, I do much prefer to just redirect all requests to PHP, even for files that exist. This is because I just find it much easier to do what I need from PHP. In a purely PHP based app, you could configure your VHOST like this: RewriteEngine on RewriteRule ^.*$ index.php [L,QSA] That should basically rewrite all requests to your PHP application. The down-side is that you need to manually handle caching headers, for static files, as well as the range header (range requests) if you want to properly support streaming of video files. I am working on a file handler for this: https://github.com/beamtic/Doorkeeper/tree/master/lib/file_handler The good thing about redirecting everything is that it is much easier to secure your application since it only has a single point of entry. This is nice when using form-based authentications with cookies. Alternatively, if you still want to support some public static files, and have them delivered by your web server, you can use the following configuration: RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^.*$ / [QSA] This would still allow you to keep some private static files outside of your web-root, and then have a file handler script serve them to the user after the user has authenticated. The configuration should also work from .htaccess, but I recommend just throwing it in your VHOST config. It should also be more efficient, although that's probably insignificant in must cases.
  10. That makes sense, thanks. I am now wondering if I should use preg_replace_callback or if it is safe to use addslashes. Guess I have to read up on those.
  11. I recently fixed a bug in my own website involving preg_replace, the thing is, each time I was editing an article in the front-end, preg_replace would be called on the HTML to replace certain HTML elements. What I suspect is that preg_replace has a bug that causes it to remove certain characters from the replacement string, leading to corruption of the output. Obviously only the HTML (haystack) should be modified, and the replacement string dropped in place of the needle, without modifying it in any way. This is not what happens if the replacement string contains backslashes. I have tried to figure out what exactly is going on here, and have come up with a fix by using str_replace instead. But, I wonder if there is a solution that would allow me to keep using preg_replace? I also wonder if there are other characters that might be removed doing the replacement operation? I know that you must escape backslashes when declaring variables, but the replacement string is obtained directly from a MySQL database, and I know the data is OK. The fact that you need to escape literal backslashes in PHP scripts makes it harder to debug the problem. For example, if you just try my solution directly, without addslashes, you will be missing backslashes. I guess you either have to escape those, or load the data from a file. This is my current solution (I do not use addslashes in the live version): $html = '<div>REPLACEMENT_ID</div>'; $replacement_id = 'REPLACEMENT_ID'; $replacement = addslashes('<pre>\\\\</pre>'); // $html = preg_replace("|{$replacement_id}|", $replacement, $html); // $html = str_replace($replacement_id, $replacement, $html); $pos = strpos($html, $replacement_id); if ($pos !== false) { $html = substr_replace($html, $replacement, $pos, strlen($replacement_id)); } print_r($html); If you comment out the substr_replace test, and instead uncomment the preg_replace one, then you will get an inaccurate number of backslashes, similar to the result I got when using data directly from my database. Hope someone can help shed some light on this 😄
  12. Hallo again, it turns out I was on a completely wrong track. If the Theme is object orientated, then it may have something like this as the top of each PHP class: if ( ! class_exists( 'TravShortcodes' ) ) : If that is the case, then it will only apply the parent class if it has not already been included. This means that you should just copy the file over to the child theme folder, and then include it from your functions.php: include_once get_stylesheet_directory_uri() . 'shortcodes.php'; This way you can easily modify any aspect of the parent that you want. It is important you remember to include the file, since simply copying it is not going to be enough. Thanks. This is not solved.
  13. I am making some progress in debugging this. Of course I did not mean "filter", as I am trying to override an existing shortcode. Anyway, I managed to verify that the shortcode has been added. I noticed the parent theme is using the init hook to add shortcodes. Then I tried print_r($shortcode_tags) again after using the init hook in my child theme, with a priority of 20, and I was finally able to verify that the shortcode is loaded. I.e.: add_action('init', 'replace_parent_theme_features', 20); function replace_parent_theme_features() { global $shortcode_tags; print_r($shortcode_tags); exit(); remove_shortcode('shortcode_search_group'); add_shortcode('shortcode_search_group', 'child_shortcode_search_group'); } Apparently the priority is also important. I have a feeling I am getting close, but I still can not get remove_shortcode to work for some reason.
  14. Hallo PHP geeks I need to override a parent-theme shortcode in Travelo from a child theme; I can edit the parent theme files just fine, but when I try to override the shortcode function from the child theme, nothing seems to happen, regardless of which hook I use to do so. I can tell that my filter function (add_new_child_shortcodes) is called, because when I echo directly from the filter, I do get my output. This fact indicates that the remove_shortcode function is called at the wrong time, and the parent function is never removed. From experimenting I know that the child-theme functions.php file is called before the parent, but according to users on stackoverflow, you should still be able to override the shortcode by using the right hook. I already tried various proposed hooks from stackoverflow and other websites, but none of them worked in my case. This includes the following hooks: after_setup_theme init wp_loaded Also, I can not seem to figure out how to get a list of the loaded shortcodes, to see if the shortcode I am trying to override has actually been loaded. I tried print_r($shortcode_tags) within my filter, but this is empty when called from within a function, and I am also not sure that is the right variable. It does output a bunch of stuff when used outside though, but obviously not the relevant stuff - presumably because it has not yet been loaded. This is my code so far: add_action('after_setup_theme', 'add_new_child_shortcodes'); function add_new_child_shortcodes() { remove_shortcode('shortcode_search_group'); add_shortcode('shortcode_search_group', 'child_shortcode_search_group'); } function child_shortcode_search_group() { echo 'hallo';exit(); } I specifically need to replace the shortcode_search_group shortcode, because I need to make modifications to the search HTML. If it is of any help, when I examine the relevant file in the parent theme (inc/functions/shortcodes.php), I can tell that shortcodes themselves are added with the following code: function add_shortcodes() { foreach ( $this->shortcodes as $shortcode ) { $function_name = 'shortcode_' . $shortcode ; add_shortcode( $shortcode, array( $this, $function_name ) ); } // to avoid nested shortcode issue for block for ( $i = 1; $i < 10; $i++ ) { add_shortcode( 'block' . $i, array( $this,'shortcode_block' ) ); } add_shortcode( 'box', array( $this,'shortcode_block' ) ); } The $this->shortcodes variable is an array of shortcode names, corresponding with the method names in the class. Help will be much appreciated!
  15. On second look, this pre-configured box is not usable to me, since I need to learn to use Bitnami as well, and the paths are also non-standard, so I have no idea where to find the files I need to edit. An old fashioned LAMP install is just so much easier to work with for me. I wasted a lot of time trying to just get it to work with a domain name instead of the bare IP address. Guess that settles my doubts.. Will go for the latest version, with a manually installed Elasticsearch. Strange that I find this much easier than all this auto-installer stuff...
×
×
  • 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.