Технические | Заметки https://t-jo.com малого бизнеса Sun, 30 Jun 2024 23:51:51 +0000 ru-RU hourly 1 https://wordpress.org/?v=6.8.1 Symfony VS Laravel https://t-jo.com/symfony-vs-laravel.html https://t-jo.com/symfony-vs-laravel.html#respond Sun, 02 Jun 2024 06:06:16 +0000 https://t-jo.com/?p=5762 table { width: 100%; border-collapse: collapse; } table, th, td { border: 1px solid #ccc; } th, td { padding: 10px; text-align: left; } th { background-color: #f2f2f2; color: gray; }

Laravel vs Symfony Comparison

Framework Features Comparison

Laravel 11 Symfony 7 Description
Artisan Symfony Console Command-line tools for managing the application, running migrations, generating code, etc.
Tinker Symfony REPL (PsySH) Interactive shell for working with the application from the command line.
Eloquent Doctrine ORM ORM (Object-Relational Mapping) for database interaction.
Facade DB Doctrine DBAL Interface for low-level database operations, below the ORM level.
Laravel Mix (uses npx) Webpack Encore Tools for compiling and managing frontend resources such as CSS and JavaScript.
Blade Twig Templating engines for generating HTML on the server side.
Laravel Scout Elasticsearch (via package) Tools for full-text search, integrating with Elasticsearch and other search systems.
Laravel Socialite HWIOAuthBundle Packages for integrating OAuth social authorizations.
Laravel Passport LexikJWTAuthenticationBundle API authentication implementations using tokens.
Laravel Horizon Symfony Messenger Tools for managing job queues and background processes.

Additional Features Comparison

Laravel 11 Symfony 7 Description
Paginate in Eloquent Pagerfanta or KnpPaginator Pagination of data, implemented in ORM or through third-party bundles.
Laravel Fortify (supports 2FA) SchebTwoFactorBundle Solutions for two-factor authentication (2FA) in web applications.
Laravel Sanctum LexikJWTAuthenticationBundle Solutions for API and SPA authentication, providing tokens and handling session states.

Directory Structure Comparison: Laravel vs Symfony

Laravel 11 Symfony 7 Description
/app /src Main application code, including controllers, models, and other classes.
/app/Http /src/Controller Controllers that manage the logic of incoming requests.
/app/Models /src/Entity Models in Laravel, entities in Symfony (used with Doctrine ORM).
/resources/views /templates User interface templates. Laravel uses Blade, Symfony uses Twig.
/resources/js /assets/js JavaScript files. Symfony uses Webpack Encore for managing assets.
/resources/sass /assets/css SASS/SCSS styles for frontend.
/bootstrap /config/bootstrap.php Bootstrap scripts in Laravel. Part of configuration in Symfony.
/config /config Application configuration files.
/database/migrations /migrations Database migrations.
/public /public Public root directory, the web application entry point.
/routes /config/routes Application routing definitions.
/storage /var Storage for log files, cache, and sessions.
/tests /tests Application tests.
/vendor /vendor Third-party libraries and dependencies installed via Composer.
.env .env Environment configuration file managing sensitive data and configurations.
composer.json composer.json Defines PHP dependencies and other Composer parameters.
package.json package.json Defines Node.js dependencies for frontend tools and libraries.
Laravel Command Symfony Command Description
php artisan list php bin/console list Displays all registered commands in the application.
php artisan make:model ModelName php bin/console make:entity EntityName Creates a new model in Laravel and a new entity in Symfony.
php artisan make:controller ControllerName php bin/console make:controller ControllerName Generates a new controller class in both frameworks.
php artisan make:event EventName php bin/console make:event EventName Creates a new event class in both Laravel and Symfony.
php artisan make:listener ListenerName —event=EventName php bin/console make:subscriber EventName Generates an event listener in Laravel and an event subscriber in Symfony.
php artisan migrate php bin/console doctrine:migrations:migrate Executes database migrations in both Laravel and Symfony.
php artisan serve php bin/console server:run Starts a development server for Laravel and Symfony applications.
php artisan route:list php bin/console debug:router Displays routes registered in the application for both frameworks.
php artisan cache:clear php bin/console cache:clear Clears the application cache in both Laravel and Symfony.
php artisan config:cache php bin/console cache:warmup Creates a cache file for faster configuration loading in Laravel and warms up the cache in Symfony.
php artisan queue:work php bin/console messenger:consume Starts the queue worker in Laravel and consumes messages from the message queue in Symfony.
php artisan make:middleware MiddlewareName php bin/console make:middleware MiddlewareName Generates a new middleware class in both Laravel and Symfony.
php artisan make:migration MigrationName php bin/console make:migration Creates a new database migration file in both frameworks.
php artisan db:seed php bin/console doctrine:fixtures:load Seeds the database with records in Laravel and loads data fixtures in Symfony.
php artisan tinker php bin/console psysh Provides an interactive shell for Laravel and Symfony, powered by PsySH.
php artisan optimize php bin/console cache:warmup Optimizes the framework loading in Laravel and preloads cache in Symfony.
php artisan schedule:run php bin/console scheduler:execute Runs the scheduled tasks configured in Laravel and Symfony.
]]>
https://t-jo.com/symfony-vs-laravel.html/feed 0
Managing Roles and Permissions in Laravel 11 with Spatie Permission https://t-jo.com/managing_roles_and_permissions_in_laravel_11_with_spatie_permission.html https://t-jo.com/managing_roles_and_permissions_in_laravel_11_with_spatie_permission.html#respond Fri, 15 Mar 2024 05:47:34 +0000 https://t-jo.com/?p=5743 This guide provides a straightforward approach to setting up and managing roles and permissions in Laravel 11 using the Spatie Permission package.

Step 1: Install Spatie Laravel Permission

Start by installing the package via Composer and publishing its configurations:

composer require spatie/laravel-permission
php artisan vendor:publish --provider="Spatie\Permission\PermissionServiceProvider"
php artisan migrate

Step 2: Rollback the Last Migration

If needed, you can rollback the last migration with this command:

php artisan migrate:rollback --step=1

Step 3: Re-run Migrations

If tables were deleted or require recreation, run:

php artisan migrate

Step 4: Update the User Model

Ensure the User model uses the HasRoles trait from Spatie:

<?php

namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Spatie\Permission\Traits\HasRoles;

class User extends Authenticatable
{
    use HasRoles;

    // Other model methods...
}

Step 5: Create and Run a Seeder for Roles and Permissions

Create a seeder then populate roles and permissions:

php artisan make:seeder RolesAndPermissionsSeeder
php artisan db:seed --class=RolesAndPermissionsSeeder

Here’s what your seeder might look like:

<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use App\Models\User;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;

class RolesAndPermissionsSeeder extends Seeder
{
    public function run()
    {
        // Create roles
        $roleSuperAdmin = Role::create(['name' => 'superadmin']);
        $roleAdmin = Role::create(['name' => 'admin']);
        $roleUser = Role::create(['name' => 'user']);
        // More roles setup...

        // Assign roles to users
        $userOne = User::where('email', 'j@solarneutrino.com')->first();
        if ($userOne) {
            $userOne->assignRole('superadmin');
        }

        $userTwo = User::where('email', 'user@gmail.com')->first();
        if ($userTwo) {
            $userTwo->assignRole('user');
        }
    }
}

Follow these steps to effectively manage roles and permissions in your Laravel 11 application using the Spatie Permission package.

Step 6: Auto-Assign ‘User’ Role on Registration

To automatically assign the «user» role to all newly registered users, you need to modify the registration handling method. This is usually the create method in the RegisterController.

  1. Open the RegisterController.php file, typically located in the app/Http/Controllers/Auth directory.

  2. Add the role assignment in the create method after creating a new user:

    protected function create(array $data)
    {
        $user = User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => Hash::make($data['password']),
        ]);
    
        // Assigning the "user" role
        $user->assignRole('user');
    
        return $user;
    }
    

This code snippet ensures that every new user is automatically granted the «user» role upon registration.

Step 7: Using @role and @hasrole Directives in Blade Templates

To manage content visibility based on user roles within Blade templates, Laravel’s Spatie Permission package provides two useful directives: @role and @hasrole. These directives help in rendering content conditionally based on the user’s roles.

Examples:

<!-- Display content only if the user has the "superadmin" role. Checks for any of the specified roles if multiple are provided. -->
@role('superadmin')
    <p>This text can see user from Superadmin group</p>
@endrole

<!-- Alternative way using @hasrole, strictly checks for the specified role. Used for checking a single role. -->
@hasrole('superadmin')
    <p>This text can see user from Superadmin group</p>
@endhasrole

<!-- Display content only if the user has the "user" role. Checks for any of the specified roles if multiple are provided. -->
@role('user')
    <p>This text can see user from User group</p>
@endrole

<!-- Alternative way using @hasrole, strictly checks for the specified role. Used for checking a single role. -->
@hasrole('user')
    <p>This text can see user from User group</p>
@endhasrole

Explanations:

  • @role: This directive checks if the current authenticated user has one or more specified roles. If multiple roles are passed (separated by commas), it returns true if the user has at least one of them. In the provided examples, only one role is specified, so the behavior is similar to @hasrole.
  • @hasrole: This directive strictly checks if the user has the specified role. It’s ideal for situations where you need to verify the presence of only one specific role. This directive always takes only one role at a time.

These directives are instrumental in controlling what content a user can see based on their roles, enhancing security and user experience by tailoring the UI to meet individual user permissions.

Step 8: Applying Roles to Routes or Route Groups

In Laravel 11, the structure for handling middleware has changed significantly, including the deprecation of the app/Http/Kernel.php file. Middleware can now be applied directly in the routing files such as web.php or api.php. Here’s how to set up and use Spatie Permission Middleware to restrict route access to users with specific roles.

Registering and Applying Middleware

You can register your middleware directly in the routing file. Below is a step-by-step guide on how to apply the Spatie Permission Middleware directly to your routes:

  1. Add the Middleware Namespace:

    At the beginning of your routing file (e.g., routes/web.php), add the namespace for the middleware:

    <?php
    use Spatie\Permission\Middlewares\RoleMiddleware;
    ?>
    
  2. Apply Middleware to a Route:

    Apply the middleware directly to the routes as follows:

    <?php
    use Illuminate\Support\Facades\Route;
    
    Route::middleware(['auth', 'verified', RoleMiddleware::class . ':superadmin'])
        ->get('/contact-messages', function () {
            return view('contact-messages');
        })->name('contact-messages');
    ?>
    

    Note that we pass the RoleMiddleware class with the role parameter (superadmin) directly into the middleware array.

Laravel 10, 9, …

To secure routes based on user roles, Laravel allows the application of middleware to individual routes or groups of routes. Using Spatie’s permission package, you can enforce role-based access controls effectively.

Applying Roles to a Single Route:

use Illuminate\Support\Facades\Route;

// Ensure you have registered the 'role' middleware in your old version Laravel - Kernel.php after Laravel 11 it can be seeder class or another tinker way. 
Route::get('/admin', function () {
    return view('admin.dashboard');
})->middleware('role:admin');

This route is accessible only to users who have the ‘admin’ role. If a user without this role tries to access it, they will be redirected as defined by your middleware handling.

Applying Roles to a Route Group:

use Illuminate\Support\Facades\Route;

Route::middleware(['role:admin'])->group(function () {
    Route::get('/admin/dashboard', function() {
        return view('admin.dashboard');
    });
    Route::get('/admin/settings', function() {
        return view('admin.settings');
    });
});

This group of routes is secured with the ‘admin’ role, ensuring that all routes within this group require a user to be an ‘admin’ to gain access. This method is particularly effective for sectioning parts of your application that should be restricted to users with specific roles.

Note: It’s important to ensure that your Kernel.php file is properly configured to recognize the Spatie middleware. Add the Spatie middleware to your $routeMiddleware array if it’s not already present:

protected $routeMiddleware = [
    // other middleware
    'role' => \Spatie\Permission\Middlewares\RoleMiddleware::class,
];

Following these best practices not only enhances the security of your application by ensuring proper role-based access control but also aligns with Spatie’s documentation, ensuring you are implementing features in the recommended manner.

For example:

Utilized Laravel Breeze for authentication with frontend-designed Tailwind CSS and Spatie for role-based access control. Integrated Laravel Sanctum for secure token-based API and Laravel Multidomain middleware for simpler project integration. Enhanced security by hosting the admin panel on a separate domain (admin.solarneutrino.com) and (solarneutrino.com). Implemented a contact form with functionalities for email notifications, logging via Eloquent MySQL, and Telegram alerts. Infrastructure set up on EC2, utilizing Route 53 for DNS management and AWS SES for email dispatch.

]]>
https://t-jo.com/managing_roles_and_permissions_in_laravel_11_with_spatie_permission.html/feed 0
Node.js vs Go vs Laravel: 5 Advantages in Microservices Development https://t-jo.com/node-js_vs_go_vs_laravel_in_microservices.html https://t-jo.com/node-js_vs_go_vs_laravel_in_microservices.html#respond Fri, 05 May 2023 22:28:55 +0000 https://t-jo.com/?p=5728 Microservices architecture has become a go-to strategy for building scalable, maintainable, and flexible applications. When considering this architectural pattern, choosing the right technology stack is crucial. Three popular options are Node.js, Go, and Laravel. This article explores five key advantages each of these technologies offers in microservices development.

Node.js

Node.js is a JavaScript runtime built on Chrome’s V8 JavaScript engine. It offers several advantages in microservices development:

  • Non-Blocking I/O Model: Node.js excels at handling concurrent requests due to its event-driven, non-blocking I/O model. This makes it ideal for building real-time microservices with high throughput requirements.
  • Vast Ecosystem: The Node Package Manager (NPM) is one of the largest open-source ecosystems in the world. This gives developers access to thousands of libraries and tools that can accelerate microservices development.
  • JavaScript Everywhere: Node.js allows developers to use JavaScript for both server-side and client-side programming. This streamlines development and fosters better collaboration between frontend and backend teams.
  • Scalability: Node.js is designed to be highly scalable. With features like clustering and worker threads, it can efficiently distribute incoming requests across multiple processors, making it well-suited for scaling microservices.
  • Active Community and Support: Node.js has a vibrant and active community, which means robust support and regular updates. This ensures that issues are quickly resolved and new features are frequently introduced.

Go

Go, or Golang, is a statically typed, compiled programming language designed at Google. It brings several unique benefits to microservices:

  • Concurrency Model: Go’s goroutines and channels provide a simple yet powerful concurrency model. This makes it easy to build high-performing, concurrent microservices that can handle multiple tasks simultaneously.
  • Performance: Go is known for its speed and efficiency. Being a compiled language, it offers lower latency and higher throughput, making it excellent for performance-critical microservices.
  • Built-In Tools: Go comes with a rich set of built-in tools for testing, benchmarking, and profiling. This simplifies development and helps maintain high code quality in microservices projects.
  • Static Typing and Compile-Time Safety: Go’s static typing helps catch errors at compile time, leading to more reliable and maintainable code. This is particularly beneficial in large microservices projects where preventing runtime errors is crucial.
  • Simplicity and Clean Syntax: Go is designed for simplicity, which leads to clean, readable code. This is advantageous in microservices development, where maintainability and clarity are key.

Laravel

Laravel is a PHP framework known for its elegance and developer-friendliness. It provides several advantages for microservices:

  • Expressive Syntax: Laravel’s expressive and intuitive syntax simplifies development, allowing developers to focus on business logic rather than boilerplate code.
  • Rich Ecosystem: Laravel boasts a robust ecosystem of tools and libraries, such as Eloquent ORM and Blade templating. These tools accelerate microservices development by providing solutions for common challenges.
  • Built-In Features: Laravel comes with built-in features like routing, authentication, and caching, which are essential for microservices. These features simplify the development process and enhance productivity.
  • Scalability: Despite being known for monolithic applications, Laravel can be effectively used for microservices with the help of tools like Lumen (a micro-framework by Laravel). This provides a lightweight and scalable option for microservices architecture.
  • Developer Community: Laravel has a strong and active developer community. This means ample resources, tutorials, and support, which is beneficial for developing and maintaining microservices.

Conclusion

Choosing the right technology for microservices development depends on various factors, including team expertise, performance requirements, and project complexity. Node.js excels at handling concurrent requests with its non-blocking I/O model. Go offers superior performance and a robust concurrency model. Laravel provides a rich ecosystem and developer-friendly features.

Each technology has its own strengths and is suited to different scenarios. The choice ultimately hinges on the specific needs of your microservices architecture and the preferences of your development team.

Node.js vs Laravel vs Golang

]]>
https://t-jo.com/node-js_vs_go_vs_laravel_in_microservices.html/feed 0
Curl Benefits for Web Developers https://t-jo.com/curl_benefits_for_web_developers.html https://t-jo.com/curl_benefits_for_web_developers.html#respond Sun, 30 Apr 2023 18:18:03 +0000 https://t-jo.com/?p=5717 As a Web Developer, Here Are the TOP 10 Reasons Why «curl» Is Beneficial in an SSH Console Environment:

1. API and Web Service Testing 🧪:

Curl simplifies sending requests to APIs and web services, aiding in functionality testing and troubleshooting. It supports various request types (GET, POST, PUT, DELETE) and allows for transmitting different headers and data. Curl can also display detailed request and response information, which is invaluable for debugging.

2. File Downloading 📁:

Curl can download files from web servers, useful for retrieving configuration files, images, scripts, or other data. It can resume interrupted downloads, particularly helpful when dealing with large files.

3. Task Automation 🤖:

Curl can automate various tasks like file downloads, API requests, and web service testing. Scripts created with curl can perform repetitive tasks, saving time and effort. Its integration with other tools and programming languages makes curl a powerful tool for automation.

4. Information Gathering 🕵️‍♂️:

Curl can collect information from websites by extracting HTML, text, images, or other data. It can process JSON and XML responses, which is beneficial for collecting structured data.

5. Website and Server Monitoring 🖥:

Curl can monitor websites and servers by checking site availability, tracking server response times, and monitoring changes in web pages. It can also send notifications via email or other channels if it detects issues.

6. Simulation of User Agent and IP Spoofing 🕶:

Curl allows you to simulate different user agents and spoof IP addresses, which is critical when testing how APIs and websites respond to various browsers or geographic locations. This can be particularly useful for developers working on applications that need to behave differently based on user-agent or IP-based rules.

7. Security Testing 🔐:

Curl is a valuable tool for security testing of web applications. It can be used to send crafted requests that test for vulnerabilities like SQL injections, XSS, and CSRF, thereby helping developers strengthen their security measures before deployment.

8. Handling Cookies and Sessions 🍪:

Curl can manage cookies and sessions, allowing developers to mimic stateful sessions while interacting with web services. This is essential for testing applications that require authenticated sessions or tracking user interactions across multiple requests.

9. Network Diagnostics and Troubleshooting 🌐:

Curl provides detailed network diagnostics that help in identifying connectivity issues, slow response times, and other network-related problems. This can be invaluable for optimizing application performance and ensuring high availability.

10. Support for Multiple Protocols 📡:

Besides HTTP, Curl supports a wide range of other protocols including FTP, SMTP, LDAP, and more. This makes it a versatile tool for developers who need to interact with different network services during the development and testing phases.

CheatSheet — curl commands

My LinkedIn post

]]>
https://t-jo.com/curl_benefits_for_web_developers.html/feed 0
Switching to mpm_event and HTTP/2 with php-fpm in Ubuntu https://t-jo.com/switching-to-mpm_event-and-http-2-with-php-fpm-in-ubuntu.html https://t-jo.com/switching-to-mpm_event-and-http-2-with-php-fpm-in-ubuntu.html#respond Sat, 05 Feb 2022 23:30:21 +0000 https://t-jo.com/?p=5733 To use mpm_event and support HTTP/2, you should disable all versions of PHP that rely on mpm_prefork. Then, you can configure php-fpm for each version of PHP you want to use.

Steps

  1. Disable all versions of PHP using mpm_prefork:

    Find out which PHP versions are active:

    apache2ctl -M | grep php

    Then disable them:

    sudo a2dismod php7.4
    sudo a2dismod php8.0
    sudo a2dismod php8.2
  2. Disable mpm_prefork and enable mpm_event:

    Disable mpm_prefork:

    sudo a2dismod mpm_prefork

    Enable mpm_event:

    sudo a2enmod mpm_event
  3. Enable php-fpm for each version:

    Install php-fpm for each version:

    sudo apt-get install php7.4-fpm
    sudo apt-get install php8.0-fpm
    sudo apt-get install php8.2-fpm

    Enable proxy_fcgi and setenvif:

    sudo a2enmod proxy_fcgi setenvif

    Enable php-fpm configurations:

    sudo a2enconf php7.4-fpm
    sudo a2enconf php8.0-fpm
    sudo a2enconf php8.2-fpm
  4. Configure virtual hosts to use php-fpm:

    In each virtual host, replace SetHandler with:

    <FilesMatch \\.php$>
        SetHandler "proxy:unix:/run/php/php7.4-fpm.sock|fcgi://localhost/"
    </FilesMatch>

    Change php7.4 to the corresponding version for each host.

  5. Restart Apache:

    sudo systemctl restart apache2

Conclusion

Now, your virtual hosts are configured to use php-fpm and support the HTTP/2 protocol.

]]>
https://t-jo.com/switching-to-mpm_event-and-http-2-with-php-fpm-in-ubuntu.html/feed 0
PHP распечатать любой массив в режиме короткий синтаксис и microtime с array_walk_recursive или php print short array syntax square https://t-jo.com/php-print-short-array-syntax-square.html https://t-jo.com/php-print-short-array-syntax-square.html#respond Fri, 02 Apr 2021 14:59:07 +0000 https://t-jo.com/?p=5611 Порой можно привести значению любого массива к нужному виду запустив рекурсивно по его значениям прописанную функцию с помощь array_walk_recursive


array_walk_recursive(
  $productsPrices,
  function( & amp; $value) {
    $value = $value / 0.85;
    $value = round($value + $value / 10, 0, PHP_ROUND_HALF_UP);
  }
);

$results = varexport($myArray, true);

Но запустив функцию микротайм можно увидеть, что данный рекурс съедает время, а порой для оптимизации это критично


$time_start = microtime(true);
$results = varexport($myArray, true);
$time_end = microtime(true);
$time = $time_end - $time_start;

Тогда приходит в голову логичная мысль, тупо распечатать этот преобразованный массив в простом виде и его так и впиндюлить в код, ну если его значения «константы» в человеческом смысле, а не программном, предположим цена продуктов.
Можно все это сделать с помощью вот этой подготовленной функции.


function varexport($expression, $return = FALSE) {
  $export = var_export($expression, TRUE);
  $export = preg_replace("/^([ ]*)(.*)/m", '$1$1$2', $export);
  $array = preg_split("/\r\n|\n|\r/", $export);
  $array = preg_replace(["/\s*array\s\($/", "/\)(,)?$/", "/\s=>\s$/"], [NULL, ']$1', ' => ['], $array);
  $export = join(PHP_EOL, array_filter(["["] + $array));
  if ((bool) $return) return $export;
  else echo $export;
}

$results2 = varexport($hidPrices, true);

 

]]>
https://t-jo.com/php-print-short-array-syntax-square.html/feed 0
Xdebug and PHPStorm remote debugging by EC2 instance on AWS with Load Balancer – Linux Server Ubuntu and Git https://t-jo.com/xdebug-and-phpstorm-remote-debugging-by-ec2-instance-on-aws-with-load-balancer-linux-server-ubuntu-and-git.html https://t-jo.com/xdebug-and-phpstorm-remote-debugging-by-ec2-instance-on-aws-with-load-balancer-linux-server-ubuntu-and-git.html#respond Thu, 12 Nov 2020 16:20:30 +0000 https://t-jo.com/?p=5606 This is short Note for Laravel framework get goal with this configuration — Xdebug by EC2 instance on AWS with Load Balancer – Linux Server Ubuntu with Apache and Git

You should do settings only one server before Amazon Load Balancer and open and redirect any queries from local machine to EC2 server IP address.

  • Redirect any queries your domain name from your local PC to IP — ONE EC2 instance with installed xdebug (USE SSH and your hosts file in local OS)
  • Install xdebug on your server and configuration it in config file and .htaccess file do separate settings individual specific domain
  • PHPStorm must have true settings with remote to this remote server use ssh tunnel with folders mapping your local machine
  • Don’t forgot about your Git on local PC must be same as your remote server every time! It’s well strategy for debugging without exception on Laravel and watch your backend scope!!!

 

 

Mini notes for this short instruction:

 

$ php -v

Console command does show info about your operation system, php version and xdubug module on your server if you don’t have xdebug than

 

$ apt-get install blah-blah or yum and etc (I mean xdebug)

Standard install xdebug module

 

You need configuration xdebug server in files for ubuntu by path /etc/php/7.2/mods-available/xdebug.ini You should remember only one line — We are disable remote mode for any domains — xdebug.remote_enable = 0 and comment ;xdebug.remote_connect_back = 1 or mast have 0

Another lines you do any want

Example:

zend_extension=/usr/lib/php/20170718/xdebug.so

xdebug.remote_enable = 0

;xdebug.remote_connect_back = 1

xdebug.remote_host = 127.0.0.1

xdebug.remote_port = 9000

;xdebug.remote_handler = dbgp

;xdebug.remote_mode = req

;xdebug.profiler_enable=0

;xdebug.profiler_enable_trigger=1

xdebug.remote_autostart=1

xdebug.idekey=PHPSTORM

xdebug.remote_log=»/var/log/xdebug/xdebug.log»

 

.htaccess main directory for your domain where you need debug must add option with enable remote mode. I mean must have — php_flag  xdebug.remote_enable on

## Enable .htaccess!!!

php_flag  xdebug.remote_enable on

#php_value xdebug.remote_host «your_ip_without_quotes»

#php_value xdebug.remote_port 9000

#php_value xdebug.idekey PHPSTORM

php_flag  xdebug.remote_autostart on

 

 

AND YOU MUST TURN your local xdebug port 9000 to remote server xdebug port 9000 from local console

I use MacOS then I had done this command:

ssh -R 9000:localhost:9000 j@t-jo.com

or if you use ssh key

ssh -R 9000:localhost:9000  -vv -i ~/.ssh/id_rsa_myssh my-login@my-domain.com

 

PHPStorm good video instruction with setting remote ssh and mapping folders

]]>
https://t-jo.com/xdebug-and-phpstorm-remote-debugging-by-ec2-instance-on-aws-with-load-balancer-linux-server-ubuntu-and-git.html/feed 0
Как установить node.js на ISPManager с защитой Nginx? https://t-jo.com/kak-ustanovit-node-js-na-ispmanager-s-zashhitoj-nginx.html https://t-jo.com/kak-ustanovit-node-js-na-ispmanager-s-zashhitoj-nginx.html#respond Mon, 03 Feb 2020 15:28:06 +0000 https://t-jo.com/?p=4280 Собственно к чему вся эта статья написана? Я занимаюсь профессиональной поддержкой данного стека и разработкой скриптов в данном направлении, поэтому если Вам требуется, что-то сделать и Ваша команда не может разобраться с поставленной задачей, то пожалуйста, обращайтесь. joker@t-jo.com

Прошло не мало времени, прежде чем я добился вменяемых результатов по интеграции nodejs на Linux сервер с панелью управления для веб сайтов ISPManager.
После данной установки появилась возможность интегрировать другие интернет приложения на базе Ноды.

На первый взгляд казалось пустяковое дело сделать такую интеграцию, а слюни так текли, так как тут отлично крутяться на этой панели много сайтов на самых разных CMS: Битрикс, Webasyst Shop-Script, Magento, Drupal, WordPress, CS-Cart, OpenCart, PrestaShop с абсолютно разными базами данных MySQL, PostgreSQL, MongoDB. Очен нужно было интегрировать это решение плюс потому что таким образом я получил отличную бэкап систему на базе ISPManager панели и мне не нужно было поднимать дополнительный сервер или VDS/VPS под ноду.

Сэкономил денег и получил рабочее решение.
Вот Вам пример сайта на NODE.JS сделанного на Express модуле, но можно сделать и любой другой, если попросите.
https://nodejs.t-jo.com/

В тонкости всех настроек и проблем при установке я вдаваться не буду, но если попытаетесь такое сделать и после первой недели у Вас начнут опускаться руки, так как будут всплывать непредвиденные проблемы, то обращайтесь. Я и моя команда специалистов Вам поможем сэкономить кучу времени.

]]>
https://t-jo.com/kak-ustanovit-node-js-na-ispmanager-s-zashhitoj-nginx.html/feed 0
Example PHP-FPM — Apache — Nginx(proxy) with SSL. Ubuntu EC2 AWS https://t-jo.com/example-php-fpm-apache-nginxproxy-with-ssl-ubuntu-ec2-aws.html https://t-jo.com/example-php-fpm-apache-nginxproxy-with-ssl-ubuntu-ec2-aws.html#respond Sat, 01 Jun 2019 22:33:25 +0000 https://t-jo.com/?p=5760 Setting Up PHP-FPM, Apache, and Nginx with SSL on Ubuntu

This guide will walk you through setting up a server where Nginx serves static frontend files and acts as a reverse proxy to Apache, which handles PHP requests via PHP-FPM. We’ll also configure SSL with Let’s Encrypt’s Certbot to ensure secure connections.

1. Install and Configure Nginx

Install Nginx

sudo apt update
sudo apt install nginx

Configure Nginx

Create a configuration file for your site at /etc/nginx/sites-available/site1:

<server>
    listen 80;
    server_name site1.com www.site1.com;
    root /var/www/site1/public;
    index index.html index.htm index.php;

    location / {
        proxy_pass http://localhost:8080;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

    location ~* \.(html|xml|txt|pdf|js|css|jpg|jpeg|png|gif|ico|svg|webp)$ {
        root /var/www/site1/public;
        expires 1y; # Set long-term caching for static files
        add_header Cache-Control "public, max-age=31536000, immutable";
    }

    location ~* \.php$ {
        proxy_pass http://localhost:8080;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

    error_log /var/log/nginx/site1-error.log;
    access_log /var/log/nginx/site1-access.log;

    listen 443 ssl; # SSL for HTTPS
    ssl_certificate /etc/letsencrypt/live/site1.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/site1.com/privkey.pem;
    include /etc/letsencrypt/options-ssl-nginx.conf;
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;
</server>

Activate the Site and Restart Nginx

sudo ln -s /etc/nginx/sites-available/site1 /etc/nginx/sites-enabled/
sudo systemctl restart nginx

2. Install and Configure Apache

Install Apache and PHP-FPM

sudo apt update
sudo apt install apache2 php-fpm

Configure Apache to Use PHP-FPM

Create a configuration file for your site at /etc/apache2/sites-available/site1.conf:

<VirtualHost *:8080>
    ServerName site1.com
    DocumentRoot /var/www/site1/public

    <Directory /var/www/site1/public>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>

    <FilesMatch \.php$>
        SetHandler "proxy:unix:/run/php/php8.2-fpm.sock|fcgi://localhost"
    </FilesMatch>

    ErrorLog ${APACHE_LOG_DIR}/site1-error.log
    CustomLog ${APACHE_LOG_DIR}/site1-access.log combined
</VirtualHost>

Enable Apache Configuration and Required Modules

sudo a2enmod proxy_fcgi setenvif
sudo a2enconf php8.2-fpm
sudo a2ensite site1.conf
sudo systemctl restart apache2

3. Configure PHP-FPM

Ensure PHP-FPM is Running

sudo systemctl start php8.2-fpm
sudo systemctl enable php8.2-fpm

4. Configure SSL with Let’s Encrypt Certbot

Install Certbot

sudo apt update
sudo apt install certbot python3-certbot-nginx

Obtain and Configure SSL Certificate

sudo certbot --nginx -d site1.com -d www.site1.com

Certbot will automatically update your Nginx configuration and set up SSL certificates.

5. Update Hosts File

Add your domain to the /etc/hosts file for local testing:

127.0.0.1 site1.com
127.0.0.1 www.site1.com

6. Restart Services

sudo systemctl restart nginx
sudo systemctl restart apache2

Now you have a server configured with Nginx serving static files and acting as a reverse proxy to Apache, which handles PHP requests via PHP-FPM. Nginx is configured to listen on ports 80 and 443 (SSL) with certificates managed by Let’s Encrypt, ensuring secure connections and optimized performance for static files according to Google Page Speed recommendations.

]]>
https://t-jo.com/example-php-fpm-apache-nginxproxy-with-ssl-ubuntu-ec2-aws.html/feed 0
Установка Windows 10 https://t-jo.com/ustanovka-windows-10.html https://t-jo.com/ustanovka-windows-10.html#respond Sat, 06 Aug 2016 17:58:35 +0000 http://t-jo.com/?p=233 Вы, наверное, не раз слышали про реальные истории из жизни, где жена гоняет метлой своего мужа, после того, как он поймал порно вирус на свой компьютер (ну, или что-то подобное). А если нет, то посмотрите на нашем ролике эту захватывающую историю, с проблемой про “Вирус и Windows”, которую не может решить даже мастер.
Ответьте на этот вопрос в конце истории, что Вы думаете по этому поводу.
А вот сама история –

Для того чтобы не попасть в аналогичную неловкую ситуацию, я показал Вам как правильно устанавливать ОС. Показанный метод позволит сделать переустановку один раз и не возвращаться к этому каждые полгода, год.

Для обеспечения данной безопасности нам сначала нужно понять, с чем мы боремся, а боремся мы с вирусами, которые мешают нашей жизни и тормозят нашу машину или вовсе блокируют доступ до нее с целью вымогания денег. Вирус – это всего лишь обычная программа, поэтому бороться мы будем с плохими для нас программами.
Любая программа, хорошая или плохая, имеет свой цикл существования.
— Это дистрибутив, он же установочный файл, который попадает к Вам на ПК
— В 90% случаев происходит процесс его установки – инсталляция. (Эффективнее всего бороться с вирусами именно на этом этапе.) В других 10% случаях – для запуска программы не нужна инсталляция, она запускается без установки — портейбл версия.
— В большинстве случаев, только после установки мы можем запустить программу и пользоваться ей, или она сама прописывается в автозагрузку и стартует вместе с Вашей операционной системой. Как правило, вирусные программы скачиваются и инсталлируются в скрытом от Вас режиме и прописываются в автозагрузку.

Основной фундамент Вашей безопасности – это учетная запись с ограниченными правами пользователя:

Любой вирус – это просто программа, чтобы он не установился, нужно сидеть под пользователем, который не может устанавливать программы и на нем должен быть пароль.
При этом на другом, втором пользователе с правами администратора (который МОЖЕТ устанавливать программы) должен быть установлен другой пароль.
То есть, при установке любой программы система должна запрашивать у вас пароль на установку, и таким образом вирус никогда не установится сам.

Практика, о которой сейчас расскажу, подходит к абсолютно любым линейкам ОС, будь то apple, linux или windows, но мы рассмотрим именно windows, потому что он самый популярный среди обычных людей. Уважаемые читатели и зрители нашего видеоролика, хочу сказать, что нельзя сравнивать, какая операционка лучше — линукс, айпл или виндоус – это полнейший бред, это все равно, что говорить — ложка лучше вилки. Так же и с операционными системами. Провайдеру предположим на своих узлах связи лучше использовать юниксовые системы, они более гибкие для выполнения сетевых задач, но вот с точки зрения обычного пользователя лучше будет Windows или Эйпл и тут тоже есть большие тонкости в зависимости от поставленных Вами задач и потребностей. Но это уже другая история, если вам это интересно, пишите в комментариях, и возможно мы подробно позже поговорим об этом.
Наша же задача достичь максимально правильной установки windows.
Этот материал получает красную метку, то есть данная ошибка может оказаться для Вас критичной. На компьютере сегодня хранится вся наработанная информация абсолютно любого человека, поэтому ролик будет полезен не только для людей, которые занимаются бизнесом, но и вообще для всех, кто ценит свое время и свою работу от школьника до пенсионера.

Посмотрите внимательно интеллект-карту (схему), которую я подготовил, с ней Вам будет намного проще научиться переустанавливать, устанавливать windows 10, windows 8, windows 7 так, чтобы он не ломался от вирусов.

Схема установки Windows

Так же, на видео ролике подробно показан сам процесс установки.
Для установки нам понадобится выполнить 6 пунктов, если Вы не знаете, как это сделать, пройдите по указанным ссылкам там будут видео инструкции:

  1. Определяем битность Вашего компьютера — 32 или 64
  2. Скачиваем лицензионный образ windows с сайта Microsoft подходящий под битность Вашего компьютера
  3. Делаем мультизагрузочную флешку со скаченным образом
  4. Скачиваем CCleaner
  5. Понадобится программа криптографии DisckCryptor, для установки пароля, перед загрузкой системы
  6. Ну и конечно же, антивирус. Где скачать и как установить

Процесс установки:

— Подготовка, заранее находим драйвера на сетевую карту и другие устройства.
— Заходим в биос или выбор загрузочного носителя DEL, F2, F8, F10, F12
— Сам процесс установки
Разбивание диска на С и D, на С:\ — устанавливаем систему и программы, а на D:\ — личные файлы
Создаем локальных пользователей: user с правами пользователя, под которым потом постоянно работаем, admin с правами администратора и своим уникальным паролем, который вас будет защищать от вирусов, пытающихся установиться в скрытом режиме.
Делаем автозагрузку, чтобы виндоус сам вводил пароль на пользователя user с помощью встроенной утилиты “control userpasswords2”. Она запускается через командную строку, которую вызываем Win + R.
Устанавливаем CCleaner и настраиваем его, чтобы он чистил браузеры: IE, Google chrome, Mozilla, Opera, Safari при каждой новой загрузке компьютера.
Защищаем свои диски — HDD, SSD надежной программой DisckCryptor , если компьютер украдут, то Вы можете не переживать за то, что ваша информация будет доступна третьим лицам.
Устанавливаем антивирус. Ссылку на антивирус оставил в начале и в конце ролика.

Бывает, попадаются программы написанные непрофессионалами, которым для конфигурации при такой настройке надо донастроить папку в которой лежит прога. Для этого нужно зайти в безопасность папки, где лежит программа, как правило на диске С в папке “C:\Program Files” или “ C:\Program Files (x86) ” и добавить туда пользователя под которым работаем, а далее выставить ему полные права на данную папку или подпапку, где лежит конфиг программы, то есть: чтение, запись, выполнение.
Есть еще второй подводный камень, если вы воспользовались программой криптографии Вашего диска. Не забывайте делать бекапы наработанной информации, так как диски имеют свойство ломаться и если он сломается, то восстановить информацию будет значительно сложнее, если бы он был бы не закриптографирован.

Красная меткаНу а в случае, если Вам некогда устанавливать ОС или просто лень, как вариант Вы можете обратиться к профессионалам из нашей команды, по контакту указанному видео ролике.
Там Вам расскажут о прайсе наших услуг.

]]>
https://t-jo.com/ustanovka-windows-10.html/feed 0