Category: CodeIgniter

Creating a lost mobile tracking software in PHP requires the backend to handle IMEI location tracking. Below is a practical guide with code snippets for building such a system.

Step 1: Conceptual Requirements

  1. Mobile App Integration:
    PHP alone can’t directly track a mobile device. You need an Android/iOS app that:
    • Continuously reports the device’s GPS coordinates to the server.
    • Monitors the IMEI, SIM card status, and connectivity changes.
  2. Backend Requirements:
    • A database to store location and device information.
    • RESTful APIs in PHP to handle data reporting and retrieval.

Database Schema

Create a database table for tracking device information:

CREATE TABLE device_tracker (
    id INT AUTO_INCREMENT PRIMARY KEY,
    imei VARCHAR(20) NOT NULL,
    latitude DECIMAL(9,6) NOT NULL,
    longitude DECIMAL(9,6) NOT NULL,
    status ENUM('active', 'lost') DEFAULT 'active',
    timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

API for Location Updates

This PHP script stores the device’s IMEI and location.

update_location.php

<?php
// Database connection
$host = "localhost";
$dbname = "tracker_db";
$username = "root";
$password = "";

try {
    $conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("Connection failed: " . $e->getMessage());
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $imei = $_POST['imei'];
    $latitude = $_POST['latitude'];
    $longitude = $_POST['longitude'];
    $status = $_POST['status'] ?? 'active';

    if (!empty($imei) && is_numeric($latitude) && is_numeric($longitude)) {
        $stmt = $conn->prepare("INSERT INTO device_tracker (imei, latitude, longitude, status) 
                                 VALUES (:imei, :latitude, :longitude, :status)");
        $stmt->bindParam(':imei', $imei);
        $stmt->bindParam(':latitude', $latitude);
        $stmt->bindParam(':longitude', $longitude);
        $stmt->bindParam(':status', $status);

        if ($stmt->execute()) {
            echo json_encode(["status" => "success", "message" => "Location updated."]);
        } else {
            echo json_encode(["status" => "error", "message" => "Failed to update location."]);
        }
    } else {
        echo json_encode(["status" => "error", "message" => "Invalid input."]);
    }
}
?>

API for Fetching Location

This endpoint retrieves the latest location for a given IMEI.

get_location.php

<?php
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $imei = $_GET['imei'];

    if (!empty($imei)) {
        $stmt = $conn->prepare("SELECT * FROM device_tracker WHERE imei = :imei ORDER BY timestamp DESC LIMIT 1");
        $stmt->bindParam(':imei', $imei);
        $stmt->execute();

        $location = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($location) {
            echo json_encode(["status" => "success", "location" => $location]);
        } else {
            echo json_encode(["status" => "error", "message" => "No location found."]);
        }
    } else {
        echo json_encode(["status" => "error", "message" => "IMEI is required."]);
    }
}
?>

Frontend Example for Tracking

<!DOCTYPE html>
<html>
<head>
    <title>Track Lost Mobile</title>
</head>
<body>
    <h1>Find My Phone</h1>
    <form method="GET" action="get_location.php">
        <label for="imei">Enter IMEI:</label>
        <input type="text" id="imei" name="imei" required>
        <button type="submit">Track</button>
    </form>
</body>
</html>

Security Considerations

  • Authentication: Secure APIs with API keys or JWT.
  • Data Encryption: Use HTTPS for secure communication.
  • Device App: Build a native app to report location data automatically.

Would you like help creating the mobile app or improving the security aspect?

IMEI Tracker code in php

Below is a simple example code to build an IMEI Tracker in PHP. This code assumes you’re collecting IMEI numbers and their corresponding device locations in a database.

Database Schema

Create a table device_locations:

CREATE TABLE device_locations (
    id INT AUTO_INCREMENT PRIMARY KEY,
    imei VARCHAR(20) NOT NULL,
    latitude DECIMAL(9,6) NOT NULL,
    longitude DECIMAL(9,6) NOT NULL,
    timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

PHP Script for Inserting Location

This endpoint saves location data based on the IMEI number:

<?php
// Database connection
$host = "localhost";
$dbname = "tracker_db";
$username = "root";
$password = "";

try {
    $conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("Connection failed: " . $e->getMessage());
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $imei = $_POST['imei'];
    $latitude = $_POST['latitude'];
    $longitude = $_POST['longitude'];

    if (!empty($imei) && is_numeric($latitude) && is_numeric($longitude)) {
        $stmt = $conn->prepare("INSERT INTO device_locations (imei, latitude, longitude) VALUES (:imei, :latitude, :longitude)");
        $stmt->bindParam(':imei', $imei);
        $stmt->bindParam(':latitude', $latitude);
        $stmt->bindParam(':longitude', $longitude);

        if ($stmt->execute()) {
            echo json_encode(["status" => "success", "message" => "Location saved."]);
        } else {
            echo json_encode(["status" => "error", "message" => "Failed to save location."]);
        }
    } else {
        echo json_encode(["status" => "error", "message" => "Invalid input."]);
    }
}
?>

PHP Script for Fetching Location

This endpoint retrieves the latest location for a given IMEI:

<?php
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $imei = $_GET['imei'];

    if (!empty($imei)) {
        $stmt = $conn->prepare("SELECT * FROM device_locations WHERE imei = :imei ORDER BY timestamp DESC LIMIT 1");
        $stmt->bindParam(':imei', $imei);
        $stmt->execute();

        $location = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($location) {
            echo json_encode(["status" => "success", "location" => $location]);
        } else {
            echo json_encode(["status" => "error", "message" => "No location found."]);
        }
    } else {
        echo json_encode(["status" => "error", "message" => "IMEI is required."]);
    }
}
?>

Sample Usage

Save Location (POST Request)

curl -X POST -d "imei=123456789012345&latitude=40.7128&longitude=-74.0060" http://yourserver/insert_location.php

Get Location (GET Request)

curl http://yourserver/get_location.php?imei=123456789012345

Security Note:

  • Validate and sanitize inputs to prevent SQL injection.
  • Secure the endpoints using API keys or authentication methods.
  • Use HTTPS to protect data during transmission.

To calculate custom product variation totals or prices in WooCommerce, you can use custom hooks and WooCommerce functions.

To calculate custom product variation totals or prices in WooCommerce, you can use custom hooks and WooCommerce functions. Here’s a step-by-step guide to achieve this:

1. Understanding Custom Variation Calculation

When dealing with custom calculations for product variations (e.g., based on user input, extra fields, or specific attributes), you’ll likely need to:

  • Modify the variation price dynamically.
  • Calculate totals based on selected attributes or custom fields.

2. Example: Adding Custom Variation Price Calculation

Here’s an example where we calculate a custom price for product variations:

Add a Custom Field for Input (e.g., Text Field)

You can use WooCommerce hooks to add custom fields on the product page.

Add this to your theme’s functions.php file:

// Add custom field for additional input (e.g., custom engraving)
add_action('woocommerce_before_add_to_cart_button', 'add_custom_variation_field');
function add_custom_variation_field() {
    echo '<div class="custom-variation-field">
        <label for="custom_input">Custom Text (e.g., engraving): </label>
        <input type="text" id="custom_input" name="custom_input" />
    </div>';
}

// Validate the custom field
add_filter('woocommerce_add_to_cart_validation', 'validate_custom_field', 10, 3);
function validate_custom_field($passed, $product_id, $quantity) {
    if (empty($_POST['custom_input'])) {
        wc_add_notice(__('Please enter custom text.', 'woocommerce'), 'error');
        $passed = false;
    }
    return $passed;
}

// Save the custom field to the cart
add_filter('woocommerce_add_cart_item_data', 'add_custom_field_to_cart', 10, 2);
function add_custom_field_to_cart($cart_item_data, $product_id) {
    if (!empty($_POST['custom_input'])) {
        $cart_item_data['custom_input'] = sanitize_text_field($_POST['custom_input']);
    }
    return $cart_item_data;
}

// Display custom field in the cart
add_filter('woocommerce_get_item_data', 'display_custom_field_in_cart', 10, 2);
function display_custom_field_in_cart($item_data, $cart_item) {
    if (!empty($cart_item['custom_input'])) {
        $item_data[] = array(
            'name' => __('Custom Text', 'woocommerce'),
            'value' => $cart_item['custom_input']
        );
    }
    return $item_data;
}

// Add a custom price based on the custom input
add_filter('woocommerce_before_calculate_totals', 'add_custom_price_based_on_field', 10, 1);
function add_custom_price_based_on_field($cart) {
    if (is_admin() && !defined('DOING_AJAX')) {
        return;
    }

    foreach ($cart->get_cart() as $cart_item) {
        if (!empty($cart_item['custom_input'])) {
            $custom_price = $cart_item['data']->get_price() + 10; // Example: Add $10 for custom text
            $cart_item['data']->set_price($custom_price);
        }
    }
}

3. Key Steps in the Code Above

  • Custom Field: Adds a text input field for custom input (e.g., engraving).
  • Validation: Ensures the custom field is filled before adding the item to the cart.
  • Cart Data: Saves and displays custom data in the cart.
  • Price Modification: Dynamically adjusts the product price based on custom input.

4. Advanced Customization

If you need calculations based on product attributes or complex formulas:

  • Use custom attributes: Fetch them with $product->get_attribute('attribute_name').
  • Apply custom logic for the price calculation in the woocommerce_before_calculate_totals filter.
  • Consider creating a custom plugin for modular code management.

5. Testing the Solution

  1. Add a variable product in WooCommerce.
  2. Enable the custom field logic by adding the code.
  3. Verify that the custom price is calculated and displayed correctly during checkout.

How to Image Size Reset Laravel

To reset or change an image size in Laravel, you can use the Intervention Image library. This library allows you to manipulate images, including resizing them.

Steps to Reset Image Size in Laravel

1. Install Intervention Image Package

Run the following command in your terminal to install the package:

composer require intervention/image

2. Configure the Service Provider

If you’re using Laravel 5.5 or later, the service provider and facade will be auto-discovered. Otherwise, you may need to add the following to your config/app.php file:

  • Add the service provider:
Intervention\Image\ImageServiceProvider::class,

Add the alias:

'Image' => Intervention\Image\Facades\Image::class,

Add the alias:

'Image' => Intervention\Image\Facades\Image::class,
  1. Publish Configuration (Optional)

You can publish the configuration file with this command if you need to customize settings:

php artisan vendor:publish --provider="Intervention\Image\ImageServiceProviderLaravelRecent"

4. Resize the Image

Here’s an example of how to resize or reset an image size:

Controller Example:
use Illuminate\Http\Request;
use Intervention\Image\Facades\Image;

class ImageController extends Controller
{
    public function resizeImage(Request $request)
    {
        // Validate the uploaded image
        $request->validate([
            'image' => 'required|image|mimes:jpeg,png,jpg,gif|max:2048',
        ]);

        // Get the uploaded image
        $image = $request->file('image');

        // Resize the image
        $imagePath = public_path('images/resized'); // Destination folder
        if (!file_exists($imagePath)) {
            mkdir($imagePath, 0777, true); // Create folder if not exists
        }

        $imageName = time() . '.' . $image->getClientOriginalExtension();

        // Use Intervention Image to resize
        $resizedImage = Image::make($image->getRealPath());
        $resizedImage->resize(300, 300, function ($constraint) {
            $constraint->aspectRatio(); // Maintain aspect ratio
            $constraint->upsize(); // Prevent upsizing
        });

        // Save the resized image
        $resizedImage->save($imagePath . '/' . $imageName);

        return back()->with('success', 'Image resized successfully!')->with('image', 'images/resized/' . $imageName);
    }
}

5. Create a Form to Upload Images

In your Blade view file, create a form to upload images:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Resize Image</title>
</head>
<body>
    @if(session('success'))
        <p>{{ session('success') }}</p>
        <img src="{{ asset(session('image')) }}" alt="Resized Image">
    @endif

    <form action="{{ route('resize.image') }}" method="POST" enctype="multipart/form-data">
        @csrf
        <label>Select an Image:</label>
        <input type="file" name="image">
        <button type="submit">Resize Image</button>
    </form>
</body>
</html>

6. Add a Route

Define a route in web.php:

use App\Http\Controllers\ImageController;

Route::get('resize-image', function () {
    return view('resize-image'); // Blade file name
});

Route::post('resize-image', [ImageController::class, 'resizeImage'])->name('resize.image');

7. Output

When you upload an image, it will be resized to the specified dimensions (300x300 in the above example) and saved in the public/images/resized directory.

You can adjust the size in the resize() method as needed. For example:

$resizedImage->resize(500, null, function ($constraint) {
    $constraint->aspectRatio();
});

This will resize the width to 500 pixels while maintaining the aspect ratio.

How to setup by setup laravel?

Setting up Laravel involves installing its dependencies, configuring the environment, and ensuring everything is ready for development. Here’s a step-by-step guide:

1. System Requirements

Before installing Laravel, ensure your system meets the following requirements:

  • PHP: 8.1 or later
  • Composer: Dependency manager for PHP
  • Web Server: Apache, Nginx, or Laravel’s built-in development server
  • Database: MySQL, PostgreSQL, SQLite, or SQL Server

2. Install Laravel

Step 1: Install Composer

Step 2: Install Laravel

You can install Laravel in one of two ways:

Option A: Using Laravel Installer

  1. Install Laravel globally:
composer global require laravel/installer

2. Create a new Laravel project:

3. Navigate to your project directory:

Option B: Using Composer Create-Project

  1. Create a new Laravel project:
composer create-project --prefer-dist laravel/laravel project_name

2. Navigate to your project directory:

3. Set Up the Environment

Step 1: Configure .env

  1. Open the .env file in the root of your project.
  2. Update database details:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database_name
DB_USERNAME=your_database_username
DB_PASSWORD=your_database_password

Step 2: Generate Application Key

Run the following command to set the application key:

4. Set Up a Web Server

Option A: Laravel Development Server

Run the built-in server:

  • Access your app at: http://localhost:8000.

Option B: Using XAMPP/WAMP

  1. Place your Laravel project in the htdocs folder (for XAMPP) or the appropriate folder for WAMP.
  2. Update the Apache configuration to point to the public folder of your Laravel project.

Option C: Using Nginx

  1. Configure your Nginx virtual host to point to the public folder.
  2. Example Nginx configuration:
server {
    listen 80;
    server_name yourdomain.com;
    root /path-to-your-project/public;

    index index.php index.html;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}

5. Migrate Database

If your Laravel project uses a database, migrate the database tables:

6. Install Additional Dependencies

If your project requires specific libraries, install them using Composer:

composer require package_name

7. Test the Application

Visit your Laravel application in a browser to verify everything is working:

  • Local: http://localhost:8000
  • Server: Your domain or IP address.

8. Optional: Frontend Assets

If your project uses frontend tools like Vite, run:

For production builds:

Would you like help configuring a specific feature, such as authentication, routing, or API setup?