Learn from your fellow PHP developers with our PHP blogs, or help share the knowledge you've gained by writing your own.
umask(0);
$pid = pcntl_fork();
if ($pid < 0) {
print('fork failed');
exit 1;
}
if ($pid > 0) { echo "daemon process started
";
exit;
}
$sid = posix_setsid();
if ($sid < 0) {
exit 2;
}
chdir('/');
file_put_contents($pidFilename, getmypid() );
run_process();
ob_start();
var_dump($some_object);
$content = ob_get_clean();
fwrite($fd_log, $content);
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');
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");
$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 onRead($buffer, $id)
{
while($read = event_buffer_read($buffer, 256)) {
var_dump($read);
}
}
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]);
}
$event2 = event_new();
$tmpfile = tmpfile();
event_set($event2, $tmpfile, 0, 'onTimer', $interval);
$res = event_base_set($event2, $base);
event_add($event2, 1000000 * $interval);
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);
}
event_delete($event);
event_free($event);
event_base_free($base);
event_base_set($event, $base);
event_add($event);
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;
}
#! /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 {start|stop|restart|status}"
;;
RETVAL=$?
exit $RETVAL
#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
$key = ftok(__FILE__, 'A');
$queue = msg_get_queue($key);
msg_send($queue, 1, 'message, type 1');
msg_send($queue, 2, 'message, type 2');
msg_send($queue, 3, 'message, type 3');
msg_send($queue, 1, 'message, type 1');
echo "send 4 messages
";
queue-receive.php$key = ftok('queue-send.php', 'A');
$queue = msg_get_queue($key);
for ($i = 1; $i <= 3; $i++) {
echo "type: {$i}
";
while ( msg_receive($queue, $i, $msgtype, 4096, $message, false, MSG_IPC_NOWAIT) ) {
echo "type: {$i}, msgtype: {$msgtype}, message: {$message}
";
}
}
u% php queue-send.php
send 4 messages
u% php queue-receive.php
type: 1
type: 1, msgtype: 1, message: s:15:"message, type 1";
type: 1, msgtype: 1, message: s:15:"message, type 1";
type: 2
type: 2, msgtype: 2, message: s:15:"message, type 2";
type: 3
type: 3, msgtype: 3, message: s:15:"message, type 3";
while (msg_receive($queue, $i, $msgtype, 4096, $message, false, MSG_IPC_NOWAIT)) {
$key = ftok('queue-send.php', 'A');
$queue = msg_get_queue($key);
while ( msg_receive($queue, 0, $msgtype, 4096, $message) ) {
echo "msgtype: {$msgtype}, message: {$message}
";
}
$pid = pcntl_fork();
$key = ftok('queue-send.php', 'A');
$queue = msg_get_queue($key);
if ($pid == -1) {
exit;
} elseif ($pid) {
exit;
} else {
while ( msg_receive($queue, 0, $msgtype, 4096, $message) ) {
echo "msgtype: {$msgtype}, message: {$message}
";
}
}
posix_setsid();
$id = ftok(__FILE__, 'A');
$shmId = shm_attach($id);
$var = 1;
if (shm_has_var($shmId, $var)) {
$data = (array) shm_get_var($shmId, $var);
} else {
$data = array();
}
$data[time()] = file_get_contents(__FILE__);
shm_put_var($shmId, $var, $data);
$id = ftok(__DIR__ . '/shared-memory-write-base.php', 'A');
$shmId = shm_attach($id);
$var = 1;
if (shm_has_var($shmId, $var)) {
$data = (array) shm_get_var($shmId, $var);
} else {
$data = array();
}
foreach ($data as $key => $value) {
$path = "/tmp/$key.php";
file_put_contents($path, $value);
echo $path . PHP_EOL;
}
$id = ftok(__FILE__, 'A');
$semId = sem_get($id);
sem_acquire($semId);
$data = file_get_contents(__DIR__.'/06050396.JPG', FILE_BINARY);
$shmId = shm_attach($id, strlen($data)+4096);
$var = 1;
if (shm_has_var($shmId, $var)) {
$data = shm_get_var($shmId, $var);
$filename = '/tmp/' . time();
file_put_contents($filename, $data, FILE_BINARY);
shm_remove($shmId);
} else {
shm_put_var($shmId, $var, $data);
}
sem_release($semId);
composer global require "laravel/installer"
and then Laravel new
or composer create-project --prefer-dist laravel/laravel
or git clone https://github.com/laravel/laravel/tree/master
and after that composer updatePHP artisan serve
php artisan serve --port
composer require consoletvs/charts
config/app.php
'providers' => [
....
ConsoleTVs\Charts\ChartsServiceProvider::class,
],
'aliases' => [
....
'Charts' => ConsoleTVs\Charts\Facades\Charts::class,
]
.env
file or config/database.php
file.database/migration
folder.php artisan tinker>>> factory(App\User::class, 20)->create();
the above command will create a set of 20 records. php artisan tinker>>> factory(App\User::class, 2000)->create();
php artisan make controller:<controller_name>
web.php
:Route::get('create-chart/{type}','ChartController@makeChart');
makeChart()
function inside chartcontrollerUse charts;
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'));
}
<!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>
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
composer create-project laravel/laravel --prefer-dist tiny_blog
cd tiny_blog
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();
});
}
public function down()
{
Schema::dropIfExists('blogs');
}
php artisan migrate
php artisan make:auth
php artisan serve
http://127.0.0.1:8000
php artisan make:controller BlogController
php artisan make:model Blog
Route::get('blog/create','BlogController@createBlog');
/create/blog/ will be url route that land on Blog Controller's createBlog method using get method.public function createBlog()
{
return view('blog.create');
}
@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
Route::post('blog/create','BlogController@saveBlog');
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 :)'); }
use App\Blog;
Model(app/Blog.php)
, but in actual it is not there:$blog->createBlog($data);
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;
}
Route::get('blog/index','BlogController@showAllBlogs');
public function showAllBlogs()
{
$blogs = Blog::where('user_id', auth()->user()->id)->get();
return view('blog.index',compact('blogs'));
}
@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
public function __construct()
{
$this->middleware('auth');
}
<?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'));
}
}
dompdf
package for generating the PDF file. barryvdh/laravel-dompdf
using composer package and thereafter we will add new route url with controller. Then we will create a blade file. Then after we have to just run project with serve and we can check the PDF file is for download. dompdf
. To get started, we need to download fresh Laravel 5.7 application using command, so open our terminal and run the below command in the command prompt: composer create-project --prefer-dist laravel/laravel blog
composer require barryvdh/laravel-dompdf
'providers' => [
....
Barryvdh\DomPDF\ServiceProvider::class,
],
'aliases' => [
....
'PDF' => Barryvdh\DomPDF\Facade::class,
]
Route::get('demo-generate-pdf','HomeController@demoGeneratePDF');
generatePDF()
method of route. <?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use PDF;
class HomeController extends Controller
{
public function demoGeneratePDF()
{
$data = ['title' => 'Welcome to My Blog'];
$pdf = PDF::loadView('myPDF', $data);
return $pdf->download('demo.pdf');
}
}
<!DOCTYPE html>
<html>
<head>
<title>Hi</title>
</head>
<body>
<h1>Welcome to My BLOG - {{ $title }}</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</body>
</html>
php artisan serve