12/31/2016

Copy all Streams of Media using ffmpeg



FAQ

  • How to copy all streams of some media using ffmpeg
  • Preserve all streams of some media, while spliting media
  • Copy selected streams of media using ffmpeg

Generally media files has two streams, one for video and other one for audio, but when your media file has multiple streams, and you want to copy all those streams to some other media file when you trying to cut or split specific parts from media file.

Example 1

I have recorded some video using TechSmith CamTasia Studio, and it has more than two streams, and i wanna split this into multiple parts, so that i can easily edit in CamTasia Video Editor, and i am using ffmpeg for this.

Case 1 [ Let me show you details of this Media File ]

C:\Users\someone\Camtasia Studio )
=$ ffprobe.exe "Rec 12-30-16.trec"
ffprobe version N-82759-g1f5630a Copyright (c) 2007-2016 the FFmpeg developers
  built with gcc 5.4.0 (GCC)
  configuration: --enable-gpl --enable-version3 --disable-w32threads --enable-dxva2 --enable-libmfx --enable-nvenc --ena
ble-avisynth --enable-bzlib --enable-fontconfig --enable-frei0r --enable-gnutls --enable-iconv --enable-libass --enable-
libbluray --enable-libbs2b --enable-libcaca --enable-libfreetype --enable-libgme --enable-libgsm --enable-libilbc --enab
le-libmodplug --enable-libmp3lame --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenh264 --enable-li
bopenjpeg --enable-libopus --enable-librtmp --enable-libschroedinger --enable-libsnappy --enable-libsoxr --enable-libspe
ex --enable-libtheora --enable-libtwolame --enable-libvidstab --enable-libvo-amrwbenc --enable-libvorbis --enable-libvpx
 --enable-libwavpack --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxavs --enable-libxvid --enable-libzi
mg --enable-lzma --enable-decklink --enable-zlib
  libavutil      55. 41.101 / 55. 41.101
  libavcodec     57. 66.109 / 57. 66.109
  libavformat    57. 58.101 / 57. 58.101
  libavdevice    57.  2.100 / 57.  2.100
  libavfilter     6. 68.100 /  6. 68.100
  libswscale      4.  3.101 /  4.  3.101
  libswresample   2.  4.100 /  2.  4.100
  libpostproc    54.  2.100 / 54.  2.100
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'Rec 12-30-16.trec':
  Metadata:
    major_brand     : mp42
    minor_version   : 0
    compatible_brands: mp42isom
    creation_time   : 2016-12-30T03:58:26.000000Z
  Duration: 00:21:29.64, start: 0.000000, bitrate: 3103 kb/s
    Stream #0:0(und): Video: tscc2 (tsc2 / 0x32637374), yuv444p, 1364x768, 2585 kb/s, 26.25 fps, 30 tbr, 30 tbn, 30 tbc
(default)
    Metadata:
      creation_time   : 2016-12-30T03:58:26.000000Z
    Stream #0:1(und): Audio: aac (LC) (mp4a / 0x6134706D), 44100 Hz, stereo, fltp, 253 kb/s (default)
    Metadata:
      creation_time   : 2016-12-30T03:58:26.000000Z
    Stream #0:2(und): Audio: aac (LC) (mp4a / 0x6134706D), 44100 Hz, stereo, fltp, 253 kb/s (default)
    Metadata:
      creation_time   : 2016-12-30T03:58:26.000000Z

Case 2 [ Cut Marked portion from this Media File ]

C:\Users\someone\Camtasia Studio )
=$ ffmpeg.exe -i "Rec 12-30-16.trec" -ss 150 -t 200 -map 0 -codec copy "Rec 12-30-16
.trec.0.avi"
ffmpeg version N-82759-g1f5630a Copyright (c) 2000-2016 the FFmpeg developers
  built with gcc 5.4.0 (GCC)
  configuration: --enable-gpl --enable-version3 --disable-w32threads --enable-dxva2 --enable-libmfx --enable-nvenc --ena
ble-avisynth --enable-bzlib --enable-fontconfig --enable-frei0r --enable-gnutls --enable-iconv --enable-libass --enable-
libbluray --enable-libbs2b --enable-libcaca --enable-libfreetype --enable-libgme --enable-libgsm --enable-libilbc --enab
le-libmodplug --enable-libmp3lame --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenh264 --enable-li
bopenjpeg --enable-libopus --enable-librtmp --enable-libschroedinger --enable-libsnappy --enable-libsoxr --enable-libspe
ex --enable-libtheora --enable-libtwolame --enable-libvidstab --enable-libvo-amrwbenc --enable-libvorbis --enable-libvpx
 --enable-libwavpack --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxavs --enable-libxvid --enable-libzi
mg --enable-lzma --enable-decklink --enable-zlib
  libavutil      55. 41.101 / 55. 41.101
  libavcodec     57. 66.109 / 57. 66.109
  libavformat    57. 58.101 / 57. 58.101
  libavdevice    57.  2.100 / 57.  2.100
  libavfilter     6. 68.100 /  6. 68.100
  libswscale      4.  3.101 /  4.  3.101
  libswresample   2.  4.100 /  2.  4.100
  libpostproc    54.  2.100 / 54.  2.100
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'Rec 12-30-16.trec':
  Metadata:
    major_brand     : mp42
    minor_version   : 0
    compatible_brands: mp42isom
    creation_time   : 2016-12-30T03:58:26.000000Z
  Duration: 00:21:29.64, start: 0.000000, bitrate: 3103 kb/s
    Stream #0:0(und): Video: tscc2 (tsc2 / 0x32637374), yuv444p, 1364x768, 2585 kb/s, 26.25 fps, 30 tbr, 30 tbn, 30 tbc
(default)
    Metadata:
      creation_time   : 2016-12-30T03:58:26.000000Z
    Stream #0:1(und): Audio: aac (LC) (mp4a / 0x6134706D), 44100 Hz, stereo, fltp, 253 kb/s (default)
    Metadata:
      creation_time   : 2016-12-30T03:58:26.000000Z
    Stream #0:2(und): Audio: aac (LC) (mp4a / 0x6134706D), 44100 Hz, stereo, fltp, 253 kb/s (default)
    Metadata:
      creation_time   : 2016-12-30T03:58:26.000000Z
Output #0, avi, to 'Rec 12-30-16.trec.0.avi':
  Metadata:
    major_brand     : mp42
    minor_version   : 0
    compatible_brands: mp42isom
    ISFT            : Lavf57.58.101
    Stream #0:0(und): Video: tscc2 (tsc2 / 0x32637374), yuv444p, 1364x768, q=2-31, 2585 kb/s, 26.25 fps, 30 tbr, 30 tbn,
 30 tbc (default)
    Metadata:
      creation_time   : 2016-12-30T03:58:26.000000Z
    Stream #0:1(und): Audio: aac (LC) ([255][0][0][0] / 0x00FF), 44100 Hz, stereo, fltp, 253 kb/s (default)
    Metadata:
      creation_time   : 2016-12-30T03:58:26.000000Z
    Stream #0:2(und): Audio: aac (LC) ([255][0][0][0] / 0x00FF), 44100 Hz, stereo, fltp, 253 kb/s (default)
    Metadata:
      creation_time   : 2016-12-30T03:58:26.000000Z
Stream mapping:
  Stream #0:0 -> #0:0 (copy)
  Stream #0:1 -> #0:1 (copy)
  Stream #0:2 -> #0:2 (copy)
Press [q] to stop, [?] for help
frame= 5365 fps=1520 q=-1.0 Lsize=   58364kB time=00:03:20.00 bitrate=2390.6kbits/s speed=56.7x
video:45405kB audio:12387kB subtitle:0kB other streams:0kB global headers:0kB muxing overhead: 0.989971%

Case 3 [ Take a look at streams inside Splited Media file ]

C:\Users\someone\Camtasia Studio )
=$ ffprobe.exe "Rec 12-30-16.trec.0.avi"
ffprobe version N-82759-g1f5630a Copyright (c) 2007-2016 the FFmpeg developers
  built with gcc 5.4.0 (GCC)
  configuration: --enable-gpl --enable-version3 --disable-w32threads --enable-dxva2 --enable-libmfx --enable-nvenc --ena
ble-avisynth --enable-bzlib --enable-fontconfig --enable-frei0r --enable-gnutls --enable-iconv --enable-libass --enable-
libbluray --enable-libbs2b --enable-libcaca --enable-libfreetype --enable-libgme --enable-libgsm --enable-libilbc --enab
le-libmodplug --enable-libmp3lame --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenh264 --enable-li
bopenjpeg --enable-libopus --enable-librtmp --enable-libschroedinger --enable-libsnappy --enable-libsoxr --enable-libspe
ex --enable-libtheora --enable-libtwolame --enable-libvidstab --enable-libvo-amrwbenc --enable-libvorbis --enable-libvpx
 --enable-libwavpack --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxavs --enable-libxvid --enable-libzi
mg --enable-lzma --enable-decklink --enable-zlib
  libavutil      55. 41.101 / 55. 41.101
  libavcodec     57. 66.109 / 57. 66.109
  libavformat    57. 58.101 / 57. 58.101
  libavdevice    57.  2.100 / 57.  2.100
  libavfilter     6. 68.100 /  6. 68.100
  libswscale      4.  3.101 /  4.  3.101
  libswresample   2.  4.100 /  2.  4.100
  libpostproc    54.  2.100 / 54.  2.100
Input #0, avi, from 'Rec 12-30-16.trec.0.avi':
  Metadata:
    encoder         : Lavf57.58.101
  Duration: 00:03:20.02, start: 0.000000, bitrate: 2390 kb/s
    Stream #0:0: Video: tscc2 (tsc2 / 0x32637374), yuv444p, 1364x768, 1860 kb/s, 30 fps, 30 tbr, 30 tbn, 30 tbc
    Stream #0:1: Audio: aac (LC) ([255][0][0][0] / 0x00FF), 44100 Hz, stereo, fltp, 253 kb/s
    Stream #0:2: Audio: aac (LC) ([255][0][0][0] / 0x00FF), 44100 Hz, stereo, fltp, 253 kb/s

Result

  • Now I can use this splited media file in CamTasia Video Editor
  • ffmpeg is OpenSource and Free to use.
  • You can download ffmpeg for Windows from https://ffmpeg.zeranoe.com/builds/
  • -map 0 parameter force ffmpeg to select all streams inside media file
  • -codec copy parameter is used to copy selected streams from media file
  • -ss time parameter is used to specify, starting marker, its value can be either in seconds or hh:mm:ss.ssss format.
  • -t time parameter is used to specify, ending marked, its value type is same as -ss parameter value.

OK friends, If anything left unexplained, you can comment below in comment box, Thanks


11/22/2016

Say Hello to `Windows Firewall`

What is a firewall?

A firewall is a software program or piece of hardware (like, Network Router) that helps screen out hackers, viruses, and worms that try to reach your computer over the Internet, But How firewall can keep you away from Hackers or unwanted viruses,
It does this by capturing/filtering network traffic of this Computer, Categories traffic as Inbound traffic or OutBound traffic, Use pre-Defined Rules/Filters, and perform action such as, Allow/Block traffic.

Types of Firewall Rules

There can be only two types of Traffic, inbound traffic or outbound traffic, Therefore, There are two Rules for Windows Firewall.
  • Inbound Rule (Let Program receive traffic from *Other_Sources)

  • Outbound Rule (Let Program send traffic to *Other_Sources)
*Other_Sources such as, Programs, system services, computers, or users
  • Custom Windows Firewall Rules serve three purposes
    • Allow the connection
    • Allow a connection only if it is secured through the use of Internet Protocol security (IPsec)
    • Block the connection

Windows Firewall

Default Behavior for Inbound/Outbound traffic
  • Inbound traffic is blocked by Default on Windows, So If you wanna use any Application/Software, Which will share something over your Network, Windows Firewall will prompt you to create/allow Inbound Connection.
  • Outbound traffic is allowed by default, But (Generally) You wanna create Outbound Rule, to Block Connection for Any Application/Software.

Why Windows Firewall has Domain, Private and Public Profiles?

Windows Firewall can automatically detect, which type of network you wanna connect to, So it will prompt you to Choose Proper Network Profile for that Network Connection, For Example, If You want to connect to your Home Router, Dongle etc, Windows will Recommend You to Choose, Private network Profile for this Network Connection. And When You want to connect to Public Network such as Public Wifi, LAN etc, Windows will detect it as Public Network as Recommend you to Choose Public Network Profile, Basically Public Network Profile is Configured as Most Secure than other two network profiles.
Note: Windows Firewall has advanced settings for these profiles.

How to Check/Configure your Current/Active Network Profile

You can check/configure current/active network profile in Windows Network and Sharing Center

How to Disable Internet/OutBound Traffic for All Apps/Software

How to Create and Allow/Block Internet Traffic for Specific Application

  1. Create New Outbound Rule
  2. Browse for Application, to Filter its Traffic
  3. What you want to do, for Captured Traffic
    • Allow Connection
    • Allow Connection (Only if Secure)
    • Block Connection
  4. For Which Profile, You want to activate this Rule
  5. Unique Name and Optional Description for this NEW OutBound Rule
  6. Lets Verify Our Firewall Rule Properties

Create New InBound Rule

netsh advfirewall firewall add rule name="wget-me" profile=domain,private,public protocol=any enable=yes DIR=In program="%ProgramFiles%\Gnu-wget\wget.exe" Action=Allow

Create New OutBound Rule

netsh advfirewall firewall add rule name="wget-me" profile=domain,private,public protocol=any enable=yes DIR=Out program="%ProgramFiles%\Gnu-wget\wget.exe" Action=Allow

Change in Registry (Because of Command Above)

HKLM\SYSTEM\ControlSet001\Services\SharedAccess\Parameters\FirewallPolicy\FirewallRules\{994CCCA0-9C02-44DD-AB5F-02E74AD3E935}: "v2.20|Action=Allow|Active=TRUE|Dir=Out|App=%ProgramFiles%\Gnu-wget\wget.exe|Name=wget-me|"
HKLM\SYSTEM\CurrentControlSet\Services\SharedAccess\Parameters\FirewallPolicy\FirewallRules\{994CCCA0-9C02-44DD-AB5F-02E74AD3E935}: "v2.20|Action=Allow|Active=TRUE|Dir=Out|App=%ProgramFiles%\Gnu-wget\wget.exe|Name=wget-me|"

Remove Existing Rule

netsh advfirewall firewall delete rule profile=domain,private,public name="wget-me"
@C:\Windows\system32
=> netsh advfirewall /?

The following commands are available:

Commands in this context:
?              - Displays a list of commands.
consec         - Changes to the `netsh advfirewall consec' context.
dump           - Displays a configuration script.
export         - Exports the current policy to a file.
firewall       - Changes to the `netsh advfirewall firewall' context.
help           - Displays a list of commands.
import         - Imports a policy file into the current policy store.
mainmode       - Changes to the `netsh advfirewall mainmode' context.
monitor        - Changes to the `netsh advfirewall monitor' context.
reset          - Resets the policy to the default out-of-box policy.
set            - Sets the per-profile or global settings.
show           - Displays profile or global properties.

The following sub-contexts are available:
 consec firewall mainmode monitor

To view help for a command, type the command, followed by a space, and then
 type ?.


@C:\Windows\system32
=> netsh advfirewall firewall /?

The following commands are available:

Commands in this context:
?              - Displays a list of commands.
add            - Adds a new inbound or outbound firewall rule.
delete         - Deletes all matching firewall rules.
dump           - Displays a configuration script.
help           - Displays a list of commands.
set            - Sets new values for properties of a existing rule.
show           - Displays a specified firewall rule.

To view help for a command, type the command, followed by a space, and then
 type ?.


@C:\Windows\system32
=> netsh advfirewall firewall add rule /?

Usage: add rule name=<string>
      dir=in|out
      action=allow|block|bypass
      [program=<program path>]
      [service=<service short name>|any]
      [description=<string>]
      [enable=yes|no (default=yes)]
      [profile=public|private|domain|any[,...]]
      [localip=any|<IPv4 address>|<IPv6 address>|<subnet>|<range>|<list>]
      [remoteip=any|localsubnet|dns|dhcp|wins|defaultgateway|
         <IPv4 address>|<IPv6 address>|<subnet>|<range>|<list>]
      [localport=0-65535|<port range>[,...]|RPC|RPC-EPMap|IPHTTPS|any (default=any)]
      [remoteport=0-65535|<port range>[,...]|any (default=any)]
      [protocol=0-255|icmpv4|icmpv6|icmpv4:type,code|icmpv6:type,code|
         tcp|udp|any (default=any)]
      [interfacetype=wireless|lan|ras|any]
      [rmtcomputergrp=<SDDL string>]
      [rmtusrgrp=<SDDL string>]
      [edge=yes|deferapp|deferuser|no (default=no)]
      [security=authenticate|authenc|authdynenc|authnoencap|notrequired 
         (default=notrequired)]

Remarks:

      - Add a new inbound or outbound rule to the firewall policy.
      - Rule name should be unique and cannot be "all".
      - If a remote computer or user group is specified, security must be
        authenticate, authenc, authdynenc, or authnoencap.
      - Setting security to authdynenc allows systems to dynamically
        negotiate the use of encryption for traffic that matches
        a given Windows Firewall rule. Encryption is negotiated based on
        existing connection security rule properties. This option
        enables the ability of a machine to accept the first TCP
        or UDP packet of an inbound IPsec connection as long as
        it is secured, but not encrypted, using IPsec.
        Once the first packet is processed, the server will
        re-negotiate the connection and upgrade it so that
        all subsequent communications are fully encrypted.
      - If action=bypass, the remote computer group must be specified when dir=in.
      - If service=any, the rule applies only to services.
      - ICMP type or code can be "any".
      - Edge can only be specified for inbound rules.
      - AuthEnc and authnoencap cannot be used together.
      - Authdynenc is valid only when dir=in.
      - When authnoencap is set, the security=authenticate option becomes an
        optional parameter.

Examples:

      Add an inbound rule with no encapsulation security for browser.exe:
      netsh advfirewall firewall add rule name="allow browser"
      dir=in program="c:\programfiles\browser\browser.exe"
      security=authnoencap action=allow

      Add an outbound rule for port 80:
      netsh advfirewall firewall add rule name="allow80"
      protocol=TCP dir=out localport=80 action=block

      Add an inbound rule requiring security and encryption
      for TCP port 80 traffic:
      netsh advfirewall firewall add rule
      name="Require Encryption for Inbound TCP/80"
      protocol=TCP dir=in localport=80 security=authdynenc
      action=allow

      Add an inbound rule for browser.exe and require security
      netsh advfirewall firewall add rule name="allow browser"
      dir=in program="c:\program files\browser\browser.exe"
      security=authenticate action=allow

      Add an authenticated firewall bypass rule for group
      acmedomain\scanners identified by a SDDL string:
      netsh advfirewall firewall add rule name="allow scanners"
      dir=in rmtcomputergrp=<SDDL string> action=bypass
      security=authenticate

      Add an outbound allow rule for local ports 5000-5010 for udp-
      Add rule name="Allow port range" dir=out protocol=udp localport=5000-5010 action=allow



@C:\Windows\system32
=> netsh advfirewall firewall delete rule /?

Usage: delete rule name=<string>
      [dir=in|out]
      [profile=public|private|domain|any[,...]]
      [program=<program path>]
      [service=<service short name>|any]
      [localip=any|<IPv4 address>|<IPv6 address>|<subnet>|<range>|<list>]
      [remoteip=any|localsubnet|dns|dhcp|wins|defaultgateway|
         <IPv4 address>|<IPv6 address>|<subnet>|<range>|<list>]
      [localport=0-65535|<port range>[,...]|RPC|RPC-EPMap|any]
      [remoteport=0-65535|<port range>[,...]|any]
      [protocol=0-255|icmpv4|icmpv6|icmpv4:type,code|icmpv6:type,code|
         tcp|udp|any]

Remarks:

      - Deletes a rule identified by name and optionally by endpoints, ports,
        protocol, and type.
      - If multiple matches are found, all matching rules are deleted.
      - If name=all is specified all rules are deleted from the specified
        type and profile.

Examples:

      Delete all rules for local port 80:
      netsh advfirewall firewall delete rule name=all protocol=tcp localport=80

      Delete a rule called "allow80":
      netsh advfirewall firewall delete rule name="allow80"


Query Information about pre-defined Rules

@rem -- Display All OutBound Firewall Rules 
@C:\Users\ssp\Desktop
=> netsh advfirewall firewall show rule name=all dir=out 

Rule Name:                            wget-me
----------------------------------------------------------------------
Enabled:                              Yes
Direction:                            Out
Profiles:                             Domain,Private,Public
Grouping:                             
LocalIP:                              Any
RemoteIP:                             Any
Protocol:                             Any
Edge traversal:                       No
Action:                               Allow

Rule Name:                            @{Microsoft.ZuneVideo_2.6.446.0_x64__8wekyb3d8bbwe?ms-resource://Microsoft.ZuneVideo/resources/IDS_MANIFEST_VIDEO_APP_NAME}
----------------------------------------------------------------------
Enabled:                              Yes
Direction:                            Out
Profiles:                             Domain,Private,Public
Grouping:                             Video
LocalIP:                              Any
RemoteIP:                             Any
Protocol:                             Any
Edge traversal:                       No
Action:                               Allow

.
.
.

Rule Name:                            Windows Media Player x86 (UDP-Out)
----------------------------------------------------------------------
Enabled:                              No
Direction:                            Out
Profiles:                             Domain,Private,Public
Grouping:                             Windows Media Player
LocalIP:                              Any
RemoteIP:                             Any
Protocol:                             UDP
LocalPort:                            Any
RemotePort:                           Any
Edge traversal:                       No
Action:                               Allow
Ok.


8/25/2016

Getting Started with PHP Archives: PHAR

You can think of PHAR Archive as tar Archive or JAVA Archive (jar), but PHAR Archive serve specific purpose and more flexible.
  1. You can convert your PHP App into single Phar archive, So it saves space and easy to distribute
  2. If you want, you can compress it either using gz, bzip2 or zip compression Algorithms
  3. You can create executable Phar Archive which can have multiple endpoints, Endpoints server very different purpose, because, When you execute this Phar Archive from Command line, it will call, shell endpoint, But when you try to run that same archive using Browser, After putting it into web document Directory, it will look for (if Exists), web endpoint. That way you can create a single Phar archive which can we used as either command line utility, or when serve through web, it behaves like web app.
If You are facing any Error about, phar.readonly setting in php.ini file Then You need to Edit Your PHP Configuration File (In My case, php.ini) search for string phar.readonly and remove any Semi-colon before that line And set it to Off Example:- phar.readonly = Off

Example - Just create a simple Phar Archive for Given Directory

cd /tmp
mkdir first
cd first
# Create 10,000 Files for Testing purpose
php -r 'foreach(range(0,10000) as $i){ echo "$i\n"; $d=sprintf("%07d.txt", $i); file_put_contents($d, "Hello from $d\n"); }'


cd ..
# Now create a Phar Archive for all those generated Files
php -r "(new Phar('archive.phar', 0, 'archive.phar'))->buildFromDirectory('first');"
ls
# archive.phar


# Check Time taken by PHP Script to access individual File inside Phar Archive
time php -r 'echo file_get_contents("phar://archive.phar/0000693.txt");'
# Hello from 0000693.txt
#
# real  0m0.056s
# user  0m0.048s
# sys   0m0.000s


# Lets create a ZIP Archive for same Directory
zip -r first.zip first/

# Check out, How much size each archive is taking
du -h archive.phar first.zip first/
# 616K  archive.phar
# 1.8M  first.zip
# 40M   first/


# Lets read the same file inside ZIP File
time php -r 'echo file_get_contents("phar://first.zip/first/0000693.txt");'
# Hello from 0000693.txt
#
# real  0m0.198s
# user  0m0.120s
# sys   0m0.068s


Although phar:// wrapper supports reading zip, tar.gz, tar.bz2, phar Archives, i have checked all supported formats, and phar is taking less time to read individual file from archive.

Example - Lets me tell you structure of my app

/app
    /web
        assets/
            jquery
            bootstrap
        index.php
    /cli
        functions.php
        index.php
    /libs
    /vendors
    index.php

Example - Lets create Executable Phar Archive

<?php

# Case 1: When You want to include all Files from GIVEN Directory
// create with alias "project.phar"
$phar = new Phar('project.phar', 0, 'project.phar');
// add all files in the project
$phar->buildFromDirectory(dirname(__FILE__) . '/project');

# You can execute it from Command line or Just run it Using Your web Browser
# final public static string Phar::createDefaultStub ([ string $indexfile [, string $webindexfile ]] )
$phar->setStub($phar->createDefaultStub('cli/index.php', 'www/index.php'));

Example - Using Regex Filter to add matched files into Phar Archive

<?php
# Case 2: When You want to include all PHP (*.php) Files from GIVEN Directory
$phar2 = new Phar('project2.phar', 0, 'project2.phar');
// add all files in the project, only include php files
$phar2->buildFromDirectory(dirname(__FILE__) . '/project', '/\.php$/');
$phar2->setStub($phar->createDefaultStub('cli/index.php', 'www/index.php'));

Example - Create NEW Phar Archive for Given Directory

# Using Phar::buildFromDirectory API
php -r '(new Phar("users_arc.phar", 0, "users_arc.phar"))->buildFromDirectory("/home/ssp/www/app/users");'
# Using Phar::buildFromIterator API
php -r '(new Phar("app_arc.phar", 0, "app_arc.phar"))->buildFromIterator( new RecursiveIteratorIterator( new RecursiveDirectoryIterator("/home/ssp/www/app")), "/home/ssp/www/app");'

Example - How to convert TAR to Phar Archive

We will use PharData class to convert tar to phar Archive
<?php
try {
    $tarphar = new PharData('myphar.tar');
    // convert it to the phar file format
    $phar = $tarphar->convertToExecutable(Phar::PHAR); // creates myphar.phar
    $phar->setStub($phar->createDefaultStub('cli/index.php', 'web/index.php'));
    // Lets Create compressed Phar Archive
    $compressed = $tarphar->convertToExecutable(Phar::TAR, Phar::GZ, '.phar.tgz');
} catch (Exception $e) {
    // handle the error here
}

Example - Convert Phar to ZIP/Tar/TAR.GZ/TAR.BZ2 Archive

php -r '(new Phar("archive.phar"))->convertToData(Phar::ZIP);'
ls
// archive.phar  archive.zip
# To create tar.bz2 Archive
php -r '(new Phar("archive.phar"))->convertToData(Phar::TAR, Phar::BZ2, ".tbz");'