SNHPS
Quick and easy code snippets
echo-json-and-die.php

A convienient helper function for outputting human readable JSON responses.

function echo_json_and_die($data, $status_code)
{
	http_response_code($status_code);
	echo json_encode($data, JSON_PRETTY_PRINT);
	die();
}

echo_json_and_die
([
	'status' => 'error',
	'text_message' => 'Could not find that resource.',
	'html_message' => '<p class="error-message">Could not find that resource.</p>',
], 404);
finish-execution-in-background.php

Continue processing a request after sending back a response and closing the connection.

function close_connection_but_continue_processing($output)
{
    if (function_exists('fastcgi_finish_request'))
    {
        echo $output;
        ignore_user_abort(true); //https://bugs.php.net/bug.php?id=68772
        fastcgi_finish_request();
    }
    
    else
    {
        ob_start();
        echo (empty($output) ? ' ' : $output); //Quirk: At least one character must be outputted for the connection to be closed
        header('Content-Length: ' . ob_get_length());
        header('Connection: close');
        ob_end_flush();
        ob_flush();
        flush();
        session_write_close();
    }
}

close_connection_but_continue_processing('Your request has been received and will now be processed.');
do_long_task();
str-contains-any.php

Check whether the given haystack string contains any of the given needle strings.

function str_contains_any($haystack, $needles, $case_sensitive)
{
    foreach ($needles as $needle)
    {
        if (str_contains($haystack, $needle) || (($case_sensitive === false) && str_contains(strtolower($haystack), strtolower($needle))))
        {
            return true;
        }
    }
    
    return false;
}

$haystack = 'This is a load of shizzle';
$needles = ['fudge', 'shizzle'];
$match_found = str_contains_any($haystack, $needles, true); //true

This website is owned and operated by SiteBolts. All the code snippets found here are intended to be a starting point and should not be treated as a perfect solution to every problem. We do not guarantee the performance, reliability, or security of the code found on this website. As always, you should ensure that you have adequate backups before adding, changing, or executing any code.