megacolorboy

Abdush Shakoor's Weblog

Writings, experiments & ideas.

Convert string to variable in PHP

I read about variable variables in PHP's official documentation.

Here's a sample:

<?php
    $a = "hello";
    // Remove special characters and tags to prevent it from crashing.
    $foo = preg_replace('/[^a-zA-Z0-9\s]/', '', $$a);
    echo $foo;
?>

Not sure if this is a good practice but it sure gets the job done!

How to resolve the "file_get_contents(): SSL operation failed" error

If you're facing this error while trying to download a file from your server, it's most probably the SSL certificate that has been hosted on your server isn't correctly verified or maybe, you're using OpenSSL on a server running PHP 5.6.

As per the documentation, there are some changes that can be made to resolve it, like the following method:

<?php
public function foo(Request $request) {
    $arrContextOptions = array(
        "ssl" => array(
            "verify_peer" => false,
            "verify_peer_name" => false,
        ),
    );
    return Response::make(file_get_contents(asset('pdf/file.pdf'), false, stream_context_create($arrContextOptions)), 200, [
        'Content-Type' => 'application/pdf',
        'Content-Disposition' => 'inline; filename="file.pdf"',
    ]);
}
?>

Although, I won't recommend this unless you are testing it on a localhost environment as it's not secure and could have significant security implications because disabling verification can permit a Man in the Middle attack to take place.

Use it at your own risk!

How to resolve the "Failed to clear cache. Make sure you have the appropriate permissions." error

This error is annoying and mostly happens if the data directory is missing under the storage/framework/cache/data directory. For some reason, this folder doesn't exist by default.

To resolve it, just manually create the data directory under the storage/framework/cache/data directory and it should fix the issue.

How to exclude certain slugs in Laravel

Using plain Regular Expressions, you can exclude certain slug from your routes, try adding the following to your routes/web.php file:

<?php
    Route::match(array('GET', 'POST'), '/{slug}', 'YourController@index')->name('page')->where('slug', '^(?!pattern).*$');
?>

Hope you found this useful!

Convert to date from timestamp using Carbon

Using Carbon's createFromFormat() method is basically a wrapper for DateTime::createFromFormat(), the main difference between the two methods is that you can add a timezone to Carbon's method.

Here's a sample on how you can convert to date using timestamp using Carbon:

<?php
    function formatDate(Request $request) {
        return \Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $request->date)->format('Y-m-d');
    }
?>

Hope you found this useful!

Clearing cache on a Shared Hosting Server

Hosted your website on a Shared Hosting Server and got limited access to clear the cache on your project?

Open up routes/web.php and create this route:

<?php
Route::get('/clearcache', function(){
    \Artisan::run('config:clear');
    \Artisan::run('cache:clear');
    \Artisan::run('view:clear');
    \Artisan::run('route:clear');
    \Artisan::run('config:cache');
});
?>

Just type the URL and it will clear all existing cache from the project.

Hope this helps you out!

Convert string to date using MySQL

Today, I was debugging a piece of code that is supposed to return a list of data based on the year, the funny thing is that the data was being returned on the development server but not on the production one.

Weird, so I opened up MySQL Workbench and wrote a simple query to see if the dates were being returned because who knows maybe they weren't stored at all.

SELECT YEAR(date_posted) FROM posts;

The values returned were null. Now, that's strange because the dates were present in the column. So, I took a deep look and figured out that the dates were stored in VARCHAR instead of DATETIME data type! ๐Ÿ˜”

Luckily, I figured that there's a way to resolve this by STR_TO_DATE() function:

SELECT YEAR(STR_TO_DATE(date_posted, '%Y-%m-%d')) FROM posts;

Bam! The results were coming now! ๐Ÿ˜Œ

Hope this helps you out!

Use MySQL 8.0 with Native Password Authentication

Last month, I was configuring an Ubuntu Server to deploy a client's project that uses MySQL 8.0 and PHP 7.2. So, I installed the necessary dependencies and finally installed MySQL 8.0, created a new schema and imported the database tables required for the project.

Next, I typed the project URL and ran into this error:

Unable to load plugin 'caching_sha2_password'

If you're running PHP 7.2 and facing this error, you should know that PHP 7.2 doesn't support native password authentication by default. But it's a simple fix, all you have to do is either one of the following:

  1. Alter the current user's authentication to native password
  2. Create a new user with native password authentication

Alter the current user's authentication to native password

ALTER USER 'your_user'@'your_server_host' IDENTIFIED WITH mysql_native_password BY 'your_password';

Create a new user with native password authentication

CREATE USER 'your_user'@'your_server_host ' IDENTIFIED WITH mysql_native_password BY 'your_password'

For the changes to take effect, you need to reload the privileges by typing the following:

FLUSH PRIVILEGES;

Hope this helps you out!