Category Archives: PHP

PHP Debugging – Look for Case Sensitivity In Variable, File Names and Class Names

This blog is coming out of conversation with one of the developer in my team. He recently made some changes in API in local development and push code to test server. But on server it was throwing an error and API was not working. So after trying hard for sometime he came to me and asked for help. He showed me lines of code he has added and as an experienced person I immediately caught his error. The problem was, he declared variable in lowercase and was using variable with uppercase in next line and that’s what breaking on server. Something like this

$var = new Class();
$VAR->prop = value;

Case sensitivity is one of the major reason for errors while you are working on local development environment with XAMPP, WAMP in Windows. At this time case sensitive is not applied and it will  treat

$var;
$VAR;
$Var;

as one and the same variables. But when you are working on server, you have unix / linux operating systems like Ubuntu, Fedora etc. At this time case sensitivity is applied and

$var;
$VAR;
$Var;

Are treated as three different variables. So by mistake if you declare it with lower case and try to use it upper case, it will give you an error. So if you are facing this issue that, code works on your local machine, but does not work on server look for the case sensitivity.

Same goes for the filenames and class names. If you have adde file with name

Myclass.php

and if you include it with

include ‘MyClass.php’;
require ‘MyClass.php’;

Then it will not be able to find file and it will throw warning or fatal error if you are using require. So make sure that you maintain case sensitivity while naming your class, variables and files in PHP because ultimately your code will be pushed to UNIX / LINUX server and it is case sensitive. 

PHP file_get_contents throws 400 Bad Request Error – Google Geocode API

Recently I was using Google Maps API to geocode address with PHP. There were thousands of addresses in CSV and I have to read it one by one and do geocode it and get lat long and other missing info of the address. So I was using file_get_contents function to fire HTTP request and get output like this.

$geocode = file_get_contents(‘https://maps.google.com/maps/api/geocode/json?address=’.urlencode($records[0]).’&key=API_KEY&sensor=false’);
$output = json_decode($geocode);

It worked for few address but for some addresses it throws error.

ErrorException in Controller.php line 535:
file_get_contents(URL): failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request

That’s because some of the addresses in the CSV were not properly formatted and there were some special characters in it as addresses were copied from web pages. But the problem was it’s eventually breaking the execution of the script. So to fix it use PHP curl instead of file_get_contents. As it does not throw exception on bad request but it gives you response code and that you can check before you get output. So here is my code.

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, ‘https://maps.google.com/maps/api/geocode/json?address=’.urlencode($records[0]).’&key=APIKEY&sensor=false’);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$geocode = curl_exec($ch);

if(curl_getinfo($ch, CURLINFO_HTTP_CODE) === 200) {
        // convert response
        $output = json_decode($geocode);
if($output->status == ‘OK’){

}
}
curl_close($ch);

So as you can see on above code, we are using checking CURLINFO_HTTP_CODE, if it’s 200 that means HTTP request is successfully executed or in case there is a bad request you can check it and skip accessing the output. So it won’t throw an error.

Laravel: Failed to connect to 192.241.224.13 port 80 on OSX

Recently I was trying to create new Laravel application with Laravel installer, it was not working and it was throwing following error.

Failed to connect to 192.241.224.13 port 80: Operation timed out [url] http://192.241.224.13/laravel-craft.zip

I was not sure about error so I tried few things like updating composer and updating laravel installer but still it was not working but finally I was able to solve problem so in this blog I am going to explain how to solve this issue.
This issue is because even after updating laravel installer version with composer it’s still using old version of composer which was installed in /usr/local/bin library. To find out this type following command in terminal.
laravel –version
If it shows following output that means you are still using old version of laravel installer.
Laravel Craft version 1.0.0
So to remove this version first of all remove old version. Go to terminal and type following command.
rm /usr/local/bin/laravel
Now will again install laravel with following command.
composer global require “laravel/installer”
It will install laravel in your users home directory, so you have to add path to it in your bash_profile file. Open the bash_profile file for editing.
sudo nano ~/.bash_profile
And copy following line in it.
export PATH=/Users/USERNAME/.composer/vendor/bin:$PATH
In above line replace USERNAME with your OSX username. Save the file and reopen the terminal. Now again type following command.
laravel –version
And it will show following output.
Laravel Installer version 1.3.1
So now you have the latest version of laravel installer, create new laravel application with following command
laravel new app-name
Hope this helps you.

PHP / MySql – Generate Big Reports from Big Data

Big data is a term that describes the large volume of data – both structured and unstructured – that inundates a business on a day-to-day basis. But it’s not the amount of data that’s important. It’s what organizations do with the data that matters. Big data as a service market to grow in near future. “Big Data” analysis is a hot and highly valuable skill now a days. For the big data analysis, an organization needs reports generated from it and to generate reports from big data we need some spacial tricks. In this blog I am going to explain some best practices to generate big reports from big data in PHP / MySql.

Challenges we face in managing Big Data with MySql

In MySql when we have big data we face certain performance issues. Most crucial issue is slow performance of MySql. When you have millions of rows in table and you want to search certain raws from it, it will take some time to get data and you need to improve in that. So in MySql there is a way to make faster data retrieval.

INDEXING

Yes, that ‘s right indexing solved my issue. There was a table in my database which has 100K records and executing query from it was taking lots of time as there was no indexing. So I created an index on columns which are used mostly for querying that table and after creating index query was working blazing fast.

If you are facing the same issue, better check your database queries and optimize it with indexing to make it faster.

Challenges we face in generating Big Reports with PHP

In PHP when we generate big reports it will surely take time and while working with PHP we have certain restrictions. For example, a PHP script can run for only certain time limits on any server and that limits can not be changed on most of server providers. So in case of generating big reports we surely need time as we have lots of data at backend and from it we are creating reports. So how to deal with it. 
Here is the one solution I always use. You can make use of scheduled cron job. Cron jobs run in background and there is no time restrictions with it so it can run for any amount of time and it can resources as much as possible. So get the reports parameters from the user and save it in database and schedule it for certain time.  For example user want to see day wise sales of products for a month. Save parameters like month in database have a scheduled cron job to read this data and start creating reports in background. Once the report is generated you can notify user about it so they can download it. Which this trick you can generated Big Reports from Big Data.

Magento 2.0 – Run Commands With PHP File

Hello,

As we know with Magento 2.0 they have introduced command line configuration. You can run command through terminal or SSH on remote server to manager and configure your Magento 2.0.

Recently for one of our project we have Magento 2.0 installed on shared server and we do not have access to terminal and SSH. So there was no way to run Magento 2.0 commands. So we solved it by running it through PHP file. Here is how we can do it.

First create a PHP file in root folder of your server where Magento is installed and name mage_command.php. Now open that file and put following code in it.

$commandToRun = ”;
shell_exec($commandToRun);

That’s it just two line of code. Now just replace value of $commandToRun with the command you want to run. For example reindex data.

$commandToRun = ‘php bin/magento indexer:reindex’;
shell_exec($commandToRun);

Now run that PHP file in browser with http://your_magento_host.com/mage_command.php

And it will execute that command. If you want to see the result, you can echo it.

$commandToRun = ‘php bin/magento indexer:reindex’;
echo shell_exec($commandToRun);

You can also run multiple commands.

$commandToRun = ‘php bin/magento indexer:reindex’;
echo shell_exec($commandToRun);

$commandToRun = ‘php bin/magento cache:clean’;
echo shell_exec($commandToRun);

Hope this helps you.

Send FireBase Push notifications from PHP Application

Hello,

Recently in one of my project we have mobile applications with PHP web services. In this we have a requirement to send Firebase Push notifications from PHP to mobile app. Here in this blog I am going to explain how to do this.

First all login to your Firebase console and get the Web Api key. Go to https://console.firebase.google.com/ and login with your user name and password.

Select your project

Click on gear icons on left and select project settings and above screen will be displayed. Here Web Api Key is the key which you need. copy it. Now let see code one by one.

$url = ‘https://fcm.googleapis.com/fcm/send’;

This is the URL we will use to send push notification.

Now lets build the payload.

$fields = array (
‘to’ => ‘REGISTRATION_KEY’,
“notification” => array(
“title”=> “Welcome To App”,
“body”=> “App Description”
),
“data”=>array(
“key_1″=>”value_1”,
                        “key_2″=>”value_2”
)
);

Here to is the filed which contains registration id for the device. This is the id which you get when you register device for push notification.

notification contains title and text to be displayed in notification area. This is a standard format and should not be changed.

data contains all the user defined data you want to send with notification, you can add any number of key value pairs here.

If you don’t want to pass any data, remove the data field from payload. So now payload is read now lets encode it to send.

$fields = json_encode ( $fields );

Now send headers with API key.

$headers = array (
‘Authorization: key=’ . “YOUR_WEB_API_KEY”,
‘Content-Type: application/json’
);

Now we will use PHP cURL to send HTTP request.

$ch = curl_init ();
curl_setopt ( $ch, CURLOPT_URL, $url );
curl_setopt ( $ch, CURLOPT_POST, true );
curl_setopt ( $ch, CURLOPT_HTTPHEADER, $headers );
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt ( $ch, CURLOPT_POSTFIELDS, $fields );

$result = curl_exec ( $ch );
echo $result;
curl_close ( $ch );

That’s it and Push notification is sent to particular device.

Laravel 5.x Store Uploaded Files to Amazon S3

Recently in one of my Laravel 5.2 project, we used Amazon s3 to store static files and user uploaded files. So here in this blog I am going to explain how to do this.

1) First of all install following plugin through composer.

composer require league/flysystem-aws-s3-v3 ~1.0

2) Now add your S3 credentials to your environment (.env file)

S3_KEY=YOUR_KEY
S3_SECRET=YOUR_SECRET
S3_REGION=YOUR_REGION
S3_BUCKET=YOUR_BUCKET

3) Open config.filesystems.php and configure s3 driver as follow.

‘s3’ => [
            ‘driver’ => ‘s3’,
            ‘key’    => env(‘S3_KEY’),
            ‘secret’ => env(‘S3_SECRET’),
            ‘region’ => env(‘S3_REGION’),y.
            ‘bucket’ => env(‘S3_BUCKET’),
        ]

4) Now open controller where you have code to manage uploaded file and add following dependency.

use IlluminateContractsFilesystemFilesystem;

5) Use following code to store your file to S3.

$image = $request->file(‘user_uploaded_image’);
$imageFileName = time() . ‘.’ . $image->getClientOriginalExtension();
$s3 = Storage::disk(‘s3’);

$filePath = ‘/mypath’/.$imageFileName;
$s3->put($filePath, file_get_contents($image), ‘public’);
$uploadedFileS3Path = ‘https://’.env(‘S3_BUCKET’).’/’.$filePath;
Please note in my case I configured S3 bucket to be direct URL of uploaded file. In case your case if you have not configured it then your path will be as follow.
$uploadedFileS3Path = ‘http://s3-‘.env(‘S3_REGION’).’.amazonaws.com/’.env(‘S3_BUCKET’).’/’.$filePath;
This path you can use to display file and you can store it to database as well.
Special Case 
If you are using it in localhost using XAMPP in your windows system. You have to do following few steps.
Download certificate pem file from this link. https://curl.haxx.se/ca/cacert.pem and store it to some where in your C drive or whatever drive you have your xampp installed.
For example I put it in  C:codecacert.pem
Now open your php.ini file and bottom of the file add following line.
curl.cainfo = C:codecacert.pem
That’s it and it will work in your local environment too. Hope this helps you.

Cordova Applicaiton Select Any File From SD Card and Upload to Server

Hello,

Recently in one of my project we were building android application with Cordova. There was a requirement where user can choose any files from SD card and upload it to server.

So in this blog I am going to explain how to do this.

Our challenges was user can pick any file like audio, video, image, pdf etc. So we have to properly save it on server with proper extension.

First of all you will need two plugins.

1) Cordova File Transfer Plugin

You can install it via following command.

cordova plugin add cordova-plugin-file-transfer

2) File Chooser Plugin

You can check this plugin here and can install it via following command.

cordova plugin add http://github.com/don/cordova-filechooser.git

Now once you install file choose plugin you can use following command to open file selector in android.

fileChooser.open(function(uri) {
    alert(uri);
});

Now the problem with this file chooser plugin is that it gives content path like this.

content://media/images/4

However this path can not be used with File Transfer Plugin as it needs absolute file URI like this.

file:///sdcard/0/downloads/myPDF.pdf

So we have to edit this file chooser plugin little bit. Go to your android project and open FileChooser.java file from the com.megster.cordova package and check the following function.

public void onActivityResult(int requestCode, int resultCode, Intent data) {
}
See the following line of code in this function.
Uri uri = data.getData();
 callback.success(uri.getPath());
So form here it returns the content path.
We have to convert that content path to absolute path. So add following functions in FileChooser.java
public static String getPath(final Context context, final Uri uri) {
        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(“:”);
                final String type = split[0];
                if (“primary”.equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + “/” + split[1];
                }
                // TODO handle non-primary volumes
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {
                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse(“content://downloads/public_downloads”), Long.valueOf(id));
                return getDataColumn(context, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(“:”);
                final String type = split[0];
                Uri contentUri = null;
                if (“image”.equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if (“video”.equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if (“audio”.equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }
                final String selection = “_id=?”;
                final String[] selectionArgs = new String[] {
                        split[1]
                };
                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        }
        // MediaStore (and general)
        else if (“content”.equalsIgnoreCase(uri.getScheme())) {
            return getDataColumn(context, uri, null, null);
        }
        // File
        else if (“file”.equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }
        return null;
    }
    /**
     * Get the value of the data column for this Uri. This is useful for
     * MediaStore Uris, and other file–based ContentProviders.
     *
     * @param context The context.
     * @param uri The Uri to query.
     * @param selection (Optional) Filter used in the query.
     * @param selectionArgs (Optional) Selection arguments used in the query.
     * @return The value of the _data column, which is typically a file path.
     */
    public static String getDataColumn(Context context, Uri uri, String selection,
            String[] selectionArgs) {
        Cursor cursor = null;
        final String column = “_data”;
        final String[] projection = {
                column
        };
        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                    null);
            if (cursor != null && cursor.moveToFirst()) {
                final int column_index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(column_index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }
    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return “com.android.externalstorage.documents”.equals(uri.getAuthority());
    }
    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return “com.android.providers.downloads.documents”.equals(uri.getAuthority());
    }
    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return “com.android.providers.media.documents”.equals(uri.getAuthority());

    }
Now update onActivityResult function as follow.
callback.success(getPath(cordova.getActivity(), uri));

It will send you correct absolute URI.  Now in your JavaScript.

var filePath = ”;
var fileType = ”;

fileChooser.open(function(obj) {
            filePath = ‘file://’+obj;
            fileType= obj.substring(uri.lastIndexOf(‘.’));
        });

As you see above we are storing file path and file extension in two variables. Now following is the code to upload your file to server.

        var win = function (r) {
                alert(‘file uploaded’);
        }

        var fail = function (error) {
         }

        var options = new FileUploadOptions();
        options.fileKey = “file”;
        options.fileName = filePath.substr(this.evidencePath.lastIndexOf(‘/’) + 1);
        options.mimeType = “text/plain”;

        var params = {};
        params.fileType = fileType;
        options.params = params;

        var ft = new FileTransfer();
        ft.upload(filePath, encodeURI(“http://yourserverpath”), win, fail, options);

On the server side your PHP code should be as follow.

$file_type = $_POST[‘fileType’];
$fileName = time().”_”.$file_type;
move_uploaded_file($_FILES[“file”][“tmp_name”], “/yourserverpath/”.$fileName);
return json_encode(array(‘success’=>true,’index’=>$index, ‘server_path’=>”http://serverpath”.$fileName));

That’s it, hope this helps you.

osTicket, Create Ticket with API

Hello,

Recently for one of my project we have a requirement to integrate laravel application and osTicket. Data from laravel app to be sent to osTicket and create ticket with that.

Now we all know that in osTicket if send an email, it will automatically create ticket. However in our case it won’t work as emails were from different domains so we have to use osTicket API.

First of all you have to create API key for that login to your osTicket admin panel and go to.

Admin Panel -> Manage -> API keys and create new API key.

Here IP address is your source IP address from where you will call an API. In our case it was server IP address. Now API key is created. Following is the code.
$config = array(
‘url’=>’http://yourosTicketURL/api/tickets.json’, 
‘key’=>’yourapikey’  // API Key goes here
);

In above code replace yourosTicketURL with your URL and replace yourapikey with your generated key.

Now prepare data to send.

$name = ‘Name of User’;
$email = ‘Email of User’;
$mobile = ‘Mobile’;
$subject = ‘Subject’;
$text = ‘Dummy message’;

$data = array(
‘name’      =>     $name,
’email’     =>      $email,
‘phone’ =>     $mobile,
‘subject’   =>      $subject,
‘message’   =>   “data:text/html;charset=utf-8,$text”,
‘ip’        =>      $_SERVER[‘REMOTE_ADDR’],
‘topicId’   =>      ‘1’,
‘attachments’ => array()
);

Now we will send data to API.

#pre-checks
function_exists(‘curl_version’) or die(‘CURL support required’);
function_exists(‘json_encode’) or die(‘JSON support required’);

#set timeout
set_time_limit(30);

#curl post
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $config[‘url’]);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_USERAGENT, ‘osTicket API Client v1.333’);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array( ‘Expect:’, ‘X_API_KEY: ‘.$config[‘key’]));
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result=curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($code != 201)
die(‘Unable to create ticket: ‘.$result);

$ticket_id = (int) $result;

# Continue onward here if necessary. $ticket_id has the ID number of the
# newly-created ticket

function IsNullOrEmptyString($question){
return (!isset($question) || trim($question)===”);
}

That’s it and it should work. No wait if you run you will always get following error.

Unable to create ticket:  Invalid API key.

Now that was really strange as API key was valid, IP address was valid everything is good but still it does not create ticket. So what to do. Well there is a bug in osTicket API code. After spending couple of hours I finally figure out the solution. We have to modify osTicket source code for this. Open following file.

include/class.api.php

And find out following functions.

function requireApiKey() {
        # Validate the API key — required to be sent via the X-API-Key
        # header

        if(!($key=$this->getApiKey()))
            return $this->exerr(401, __(‘Valid API key required’));
        elseif (!$key->isActive() || $key->getIPAddr()!=$_SERVER[‘REMOTE_ADDR’])
            return $this->exerr(401, __(‘API key not found/active or source IP not authorized’));

        return $key;
    }

    function getApiKey() {

        if (!$this->apikey && isset($_SERVER[‘HTTP_X_API_KEY’]) && isset($_SERVER[‘REMOTE_ADDR’]))
            $this->apikey = API::lookupByKey($_SERVER[‘HTTP_X_API_KEY’], $_SERVER[‘REMOTE_ADDR’]);

        return $this->apikey;
    }

Here the problem was it never get HTTP_X_API_KEY and REMOTE_ADDR was never set. So replace above two function with following code.

function requireApiKey() {
        # Validate the API key — required to be sent via the X-API-Key
        # header
        if(!($key=$this->getApiKey()))
            return $this->exerr(401, __(‘Valid API key required’));
        elseif (!$key->isActive() || $key->getIPAddr()!=$_SERVER[‘HTTP_X_REAL_IP’])
            return $this->exerr(401, __(‘API key not found/active or source IP not authorized’));

        return $key;
    }

    function getApiKey() {

foreach (getallheaders() as $name => $value) {
    $_SERVER[‘HTTP_’.$name] = $value;
}

        if (!$this->apikey && isset($_SERVER[‘HTTP_X_API_KEY’]) && isset($_SERVER[‘HTTP_X_REAL_IP’]))
            $this->apikey = API::lookupByKey($_SERVER[‘HTTP_X_API_KEY’], $_SERVER[‘HTTP_X_REAL_IP’]);

        return $this->apikey;
    }

As you can see in above code we are getting all headers we set when we call API and put it in $_SERVER variable. and instead of REMOTE_ADDR we are using HTTP_X_REAL_IP.  Now save the file and again run API code. It should work fine.

Laravel 5.3 Run Artisan Command Through Routes

Recently for one my project we installed Laravel 5.3 on shared server where we were not having SSH or route access.

As we know general practice with Laravel is to create database tables with migrations and for that we have to run artisan commands through terminal and SSH.

But in our case we were not having SSH access, we have only FTP and database access so we have to figure out a way to run this commands through web. In this blog I am going to explain how to do this.

After reading Laravel 5.3 document I came to know that Laravel gives you Artisan class to run artisan command. So what I did is I created two routes, one for creating migration and other to run migration.

To create migration

Route::get(‘/create-migration-command’, function () {
    Artisan::call(‘make:migration’, [‘name’ => ‘migration_name’]);
});
As you can see here the command is make:migration and parameter passed is name of migration. 
Virtually it is equivalent to following SSH command.
php artisan make:migration migration_name
This will generate migration file in database folder, you can open it through FTP and add necessary code of migration.

Run Migration

Route::get(‘/run-migration-command’, function () {
    Artisan::call(‘migrate’, []);
});
Virtually it is equivalent to following SSH command.
php artisan migrate
Hope this helps you.