PHP & Web Development Blogs

Search Results For: install
Showing 11 to 15 of 17 blog articles.
11623 views · 5 years ago
Creating a Tiny Blog Management system in Laravel 5.7

Hey There,
I am expecting you are familiar with PHP. In this post I will be using the Laravel framework to create a small blog system. I am showing here very simple steps to create blogs, If you want this complete code then please message me.
What are major Prequisites for Laravel:
* PHP version >= 5.6
* Composer should be installed in system

Create a project with name tiny_blog with following command

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


enter into the laravel project

cd tiny_blog


create a migration file using following artisan command
<pre>php artisan make:migration create_blog_table</pre>
After this command you will found a new file created in database/migrations folder in your project, Just edit the file having 'create_blog_table' appended in its name

Now replace following code to create table schema with function up(), So now the method will look like following:

public function up()
{
Schema::create('blogs', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id');
$table->string('category');
$table->string('title');
$table->text('description');
$table->timestamps();
});

}


replace following snippet with down method, it will look like following:

public function down()
{
Schema::dropIfExists('blogs');
}


Its time to run the migration file we have created

php artisan migrate



After running,It will create the blogs table in database.Now time to create form and insert data into the table

Laravel itsef provide authentication , use following artisan command :

php artisan make:auth


Now start Larvel:

php artisan serve


it will start the laravel development server at http://127.0.0.1:8000


Now if you run that url the basic default ui will be created and login & register link you can see in Top right position of header

You can register and login now.this feature is provided by authentication module.
Now we need to create a controller for manage blogs with following command:

php artisan make:controller BlogController


will create a file namedBlogController.php in** app/HTTP/controllers** folder location

Now we need to create a Model also, use following command

php artisan make:model Blog


will create a file namedBlog.php in app folder location

Now in Controller we need to create a method for create blogs and available that method in Routes to access it via url. Just editroutes/web.php file and add the following line

Route::get('blog/create','BlogController@createBlog');

/create/blog/ will be url route that land on Blog Controller's createBlog method using get method.

Now before running this route just go to the app/Http/Controllers folder and Edit BlogController.php file and Add the createBlog method in that class as following

public function createBlog()
{
return view('blog.create');
}


This code will try to load the view from/resources/views/blog/create.blade.php

In Laravel blade is a template engine. As we had not created the view file yet, so we need to create a blog folder inside/resources/views/ folder then inside blog folder create a file create.blade.php with following form

@extends('layouts.app')

@section('content')
<div class="container">
@if ($errors->any())
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div><br />
@endif
<div class="row">
<form method="post" action="{{url('blog/create')}}">
<div class="form-group">
<input type="hidden" value="{{csrf_token()}}" name="_token" />
<label for="title">Title:</label>
<input type="text" class="form-control" name="title"/>
</div>
<div class="form-group">
<label for="title">Category/Tags:</label>
<input type="text" class="form-control" name="category"/>
</div>
<div class="form-group">
<label for="description">Description:</label>
<textarea cols="10" rows="10" class="form-control" name="description"></textarea>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
@endsection



Now we need to add a additional route to handle the post request on blog/create route, Just edit routes/web.php file and just add following line in last:

Route::post('blog/create','BlogController@saveBlog'); 


post route to handle the form post on route blog/create


Now create a method name saveBlog to save the user input data in the form
 public function saveBlog(Request $request)
{
$blog = new Blog();

$this->validate($request, [
'title'=>'required',
'category'=>'required',
'description'=> 'required'
]);

$blog->createBlog($request->all());
return redirect('blog/index')->with('success', 'New blog has been created successfully :)'); }


Notice This method is using Blog object that we don't know that where it comes from? , So to make above code working we need to include the model which we created earlier need to include in our controller file So use following code to include it before the class created.

use App\Blog;


Now following line shows that there is a method named createBlog in Model(app/Blog.php), but in actual it is not there:

$blog->createBlog($data);



So go to the file app/Blog.php and Edit it and inside the class add following method:

 public function createBlog($data)
{

$this->user_id = auth()->user()->id;
$this->title = $data['title'];
$this->description = $data['description'];
$this->category = $data['category'];
$this->save();
return 1;
}


Now the creation of blog task has been done , Its time to show the created Entries So just create a route blog/index in routes/web.php

Route::get('blog/index','BlogController@showAllBlogs');


get route blog/index to show all the created blogs by current user


Now just add a method in controller
public function showAllBlogs()
{
$blogs = Blog::where('user_id', auth()->user()->id)->get();

return view('blog.index',compact('blogs'));
}



This method requires to create a index view in blog folder , So create a file named index.blade.php in /resources/views/blog/ folder with following code

@extends('layouts.app')

@section('content')
<div class="container">
@if(\Session::has('success'))
<div class="alert alert-success">
{{\Session::get('success')}}
</div>
@endif
<a type="button" href="{{url('blog/create')}}" class="btn btn-primary">Add New Blog</a>
<br>
<table class="table table-striped">
<thead>
<tr>
<td>ID</td>
<td>Title</td>
<td>Category</td>
<td>Description</td>
<td colspan="2">Action</td>
</tr>
</thead>
<tbody>
@foreach($blogs as $blog)
<tr>
<td>{{$blog->id}}</td>
<td>{{$blog->title}}</td>
<td>{{$blog->category}}</td>
<td>{{$blog->description}}</td>
<td>Edit</td>
<td>Delete</td>
</tr>
@endforeach
</tbody>
</table>
<div>
@endsection



Now all code is ready but we need to add 1 line of code to prevent the blog controller without authentication or without login

just add the following constructor method in BlogController class

 public function __construct()
{
$this->middleware('auth');
}


this constructor method will call very first when user will try to access any of BlogController class method, and the middleware will check whether user is logged in then only it will allow to access that method otherwise it will redirect to login page automatically.


After It Run your Code and you will able to create and listing your created blogs/articles. but the Edit and Delete links are not working right now, If you want that also working then please comment here or message me. If we get multiple requests then definitely i will write its part 2 article


Thanks very much for reading this blog, if you have any doubt about it then let me know in comments or by messaging me.

Following is the final code for BlogController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Blog;



class BlogController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}

public function createBlog()
{
return view('blog/create');
}


public function saveBlog(Request $request)
{
$blog = new Blog();

$this->validate($request, [
'title'=>'required',
'category'=>'required',
'description'=> 'required'
]);

$blog->createBlog($request->all());
return redirect('blog/index')->with('success', 'New blog has been created successfully :)');
}

public function showAllBlogs()
{
$blogs = Blog::where('user_id', auth()->user()->id)->get();

return view('blog.index',compact('blogs'));
}

}

20473 views · 5 years ago
Making Charts and Graphs using Laravel

Installing composer

Composer is a package management tool for PHP. Laravel requires composer for installation. We can download composer from https://getcomposer.org/download/

After installation that you can test whether composer installed or not by command
composer

Installing Laravel

The current stable version of laravel is laravel 5.6. We can install laravel package with three ways.

In command prompt or terminal by running composer global require "laravel/installer" and then Laravel new

or

We can create the project with Composer by running composer create-project --prefer-dist laravel/laravel

or

Directly clone from github
git clone https://github.com/laravel/laravel/tree/master and after that composer update

Laravel local development server

Run the below command in command prompt or terminal
PHP artisan serve


Above command will start to local development servehttp://localhost:8000 or if you want to change default port:

php artisan serve --port 


Generating charts and graphs

We are using consoletvs package for generating charts. So for installation we can first move inside to our project using command prompt or terminal. We are following the below steps to install

Step 1:

First we need to install ConsoleTVs/Charts composer package inside our laravel project.
composer require consoletvs/charts


Step 2:

After successfully installation of above package, open app/config.php and add service provider.
In config/app.php


'providers' => [
....
ConsoleTVs\Charts\ChartsServiceProvider::class,
],


After the service provider we need to add alias
'aliases' => [
....
'Charts' => ConsoleTVs\Charts\Facades\Charts::class,
]



Step 3

We need to configure of database for application. We can configure in either .env file or config/database.php file.


Step 4

We can migrate our default tables that is user. We can find the table in database/migration folder.

Step 5

We can generate dummy records for demo in users table. For creating dummy records, we need to run the below command in command prompt or terminal
php artisan tinker>>> factory(App\User::class, 20)->create();

the above command will create a set of 20 records.

If we need to add more records we need to run the above command or we can increase the count as much as we want. For example
php artisan tinker>>> factory(App\User::class, 2000)->create();


Step 6Creating controller

For creating controller we need to run below command in terminal or command prompt
php artisan make controller:<controller_name>


Step 7Adding the routes

We can add the routes for navigating our application. You can find routes file inside routes folder. Before 5.4 we can find routes.php file itself, now its web.php. If you are using laravel 5.2 routes.php will inside app/http folder.

So inside web.php:

Route::get('create-chart/{type}','ChartController@makeChart');


Here type will be the parameter we are passing and it will focus to makeChart() function inside chartcontroller

Step 8

Import charts to controller, for that in the namespace section add:

Use charts;


Step 9

We can put the below code into chartController

public function makeChart($type)
{
switch ($type) {
case 'bar':
$users = User::where(DB::raw("(DATE_FORMAT(created_at,'%Y'))"),date('Y'))
->get();
$chart = Charts::database($users, 'bar', 'highcharts')
->title("Monthly new Register Users")
->elementLabel("Total Users")
->dimensions(1000, 500)
->responsive(true)
->groupByMonth(date('Y'), true);
break;
case 'pie':
$chart = Charts::create('pie', 'highcharts')
->title('HDTuto.com Laravel Pie Chart')
->labels(['Codeigniter', 'Laravel', 'PHP'])
->values([5,10,20])
->dimensions(1000,500)
->responsive(true);
break;
case 'donut':
$chart = Charts::create('donut', 'highcharts')
->title('HDTuto.com Laravel Donut Chart')
->labels(['First', 'Second', 'Third'])
->values([5,10,20])
->dimensions(1000,500)
->responsive(true);
break;
case 'line':
$chart = Charts::create('line', 'highcharts')
->title('HDTuto.com Laravel Line Chart')
->elementLabel('HDTuto.com Laravel Line Chart Lable')
->labels(['First', 'Second', 'Third'])
->values([5,10,20])
->dimensions(1000,500)
->responsive(true);
break;
case 'area':
$chart = Charts::create('area', 'highcharts')
->title('HDTuto.com Laravel Area Chart')
->elementLabel('HDTuto.com Laravel Line Chart label')
->labels(['First', 'Second', 'Third'])
->values([5,10,20])
->dimensions(1000,500)
->responsive(true);
break;
case 'geo':
$chart = Charts::create('geo', 'highcharts')
->title('HDTuto.com Laravel GEO Chart')
->elementLabel('HDTuto.com Laravel GEO Chart label')
->labels(['ES', 'FR', 'RU'])
->colors(['#3D3D3D', '#985689'])
->values([5,10,20])
->dimensions(1000,500)
->responsive(true);
break;
default:
break;
}
return view('chart', compact('chart'));
}


Step 10

Create a blade file. Blade is the view file used inside the laravel. You can add new blade file with any name with an extension of .blade.php
Here we are creating chart.blade.php

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>My Charts</title>
{!! Charts::styles() !!}
</head>
<body>

<div class="app">
<center>
{!! $chart->html() !!}
</center>
</div>

{!! Charts::scripts() !!}
{!! $chart->script() !!}
</body>
</html>


Step 11

We can run our laravel application in local development server by php artisan serve command:

http://localhost:8000/create-chart/bar
http://localhost:8000/create-chart/pie
http://localhost:8000/create-chart/donut
http://localhost:8000/create-chart/line
http://localhost:8000/create-chart/area
http://localhost:8000/create-chart/geo



In the above example we was creating line chart, geo chart, bar chart, pie chart, donut chart, line chart and area chart. We can also create gauge chart, progressbar chart, areaspline chart, scatter chart, percentage chart etc using consoletvs charts composer package.

There are a lot of jQuery libraries also available like amcharts, chartjs, highcharts, google, material, chartist, fusioncharts, morris, plottablejs etc. However, using this plugin we can easily create charts without having to use jQuery, another advantage to building it in with Laravel.
12423 views · 5 years ago
Creating a PHP Daemon Service

What is a Daemon?

The term daemon was coined by the programmers of Project MAC at MIT. It is inspired on Maxwell's demon in charge of sorting molecules in the background. The UNIX systems adopted this terminology for daemon programs.

It also refers to a character from Greek mythology that performs the tasks for which the gods do not want to take. As stated in the "Reference System Administrator UNIX", in ancient Greece, the concept of "personal daemon" was, in part, comparable to the modern concept of "guardian angel." BSD family of operating systems use the image as a demon's logo.

Daemons are usually started at machine boot time. In the technical sense, a demon is considered a process that does not have a controlling terminal, and accordingly there is no user interface. Most often, the ancestor process of the deamon is init - process root on UNIX, although many daemons run from special rcd scripts started from a terminal console.

Richard Stevenson describes the following steps for writing daemons:
    . Resetting the file mode creation mask to 0 function umask(), to mask some bits of access rights from the starting process.
    . Cause fork() and finish the parent process. This is done so that if the process was launched as a group, the shell believes that the group finished at the same time, the child inherits the process group ID of the parent and gets its own process ID. This ensures that it will not become process group leader.
    . Create a new session by calling setsid(). The process becomes a leader of the new session, the leader of a new group of processes and loses the control of the terminal.
    . Make the root directory of the current working directory as the current directory will be mounted.
    . Close all file descriptors.
    . Make redirect descriptors 0,1 and 2 (STDIN, STDOUT and STDERR) to /dev/null or files /var/log/project_name.out because some standard library functions use these descriptors.
    . Record the pid (process ID number) in the pid-file: /var/run/projectname.pid.
    . Correctly process the signals and SigTerm SigHup: end with the destruction of all child processes and pid - files and / or re-configuration.

How to Create Daemons in PHP

To create demons in PHP you need to use the extensions pcntl and posix. To implement the fast communication withing daemon scripts it is recommended to use the extension libevent for asynchronous I/O.

Lets take a closer look at the code to start a daemon:
umask(0);
$pid = pcntl_fork(); 
if ($pid < 0) {
print('fork failed');
exit 1;
}


After a fork, the execution of the program works as if there are two branches of the code, one for the parent process and the second for the child process. What distinguishes these two processes is the result value returned the fork() function call. The parent process ID receives the newly created process number and the child process receives a 0.
if ($pid > 0) { echo "daemon process started
";
exit; }

$sid = posix_setsid(); if ($sid < 0) {
exit 2;
}

chdir('/'); file_put_contents($pidFilename, getmypid() );
run_process();


The implementation of step 5 "to close all file descriptors" can be done in two ways. Well, closing all file descriptors is difficult to implement in PHP. You just need to open any file descriptors before fork(). Second, you can override the standard output to an error log file using init_set() or use buffering using ob_start() to a variable and store it in log file:
ob_start();
var_dump($some_object);
$content = ob_get_clean();
fwrite($fd_log, $content); 


Typically, ob_start() is the start of the daemon life cycle and ob_get_clean() and fwrite() calls are the end. However, you can directly override STDIN, STDOUT and STDERR:
ini_set('error_log', $logDir.'/error.log');
fclose(STDIN); 
fclose(STDOUT);
fclose(STDERR);
$STDIN = fopen('/dev/null', 'r');
$STDOUT = fopen($logDir.'/application.log', 'ab');
$STDERR = fopen($logDir.'/application.error.log', 'ab');


Now, our process is disconnected from the terminal and the standard output is redirected to a log file.

Handling Signals

Signal processing is carried out with the handlers that you can use either via the library pcntl (pcntl_signal_dispatch()), or by using libevent. In the first case, you must define a signal handler:
function sig_handler($signo)
{
global $fd_log;
switch ($signo) {
case SIGTERM:
fclose($fd_log); unlink($pidfile); exit;
break;
case SIGHUP:
init_data(); break;
default:
}
}

pcntl_signal(SIGTERM, "sig_handler");
pcntl_signal(SIGHUP, "sig_handler");


Note that signals are only processed when the process is in an active mode. Signals received when the process is waiting for input or in sleep mode will not be processed. Use the wait function pcntl_signal_dispatch(). We can ignore the signal using flag SIG_IGN: pcntl_signal(SIGHUP, SIG_IGN); Or, if necessary, restore the signal handler using the flag SIG_DFL, which was previously installed by default: pcntl_signal(SIGHUP, SIG_DFL);

Asynchronous I/O with Libevent

In the case you use blocking input / output signal processing is not applied. It is recommended to use the library libevent which provides non-blocking as input / output, processing signals, and timers. Libevent library provides a simple mechanism to start the callback functions for events on file descriptor: Write, Read, Timeout, Signal.

Initially, you have to declare one or more events with an handler (callback function) and attach them to the basic context of the events:
$base = event_base_new();
$event = event_new();
$errno = 0;
$errstr = '';
$socket = stream_socket_server("tcp://$IP:$port", $errno, $errstr);
stream_set_blocking($socket, 0); event_set($event, $socket, EV_READ | EV_PERSIST, 'onAccept', $base);


Function handlers 'onRead', 'onWrite', 'onError' must implement the processing logic. Data is written into the buffer, which is obtained in the non-blocking mode:
function onRead($buffer, $id)
{
while($read = event_buffer_read($buffer, 256)) {
var_dump($read);
}
}


The main event loop runs with the function event_base_loop($base);. With a few lines of code, you can exit the handler only by calling: event_base_loobreak(); or after the specified time (timeout) event_loop_exit();.

Error handling deals with failure Events:
function onError($buffer, $error, $id)
{
global $id, $buffers, $ctx_connections;
event_buffer_disable($buffers[$id], EV_READ | EV_WRITE);
event_buffer_free($buffers[$id]);
fclose($ctx_connections[$id]);
unset($buffers[$id], $ctx_connections[$id]);
}


It should be noted the following subtlety: Working with timers is only possible through the file descriptor. The example of official the documentation does not work. Here is an example of processing that runs at regular intervals.
$event2 = event_new();
$tmpfile = tmpfile();
event_set($event2, $tmpfile, 0, 'onTimer', $interval);
$res = event_base_set($event2, $base);
event_add($event2, 1000000 * $interval);


With this code we can have a working timer finishes only once. If we need a "permanent" Timer, using the function onTimer we need create a new event each time, and reassign it to process through a "period of time":
function onTimer($tmpfile, $flag, $interval)
{
$global $base, $event2;

if ($event2) {
event_delete($event2);
event_free($event2);
}

call_user_function(‘process_data’,$args);

$event2 = event_new();
event_set($event2, $tmpfile, 0, 'onTimer', $interval);
$res = event_base_set($event2, $base);
event_add($event2, 1000000 * $interval);
}


At the end of the daemon we must release all previously allocated resources:
event_delete($event);
event_free($event);
event_base_free($base);

event_base_set($event, $base);
event_add($event);


Also it should be noted that for the signal processing handler is set the flag EV_SIGNAL: event_set($event, SIGHUP, EV_SIGNAL, 'onSignal', $base);

If needed constant signal processing, it is necessary to set a flag EV_PERSIST. Here follows a handler for the event onAccept, which occurs when a new connection is a accepted on a file descriptor:
function onAccept($socket, $flag, $base) {
global $id, $buffers, $ctx_connections;
$id++;
$connection = stream_socket_accept($socket);
stream_set_blocking($connection, 0);
$buffer = event_buffer_new($connection, 'onRead', NULL, 'onError', $id);
event_buffer_base_set($buffer, $base);
event_buffer_timeout_set($buffer, 30, 30);
event_buffer_watermark_set($buffer, EV_READ, 0, 0xffffff); event_buffer_priority_set($buffer, 10); event_buffer_enable($buffer, EV_READ | EV_PERSIST); $ctx_connections[$id] = $connection;
$buffers[$id] = $buffer;
}


Monitoring a Daemon

It is good practice to develop the application so that it was possible to monitor the daemon process. Key indicators for monitoring are the number of items processed / requests in the time interval, the speed of processing with queries, the average time to process a single request or downtime.

With the help of these metrics can be understood workload of our demon, and if it does not cope with the load it gets, you can run another process in parallel, or for running multiple child processes.

To determine these variables need to check these features at regular intervals, such as once per second. For example downtime is calculated as the difference between the measurement interval and total time daemon.

Typically downtime is determined as a percentage of a measurement interval. For example, if in one second were executed 10 cycles with a total processing time of 50ms, the time will be 950ms or 95%.

Query performance wile be 10rps (request per second). Average processing time of one request: the ratio of the total time spent on processing requests to the number of requests processed, will be 5ms.

These characteristics, as well as additional features such as memory stack size queue, number of transactions, the average time to access the database, and so on.

An external monitor can be obtain data through a TCP connection or unix socket, usually in the format of Nagios or zabbix, depending on the monitoring system. To do this, the demon should use an additional system port.

As mentioned above, if one worker process can not handle the load, usually we run in parallel multiple processes. Starting a parallel process should be done by the parent master process that uses fork() to launch a series of child processes.

Why not run processes using exec() or system()? Because, as a rule, you must have direct control over the master and child processes. In this case, we can handle it via interaction signals. If you use the exec command or system, then launch the initial interpreter, and it has already started processes that are not direct descendants of the parent process.

Also, there is a misconception that you can make a demon process through command nohup. Yes, it is possible to issue a command: nohup php mydaemon.php -master >> /var/log/daemon.log 2 >> /var/log/daemon.error.log &

But, in this case, would be difficult to perform log rotation, as nohup "captures" file descriptors for STDOUT / STDERR and release them only at the end of the command, which may overload of the process or the entire server. Overload demon process may affect the integrity of data processing and possibly cause partial loss of some data.

Starting a Daemon

Starting the daemon must happen either automatically at boot time, or with the help of a "boot script."

All startup scripts are usually in the directory /etc/rc.d. The startup script in the directory service is made /etc/init.d/ . Run command start service myapp or start group /etc/init.d/myapp depending on the type of OS.

Here is a sample script text:
#! /bin/sh
#
$appdir = /usr/share/myapp/app.php
$parms = --master –proc=8 --daemon
export $appdir
export $parms
if [ ! -x appdir ]; then
exit 1
fi

if [ -x /etc/rc.d/init.d/functions ]; then
. /etc/rc.d/init.d/functions
fi

RETVAL=0

start () {
echo "Starting app"
daemon /usr/bin/php $appdir $parms
RETVAL=$?
[ $RETVAL -eq 0 ] && touch /var/lock/subsys/mydaemon
echo
return $RETVAL
}

stop () {
echo -n "Stopping $prog: "
killproc /usr/bin/fetchmail
RETVAL=$?
[ $RETVAL -eq 0 ] && rm -f /var/lock/subsys/mydaemon
echo
return $RETVAL
}

case in
start)
start
;;
stop)
stop
;;
restart)
stop
start
;;
status)
status /usr/bin/mydaemon
;;
*)
echo "Usage:
php
if (is_file('app.phar')) {
unlink('app.phar');
}
$phar = new Phar('app.phar', 0, 'app.phar');
$phar->compressFiles(Phar::GZ);
$phar->setSignatureAlgorithm (Phar::SHA1);
$files = array();
$files['bootstrap.php'] = './bootstrap.php';
$rd = new RecursiveIteratorIterator(new RecursiveDirectoryIterator('.'));
foreach($rd as $file){
if ($file->getFilename() != '..' && $file->getFilename() != '.' && $file->getFilename() != __FILE__) {
if ( $file->getPath() != './log'&& $file->getPath() != './script'&& $file->getPath() != '.')
$files[substr($file->getPath().DIRECTORY_SEPARATOR.$file->getFilename(),2)] =
$file->getPath().DIRECTORY_SEPARATOR.$file->getFilename();
}
}
if (isset($opt['version'])) {
$version = $opt['version'];
$file = "buildFromIterator(new ArrayIterator($files));
$phar->setStub($phar->createDefaultStub('bootstrap.php'));
$phar = null;
}
 {start|stop|restart|status}"
;;

RETVAL=$?
exit $RETVAL


Distributing Your PHP Daemon

To distribute a daemon it is better to pack it in a single phar archive module. The assembled module should include all the necessary PHP and .ini files.

Below is a sample build script:
#php app.phar
myDaemon version 0.1 Debug
usage:
--daemon – run as daemon
--debug – run in debug mode
--settings – print settings
--nofork – not run child processes
--check – check dependency modules
--master – run as master
--proc=[8] – run child processes


Additionally, it may be advisable to make a PEAR package as a standard unix-console utility that when run with no arguments prints its own usage instruction:
[NMD%%CODE%%]


Conclusion

Creating daemons in PHP it is not hard but to make them run correctly it is important to follow the steps described in this article.

Post a comment here if you have questions or comments on how to create daemon services in PHP.
11993 views · 5 years ago
Welcome to PHP 7.1

In case you are living under a rock, the latest version of PHP released last week. PHP developers around the world began rebuilding their development containers with it so they can run their tests. Now it’s your turn. If you haven’t already installed it, you can download it here http://php.net/downloads.php Grab it, get it running in your development environment, and run those unit tests. If all goes well, you can begin planning your staged deployment to production.

If you need a quick start guide to get you going, our good friend Mr Colin O’Dell has just the thing for you “Installing PHP 7.1”. It’ll get you up and going quickly on PHP 7.1.

What’s the big deal about PHP 7.1? I am so glad you asked. Here are the major new features released in PHP 7.1.

* Nullable types
* Void return type
* Iterable pseudo-type
* Class constant visiblity modifiers
* Square bracket syntax for list() and the ability to specify keys in list()
* Catching multiple exceptions types

Now if you want a quick intro to several of these new features, check out our “RFCs of the Future” playlist on YouTube. In it, I talk about 4 of the new features.

Oh and while you are watching things download & compile, why not take the time to give a shoutout to all the core contributors, and a special thank you to Davey Shafik and Joe Watkins, the PHP 7.1 release managers.

Cheers!
=C=
18920 views · 5 years ago
Install Composer for PHP

Composer is a must-have tool for every PHP developer these days. This page is a simple breakdown of quick-install instructions.

How do I install composer?
   

. Use PHP to download the composer installer, place it in the current directory, and name it composer-setup.php


    . Use PHP to check the hash of the file you downloaded and compare it to the known value of the hash. You can always find the current value of the hash for the installer on the Composer Public Keys / Signatures page.
   
. Run the setup program to install composer. This does more than just download the latest copy of composer, it also sets up your local ~/.composer directory. This will install composer into the current directory. You can add the --install-dir=DIR to specify where you want composer installed. You can also specify --filename=composer to change the installed filename. You can use anything you like that doesn’t already exist in your specified directory, you don’t have to use the name composer. This is a great way to get rid of the .phar at the end of the name if you don’t like it.
   
. Use PHP to remove the installer from the current directory.

To install composer for PHP you use PHP to download the installer, set a few options, and then actually perform the install.

php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"

php -r "if (hash_file('SHA384', 'composer-setup.php') === '55d6ead61b29c7bdee5cccfb50076874187bd9f21f65d8991d46ec5cc90518f447387fb9f76ebae1fbbacf329e583e30') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"

php composer-setup.php

php -r "unlink('composer-setup.php');"


Below is a version you can copy ‘n paste.

Breakdown:

Recommended Setup for Linux and macOS:

php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"

php -r "if (hash_file('SHA384', 'composer-setup.php') === '55d6ead61b29c7bdee5cccfb50076874187bd9f21f65d8991d46ec5cc90518f447387fb9f76ebae1fbbacf329e583e30') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"

php composer-setup.php --install-dir=/usr/local/bin --filename=composer

php -r "unlink('composer-setup.php');"

WARNING: Line two IS WHERE IT compares the hasH of the installer you just downloaded to a hard-coded value. The value specified in the script is the value for the current version of the installer as of this writing. If it fails, check the Composer Public Keys / Signatures page and get the latest version. Plug it into the script below and try again.

Windows user, change the --installdir= to a directory in your path.

Recommended Setup for Windows

If you are running Microsoft Windows, the instructions above will work for you as long as you use the proper install paths. You can however download ComposerSetup.exe from the Composer Introduction page. Execute this and it will install composer and set your path so that you can run composer from anywhere. You will have to close your terminal window and open a new one after the install for the path to be updated.

That’s it, you should now have Composer installed.

Composer installation Resources

* Composer Homepage
* Composer Introduction
* Download Composer
* Composer Public Keys / Signatures

SPONSORS