Category: Coding & Scripting

WordPress: how to remove the ‘link rel=shortlink’ tag from your site

By default, WordPress adds <link rel="shortlink"> meta tag to the <head> of a website and uses the short url like https://mixable.blog/?p=12345 for this. When you already use nice slugs as permalink structure, such a tag is not necessary, because you already have unique urls.

To remove the shortlink tag, you can use an additional plugin or simply add some code to your themes functions.php:

PHP
add_filter('after_setup_theme', 'remove_redundant_shortlink');

function remove_redundant_shortlink() {
    // Remove HTML meta tag
    // <link rel='shortlink' href='http://mixable.blog/?p=12345' />
    remove_action('wp_head', 'wp_shortlink_wp_head', 10);

    // Remove HTTP header
    // Link: <https://mixable.blog/?p=12345>; rel=shortlink
    remove_action( 'template_redirect', 'wp_shortlink_header', 11);
}

This code will also remove a http header from each response.

Foto von Markus Winkler auf Unsplash

 

How to delete a single element from an array in PHP

php logo on purple background

There are multiple ways to remove an element from an array in PHP. The simplest one is the method unset().

unset()

The method unset() can be used to remove a single element of the array:

PHP
$myArray = ['apple', 'banana', 'cherry', 'date'];
unset($myArray[1]); // Remove the element at index 1 (banana)
$myArray = array_values($myArray); // Re-index the array if you want to remove the gap

print_r($myArray);

The output of print_r() is:

Array
(
    [0] => 'apple'
    [1] => 'cherry'
    [2] => 'date'
)

array_splice()

This function can be used to remove a portion of an array and replace it with something else. If you want to remove a single element, you can specify a length of 1:

PHP
$myArray = ['apple', 'banana', 'cherry', 'date'];
array_splice($myArray, 1, 1); // Remove 1 element starting from index 1

print_r($myArray);

array_diff()

You can use this function to create a new array with all the elements of the first array that are not in the other arrays:

PHP
$myArray = ['apple', 'banana', 'cherry', 'date'];
$elementToRemove = 'banana';
$myArray = array_diff($myArray, [$elementToRemove]);

print_r($myArray);

array_filter()

This function can be used with a callback function to filter elements from an array:

PHP
$myArray = ['apple', 'banana', 'cherry', 'date'];
$elementToRemove = 'banana';
$myArray = array_filter($myArray, function($value) use ($elementToRemove) {
   return $value !== $elementToRemove;
});

print_r($myArray);

unset() with array_search()

You can combine unset() with array_search() to remove an element based on its value:

PHP
$myArray = ['apple', 'banana', 'cherry', 'date'];
$elementToRemove = 'banana';
$index = array_search($elementToRemove, $myArray);
if ($index !== false) {
   unset($myArray[$index]);
}

print_r($myArray);

 

PHP fatal error: Uncaught TypeError: ftp_nlist(): Argument #1 ($ftp) must be of type FTP\Connection, null given

broken plate on the floor

This error happened after moving a WordPress installation to another server. The new server had a different linux distribution and a newer PHP version. In my case, the environment changed from PHP 7.4 to PHP 8.2.

I already added some missing PHP extensions and updated the configuration to match the old one, but the error still exists.

At the end, this could be solved by adding the following code in wp-config.php file:

if ( ! defined( 'FS_METHOD' ) ) define( 'FS_METHOD', 'direct' );

Source

Foto von CHUTTERSNAP auf Unsplash

JavaScript: how to check if a string variable is an integer value

JS on yellow background

One way to check if a variable is of type integer, Number.isInteger() can be used:

JavaScript
Number.isInteger(22); // true
Number.isInteger(22.2); // false
Number.isInteger('22'); // false

But this solution has the disadvantage, that a string with integer value like '22' will result in false.

To address this case, another solution is required:

JavaScript
function isInteger(data) {
  return +data === parseInt(data);
}

isInteger(22); // true
isInteger(22.2); // false
isInteger('22'); // true

This will result in true for integer 22 as well as a string '22'.

How to decode the exception backtrace of an ESP32

ESP32

When the execution of code on an ESP32 throws an exception, the output might look like this:

Guru Meditation Error: Core  1 panic'ed (LoadProhibited). Exception was unhandled.??
??
Core  1 register dump:??
PC      : 0x420383b2  PS      : 0x00060c30  A0      : 0x820059ec  A1      : 0x3fcebd70  ??
A2      : 0x3fc97708  A3      : 0x3fcebdcb  A4      : 0x00000001  A5      : 0x0000ff00  ??
A6      : 0x00ff0000  A7      : 0xff000000  A8      : 0x3fcecf5b  A9      : 0x0000723f  ??
A10     : 0x3fcecf5b  A11     : 0x00000001  A12     : 0x00000001  A13     : 0x3fcf06b4  ??
A14     : 0x00000001  A15     : 0x00000003  SAR     : 0x00000017  EXCCAUSE: 0x0000001c  ??
EXCVADDR: 0x0000728b  LBEG    : 0x40056f08  LEND    : 0x40056f12  LCOUNT  : 0x00000000  ??
??
??
Backtrace: 0x420383af:0x3fcebd70 0x420059e9:0x3fcebd90 0x42004e26:0x3fcebdb0 0x420035a2:0x3fcebe00 0x42003595:0x3fcebe20 0x4200542c:0x3fcebe40 0x42008891:0x3fcebe60??
...

The Espressif tools contain a binary called xtensa-esp32-elf-addr2line which will decode the backtrace addresses and return details about the source files, lines and function names, etc.

To run the tool, call:

/home/user/.espressif/tools/xtensa-esp32-elf/esp-2020r3-8.4.0/xtensa-esp32-elf/bin/xtensa-esp32-elf-addr2line -fe /path/to/build/<ELFFILE>.elf <BACKTRACE>

In the command above, simply…

  • replace the path to the xtensa-esp32-elf-addr2line binary
    (in my case the binary is located in the users home directory in the folder .espressif)
  • replace the path to your elf file
    (normally, the elf file is located in the build path and generated during compilation)
  • replace the backtrace output string
    (it’s the string that is shown after Backtrace: )

FutureBuilder: handle multiple futures in a single widget

moving staircase at night

By default, FutureBuilder provides a single future parameter that handles a single Future. For multiple Futures, we can combine them into a single Future using Future.wait. Here’s a step-by-step guide on how to do this:

Create a list of Future objects

Create a list of Future objects that represent the asynchronous operations you want to perform. For example, let’s assume you have two futures:

Future<String> fetchFirstData() async {
  // Simulate a network request or other asynchronous operation.
  await Future.delayed(Duration(seconds: 2));
  return "First Data";
}

Future<int> fetchSecondData() async {
  // Simulate another asynchronous operation.
  await Future.delayed(Duration(seconds: 3));
  return 42;
}

Combine the futures using Future.wait

Use the Future.wait method to combine the individual futures into a single future. Future.wait takes a list of futures as an argument and returns a single future that completes when all the input futures have completed.

Future<void> fetchData() async {
  await Future.wait([fetchFirstData(), fetchSecondData()]);
}

Create a FutureBuilder widget

Now, use the FutureBuilder widget to handle the combined future and display the results in your widget tree. You can place this widget in your build method.

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: fetchData(),
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.done) {
          // Use the results from the futures here.
          if (snapshot.hasError) {
            return Text("Error: ${snapshot.error}");
          } else {
            return Column(
              children: [
                Text("First Data: ${snapshot.data[0]}"),
                Text("Second Data: ${snapshot.data[1]}"),
              ],
            );
          }
        } else {
          // While waiting for the futures to complete, you can show a loading indicator or placeholder.
          return CircularProgressIndicator();
        }
      },
    );
  }
}

In the code above, we use the snapshot to check the connectionState. When the connectionState is ConnectionState.done, it means that both futures have completed. You can access the results using snapshot.data.

Remember to replace the fetchFirstData and fetchSecondData functions with your actual asynchronous operations. This example demonstrates how to use FutureBuilder to handle multiple futures in a single widget in Flutter.

Foto von Tomasz Frankowski auf Unsplash

mysqldump: how to use a specific port

wine barrels in a wine cellar

To use a specific port with the mysqldump command, you can provide the --port (or -P) option followed by the port number you want to use. The --port option specifies the TCP/IP port number to use when connecting to the MySQL server.

When using -P remember to use an uppercase P, because the lowercase option -p refers to the password.

Here’s the general syntax of using mysqldump with a specific port:

Bash
mysqldump --port=PORT_NUMBER -u USERNAME -p DATABASE_NAME > dump.sql

Replace the following placeholders:

  • PORT_NUMBER: The specific port number you want to use (e.g., 3306).
  • USERNAME: Your MySQL username.
  • DATABASE_NAME: The name of the database you want to dump.
  • dump.sql: The name of the file where you want to save the database dump.

After executing this command, you’ll be prompted to enter your MySQL password. Once you provide the correct password, the mysqldump command will connect to the MySQL server using the specified port and create a dump of the specified database.

Foto von André Carvalho auf Unsplash

JavaScript: the differences between escape(), encodeURI(), and encodeURIComponent()

minimized programming code

In JavaScript, escape(), encodeURI(), and encodeURIComponent() are three functions used to encode strings for different purposes. Each function serves a distinct purpose, and it’s essential to understand their differences:

escape()

The escape() function is used to encode a string so that it can be safely included in a URL query string. It encodes special characters, except for alphanumeric characters and the following set of symbols: @*_+-./. The main drawback of escape() is that it does not encode all characters, and it’s considered deprecated in favor of encodeURIComponent().

Example:

const originalString = "Hello, World!";
const encodedString = escape(originalString);
console.log(encodedString); // "Hello%2C%20World%21"

encodeURI()

The encodeURI() function is used to encode a complete URI (Uniform Resource Identifier) but leaves the special characters used in the query string (?, &, =, etc.) untouched. It is primarily used to encode the main part of a URL, such as the protocol, domain, and path.

Example:

const originalURI = "https://www.example.com/my page.html?name=John Doe";
const encodedURI = encodeURI(originalURI);
console.log(encodedURI); // "https://www.example.com/my%20page.html?name=John%20Doe"

encodeURIComponent()

The encodeURIComponent() function is used to encode a component of a URI, such as a query parameter, fragment identifier, or any part that needs to be included in the query string. Unlike encodeURI(), this function encodes all special characters to ensure they are safely passed as parameters in a URL.

Example:

const originalParameter = "John Doe";
const encodedParameter = encodeURIComponent(originalParameter);
console.log(encodedParameter); // "John%20Doe"

In summary

Use escape() for encoding a string to be safely included in a query string, but it’s deprecated and not recommended for general use.

Use encodeURI() for encoding a complete URI (protocol, domain, path) but not the query string parameters.

Use encodeURIComponent() for encoding individual components (e.g., query parameters) of a URI to ensure all special characters are encoded properly. This is the most commonly used encoding function for URLs.

Foto von Markus Spiske auf Unsplash