megacolorboy

Abdush Shakoor's Weblog

Writings, experiments & ideas.

Prevent loading a webpage from Back-Forward cache

I'm working on an eCommerce project and I encountered a really weird problem, whenever I saved items into my cart and proceed to the checkout page and then go back to previous page, my cart isn't updated until I refresh the page.

Honestly, I thought this was a bug until I came around to learn about Back-Forward Caching a.k.a bfcache, which allows the user to navigate between pages faster. That's a good thing, though!

But that didn't help resolve my issue, so I thought of going around with a tiny hack:

window.onpageshow = function(event) {
    if (event.persisted) {
        window.location.reload() 
    }
};

The code above will look any persistence of the onpageshow event. Initially, it's set to false and if the page is loaded from bfcache, it'll set to true.

I wouldn't really consider this as a solution as it only worked on Safari instead of Chrome or Firefox.

But hey, it gets the job done! 😂

Refresh browser window without query parameters

If you want to reload the current page in your browser without any query string or parameters, here's how you can do it:

window.location = window.location.pathname;

By doing so, it'll preserve the HTTP/HTTPS protocols of the URL and also remove the fragments that start with a #.

If you want to preserve the fragments, you can try this:

var reloadURL = window.location.pathname;
var fragments = (window.location.part === undefined) ? "" : "#" + window.location.part;
window.location = reloadURL + fragments;

Hope you found this useful!

Input sanitization with PHP

This can come in handy when you're dealing with user inputs during a form submission and in most cases, your web application will be using a database query to store the data.

Using filter_var()

This method uses a number of flags to validate and sanitize a string. Here are some examples I have tried:

Removing special characters

Want to strip out all tags and certain characters? Try this:

<?php
$str = "<h1>Hello World</h1>";
$filtered = filter_var($str, FILTER_SANITIZE_STRING);
echo $filtered;
?>

Integer validation

You can check if the input is an integer and if it's a value between 1 and 20:

<?php
$x = 10;
$min = 1;
$max = 20;
$options = [
    "min_range" => $min,
    "max_range" => $max
];

if(!filter_var($x, FILTER_VALIDATE_INT, $options)){
    echo "This input is invalid.";
}
else {
    echo "This input is valid.";
}
?>

URL validation

Want to check if the input is a valid URL? Try this out:

<?php
// Make sure the URL is sanitized
$url = filter_var("https://www.google.com", FILTER_SANITIZE_URL);
if(filter_var($url, FILTER_VALIDATE_URL)){
    echo "This URL is valid.";
}
else {
    echo "This URL is invalid.";
}
?>

Using these in-built features makes it easier for PHP developers to process data from external sources in a safer manner and also adds an extra layer of protection to your web application.

Read more about this method in PHP's official documentation.

Extract unique characters from a string

I thought of getting back into competitive programming again and started practicing my python coding-chops on Codewars.

Here's a neat trick on how to extract unique characters from a string:

from collections import OrderedDict

word = "HelloWorld"
uniq = ''.join(OrderedDict.fromkeys(word).keys())

print(uniq) # prints HeloWrd

Using OrderedDict allows you to preserve the order in which the keys are inserted as a normal dict doesn't track the order.

Hope you found this useful!

Increase execution time in PHP

Ever process a file that's larger than 2GB and got an error that said something like this:

Maximum execution time of 30 seconds exceeded

Though, PHP doesn't have an efficient way of processing files of large sizes, you can prevent your web application from timing out by adding this to your code:

<?php
// 300 seconds == 5 minutes
ini_set('max_execution_time', 300);
?>

Hopefully, some day, this might come in handy for you! 😜

Increase memory limit in PHP

Last month, I was building a web application that collected a lot of data via form submissions. I wrote a method to export attachments and form data by zipping them all together.

It worked for a smaller archives but as the records grew larger, I got a fatal error which said that I've exhausted the PHP's memory limit.

So, I found an easy way to increase the memory limit to 1024MB (1GB) like this:

<?php
ini_set('memory_limit', '1024M');
?>

Before you write this stub in your script, make sure you have enough resources in your system or else, it'll go splat!

Hello, Go!

After reading a lot of articles about using Go as a programming language to write high-performing concurrent web applications and services yet maintain a clean codebase, I thought of starting to learn it to see what's it about and so far, it's been great!

This mini-tutorial will show you how to install Go on your system and write a simple "Hello, World" program.

Note: This tutorial will go through installing Go on Linux.

Install Go

Make sure you have the latest updates and upgrades on your Linux system before installing Go.

You need to download the binary file from their official package. Find the version that suits your OS and architecture.

cd /tmp
wget https://golang.org/dl/go1.14.6.linux-amd64.tar.gz

Extract the downloaded archive and install it in the /usr/local directory (as per the standards):

sudo tar -xvf go1.14.6.linux-amd64.tar.gz
sudo mv go /usr/local

Set up environment

Now, we need to set up three variables:

  • GOROOT: Location of where your Go package is installed.
  • GOPATH: Location of your work directory.'
  • PATH: Tells bash on where to look for programs that are being executed.

Open up your .bashrc file and add these lines at the end of the file:

export GOROOT=/usr/local/go
export GOPATH=$HOME/go
export PATH=$GOPATH/bin:$GOROOT/bin:$PATH

Save your .bashrc file and update the current shell session:

source ~/.bashrc

Verify your installation

Type the following command to ensure that your Go installation is successful:

go version go1.14.6 linux/amd64

Hello, world!

As per traditions, whenever you learn a programming language, you start off with a "Hello, world!" program, so here it is:

package main

import "fmt"

func main() {
    fmt.Printf("Hello, world!\n")
} 

Conclusion

I just started learning it today and at first, you might have the tendency to write code in Go the same way you write in any other language but beware, it doesn't work that way. It forces you to write good code including the way it formats the code using the gofmt tool.

Lots of cool things are coming!

Stay tuned for more.

How to delete files inside a zip file?

Ever compressed your project directory but forgot to delete that useless file or folder and turns out the compresed file is larger than it's supposed to be?

Here's a quick solution you can try:

If you want to delete a file inside a .zip file, try this:

zip --delete file.zip "file.ext"

And if you want to delete a folder, try this:

zip --delete file.zip "folder/*"

Hope this helps you out!