Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

Friday, September 27, 2024

Create rest API using Laravel 11

REST APIs (Representational State Transfer Application Programming Interfaces) are a crucial part of modern web applications, allowing different software systems to communicate with each other. In this tutorial, we will explore how to create a REST API using Laravel 11, the latest version of the popular PHP framework known for its elegant syntax and powerful features.

Before diving in, ensure you have the following installed on your system

  • PHP 8.2 or higher
  • Composer
  • MySQL or any other supported database
  • Laravel 11 (we will install this)

Step 1: Setting Up the Laravel Project

First, install a fresh Laravel 11 application using Composer. Run the following command:
composer create-project --prefer-dist laravel/laravel RestApiDemo

Which will install laravel latest in  RestApiDemo directory. Now navigate to the project directory with `cd RestApiDemo`

Step 2: Configuring the Database

Open the .env file in the root of your project and configure your database settings
DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=restapidemo
DB_USERNAME=*****
DB_PASSWORD=*****

Now make new tables as 'customers' for save customer data as below.

php artisan make:migration create_customers_table 

Which will create new db migration file `*create_customers_table.php` in `/database/migrations/` directory. open that file and create table schema in up() function as below.

 public function up(): void

{

    Schema::create('customers', function (Blueprint $table) {

        $table->increments('id');

        $table->string('name')->comment('Customer full name');

        $table->string('gender')->length(50)->nullable();

        $table->date('date_of_birth')->nullable();

        $table->string('email')->unique();

        $table->text('notes')->nullable();

        $table->timestamps();

    });

}

Now need create that table in database run db migration as `php artisan migrate` (verify new table customers created in database).

Step 3: Creating the Controller and Model

In laravel need to create controller with resource model use below command.
php artisan make:controller CustomersController --resource --model=Customer

Which will create new `CustomersController.php` in `app/Http/Controllers` directory with basic functions and `Customer.php` model in `app\Models` directory.

Update customer controller functions as below for basic CURD operation.

class CustomersController extends Controller

{

    /**

     * Display a listing of the resource.

     */

    public function index()

    {

        $customers = Customer::latest()->paginate(10);

        return [

            "status" => 1,

            "data" => $customers

        ];

    }


    /**

     * Store a newly created resource in storage.

     */

    public function store(Request $request)

    {

        $request->validate([

            'name' => 'required',

            'email' => 'required|email',

            'date_of_birth' => 'date_format:Y-m-d',

        ]);

        $customer = Customer::create($request->all());

        return [

            "status" => 1,

            "data" => $customer

        ];

    }


    /**

     * Display the specified resource.

     */

    public function show(Customer $customer)

    {

        return [

            "status" => 1,

            "data" =>$customer

        ];

    }


    /**

     * Update the specified resource in storage.

     */

    public function update(Request $request, Customer $customer)

    {

        $request->validate([

            'name' => 'required',

            'email' => 'required|email',

            'date_of_birth' => 'date_format:Y-m-d',

        ]);

        $customer->update($request->all());

        return [

            "status" => 1,

            "data" => $customer,

            "msg" => "Customer updated successfully"

        ];

    }


    /**

     * Remove the specified resource from storage.

     */

    public function destroy(Customer $customer)

    {

        $customer->delete();

        return [

            "status" => 1,

            "data" => $customer,

            "msg" => "Customer deleted successfully"

        ];

    }

}

Update customer model with define database columns which needs to add or update as below.

class Customer extends Model

{

    /**

     * The attributes that are mass assignable.

     */

    protected $fillable = [

        'name',

        'gender',

        'date_of_birth',

        'email',

        'notes'

    ];


    use HasFactory;

Step 4: Creating the API Routes

Laravel 11 need to install the routes/api.php file for defining API routes with below command.
php artisan install:api
Open this file and define the routes for CRUD operations

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\CustomersController;

Route::resource('customers', CustomersController::class);

Step 5: Testing the API 

To test the API, you can use tools like Postman or Insomnia by run `php artisan serve` (can open directly with directory URL). Here are some endpoints to test.

  • GET /api/customers - Fetch all customers.
  • POST /api/customers - Create a new customer.
  • GET /api/customers/{id} - Get a single customer.
  • PUT /api/customers/{id} - Update an existing customer.
  • DELETE /api/customers/{id} - Delete a customer.
  • For create and update customer details use below JSON format send in POST/PUT request.

    {

        "name" : "John Doe",

        "gender": "Male",

        "date_of_birth": "2000-01-01",

        "email": "john@deo.com",

        "notes": "Test comment"

    }

    Creating a REST API in Laravel 11 is straightforward, thanks to its powerful built-in features. This guide covered the basics of setting up a Laravel project, configuring the database, creating models, controllers, and defining API routes. With this foundation, you can extend your API by adding more features like authentication, validation, and error handling.

    For the complete source code of this project, you can visit the GitHub repository: Laravel API CRUD.

    Tuesday, January 1, 2019

    Create zebra language code in php

    Zebra Programming Language (ZPL) is a page description language from Zebra Technologies, which is used for label printing. It is a command based language used by the printer as instructions for creating the images printed on the labels. Zebra language commands always start with a caret sign (^) Currently, many command exits for new version of ZPL II. In this language each format has to start with the command `^XA` and end with `^XZ` which is ANSI BASIC oriented.
    So when you are working with printing application in PHP or some label printing than must use ZPL code to send to zebra printer. For FedEx, USPS, DHL and other other courier services use ZPL language for own label printing software. So when you want to work with label printing for eCommerce use than must need ZPL code for the printer.
    Here you can write direct text to ZPL using start with `^XA` & end with `^XZ`. Here below example to create ZPL language from image.
    For that create `Image.php` file as below
    
    class Image
    {
        protected $width;
        protected $height;
        public function __construct($image)
        {
            if (!$this->isGdResource($image)) {
                throw new InvalidArgumentException('Invalid resource');
            }
            if (!imageistruecolor($image)) {
                imagepalettetotruecolor($image);
            }
            imagefilter($image, IMG_FILTER_GRAYSCALE);
            $this->image = $image;
            $this->width = imagesx($this->image);
            $this->height = imagesy($this->image);
        }
        public function __destruct()
        {
            imagedestroy($this->image);
        }
        public function isGdResource($image)
        {
            if (is_resource($image)) {
                return get_resource_type($image) === 'gd';
            }
            return false;
        }
        public function width()
        {
            return (int)ceil($this->width / 8);
        }
        public function height()
        {
            return $this->height;
        }
        public function toAscii()
        {
            return $this->encoded ?: $this->encoded = $this->encode();
        }
        protected function encode()
        {
            $bitmap = null;
            $lastRow = null;
            for ($y = 0; $y < $this->height; $y++) {
                $bits = null;
                for ($x = 0; $x < $this->width; $x++) {
                    $bits .= (imagecolorat($this->image, $x, $y) & 0xFF) < 127 ? 1 : 0;
                }
                $bytes = str_split($bits, 8);
                $bytes[] = str_pad(array_pop($bytes), 8, '0');
                $row = null;
                foreach ($bytes as $byte) {
                    $row .= sprintf('%02X', bindec($byte));
                }
                $bitmap .= $this->compress($row, $lastRow);
                $lastRow = $row;
            }
            return $bitmap;
        }
        protected function compress(string $row, ?string $lastRow): string
        {
            if ($row === $lastRow) {
                return ':';
            }
            $row = $this->compressTrailingZerosOrOnes($row);
            $row = $this->compressRepeatingCharacters($row);
            return $row;
        }
        protected function compressTrailingZerosOrOnes(string $row): string
        {
            return preg_replace(['/0+$/', '/F+$/'], [',', '!'], $row);
        }
        protected function compressRepeatingCharacters(string $row): string
        {
            $callback = function ($matches) {
                $original = $matches[0];
                $repeat = strlen($original);
                $count = null;
                if ($repeat > 400) {
                    $count .= str_repeat('z', floor($repeat / 400));
                    $repeat %= 400;
                }
                if ($repeat > 19) {
                    $count .= chr(ord('f') + floor($repeat / 20));
                    $repeat %= 20;
                }
                if ($repeat > 0) {
                    $count .= chr(ord('F') + $repeat);
                }
                return $count . substr($original, 1, 1);
            };
            return preg_replace_callback('/(.)(\1{2,})/', $callback, $row);
        }
    }
    

    Now create `Builder.php` file from convert image to zpl as below
    
    class Builder
    {
        protected $zpl = [];
        public function command()
        {
            $parameters = func_get_args();
            $command = strtoupper(array_shift($parameters));
            $parameters = array_map([$this, 'parameter'], $parameters);
            $this->zpl[] = '^' . $command . implode(',', $parameters);
            return $this;
        }
        protected function parameter($parameter)
        {
            if (is_bool($parameter)) {
                return $parameter ? 'Y' : 'N';
            }
            return $parameter;
        }
        public function __call($method, $arguments)
        {
            array_unshift($arguments, $method);
            return call_user_func_array([$this, 'command'], $arguments);
        }
        public function gf()
        {
            $arguments = func_get_args();
            if (func_num_args() === 1 && ($image = $arguments[0])) {
                $bytesPerRow = $image->width();
                $byteCount = $fieldCount = $bytesPerRow * $image->height();
                return $this->command('GF', 'A', $byteCount, $fieldCount, $bytesPerRow, $image->toAscii());
            }
            array_unshift($arguments, 'GF');
            return call_user_func_array([$this, 'command'], $arguments);
        }
        public function toZpl($newlines = false, $top = null, $shift = null)
        {
            $start = '^XA';
            if($top) {
                $start .= '^LT'.$top;
            }
            if($shift) {
                $start .= '^LS'.$shift;
            }
            return implode($newlines ? "\n" : '', array_merge([$start], $this->zpl, ['^XZ']));
        }
        public function __toString()
        {
            return $this->toZpl();
        }
    }
    

    After create below files convert your image file to zpl code by including both files as below.
    
    include 'Image.php';
    include 'Builder.php';
    $image = new Image(imagecreatefrompng('test.png')); //You can also use imagecreatefromjpeg for jpg image
    $zpl = new Builder();
    echo $zpl->gf($image)->toZpl(false, 10, -10); // toZpl(Newline, Top Margin, Left Shift)
    

    Install Radis Server on Windows (WAMP Server)


    Radius (Remote Dictionary Server) is an open-source advanced key-value database storage system like NoSQL. Redis supports different kinds of abstract data structures, such as strings, lists, maps, sets, sorted sets, bitmaps and spatial indexes. radius is used for caching to speed up a web application.
    If you want to install radios on Linux system than it's easy to install using command line and configure auto in any programming language. when you want to install in window server than manually make some changes for works perfectly.
    Process below steps for installing & work redis on a window server.
    • Download redis setup file for window (32bit & 64bit) here. (You can also download files from here)
    • Install/Put redis in any location you want.
    • Run `redis-server.exe` file from instillation files for start radis server.
    • Now check your php version by running phpinfo(); command in any file.
    • Find redis version match your PHP version from PECL package here.
    • Download radis as php extension according to radis version from https://pecl.php.net/package/redis/RADISVERSION(from below point)/windows. (Ex. https://pecl.php.net/package/redis/4.1.1/windows)
    • Here download DLL files list accoring to your PHP version and Thread Safe / Non Thread Safe.
    • Copy the `php_redis.dll` and paste to following folder in Wamp Server `wamp\bin\php\phpVERSION\ext\`.
    • Open php.ini file add redis extension to extensions list as below `extension=php_redis.dll`
    • Restart wamp server & check phpinfo() which shows redis to confirm radis install successfully.
    • Here you can check radis using php code as below.
      
      try {
          $redis = new Redis();
          $redis->connect('localhost', 6379); //connect redis server
          $redis->set('variable', 'Redis Test'); //save data in server
          $redis->get('variable');  //get data from server
      } catch (Exception $e) {
          echo $e->getMessage();
      }
      
      
    • Here for radis connection you must open redis-server.exe file which installed first(don't close radis server window).

    Tuesday, May 10, 2016

    Install ElasticSearch on Window(wamp) Server

    Elasticsearch is an open-source search server based on Lucene. It provides a broadly-distributed, readily-scalable, multitenant-capable full-text search engine with an HTTP web interface as JSON schema documents. Elasticsearch can power extremely fast searches that support your data discovery applications.
    ElasticSearch  is mostly use for searching functionality implementation first it's store huge data as local storage and than after give data according to our search as JSON format.It's easy to use so mostly people use this for faster search functionality.
    For installation of ElasticSearch with PHP based application than it's some complicated for installation in window server. Here describe simple and basic steps of the installation process of ElasticSearch.
    • First download ElasticSearch latest version from Here
    • Than after download Zip or Tar file package.
    • First check in your system java is installed or not.for that open cmd and write `java -version` that display version if installed.
    • If not installed than find latest version of Java from Here and install into your system.
    • Set new "Environment Variables" path as 'JAVA_HOME' and path 'C:\Program Files\Java\jre1.8.0_77' (Where you install java).
    • Extract all files of ElasticSearch downloaded from site to system drive.
    • Now open 'elasticsearch.bat' file in 'C:\elasticsearch-2.3.2\bin\' directory.
    • If there is any error than it's display otherwise it's execute all process. 
    • After complete all process don't close it.Now open http://localhost:9200
    • It's display  ElasticSearch information.
    For use ElasticSearch in PHP based application download from Here and follow steps describe there and also describe basic exampled for how to use.Install elastic search in PHP through Composer.
    If you want to install  ElasticSearch on live server than follow Here.and must set `elasticsearch.yml` file(in C:\elasticsearch-2.3.2\config\ folder) variable according to server.

    Tuesday, March 8, 2016

    Install Laravel Framework on WAMP(Windows) Server

    Laravel is a free, open-source PHP framework created by Taylor Otwell on June 2011.It's use for developing web application based on Model View Controller (MVC) patten.There are many others PHP based frameworks likes Codeigniter, Symfony, Yii and many more but Laravel is most famous and used framework on 2015.It's easy for this framework install in linux server.
    Here describe some basic steps for install laravel on window (WAMP) server and configure that.follow below steps for that.
    • Download Laravel latest version form Github (Check your PHP version configuration for that).
    • Extract all directory and files in your WWW folder on WAMP.
    • Enable OpenSSLfrom Wamp icon->PHP->Php extensions `php_openssl` and Wamp icon->Apache->Apache modules `ssl_module`
    • You can also enable ssl from php.ini file in `C:\wamp\bin\php\{PHPVersion}\` and apache `C:\wamp\bin\apache\{ApacheVersion}\bin`find `;extension=php_openssl.dll` and remove preceding semicolon (if there is).
    • Download Composer exe file setup from Here.
    • Run setup file and click on next (Select Shell Menus option).
    • Than enter `php.exe` file location path as  `C:\wamp\bin\php\{PHPVersion}\php.exe`.
    • Open CMD(Command Line Interface) window using  Ctrl+R and enter 'cmd'.
    • Enter directory where you install Laravel using CD command `C:\wamp\www\laravel`
    • Now run below code in cmd window.
      composer create-project laravel/laravel NEWPROJECT --prefer-dist
    • This will install Laravel in a sub directory named NEWPROJECT under current working directory.
    Most of common error display in Laravel 5 is 'Failed opening required bootstrap/../vendor/autoload.php'.
    This error display when Laravel dependency not installed properly. that time delete all data in newly created directory 'NEWPROJECT ' and open cmd navigate to Laravel directory and run below command.
    composer create-project laravel/laravel NEWPROJECT

    Saturday, February 6, 2016

    Rename all Files in Folder According to Date in PHP


    In any operating System like window, ios or Linux does not support same name files in the same directory so when you try to copy other files with same name it's overwrite or rename new file according to operating system functionality.
    Now when you collect many pictures or documents in any specific folder for the long term then you may fetch this problem many times and for that you want to find some solution like separate each file name according to date modify or created. so it's easy to do this using PHP language.
    In PHP for get all files in directory use `readdir()` function.get all files list in some specify directory as below.

    if ($handle = opendir('.')) { //Here list directory and files of present folder
        while (false !== ($entry = readdir($handle))) {
            if ($entry != "." && $entry != "..") {
              echo $entry; 
     }
        }
        closedir($handle);
    }

    Here below you can insert folder path in `opendir()`.for example if you want to get all list from 'News/Info/' directory than enter `opendir('News/Info/')`.Here below display list of all files.now you want date of file for that use `filemtime()` function as below.

    if ($handle = opendir('.')) { //Here list directory and files of present folder
        while (false !== ($entry = readdir($handle))) {
            if ($entry != "." && $entry != "..") {
              echo filemtime($entry); //Here if file in any folder than must put folder name like filemtime('News/Info/'.$entry) 
     }
        }
        closedir($handle);
    }

    Now you want to rename all listed file according to file time.Note that here below time display as timestamp so you must convert to date time.and for rename any file you must know file extension for that `pathinfo()` function use.so complete code for rename all files according to file date as below.

    if ($handle = opendir('.')) {
        while (false !== ($entry = readdir($handle))) {
            if ($entry != "." && $entry != "..") {
             $filedate = date('d-M-Y H-i-s',filemtime($entry));
             $extension = pathinfo($entry, PATHINFO_EXTENSION);
      rename($entry,$filedate.'.'.$extension); //If here file is not in code directory than must enter folder name like rename('News/Info/'.$entry,'News/Info/'.$filedate.'.'.$extension); 
     }
        }
        closedir($handle);
    }

    Here from below date function you can convert file name like `06-Feb-2016 08-10-12` for using PHP date function you can change this format also.

    Saturday, June 27, 2015

    Add or Remove Table Rows Using jQuery

    When you create any dynamic HTML website than in website must save records. For that you use HTML tables for display records from database or from some array variable. Sometimes in table row data should be added dynamically by input text without no limit and not sure about how much row add or remove. That time you can use buttons to add and remove rows. For that see below code to add and remove table rows using jQuery.
    For implement that code or integrate to any table first create HTML table with basic table tags.
    
    <table cellpadding="1" id="tabledata" cellspacing="1" width="100%" border="1">
    <thead>
    <tr>
        <th>NO</th>
        <th>NAME</th>
        <th>EMAIL</th>
        <th>REMOVE</th>
    </tr>
    </thead>
    <tbody>
    <tr>
        <td align="center">1</td>
        <td align="center"><input type="text" /></td>
        <td align="center"><input type="email" /></td>
        <td align="center"><input type="button" class="removebutton" value="REMOVE" /></td>
    </tr>
    </tbody>
    <tfoot>
    <tr>
        <td colspan="4" align="right"><input type="button" class="addnewbutton" value="ADD NEW" /></td>
    </tr>
    </tfoot>
    </table>
     
    Now you want to set add and remove row data by click on `Add New` and `Remove` button, then use jQuery for that put live latest jQuery link from https://jquery.com/download on your page as below.
    
    <script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
     

    Add new table row using jQuery

    For an added new row with name and email id input text when click on add a new button on above table, then adds jQuery event as script on `Add New` button click. for that assign class `addnewbutton` for that button as above table and script as below.
    
    <script>
    $(document).on('click', '.addnewbutton', function (){ //Add new row below Add New button row
    $(this).closest('tr').before('<tr>'+
        '<td align="center">1</td>'+
        '<td align="center"><input type="text" /></td>'+
        '<td align="center"><input type="email" /></td>'+
        '<td align="center"><input type="button" class="removebutton" value="REMOVE" /></td>'+
        '</tr>');
         return false;
     });
    </script>
    

    Add row with number

    Here for adding new row you want to also add an auto increment number for count total records than using jQuery find total table rows and then add an extra row of that table according to the next increment number. For that add `tabledata`as table id as above table and script as below.
    
    <script>
    $(document).on('click', '.addnewbutton', function (){
    var totaltr = ($("#tabledata").find('tr').length) - 2; //For calculation of data row after remove table head and footer
    $(this).closest('tr').before('<tr>'+
        '<td align="center">'+(totaltr + 1)+'</td>'+ //Add next increment value for new row
        '<td align="center"><input type="text" /></td>'+
        '<td align="center"><input type="email" /></td>'+
        '<td align="center"><input type="button" class="removebutton" value="REMOVE" /></td>'+
        '</tr>');
         return false;
     });
    </script>
     

    Remove table row using jQuery

    For removing any row and its data when click on remove button in a table than add jQuery remove function use. For that create new class `removebutton` for each new Remove button and remove table row script as below.
    
    <script>
      $(document).on('click', '.removebutton', function (){
          $(this).closest('tr').remove();
     });
    </script>
    

    Thursday, June 4, 2015

    Solve Unknown collation: 'utf8mb4_unicode_ci' Error in Wordpress

    If you use Wordpress for Blog/Website or are you Wordpress developer than must know import and export database for upload website on live or move website from one server to another server.
    If you want to change Wordpress website server live to local or move website than another server than first export old Wordpress database and than upload it to new server than sometimes you fetch below error in cpanel phpMyAdmin.

    #1273 - Unknown collation: 'utf8mb4_unicode_ci'

    This error because of change php version if php version is higher than 5.5 than it save all database as 'utf8mb4_unicode_ci' and that database import to lower version of cpanel than it's display below error. Solve that error just exporting database according to below step for import it on lower version of PHP.

    1) Select database of phpmyadmin.
    2) Click on 'Export' tab on database.
    3) Select `Custom` Export Method.
    4) Select tables from list of all database tables for export.
    5) Select `Format-specific options`->'Database system or older MySQL server to maximize output compatibility with' MYSQL40 instead of NONE.
    6) Click on GO button at bottom for export.
    7) Save exporting database.

    Now import new exporting database to new server it's install successfully.Here from below step 5th step is most important and compulsory for solve 'Unknown collation' error.

    Saturday, May 9, 2015

    Custom integration of Google Translate in website

    If you are developer or site owner and want to create multi language website using google translate than must add google translate toolbar easily from your google account Website Translator.Google provide you source code for your website just copy and past it to your website according to your setting that you set while create translate toolbar from Google Account.See complete steps.
    When you want to add google translate with custom option like as check box,radio button,drop down or listing event for change language than need to old translate code as below.
    Add translate script at head of website
     
    <script src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit" type="text/javascript">
     
    Set new translate element for define translate languages.
     
    <script>
    function googleTranslateElementInit() {
          new google.translate.TranslateElement({ includedLanguages: 'en,ar,hi,fr', layout: google.translate.TranslateElement.InlineLayout.SIMPLE}, 'google_translate_element');
    }
    </script>
    
    
    Here in  'includedLanguages' set all languages code that you want to translate here include only 4 languages.
    Create list for change language with onclick event.

    
    <li><a onclick="return ChnageLang('ar')" title="ar">العربية -  Arabic</a></li>
    <li><a onclick="return ChnageLang('')" title="ar">English  -  English</a></li>
    <li><a onclick="return ChnageLang('fr')" title="ar">Français  -  French</a></li>
    <li><a onclick="return ChnageLang('hi')" title="ar">हिंदी  -  Hindi</a></li> 
     
    Here create new 'ChnageLang' event when click on below list for change language.
     
    <script>
          function ChnageLang(value){
           createCookie('googtrans','/auto/'+value,1,'');
          }
          function createCookie(name, value, days, domain) {
             var date = new Date();
             date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
             var expires = "; expires=" + date.toGMTString();
             document.cookie = name + "=" + value + expires + "; domain=" + domain + "; path=/"';
          } 
    </script>

    Thursday, March 5, 2015

    Install Imagick on WAMP Server

    Imagick is one type of library for image customization in PHP its use is same as GD library, but provides better results and more functionality.
    When you want to work with Imagick functions in localhost than must be installed Imagick library in your WAMP server. Here is a simple way for installing Imagick libraries on a WAMP server.

    1. Download Imagick DLL files according to your system. 
    2. In that folder copy `php_imagick.dll` file, and move it you PHP extension folder like C:\wamp\bin\php\php5.5.12\ext 
    3. The other DLL's  which are starting with CORE_RL_* moved into Apache's binary folder like C:\wamp\bin\apache\apache2.4.9\bin 
    4. Now change php.ini file for add extension in list as below (You can check with phpinfo() for find php.ini file path) `extension=php_imagick.dll`
    5. Restart WAMP server and check Imagick from phpinfo() as below.

    Wednesday, February 11, 2015

    Use of at sign (@) in PHP

    In PHP sometimes you seen @ sign in your code or some CMS or e-commerce coding than first time see that sign every one thought common question is what is use of that symbol in PHP?
    Generally @ symbol use for email and when you see that in PHP coding without email than you Surprised is that use in code?Yes, this is use in PHP.This is called error control operator.It is error suppression operator in PHP.

    What is use of @ symbol ?

    In PHP at sign is use for stop any error or run code without display an error than just put @ sign in code before any PHP function.
    Generally for Database connect every one use `mysql_connect()` function but when you use PHP version higher than 5.4 than it's display error even if you enter complate connection data with username and password than just put @ at the start of mysql_connect function like `@mysql_connect()` that connection make complete.
    You can use @ symbol  some other functions also like `move_uploaded_files`,`get_file_contents`,`file_get_contents`,`file`,`include`,etc..

    Please note than @ sign make your page slower and this only stop E_NOTICE errors not stop E_WARNING and E_ERROR types errors.

    Friday, February 6, 2015

    Get User Location Using PHP

    In php many times need to know register user or some visitor location for some functionality improvement in website like if you want to access your website only from USA country than must know visitor is from which country and than display and message or restriction page.so there are two way for fetch current user location which is common or only two way for getting location. one is from IP Address and second from latitude and longitude here discuss how get address,city,country of current user.

    Get Current Address From IP

    If you get user location from IP address than there are many websites provide API for that. Here http://www.geoplugin.net/ is one of best and most use for provide that services in that only pass IP address and you got all related information about location below describe PHP code.
    $ip = $_SERVER['REMOTE_ADDR']; //for get currunt IP
    $unarr= @file_get_contents('http://www.geoplugin.net/php.gp?ip='.$ip);   
    $AddArr = unserialize($unarr); //get all variable.
    
    From below code you got many parameters related to address and find your needed from them.This method only work on live server because IP address not fetch for localhost.

    Get Current Address From Latitude and Longitude

    If you want to get address from latitude and longitude that this method is useful in this also pass latitude and longitude variable and you got complete address.PHP code for that describe as below.Here also use JavaScript for get current latitude and longitude.
    < script type="text/javascript" >
        function onPositionUpdate(position)
        {
           var latitude = position.coords.latitude;   //get latitude variable
           var longitude = position.coords.longitude; //get longitude variable
           document.cookie = "latitude ="+lat+";path=/";
           document.cookie = "longitude ="+lng+";path=/"; //save in COOKIE
        }
        if(navigator.geolocation){navigator.geolocation.watchPosition(onPositionUpdate);}
        else{alert("navigator.geolocation is not available");}
    < /script >
    
    //PHP code for getting address
    $json = @file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?latlng='.trim($_COOKIE['latitude']).','.trim($_COOKIE['longitude']).'&sensor=false');
    $data= json_decode($json);
    $status = $data->status;
    if($status=="OK"){echo $data->results[0]->formatted_address}//display complete address
    
    Here using below code you return difference address variable in `$data` so use that according to your use.