How to convert string to date and datetime with PHP?

Sometimes, we want to convert string to date and datetime with PHP.

In this article, we’ll look at how to convert string to date and datetime with PHP.

How to convert string to date and datetime with PHP?

To date and datetime with PHP, we can use the date_create_from_format function.

For instance, we write

$date = date_create_from_format("m-d-Y", "10-16-2022")->format("Y-m-d");

to call date_create_from_format with the date format string and the date to parse the date string to a date.

Then we call format to return a new date string in the new format.

Y stands for 4 digit year.

m stands for 2 digit month.

d stands for 2 digit date.

Conclusion

To date and datetime with PHP, we can use the date_create_from_format function.

How to read any request header in PHP?

Sometimes, we want to read any request header in PHP.

In this article, we’ll look at how to read any request header in PHP.

How to read any request header in PHP?

To read any request header in PHP, we can use the $_SERVER array.

For instance, we write

function get_request_headers()
{
    $headers = [];
    foreach ($_SERVER as $key => $value) {
        if (substr($key, 0, 5) != "HTTP_") {
            continue;
        }
        $header = str_replace(
            " ",
            "-",
            ucwords(str_replace("_", " ", strtolower(substr($key, 5))))
        );
        $headers[$header] = $value;
    }
    return $headers;
}

$headers = get_request_headers();

foreach ($headers as $header => $value) {
    echo "$header: $value <br />\n";
}

to define the get_request_headers function.

In it, we loop through the $_SERVER array entries with a foreach loop.

In the loop, we check if the $key starts with 'HTTP_'.

If it does, then we put the entry in the $headers array.

The key for each entry is the $key string without the 'HTTP_' part.

Then we call get_request_headers to get an array of $headers and loop through the entries with the foreach loop.

Conclusion

To read any request header in PHP, we can use the $_SERVER array.

How to fix “date(): It is not safe to rely on the system’s timezone settings…” error with PHP?

Sometimes, we want to fix "date(): It is not safe to rely on the system’s timezone settings…" error with PHP.

In this article, we’ll look at how to fix "date(): It is not safe to rely on the system’s timezone settings…" error with PHP.

How to fix "date(): It is not safe to rely on the system’s timezone settings…" error with PHP?

To fix "date(): It is not safe to rely on the system’s timezone settings…" error with PHP, we can set the time zone with date_default_timezone_set.

For instance, we write

if (!ini_get("date.timezone")) {
    date_default_timezone_set("GMT");
}

to check if the time zone is set with ini_get.

If it’s not, then we set the time zone to GMT with date_default_timezone_set.

Conclusion

To fix "date(): It is not safe to rely on the system’s timezone settings…" error with PHP, we can set the time zone with date_default_timezone_set.

How to bypass Access-Control-Allow-Origin with PHP?

Sometimes, we want to bypass Access-Control-Allow-Origin with PHP.

In this article, we’ll look at how to bypass Access-Control-Allow-Origin with PHP.

How to bypass Access-Control-Allow-Origin with PHP?

To bypass Access-Control-Allow-Origin with PHP, we can set the Access-Control-Allow-Origin to the domains that we allow CORS for.

For instance, we write

header("Access-Control-Allow-Origin: https://www.example.com");

to allow CORS communication with https://www.example.com.

We can also write

header("Access-Control-Allow-Origin: *");

to allow CORS communication with all domains.

Conclusion

To bypass Access-Control-Allow-Origin with PHP, we can set the Access-Control-Allow-Origin to the domains that we allow CORS for.

How to filter an array by its keys using an array of allowed keys with PHP?

Sometimes, we want to filter an array by its keys using an array of allowed keys with PHP.

In this article, we’ll look at how to filter an array by its keys using an array of allowed keys with PHP.

How to filter an array by its keys using an array of allowed keys with PHP?

To filter an array by its keys using an array of allowed keys with PHP, we can use the array_intersect_key function.

For instance, we write

$allowed = ["foo", "bar"];

var_dump(array_intersect_key($my_array, array_flip($allowed)));

to call array_intersect_key with $my_array and the values we get from the $allowed array to return an new array that has the keys that are in the $allowed array.

Conclusion

To filter an array by its keys using an array of allowed keys with PHP, we can use the array_intersect_key function.

How to create resumable downloads when using PHP to send the file?

Sometimes, we want to create resumable downloads when using PHP to send the file.

In this article, we’ll look at how to create resumable downloads when using PHP to send the file.

How to create resumable downloads when using PHP to send the file?

To create resumable downloads when using PHP to send the file, we can use the mod_xsendfile Apache module.

After we add the mod_xsendfile module, we write

header("X-Sendfile: /path/to/file");
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; file=\"filename\"");

to call header to return the headers for the download file.

We set its MIME type with

header("Content-Type: application/octet-stream");

And we set the download file name with

header("Content-Disposition: attachment; file=\"filename\"");

Conclusion

To create resumable downloads when using PHP to send the file, we can use the mod_xsendfile Apache module.

How to add a cross-site request forgery (CSRF) token using PHP?

Sometimes, we want to add a cross-site request forgery (CSRF) token using PHP.

In this article, we’ll look at how to add a cross-site request forgery (CSRF) token using PHP.

How to add a cross-site request forgery (CSRF) token using PHP?

To add a cross-site request forgery (CSRF) token using PHP, we can use the bin2hex function.

For instance, we write

session_start();
if (empty($_SESSION["token"])) {
    $_SESSION["token"] = bin2hex(random_bytes(32));
}
$token = $_SESSION["token"];

to call bin2hex with a random byte string created with random_bytes(32) to return a random token.

Then we set it as the value of $_SESSION["token"].

Conclusion

To add a cross-site request forgery (CSRF) token using PHP, we can use the bin2hex function.

How to convert a PDF document to a preview image in PHP?

Sometimes, we want to convert a PDF document to a preview image in PHP.

In this article, we’ll look at how to convert a PDF document to a preview image in PHP.

How to convert a PDF document to a preview image in PHP?

To convert a PDF document to a preview image in PHP, we can use ImageMagick.

For instance, we write

$im = new imagick("file.pdf[0]");
$im->setImageFormat("jpg");
header("Content-Type: image/jpeg");
echo $im;

to create the $im object with the imagick class called with the path to the image.

Then we call setImageFormat to set the image format to jpg.

Then we call header to return the Content-Type header with the MIME type of the image.

Conclusion

To convert a PDF document to a preview image in PHP, we can use ImageMagick.

How to use PDO to fetch a results array in PHP?

Sometimes, we want to use PDO to fetch a results array in PHP.

In this article, we’ll look at how to use PDO to fetch a results array in PHP.

How to use PDO to fetch a results array in PHP?

To use PDO to fetch a results array in PHP, we can use the fetchAll method.

For instance, we write

$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();
$result = $sth->fetchAll(\PDO::FETCH_ASSOC);
print_r($result);

to create a prepared statement with prepare called with a SQL string.

Then we call execute to run the statement.

Then we call fetchAll to fetch all the results.

And we fetch them as an associative array by calling it with \PDO::FETCH_ASSOC.

Conclusion

To use PDO to fetch a results array in PHP, we can use the fetchAll method.

How to view query error in PDO PHP?

Sometimes, we want to view query error in PDO PHP.

In this article, we’ll look at how to view query error in PDO PHP.

How to view query error in PDO PHP?

To view query error in PDO PHP, we can use the errorInfo method.

For instance, we write

if (!$st->execute()) {
    print_r($st->errorInfo());
}

to check if the $st statement failed to execute by checking if execute returns false.

If it does, then we call errorInfo to get the error and print it with print_r.

Conclusion

To view query error in PDO PHP, we can use the errorInfo method.