Thursday, 12 September 2019

PHP://temp, php://memory life time, php:// output and how it works with laravel

When you create a file in php://temp (or php://memory for that matter) the resource only lasts the lifetime of the script. If you open the file using fopen() to get a resource handle, the lifetime can be shortened using fclose($resource_handle).
In your case, as soon as your script is done executing, the file will no longer be in memory.
In the circumstance where you would like to clear the memory prior to script completion, all you have to do is fclose() the resource file pointer.
On another note, the /img you are using is invalid and is being ignored. The only added data that is recognized is /maxmemory:n.
https://stackoverflow.com/questions/8894030/how-to-delete-a-file-from-php-temp-wrapper


php://output 
php://output is a write-only stream that allows you to write to the output buffer mechanism in the same way as print and echo.

https://www.php.net/manual/en/wrappers.php.php

These are two of the streams that PHP provides. Streams can be used by functions like fopen, fwrite, stream_get_contents, etc.

php://input is a read-only stream that allows you to read the request body sent to it (like uploaded files or POST variables).

$request_body = stream_get_contents('php://input');
php://output is a writable stream that is sent to Apache and will be returned to the browser that requested your page.

$fp = fopen('php://output', 'w');
fwrite($fp, 'Hello World!'); //User will see Hello World!
fclose($fp);

https://stackoverflow.com/questions/7186189/what-is-the-meaning-of-php-input-php-output-and-when-it-needs-to-use

Laravel you can create a simple cors middleware and set it to global, so it will add cors headers to every response
https://joeyxff.blogspot.com/2019/02/create-project-middleware.html

Then in your controller you can just use:

$fp = fopen('php://output', 'w');
fwrite($fp, 'Hello World!'); //User will see Hello World!
fclose($fp);

Without any return response statement

Wednesday, 11 September 2019

PHP remove installed php, tricks including php.ini, conf.d, php-fpm

// PHP find location of php.ini file

php -i | grep php.ini

https://www.howtogeek.com/50853/find-the-php-ini-file-location-from-the-command-line/

// PHP SYSTEM installed Modules located

/etc/php/PHP_VERSION/mods-available

// PHP init file located
/etc/php/PHP_VERSION/cli/php.ini

// PHP dynmic extension loader
/etc/php/PHP_VERSION/cli/conf.d

// PHP user installed module located in 
/usr/lib/php/20170718 (folder for php7.2)


// Use of /etc/php7.x/cli/conf.d ?
Those files will overwrite the settings in php.ini. Putting config stuff here allows you to have custom settings while keeping updates simpler: if you modify php.ini itself then you either have to retain the old php.ini or overwrite it when you update PHP. If you keep your custom settings in, eg. conf.d/local.ini then you can update PHP easily while retaining any environment-specific settings

// in conf.d
each xxx.ini file changes the php.ini file, its just a centralized place to manage

// for example vim 20-xxx.ini  , extension=sqlsrv.so

https://stackoverflow.com/questions/13383806/what-the-ini-files-in-etc-php5-conf-d-folder-are-for

// Find duplicate file
fdupes
https://www.howtogeek.com/201140/how-to-find-and-remove-duplicate-files-on-linux/

// phpsize not found?
sudo apt-get install php7.x-dev
https://stackoverflow.com/questions/3108937/how-to-install-and-run-phpize

// PHP extension installed in another directory?
Probably have two php installed
check whereis php command to see if there are two php dir specified, and one is infront of other
need to uninstall a php version

apt purge php 7.x php 7.x-common
https://ayesh.me/Ubuntu-PHP-7.3

// PHP FPM status
ps aux | grep php-fpm
service php7.x-fpm status
https://stackoverflow.com/questions/14915147/php-fpm-check-if-running


// PHP version
php -v



which php - will locate the php executable (this should be the default php used by you)
whereis php - The first path displayed will be the location of the php executable
echo $PATH - will print a list of paths separated by ":" where the system looks for commands

// PHP sytem mods located

/etc/php/PHP_VERSION/mods-available
https://tecadmin.net/enable-disable-php-modules-ubuntu/

// PHP user installed mods located
/usr/lib/php/20170718 - for php7.2
https://github.com/microsoft/msphpsql/issues/736


// sqlsrv already loaded error (PHP Warning: Module 'XXX' already loaded in Unknown on line 0)

Check /etc/php7.x/cli/conf.d to see if there are duplicate files, if not, check ini files to see if there are duplicate lines in each ini file.

execute

echo extension=pdo_sqlsrv.so >> `php --ini | grep "Scan for additional .ini files" | sed -e "s|.*:\s*||"`/20-pdo_sqlsrv.ini (Correction pdo_sqlsrv.ini must run before sqlsrv.ini)
echo extension=sqlsrv.so >> `php --ini | grep "Scan for additional .ini files" | sed -e "s|.*:\s*||"`/30-sqlsrv.ini

multiple times will result
extension =pdo_sqlsrv.so
extension =pdo_sqlsrv.so
extension =pdo_sqlsrv.so

be created multiple times in 20-pdo_sqlsrv.ini
https://github.com/Homebrew/homebrew-php/issues/3896


PHP CSV in case returning a string instead of file

 NEVER use explode(). It won't recognize escaped and/or enclosed separator. That's even worse, because explode() will work in most cases, so without proper testing (which is not so simple), you can think that code is working and it will crash in unexpected time, probably, basing on Murphy's law, when you show it to client.


 function array2csv($fields, $delimiter = ",", $enclosure = '"', $escape_char = "\\")
{
    $buffer = fopen('php://temp', 'r+');
    fputcsv($buffer, $fields, $delimiter, $enclosure, $escape_char);
    rewind($buffer);
    $csv = fgets($buffer);
    fclose($buffer);
    return $csv;
}



https://www.electrictoolbox.com/php-fputcsv-without-file/


Recomment use php output stream, as write in memory and temp has size limitation, and other weird issues:

https://joeyxff.blogspot.com/2019/09/phptemp-phpmemory-life-time-php-output.html

$fp = fopen('php://output', 'w');
fwrite($fp, 'Hello World!'); //User will see Hello World!
fclose($fp);

ping vs curl, route two subnets,

Ping uses ICMP, no port #
Curl uses TCP
https://networkengineering.stackexchange.com/questions/37896/ping-port-number


ICMP VS TCP:

 ICMP is a control protocol, meaning that it designed to not carry application data, but rather information about the status of the network itself. The best known example of ICMP in practice is the ping utility, that uses ICMP to probe remote hosts for responsiveness and overall round-trip time of the probe messages.

Both Transmission Control Protocol (TCP) and User Datagram Protocol (UDP) are transportation protocols, they are used to pass the actual data. The main difference between TCP and UDP is that TCP is a connection oriented protocol, it guarantees that all sent packets will reach the destination in the correct order.

UDP, on the other hand, is a connection-less protocol. Communication is datagram oriented, so the integrity is guaranteed only on the single datagram. Datagrams reach destination and can arrive out of order or don't arrive at all. It's generally used for real time communication, where a little percentage of packet loss rate is preferable to the overhead of a TCP connection.

https://superuser.com/questions/1044361/why-icmp-is-different-that-tcp-and-udp



Routing table must be modified in router to add a route from one subnet to the other subnet, in case there are two routers:(CISCO ROUTER EXAMPLE)
Suppose we have two routers connected to each other with FastEthernet0/0:

R1 <--------> R2



R1's IP address is 192.168.1.1/24, and R2's IP address is 10.0.0.1/24.



R1#conf t

Enter configuration commands, one per line.  End with CNTL/Z.

R1(config)#int fa0/0

R1(config-if)#ip addr 192.168.1.1 255.255.255.0

R1(config-if)#no shut

R1(config-if)#

*Mar  1 00:01:48.155: %LINK-3-UPDOWN: Interface FastEthernet0/0, changed state to up

*Mar  1 00:01:49.155: %LINEPROTO-5-UPDOWN: Line protocol on Interface FastEthernet0/0, changed state to up

R1(config-if)#exit

R1(config)#ip route 10.0.0.0 255.0.0.0 fa0/0

R1(config)#end

R1#

*Mar  1 00:02:24.139: %SYS-5-CONFIG_I: Configured from console by console

R1#



R2#conf t

Enter configuration commands, one per line.  End with CNTL/Z.

R2(config)#int fa0/0

R2(config-if)#ip addr 10.0.0.1 255.255.255.0

R2(config-if)#no shut

R2(config-if)#

*Mar  1 00:03:51.971: %LINK-3-UPDOWN: Interface FastEthernet0/0, changed state to up

*Mar  1 00:03:52.971: %LINEPROTO-5-UPDOWN: Line protocol on Interface FastEthernet0/0, changed state to up

R2(config-if)#exit

R2(config)#ip route 192.168.1.0 255.255.255.0 fa0/0

R2(config)#end

R2#

*Mar  1 00:04:26.463: %SYS-5-CONFIG_I: Configured from console by console

R2#



R2#ping 192.168.1.1

https://learningnetwork.cisco.com/thread/28157



Routing table:
ubuntu command : route -n
destination: the destination ip
gateway: whether to use gateway or not



Port forwarding is to add an entry in the port fowarding table of router so that the public port of router is forwarded to a subnet ip port

MSSQL get current date query && with different time zone && get one day less && get column names && get database

SELECT [Title], [Firstname], [Surname], [Company_name], [Interest]
FROM [dbo].[EXTRANET]
WHERE day(Submission_date)=day(now) and
     month(Submission_date)=month(now)
     and year(Submission_date)=year(now)


https://stackoverflow.com/questions/11955281/sql-where-datetime-column-equals-todays-date


// In case of different timezone get time with left join

SELECT table1.time AT TIME ZONE 'UTC' AT TIME ZONE 'Pacific Standard Time' as TriageEndTime
        FROM table1 LEFT JOIN table2 ON table1.id = table2.Id
        AND DAY(table1.CreatedTime AT TIME ZONE 'UTC' AT TIME ZONE 'Pacific Standard Time') = DAY(CAST(GETDATE() AS DATETIME) AT TIME ZONE 'Pacific Standard Time')
        AND MONTH(table1.CreatedTime AT TIME ZONE 'UTC' AT TIME ZONE 'Pacific Standard Time') = MONTH(CAST(GETDATE() AS DATETIME) AT TIME ZONE 'Pacific Standard Time')
        AND YEAR(table1.CreatedTime AT TIME ZONE 'UTC' AT TIME ZONE 'Pacific Standard Time') = YEAR(CAST(GETDATE() AS DATETIME) AT TIME ZONE 'Pacific Standard Time')


https://stackoverflow.com/questions/11955281/sql-where-datetime-column-equals-todays-date
https://www.w3schools.com/sql/sql_join_left.asp


// 1 day prior
        SELECT *
        FROM table1 LEFT JOIN table2 ON table1.id = table2.id
        AND DAY(table1.CreatedTime AT TIME ZONE 'UTC' AT TIME ZONE 'Pacific Standard Time') = DAY(DATEADD(DAY, -1, CAST(GETDATE() AS DATETIME) AT TIME ZONE 'Pacific Standard Time'))
        AND MONTH(table1.CreatedTime AT TIME ZONE 'UTC' AT TIME ZONE 'Pacific Standard Time') = MONTH(DATEADD(DAY, -1, CAST(GETDATE() AS DATETIME) AT TIME ZONE 'Pacific Standard Time'))
        AND YEAR(table1.CreatedTime AT TIME ZONE 'UTC' AT TIME ZONE 'Pacific Standard Time') = YEAR(DATEADD(DAY, -1, CAST(GETDATE() AS DATETIME) AT TIME ZONE 'Pacific Standard Time'))

// get db
SELECT name FROM master.sys.databases
https://stackoverflow.com/questions/147659/get-list-of-databases-from-sql-server
// Get column names
 SELECT COLUMN_NAME  FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = N'table'

MSSQL FireWall rules (Allow remote connection)

If you are using a named instance, create an extra rule in your firewall with the port 1434.
Note: For a named SQL Server instance (e.g. [yourServerInstance]\SQL2012SP2), the firewall needs an extra rule on the UDP protocol with the specific port 1434. Without this rule the system will return the exception error: 26 - Error Locating Server/Instance Specified.
Display the firewall advanced settings by navigating to Control Panel > System and Security > Windows Firewall > Advanced settings.
Select Inbound Rules in the left-hand pane, then click New Rule in the right-hand pane.
In the New Inbound Rule Wizard, Rule Type step, select Port.
Protocols and Ports step, select UDP and set Specific local ports to 1434.
Action step, select Allow the connection.
Profile step, tick the Domain checkbox.
Name step, enter a name for this rule, e.g. Named instance port 1434.
Select Finish.


Wednesday, 28 August 2019

Laravel and condition on JOIN && add paramteres to laravel commands

Laravel add and condition on JOIN :

$results = DB::table('rooms')
                     ->distinct()
                     ->leftJoin('bookings', function($join)
                         {
                             $join->on('rooms.id', '=', 'bookings.room_type_id');
                             $join->on('arrival','>=',DB::raw("'2012-05-01'"));
                             $join->on('arrival','<=',DB::raw("'2012-05-10'"));
                             $join->on('departure','>=',DB::raw("'2012-05-01'"));
                             $join->on('departure','<=',DB::raw("'2012-05-10'"));
                         })
                     ->where('bookings.room_type_id', '=', NULL)
                     ->get();


https://stackoverflow.com/questions/16848987/a-join-with-additional-conditions-using-query-builder-or-eloquent


Laravel add parameter on Commands :

command class:


        protected $signature = 'command:command {--parameter1=} {--parameter2=}'
        // Retrieve command
        $this->option('parameter1');
         $this->option('parameter2');   

https://stackoverflow.com/questions/46670304/laravel-command-only-optional-argument
https://stillat.com/blog/2016/12/01/laravel-artisan-command-input-and-command-signatures