Split file and having header kept in all generated files

head -n 1 upload_images.csv > header.csv; tail -n +2 upload_images.csv | split --numeric-suffixes=1 --additional-suffix=.csv -l 320 - --filter='sh -c "{ head -n1 header.csv; cat; } > $FILE"'
 split filename.csv --numeric-suffixes=1 --additional-suffix=.csv -l 50

Result: 50 files named as x{number}.csv

Regex keep only alphanumeric characters with unicode support

echo preg_replace("/[\W]/u", "", $str);

About Unicode

UCS-2 is old encoding standard. It uses fixed size per encoded character and therefore is not compatible with ASCII.
UTF-8 is newer standard. It uses dynamic size between 8 – 32 bits per encoded character and is compatible with ASCII.

Я так понял что UCS-2 ещё называют UNICODE т.к. каждый символ это полные 2 байта тогда как UTF-8 называют просто UTF-8 изза того что размер используемых байтов меняется динамически взависимости от кодируемого символа.

But UCS-2 is used when sending SMS text message to mobile network, so if for single English SMS message 140 chars are used, for single Russian SMS message it is 70.
If you want to send web text as SMS to mobile phone do convert from UTF-8 to UCS-2 and then send.

For example, text here is stored in UTF-8 so I have to first convert it to UNICODE and then convert to URLencoded format. Then to send it via kannel we use charset=UCS-2

$in_msg = "проверим-ка-кодировку";
print urlencode(iconv('utf-8', 'ucs-2', $in_msg));

Php check if English date time format correct

if(preg_match('/\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/',$datetime)) {
echo "correct";
}

Does PHP have a virtual machine like Java?

Yes.

Independently from the platform PHP is running on, the scripts are compiled into the same bytecode and run by the Zend Engine.

The difference from Java is that this compiled code is usually not stored into separate files and the scripts are re-compiled on each execution (however, see opcode caches).

Another important difference between the Zend Engine and a typical JVM is in the way they execute bytecodes:

The Zend Engine executes (interprets) the compiled bytecodes directly. (At least that’s what I think happens.)
A JVM will normally use a JIT compiler to compile bytecodes to native instructions, and then execute the native instructions.

Actually, JVM behaviour is more complicated than this. JVMs don’t always compile to native code, and when they do, they typically delay JIT compilation until they figure it is worth doing. Prior to that, they execute the bytecodes directly.

If github shows wrong language icon

1. Create .gitattributes in repo’s main directory
2. Add the following line to it

*.css linguist-language=PHP

3. Change css extension to right extension that causes the problem, for example to *.twig

Creating Laravel Package

If you already have Laravel move to Step 2

Step 1. Get Laravel

composer create-project --prefer-dist laravel/laravel .

Step 2. Create following folder structure:

mkdir -p packages/aghayevi/modulename/src

Step 3. Do the following

cd  packages/aghayev/modulename
composer init
 
This command will guide you through creating your composer.json config.
 
Package name (<vendor>/<name>) [root/modulename]: aghayevi/modulename
Description []: My package for Laravel 5.6
Author [Imran Aghayev <imran.aghayev@hotmail.co.uk.co.uk>, n to skip]: n
Minimum Stability []: dev
Package Type []: 
License []: Apache License 2.0
 
Define your dependencies.
 
Would you like to define your dependencies (require) interactively [yes]? no
Would you like to define your dev dependencies (require-dev) interactively [yes]? no
 
{
    "name": "aghayevi/modulename",
    "description": "My package for for Laravel 5.6",
    "license": "Apache License 2.0",
    "authors": [
        {
            "name": "Imran Aghayev",
            "email": "imran.aghayev@hotmail.co.uk"
        }
    ],
    "minimum-stability": "dev",
    "require": {}
}
 
Do you confirm generation [yes]? y

Step 4. Add package to laravel’s composer.json PSR-4 autoload section

cd ../..
...
    "autoload": {
        "classmap": [
            "database/seeds",
            "database/factories"
        ],
        "psr-4": {
            "App\\": "app/",
            "Aghayevi\\Modulename\\": "packages/aghayevi/modulename/src"
        }
...

Step 5. Do composer dump-autoload to regenerate autoloading classes

Difference between abstract class and interface

In short, in case of full abstraction of methods you want to define use interface, in case of partial abstraction, if some methods you want to define are common among concrete classes but some are not then use abstract class

Abstract class can have definitions of constants, abstract methods or method stubs (methods without body/implementation) and normal
methods with implementation. A child class can extend only one abstract class and it can override (polymorphism) visibility of methods from abstract
classes as public, protected or private.

Interface can have only constants and abstract methods and all abstract methods of an interface must be public. A child
class can implement multiple interfaces at once and all methods must be/remain public.

Top 10 security vulnerabilities by OWASP

A1 Injection (PHP include, global variables, Sql Injection through Url)
A2 Broken authentication (To avoid broken authentication put into practice not leaving the login page for admins publicly accessible. Rename /wp-admin/ on WordPress to something else. Rename /admin in Magento to something else)
A3 Sensitive data exposure (arp spoofing resulting traffic sniffing, stealing auth passwords, http or pop3 passwords.Protect Data in Transit.Sensitive data: passwords, credit card numbers, credentials, social security numbers, health information, personal identity information)
A4 XML external entities (XXE vulnerability) (XML processor implementation issues with ability to access contents of local files and access to other systems. XML processor should have such capability off)
A5 Broken access control
A6 Security misconfiguration (default settings on production server)
A7 Cross-site Scripting (XSS) – (Uset input should be properly sanitized. Sanitization. Remove unaccepted characters)
A8 Insecure desirialization – (When you keep php serialize() object inside the text field in DB it can be silently updated to another one)
A9 Using Components with known vulnerabilities (Using out of dates WordPress website. Do not applying patches in time)
A10 Insufficient logging and monitoring (Lack of logging and monitoring)
Also:
Cross-site request forgery (CSRF) (Protect your forms with csrf_token to prevents posting form from a different website)
Unvalidated redirects and forwards (Third parties can redirect users to malicious websites or routing rules can be altered to have user being redirected to malicious website)

Types and principles of object oriented programming

3 Main types of object oriented programming

Creational, structural and behavioral patterns.

Only these types are general because they address interactions with objects used within programming:

object creation, object composition, and object interaction.

Можно провести параллель с человеком если рассматривать человека с позиции Высшего Разума – человек был создан (creational), потом организована инфраструктура для деятельности – другие люди, животные, природа и далее уже организовано то как происходит взаимодействие между людьми

 

4 Main principles of modern object based programming

Abstraction (Abstract classes and Interfaces) > Inheritance (class extends parent Abstract or concrete class).
Encapsulation (blackbox, isolation methods, getters, setters, Creational Patterns)
Polymorphism (overriding, logical cluster principle – many classes (nodes) on same level with diff implementation of same function (operation), Operational patterns, Strategy pattern)

Inheritance – пожалуй, важнейшая особенность object based programming. Если требуется новый виток эволюции, программист создает новый класс, расширяющий умения его родителя, а иногда и реализующий по новому, т.е. перекрывающий методы родителя — override (polymorphism). Ведь у каждого поколения свои понятия в жизни… Если же программисту нужен «опыт и понятия» прежних поколений — он обращается к ним. Ничто не потеряно в этой структуре, поэтому крайне важно уметь ею пользоваться.

Object based programming – просто методика организации приложений, структурирования кода, централизации методов и объединения сущностей в единое иерархическое семейство. Подобно тому, как строились субмарины и самолеты, перенимая опыт плавучести и летучести из живой природы, Object based приложения также используют восприятие программных сущностей, как неких «живых» объектов, перенимая известные нам из реального(offline — помните о таком?) мира характеристики и свойства.

Другими словами, создается некая сущность, которая не только имеет свои свойства и методы, но умеет порождать потомков и эволюционировать! Это называется расширением – extending. Словно бережный родитель, объект передает имущество по наследству, либо получает опыт поколений, будучи потомком другой родительской сущности – parent. Таким образом, создается единое древо поколений, в котором удобно ориентироваться и массово управлять в отличие от разрозненных библиотек — процедурный метод.

Создатель или архитектор такой системы может переноситься по поколениям, внося изменения в самом корне, либо в отдельных ветвях развития. Конфликты устраняем! Новые знания — добавляем!
Сам принцип object based programming обязывает разработчика структурировать приложение по правилам, а не как приспичит, что облегчает и систематизирует его поддержку

На мой взгляд, освоению ООП очень помогает именно такое «человеческое» восприятие принципов. Например, как и в жизни существуют строгие родители, которые заставляют детей уметь что-либо, что сами считают нужным! Их называют Абстрактные классы — abstract. Помните, как родители заставляли вас играть на фортепиано или учить стихи?.. Так вот, Абстрактные классы также как и многие родители вовсе и знать не знают зачем ребенку-потомку это будет нужно, и как он это будет использовать, но уверены, что так НАДО! Т.е. такие классы содержат абстрактные методы, которые являют собой объявление метода без самой реализации, как фантик без конфетки, тем самым обязывая потомка, этот метод реализовать. Как и в жизни, где родители нередко перекладывают на детей свои нереализованные мечты.

Разумеется, в программировании не должно быть случайных методов, и любые методы и свойства являются частью продуманной иерархии классов, которая как генеалогическое дерево, может давать возможности расширять функционал от поколения к поколению. А абстрактные классы, и еще более абстрактные – интерфейсы ( interface — вообще не содержит реализаций ), помогают программисту не потерять, не забыть реализовать общие необходимые для всех потомков “умения в жизни” функционирования программы.