Recent Posts

Security risks and vulnerabilities associated with PHP’s mysql_ functions

 Here are some considerations about mysql extension:

The mysql_* extension is completely obsolete and has been officially removed from PHP since version 7.0 (2015). Continuing to use it requires running an end-of-life version of PHP that no longer receives security patches, leaving your server vulnerable to exploits. Furthermore, it lacks modern database features such as:

  • Security: No support for prepared statements or parameterized queries (the standard for preventing SQL injection).

  • Performance: Missing asynchronous, non-blocking query capabilities.

  • Functionality: No support for transactions, stored procedures, or multiple statements.

  • Compatibility: It cannot handle the modern password authentication used in MySQL 5.6+ and lacks all features introduced in MySQL 5.1 or later.

 Here is a table of some considerations to have in mind:

FeatureStatus in mysql_*Modern Alternative (PDO/MySQLi)
Prepared Statements❌ Not Supported✅ Standard (Prevents SQLi)
Transactions❌ Not Supported✅ Full Support
Asynchronous Queries❌ Not Supported✅ Supported
Stored Procedures❌ Not Supported✅ Full Support
Modern Password Auth❌ Incompatible✅ Native Support


A Comprehensive Guide to Unresolved External Symbols in C++

 Consider you have this piece of code:

 

 

During the compilation of b.cpp, the compiler treats the get() symbol as an external reference, deferring its resolution. The linker is subsequently responsible for locating the symbol's definition and unifying the object files generated from a.cpp and b.cpp.

If a.cpp didn't define get, you would get a linker error saying "undefined reference" or "unresolved external symbol".

 In accordance with C++ Standard terminology, the compilation process is partitioned into various translation phases. The concluding phase is the one that directly applies here:

All external entity references are resolved. Library components are linked to satisfy external references to entities not defined in the current translation. All such translator output is collected into a program image which contains information needed for execution in its execution environment. 

 These errors surface during the final stage of the build process, known as linking. At this point, the compiler has already turned your individual source files into object files or libraries; the linker’s job is to "stitch" them together so they can function as a single program.

 Linking in the Wild: Visual Studio & Beyond

In Microsoft Visual Studio, projects typically produce .lib files. Think of these as catalogs containing two specific lists:

  • Exported symbols: The functions or variables this library provides to others.

  • Imported symbols: The "missing pieces" this library needs from elsewhere to work.

The linker looks at these tables and matches the imports of one file to the exports of another. While the terminology might change slightly, this same fundamental "handshake" happens across almost all compilers and platforms.

 Common Linker Error Messages

If the linker can't find a definition for one of those imported symbols, it will throw an error. Here is what that looks like depending on your environment: 

EnvironmentTypical Error Codes / Messages
MS Visual Studioerror LNK2001, error LNK2019, error LNK1120
GCC / Clangundefined reference to 'symbolName'

Essentially, the compiler is saying: "I know you want to use this function, but I can't find the actual code for it anywhere." 


struct X
{
   virtual void foo();
};
struct Y : X
{
   void foo() {}
};
struct A
{
   virtual ~A() = 0;
};
struct B: A
{
   virtual ~B(){}
};
extern int x;
void foo();
int main()
{
   x = 0;
   foo();
   Y y;
   B b;
}


will generate the following errors with GCC:


1>test2.obj : error LNK2001: unresolved external symbol "void __cdecl foo(void)" (?foo@@YAXXZ)
1>test2.obj : error LNK2001: unresolved external symbol "int x" (?x@@3HA)
1>test2.obj : error LNK2001: unresolved external symbol "public: virtual __thiscall A::~A(void)" (??1A@@UAE@XZ)
1>test2.obj : error LNK2001: unresolved external symbol "public: virtual void __thiscall X::foo(void)" (?foo@X@@UAEXXZ)
1>...\test2.exe : fatal error LNK1120: 4 unresolved externals

Matching HTML Opening Tags with Regex while Excluding Self-Closing XHTML Tags

 I need to match all of these opening tags:


<p>
<a href="foo">
 

But not self-closing tags:


<br />
<hr class="foo" />
 
 

HTML is a non-regular language, meaning its nested and recursive structure cannot be reliably parsed using Regular Expressions (Regex). Regex is designed for regular languages and lacks the memory and logic required to handle the complexities of HTML tag balancing, attributes, and comments. Attempting to use Regex for this task leads to brittle code, significant security vulnerabilities, and logic that fails on edge cases. Always use a dedicated DOM parser library instead.

I know it’s tempting to grab a Regex for a quick HTML fix, but trust me: don't do it. HTML is way too complex for Regex to understand. Even 'advanced' expressions can't handle the way HTML tags nest inside each other. If you try, you’ll end up with a mess of 'spaghetti code' that breaks the moment the input changes slightly. Save yourself the headache and use a tool built for the job, like a proper HTML parser.

Trying to parse HTML with Regex is the fastest way to lose your mind. You aren't just writing a bad pattern; you're inviting chaos into your codebase. HTML is a recursive labyrinth that Regex wasn't built to navigate. Every time you try to 'hack' a solution with a regular expression, a bug is born that will eventually crash your app and ruin your weekend. For the sake of your sanity and your security, put down the Regex and pick up a DOM library. The abyss is real, and it doesn't want your code.

A Guide to Troubleshooting NullPointerExceptions

In the world of Java, variables aren't all created equal. Understanding the "Billion Dollar Mistake"—the **NullPointerException (NPE)**—requires first understanding how Java stores data.

---

1. The Java Divide: Primitives vs. References

Java categorizes variables into two distinct camps:

Primitives (The "Values")

These variables hold actual data. When you change a primitive, you are manipulating the data directly.

* **Convention:** Always lowercase (`int`, `double`, `boolean`, `char`). * **Behavior:** They cannot be `null`. They must be initialized before use, or the compiler will stop you.

References (The "Pointers")

These variables don't hold the object itself; they hold the **memory address** (a pointer) where the object lives. * **Convention:** Usually start with an uppercase letter
(`String`, `Integer`, `Object`).
* **The "Dereference":** To interact with the object, you must "dereference" the variable using the dot operator (`.`) for methods/fields or brackets (`[]`) for arrays. ---

2. The Anatomy of a `NullPointerException`

An NPE occurs when you try to dereference a variable that is currently pointing to **nothing** (`null`).

Declaration vs. Instantiation

Consider this common pitfall:

```java
Integer num;             // Declaration: num is null (it points to nothing)
num = new Integer(10);   // Instantiation: num now points to a memory address
```

If you try to call `num.toString()` before the second line, the program crashes. You are essentially trying to follow a map that has no destination.

The Method Parameter Trap

Often, an NPE isn't your fault directly, but rather the fault of the data passed into your method:

```java
public void process(SomeObject obj) {
    obj.doWork(); // If 'obj' is passed as null, this line throws an NPE.
}
```

---

3. Defensive Programming: Strategies for Success

The "Fail Fast" Approach

Instead of letting a `null` value sneak deep into your logic, catch it immediately at the "gate" of your method.

```java
public void process(SomeObject obj) {
    // Throws an NPE immediately with a clear message
    java.util.Objects.requireNonNull(obj, "The input object 'obj' cannot be null.");
    
    obj.doWork(); 
}
```

The "Safe Handling" Approach

If `null` is a valid, expected state, use conditional logic to handle it gracefully.

```java
/**
 * @param obj Optional object. If null, the method performs a default action.
 */
public void process(SomeObject obj) {
    if (obj == null) {
        // Handle the null case (e.g., log it or return early)
    } else {
        obj.doWork();
    }
}
```

---

4. Modern Diagnostics (Java 14+)

Historically, NPE error messages were frustratingly vague. However, **Java 14** introduced "Helpful NullPointerExceptions" which tell you exactly what was null:

> `Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.util.List.size()" because "list" is null`

---

5. The "NPE Hall of Fame"

According to the **Java Language Specification (JLS)**, an NPE is triggered in these specific scenarios:
  • Instance Access: Accessing a field or calling a method of a `null` reference (note: `static` members are safe!).
  • Throwing Null: Executing `throw null;`.
  • Array Access: Attempting to get the length or access an index of a `null` array.
  • Synchronization: Using `synchronized(null)`.
  • Unboxing: Converting a boxed type (like `Integer`) that is `null` into a primitive (`int`).
  • Enhanced For-Loop: Attempting to iterate over a `null` collection or array.
  • Switch Statements: Passing `null` into a `switch` expression.
  • Method References: Evaluating a method reference (e.g., `obj::method`) where `obj` is null.

Note on Statics: Interestingly, someInstance.someStaticMethod() will not throw an NPE even if someInstance is null, because the compiler resolves static methods via the class type, not the specific instance. However, using that same instance in a method reference (someInstance::someStaticMethod) will throw an NPE. Java is quirky like that! 

iOS: Encode base64 on iphone SDK

If you want to encode base64 on iPhone SDK you can try the next code snippet:  


(NSString )decodeBase64:(NSString )input { 
NSString alphabet = @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-"; 
NSString decoded = @""; 
NSString *encoded = [input stringByPaddingToLength:(ceil([input length] / 4) * 4) withString:@"A" startingAtIndex:0];

int i; char a, b, c, d; UInt32 z;

for(i = 0; i < [encoded length]; i += 4) { a = [alphabet rangeOfString:[encoded substringWithRange:NSMakeRange(i + 0, 1)]].location; b = [alphabet rangeOfString:[encoded substringWithRange:NSMakeRange(i + 1, 1)]].location; c = [alphabet rangeOfString:[encoded substringWithRange:NSMakeRange(i + 2, 1)]].location; d = [alphabet rangeOfString:[encoded substringWithRange:NSMakeRange(i + 3, 1)]].location;

z = ((UInt32)a << 26) + ((UInt32)b << 20) + ((UInt32)c << 14) + ((UInt32)d << 8); decoded = [decoded stringByAppendingString:[NSString stringWithCString:(char *)&z]]; }

return decoded; }

The following code converts an NS Data Object to a base64 string:

(NSString )base64Encoding { NSTask task = [NSTask alloc] init] autorelease]; NSPipe inPipe = [NSPipe pipe], outPipe = [NSPipe pipe]; NSFileHandle inHandle = [inPipe fileHandleForWriting], outHandle = [outPipe fileHandleForReading]; NSData *outData = nil;

[task setLaunchPath:@"/usr/bin/openssl"]; [task setArguments:[NSArray arrayWithObjects:@"base64", @"-e", nil; [task setStandardInput:inPipe]; [task setStandardOutput:outPipe]; [task setStandardError:outPipe];

[task launch];

[inHandle writeData:self]; [inHandle closeFile];

[task waitUntilExit];

outData = [outHandle readDataToEndOfFile]; if (outData) { NSString *base64 = [NSString alloc] initWithData:outData encoding:NSUTF8StringEncoding] autorelease]; if (base64) return base64; }

return nil; }

JavaScript closure inside loop example

When we want to bind a variable within an anonymous function unchanging value outside of the function, you can implement the following javascript code:

var funcs = [];

function createfunc(i) {
    return function() { console.log("My value: " + i); };
}

for (var i = 0; i < 3; i++) {
    funcs[i] = createfunc(i);
}

for (var j = 0; j < 3; j++) {
    funcs[j]();                        // and now let's run each one to see
}

Since there is no block scope in JavaScript - only function scope - by wrapping the function creation in a new function, you ensure that the value of "i" remains as you intended.

With the relatively widespread availability of the Array.prototype.forEach function (in 2015), it's worth noting that in those situations involving iteration primarily over an array of values, .forEach() provides a clean, natural way to get a distinct closure for every iteration. That is, assuming you've got some sort of array containing values (DOM references, objects, whatever), and the problem arises of setting up callbacks specific to each element, you can do this:

var someArray = [ /* whatever */ ];
// ...
someArray.forEach(function(arrayElement) {
  // ... code code code for this one element
  someAsynchronousFunction(arrayElement, function() {
    arrayElement.doSomething();
  });
});

The idea is that each invocation of the callback function used with the .forEach loop will be its own closure. The parameter passed in to that handler is the array element specific to that particular step of the iteration. If it's used in an asynchronous callback, it won't collide with any of the other callbacks established at other steps of the iteration.

If you happen to be working in jQuery, the $.each() function gives you a similar capability.

ECMAScript 6 (ES6), the newest version of JavaScript, is now starting to be implemented in many evergreen browsers and backend systems. There are also transpilers like Babel that will convert ES6 to ES5 to allow usage of new features on older systems.

ES6 introduces newletandconstkeywords that are scoped differently than var-based variables. For example, in a loop with a let-based index, each iteration through the loop will have a new value of i where each value is scoped inside the loop, so your code would work as you expect. There are many resources, but I'd recommend 2ality's block-scoping post as a great source of information.

for (let i = 0; i < 3; i++) {
    funcs[i] = function() {
        console.log("My value: " + i);
    };
}

Javascript: How to return response from asynchronous ajax call

The next piece of code tries to return the response fron an ajax asynchronous call but with this we can only get undefined values:


function foo() {
    var result;

    $.ajax({
        url: '...',
        success: function(response) {
            result = response;
            // return response; // <- tried that one as well
        }
    });

    return result;
}

var result = foo(); // always ends up being `undefined`.

The explanation of this ajax asynchronous methods


The A in AJAX stands for asynchronous. That means sending the request (or rather receiving the response) is taken out of the normal execution flow. In your example, $.ajax returns immediately and the next statement, return result;, is executed before the function you passed as success callback was even called.

Here is an analogy which hopefully makes the difference between synchronous and asynchronous flow clearer:

Synchronous


Imagine you make a phone call to a friend and ask him to look something up for you. Although it might take a while, you wait on the phone and stare into space, until your friend gives you the answer you needed.

The same is happening when you make a function call containing "normal" code:

function findItem() {
    var item;
    while(item_not_found) {
        // search
    }
    return item;
}

var item = findItem();
// do something with item
doSomethingElse();
Even though findItem might take a long time to execute, any code coming after var item = findItem(); has to wait until the function returns the result.

Asynchronous

You call your friend again for the same reason. But this time you tell him that you are in a hurry and he should call you back on your mobile phone. You hang up, leave the house and do whatever you planned to do. Once your friend calls you back, you are dealing with the information he gave to you.

That's exactly what's happening when you do an AJAX request.

findItem(function(item) {
    // do something with item
});
doSomethingElse();
Instead of waiting for the response, the execution continues immediately and the statement after the AJAX call is executed. To get the response eventually, you provide a function to be called once the response was received, a callback (notice something? call back ?). Any statement coming after that call is executed before the callback is called.

Solution(s)


Embrace the asynchronous nature of JavaScript! While certain asynchronous operations provide synchronous counterparts (so does "Ajax"), it's generally discouraged to use them, especially in a browser context.

Why is it bad do you ask?


JavaScript runs in the UI thread of the browser and any long running process will lock the UI, making it unresponsive. Additionally, there is an upper limit on the execution time for JavaScript and the browser will ask the user whether to continue the execution or not. All of this is really bad user experience. The user won't be able to tell whether everything is working fine or not. Furthermore the effect will be worse for users with a slow connection.

Restructure code


Let functions accept callbacks

The better approach is to organize your code properly around callbacks. In the example in the question, you can make foo accept a callback and use it as success callback. So this

var result = foo();
// code that depends on 'result'
becomes:

foo(function(result) {
    // code that depends on 'result'
});
Here we pass a function as argument to foo. You can pass any function reference, for example:

function myCallback(result) {
    // code that depends on 'result'
}

foo(myCallback);
foo itself is defined as follows:

function foo(callback) {
    $.ajax({
        // ...
        success: callback
    });
}
callback will refer to the function we pass to foo when we call it and we simply pass it on to success. I.e. once the AJAX request is successful, $.ajax will call callback and pass the response to the callback (which can be referred to with result, since this is how we defined the callback).

You can also process the response before passing it to the callback:

function foo(callback) {
    $.ajax({
        // ...
        success: function(response) {
            // e.g. filter the response
            callback(filtered_response);
        }
    });
}
It's easier to write code using callbacks than it seems. After all, JavaScript in the browser is heavily event driven (DOM events). Receiving the AJAX response is nothing else but an event.
Difficulties could arise when you have to work with third party code, but most problems can be solved by just thinking through the application flow.

Use promises


The Promise API is a new feature of ECMAScript 6, but it has good browser support already. There are also many libraries which implement the standard Promises API and provide additional methods to ease the use and composition of asynchronous functions (e.g. bluebird).

Promises are containers for future values. When the promise receives the value (it is resolved) or when it is cancelled (rejected), it notifies all of its "listeners" who want to access this value.

The advantage over plain callbacks is that they allow you do decouple your code and they are easier to compose.

Here is a simple example of using a promise:

function delay() {
  // `delay` returns a promise
  return new Promise(function(resolve, reject) {
    // only `delay` is able to resolve or reject the promise
    setTimeout(function() {
      resolve(42); // after 3s, resolve the promise with value 42
    }, 3000);
  });
}

delay().then(function(v) { // `delay` returns a promise
  console.log(v); // log the value once it is resolved
}).catch(function(v) {
  // or do something else if it is rejected 
  // (would not happen in this example, since `reject` is not called
});
Applied to our Ajax call we could use promises like this:

function ajax(url) {
  return new Promise(function(resolve, reject) {
    var xhr = new XMLHttpRequest();
    xhr.onload = function() {
      resolve(this.responseText);
    };
    xhr.onerror = reject;
    xhr.open('GET', url);
    xhr.send();
  });
}

ajax("/echo/json").then(function(result) {
  // code depending on result
}).catch(function() {
  // an error occurred
});
Describing all the advantages that promises offer is beyond the scope of this answer, but if you write new code, you should seriously consider them. They provide a great abstraction and separation of your code.

More information about promises: HTML5 rocks - JavaScript Promises

jQuery: Use deferred objects


Deferred objects are jQuery's custom implementation of promises (before the Promise API was standardized). They behave almost like promises, but expose a slightly different API.

Every AJAX method of jQuery already returns a "deferred object" (actually a promise of a deferred object) which you can just return from your function:

function ajax() {
    return $.ajax(...);
}

ajax().done(function(result) {
    // code depending on result
}).fail(function() {
    // an error occurred
});
Promise gotchas

Keep in mind that promises and deferred objects are just containers for a future value, they are not the value itself. For example suppose you had the following:

function checkPassword() {
    return $.ajax({
        url: '/password',
        data: {
            username: $('#username').val()
            password: $('#password').val()
        },
        type: 'POST',
        dataType: 'json'
    });
}

if (checkPassword()) {
    // Tell the user they're logged in
}
This code misunderstands the above asynchrony issues. Specifically, $.ajax() doesn't freeze the code while it checks the '/password' page on your server - it sends a request to the server and while it waits, immediately returns a jQuery Ajax Deferred object, not the response from the server. That means the if statement is going to always get this Deferred object, treat it as true, and proceed as though the user is logged in. Not good.

But the fix is easy:

checkPassword()
.done(function(r) {
    if (r) {
        // Tell the user they're logged in
    } else {
        // Tell the user their password was bad
    }
})
.fail(function(x) {
    // Tell the user something bad happened
});
So now we're still calling the '/password' page on the server, but our code now properly handles the wait time for the server to respond. The $.ajax() call still returns immediately with a jQuery Ajax Deferred object, but we use it to attach event listeners to .done() and .fail(). In the .done() call, where the server responded with a normal response (HTTP 200), we check the object returned by the server. In this example the server is just returning true if the login was successful, false if not, so if (r) is checking for true/false.

In the .fail() handler we're dealing with something going wrong - for example if the user lost their internet connection while they were typing in their username and password, or if your server went down.

Not recommended: Synchronous "AJAX" calls

As I mentioned, some asynchronous operations have synchronous counterparts. While I don't advocate there use, for completeness, here is how you would perform a synchronous call:

Without jQuery

If you directly use a XMLHTTPRequest object, pass false as third argument to .open.

jQuery

If you use jQuery, you can set the async option to false. Note that this option is deprecated since jQuery 1.8. You can then either still use a success callback or access the responseText property of the jqXHR object:

function foo() {
    var jqXHR = $.ajax({
        //...
        async: false
    });
    return jqXHR.responseText;
}
If you use any other jQuery AJAX method, such as $.get, $.getJSON, etc., you have to change it to $.ajax (since you can only pass configuration parameters to $.ajax).

Heads up! It is not possible to make a synchronous JSONP request. JSONP by its very nature is always asynchronous (one more reason to not even consider this option).