Laravel database migrate command

php artisan migrate
php artisan migrate:fresh
php artisan migrate:install
php artisan migrate:refresh
php artisan migrate:reset
php artisan migrate:rollback
php artisan migrate:status

Fatal error: Maximum execution time of 300 seconds exceeded in

Xampp Users

  1. Go to xampp\phpMyAdmin\
  2. Open config.inc.php
  3. Search for $cfg['ExecTimeLimit'] = 300;
  4. Set a larger value or change to 0 for unlimited
  5. If not found add $cfg['ExecTimeLimit'] = 900; (or 0 for unlimited)
  6. Save the file and restart the server

How to implement firebase notification / push notification on php, wordpress any website using javascript

Insert this code before closing body tag

<script type="module">
  // Import the functions you need from the SDKs you need
  import { initializeApp } from "https://www.gstatic.com/firebasejs/9.0.1/firebase-app.js";
  import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.0.1/firebase-analytics.js";
  import { getMessaging, getToken } from "https://www.gstatic.com/firebasejs/9.0.1/firebase-messaging.js";

  // TODO: Add SDKs for Firebase products that you want to use
  // https://firebase.google.com/docs/web/setup#available-libraries

  // Your web app's Firebase configuration
  // For Firebase JS SDK v7.20.0 and later, measurementId is optional
  const firebaseConfig = {
    apiKey: "AIzaSyBql0gSNeGoc4tS0rU__tfQ3A",
    authDomain: "aditya-bd972.firebaseapp.com",
    databaseURL: "https://aditya-bd972.firebaseio.com",
    projectId: "aditya-bd2=972",
    storageBucket: "aditya-bd972.appspot.com",
    messagingSenderId: "730776396949",
    appId: "1:730776396449:web:ff1174fa2aac6dfbdc46e0"
  };
  //Initialize Firebase
  const app = initializeApp(firebaseConfig);
  const analytics = getAnalytics(app);
  const messaging = getMessaging();

  getToken(messaging, { vapidKey: 'BM-QUwBccFqQAlfA2XuYNXVb7RttdqHwfv9e2a_XwQ0QoQ05VI25JDVkGhjh_bEJl9fONflY6tPvQ' }).then((currentToken) => {
  if (currentToken) {
    // Send the token to your server and update the UI if necessary
    // ...
    console.log(currentToken);
  } else {
    // Show permission request UI
    console.log('No registration token available. Request permission to generate one.');
    // ...
  }
}).catch((err) => {
  console.log('An error occurred while retrieving token. ', err);
  // ...
});


 // console.log(messaging);
 // console.log(app);
</script>

Create two file init.js and firebase-messaging-sw.js store it in root of website

Content for init.js

    // TODO: Replace the following with your app's Firebase project configuration
    
    const firebaseConfig = {
      apiKey: "AIzaSyBql0g4w_K19oc4tS0rU__tfQ3A",
      authDomain: "aditya-bd272.firebaseapp.com",
      databaseURL: "https://aditya-bd972.firebaseio.com",
      projectId: "aditya-bd972",
      storageBucket: "aditya-bd972.appspot.com",
      messagingSenderId: "730776396449",
      appId: "1:730776396449:web:ff1174fa2aac6dfbdc46e0"
    };
  
    //Initialize Firebase
  
    
    
  // Initialize Firebase with a "default" Firebase project
var defaultProject = firebase.initializeApp(firebaseConfig);

console.log(defaultProject.name);  // "[DEFAULT]"

Content for firebase-messaging-sw.js

// Import and configure the Firebase SDK
// These scripts are made available when the app is served or deployed on Firebase Hosting
// If you do not serve/host your project using Firebase Hosting see https://firebase.google.com/docs/web/setup
 importScripts('https://www.gstatic.com/firebasejs/4.8.1/firebase-app.js');
 importScripts('https://www.gstatic.com/firebasejs/4.8.1/firebase-messaging.js');
  importScripts('init.js');

var messaging = firebase.messaging();

/**
 * Here is is the code snippet to initialize Firebase Messaging in the Service
 * Worker when your app is not hosted on Firebase Hosting.
 // [START initialize_firebase_in_sw]
 // Give the service worker access to Firebase Messaging.
 // Note that you can only use Firebase Messaging here, other Firebase libraries
 // are not available in the service worker.
 importScripts('https://www.gstatic.com/firebasejs/4.8.1/firebase-app.js');
 importScripts('https://www.gstatic.com/firebasejs/4.8.1/firebase-messaging.js');
 // Initialize the Firebase app in the service worker by passing in the
 // messagingSenderId.
 firebase.initializeApp({
   'messagingSenderId': 'YOUR-SENDER-ID'
 });
 // Retrieve an instance of Firebase Messaging so that it can handle background
 // messages.
 const messaging = firebase.messaging();
 // [END initialize_firebase_in_sw]
 **/


// If you would like to customize notifications that are received in the
// background (Web app is closed or not in browser focus) then you should
// implement this optional method.
// [START background_handler]
messaging.setBackgroundMessageHandler(function(payload) {
  console.log('[firebase-messaging-sw.js] Received background message ', payload);
  // Customize notification here
  var notificationTitle = 'Background Message Title';
  var notificationOptions = {
    body: 'Background Message body.',
    icon: '/favicon.ico'
  };

  return self.registration.showNotification(notificationTitle,
    notificationOptions);
});
// [END background_handler]

Login in https://console.firebase.google.com/u/0/project and send notification from firebase panel

multiple database laravel 8

DB_CONNECTION=mysql

DB_HOST=127.0.0.1

DB_PORT=3306

DB_DATABASE=mydatabase

DB_USERNAME=aditya

DB_PASSWORD=aditya

   

DB_CONNECTION_SECOND=mysql

DB_HOST_SECOND=127.0.0.1

DB_PORT_SECOND=3306

DB_DATABASE_SECOND=mydatabase2

DB_USERNAME_SECOND=aditya

DB_PASSWORD_SECOND=aditya

config/database.php

<?php

  

use Illuminate\Support\Str;

  

return [

   

    'default' => env('DB_CONNECTION', 'mysql'),

   

    'connections' => [

        .....

   

        'mysql' => [

            'driver' => 'mysql',

            'url' => env('DATABASE_URL'),

            'host' => env('DB_HOST', '127.0.0.1'),

            'port' => env('DB_PORT', '3306'),

            'database' => env('DB_DATABASE', 'forge'),

            'username' => env('DB_USERNAME', 'forge'),

            'password' => env('DB_PASSWORD', ''),

            'unix_socket' => env('DB_SOCKET', ''),

            'charset' => 'utf8mb4',

            'collation' => 'utf8mb4_unicode_ci',

            'prefix' => '',

            'prefix_indexes' => true,

            'strict' => true,

            'engine' => null,

            'options' => extension_loaded('pdo_mysql') ? array_filter([

                PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),

            ]) : [],

        ],

        'mysql2' => [

            'driver' => env('DB_CONNECTION_SECOND'),

            'host' => env('DB_HOST_SECOND', '127.0.0.1'),

            'port' => env('DB_PORT_SECOND', '3306'),

            'database' => env('DB_DATABASE_SECOND', 'forge'),

            'username' => env('DB_USERNAME_SECOND', 'forge'),

            'password' => env('DB_PASSWORD_SECOND', ''),

            'unix_socket' => '',

            'charset' => 'utf8mb4',

            'collation' => 'utf8mb4_unicode_ci',

            'prefix' => '',

            'prefix_indexes' => true,

            'strict' => true,

            'engine' => null,

        ],
<?php

.....

public function up()

{

    Schema::create('blog', function (Blueprint $table) {

        $table->increments('id');

        $table->string('title');

        $table->string('body')->nullable();

        $table->timestamps();

    });

}
<?php

.....

public function up()

{

    Schema::connection('mysql2')->create('blog', function (Blueprint $table) {

        $table->increments('id');

        $table->string('title');

        $table->string('body')->nullable();

        $table->timestamps();

    });

}
<?php

   

namespace App;

  

use Illuminate\Database\Eloquent\Model;

   

class Blog extends Model

{

}
<?php

   

namespace App;

  

use Illuminate\Database\Eloquent\Model;

   

class Blog extends Model

{

    protected $connection = 'mysql2';

}
<?php

  

class BlogController extends BaseController

{

    public function getRecord()

    {

        $blogModel = new Blog;

        $find = $blogModel->find(1);

        return $find;

    }

}
<?php

  

class BlogController extends BaseController

{

    public function getRecord()

    {

        $blogModel = new Blog;

        $blogModel->setConnection('mysql2');

        $find = $blogModel->find(1);

        return $find;

    }

}
$blogs = DB::table("blog")->get();

print_r($blogs);
$blogs = DB::connection('mysql2')->table("blog")->get();

print_r($blogs);

Complete Laravel installation and API guide

How to install Laravel using composer

composer create-project laravel/laravel example-app

cd example-app

php artisan serve

Create View in Laravel

<!-- View stored in resources/views/home.blade.php -->

<html>
    <body>
        <h1>My Home Page {{ $name }}</h1>
    </body>
</html>


<!-- Route stored in routes/web.php -->


Route::get('/', function () {
    return view('greeting', ['name' => 'James']);
});

Create model, controller and view in Laravel

Step 1: Create model and controller

php artisan make:controller HomeController --resource --model=Home

Step 2: Create View in Laravel



<!-- View stored in resources/views/home.blade.php -->

<html>
    <body>
        <h1>My Home Page {{ $name }}</h1>
    </body>
</html>

Step 3: call controller using route and display view




<!-- Route stored in routes/web.php -->

Route::get('/home', 'App\Http\Controllers\HomeController@index');

or 

Route::get('/home', 'HomeController@index');

Note: changing the RouteServiceProvider.php file in App/Providers/ path by uncommenting the code.

protected $namespace = ‘App\Http\Controllers’;

Create and Rest Api in Laravel

php artisan make:controller ApiController

You will find a new file named ApiController.php in the app\http\controllers directory. Next, we can add the following methods:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ApiController extends Controller
{
    public function sendResponse($result, $message)
  {
    $response = [
          'success' => true,
          'data'    => $result,
          'message' => $message,
      ];
   return response()->json($response, 200);
  }

  /**
     * return error response.
     *
     * @return \Illuminate\Http\Response
     */
    public function sendError($error, $errorMessages = [], $code = 404)
    {
    	$response = [
            'success' => false,
            'message' => $error,
        ];


        if(!empty($errorMessages)){
            $response['data'] = $errorMessages;
        }


        return response()->json($response, $code);
    }


//
    public function getList() {

      /*  $test = Test::get()->toJson(JSON_PRETTY_PRINT);
        return response($tests, 200);*/

      /*  return response()->json([
            "message" => "student record created"
        ], 201);*/

$data= array();     
          $data = DB::connection('default')->table('users')->where('id',$id)->get();
        return $this->sendResponse($data, 'Successfully');
        
      }
}

Proceed to the routes directory and open the api.php file and create the endpoints that will reference the methods created earlier in the ApiController

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

<!-- Route stored in routes/api.php -->

Route::get('getList', 'App\Http\Controllers\ApiController@getList');

or

Route::get('getList', 'ApiController@getList');

Test Api using Postman

Useful command for Laravel

composer dumpautoload

php artisan cache:clear

php artisan config:clear

php artisan view:clear

command php artisan list

 make:channel         Create a new channel class
  make:command         Create a new Artisan command
  make:controller      Create a new controller class
  make:event           Create a new event class
  make:exception       Create a new custom exception class
  make:factory         Create a new model factory
  make:job             Create a new job class
  make:listener        Create a new event listener class
  make:mail            Create a new email class
  make:middleware      Create a new middleware class
  make:migration       Create a new migration file
  make:model           Create a new Eloquent model class
  make:notification    Create a new notification class
  make:observer        Create a new observer class
  make:policy          Create a new policy class
  make:provider        Create a new service provider class
  make:request         Create a new form request class
  make:resource        Create a new resource
  make:rule            Create a new validation rule
  make:seeder          Create a new seeder class
  make:test            Create a new test class

Convert your website into a Desktop App for Windows, Mac, Linux

1, Node.js from here: https://nodejs.org/en/download/

2, Install git from here: https://git-scm.com/downloads

Clone this sample project:

git clone https://github.com/electron/electron-quick-start
cd electron-quick-start
npm install
npm start

It will download a sample project in your computer and “npm install” to install the required node modules in the project.

main.js

// Modules to control application life and create native browser window
const {app, BrowserWindow} = require('electron')
const path = require('path')

function createWindow () {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js')
    }
  })

  // and load the index.html of the app.
  mainWindow.loadURL('index.html')

  // Open the DevTools.
  // mainWindow.webContents.openDevTools()
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
  createWindow()
  
  app.on('activate', function () {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', function () {
  if (process.platform !== 'darwin') app.quit()
})

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.

index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP -->
    <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'">
    <meta http-equiv="X-Content-Security-Policy" content="default-src 'self'; script-src 'self'">
    <title>Hello World!</title>
  </head>
  <body>
    <h1>Hello World!</h1>
    We are using Node.js <span id="node-version"></span>,
    Chromium <span id="chrome-version"></span>,
    and Electron <span id="electron-version"></span>.
  </body>
</html>

Whatever you do in this HTML file it will be included in your application.

Now how to convert a website into an app:

mainWindow.loadURL('https://phplift.net/')

This will open your website in the application you can give it to your users to install in computers.

Commands to generate software build

Mac: electron-packager . --overwrite --platform=darwin --arch=x64 --icon=assets/icons/mac/icon.icns --prune=true --out=release-builds,
Windows: electron-packager . --overwrite --asar=true --platform=win32 --arch=ia32 --icon=assets/icons/win/icon.ico --prune=true --out=release-builds --version-string.CompanyName=CE --version-string.FileDescription=CE --version-string.ProductName="Electron Webview",
Linux: electron-packager . --overwrite --platform=linux --arch=x64 --icon=assets/icons/png/1024x1024.png --prune=true --out=release-builds,

Edit options as per your requirements.

This is just a simple application demo you can do a lot of things with this framework some amazing demos are available here: https://github.com/hokein/electron-sample-apps

Some desktop apps created on electron framework almost all developers use them is:

1. VS Code

2. Whatsapp Desktop app

3. Slack Desktop app

www-data is safe or not

For security.

The files are not world writeable. They are restricted to the owner of the files for writing.

The web server has to be run under a specific user. That user must exist.

If it were run under root, then all the files would have to be accessible by root and the user would need to be root to access the files. With root being the owner, a compromised web server would have access to your entire system. By specifying a specific ID a compromised web server would only have full access to its files and not the entire server.

If you decide to run it under a different user ID, then that user would need to be the effective owner of the files for proper privileges. It could be confusing to have personal ownership of system-wide files to your personal account.

Creating a specific user would make it easier to recognize the files and consistent to recognize which ID to chown to new files and folders added to the site.

The Userid or Name of the owner doesn’t matter. Whatever is chosen or decided upon will have to be configured in the web server configuration files.

By default the configuration of the owner is www-data in the Ubuntu configuration of Apache2. Since that is the default configuration, you conveniently know the ownership needed for your web files. If you change it, you would have to change the files in your site to match.

Important

It’s not a good idea to have write permissions on the entire folder, the most websites (for example: wordpress, joomla and magento) needs write permission on specific folders (image upload, file upload) A better way is to give write permission on folders and do not allow script (PHP, python) execution, always check if the user is uploading the right content, example, if you website allow an user to upload an image as it avatar, check if it is an image and not a fake image with PHP script inside. And the problem to have write permissions on the website root is if someone finds an vulnerability he could use that to write a new index.php file and ‘hack’ your website.

How to create static html page from dynamic php page

  • Opportunity to working on live project
  • Learn Advance topic in low cost
  • Get experience certificate
  • Learn Advance topic in limited time period
  • Get job opportunity
  • Topic cover on fast track
<?php
include ("include/conn.php");
error_reporting(E_ALL);
ini_set('display_errors', '1');
$cmdm="select * from satta_cms";
 $resultm=mysqli_query($link,$cmdm); 
 if($rowm=mysqli_fetch_array($resultm)){ 
	 $srno=$rowm['srno']; 
	 $message1=nl2br($rowm['message1']); 
	 $message2=nl2br($rowm['message2']); 
	 $message3=nl2br($rowm['message3']); } 
date_default_timezone_set('Asia/Kolkata');
$cmd1="select * from record"; $result1=mysqli_query($link,$cmd1);
 while($row1=mysqli_fetch_array($result1)){
	  $recno=$row1['recno'];
	 $tablename=$row1['tablename'];
			
 $cmd="select * from $tablename";
$result=mysqli_query($link,$cmd);
while($row=mysqli_fetch_array($result)){
	$recname=$row['recname'];
	$recdate=$row['recdate'];
	$rec=$row['new'];
	$recdispdate=date('d-M-Y',strtotime($recdate)); 
	ob_start();
?>
 
<!DOCTYPE html>
<html lang="en">
<head>
  <?php include('common/head.php'); ?>
 <style>
 h1.text-center {
    background-color: #000000;
    color: white !important;
    padding: 15px;
    text-align: center;
}
 </style>
  </head>
  <body>
<?php include('common/nav.php'); ?>


<div class="container">
<div class="row">
<?php include('common/advertise1.php'); ?>
<div class="col-lg-12"><h1 class="text-center"><?php echo date('d-M-Y',strtotime($recdate)); ?></h1></div>
<div class="live text-center">
    <h1><img src="satta-king.gif" width="70px"></h1>
 <div id="recbadge"> <h4 id="rectime"><?php echo $rec;?></h4><h2 id="recname" class="text-uppercase"><?php echo $recname;?></div>
 </div>

</div>
<hr>

</div>


<div class="container">
<div class="row">
<div class="col-lg-12">
<?php include('common/advertise0.php'); ?>
<?php include('common/message1.php'); ?>
<?php include('common/message2.php'); ?>
<?php include('common/message3.php'); ?>
    <?php include('common/advertise.php'); ?>
<?php //$cmd="select * from record order by rectime"; include('common/record-display.php');
?>
</div>
</div>
</div>
<?php
include('common/script.php');
 ?>

  </body>
</html>
<?php


$MainDir="satta-king-result";
 if(!is_dir($MainDir))
{
	mkdir($MainDir,0777);
}
$fileName=str_ireplace(' ','-',$recname).'-'.$recdispdate;

//
//$fp=fopen($MainDir.$QuestionId.".html","w");
$fp=fopen($MainDir."/".$fileName.".html","w");
$html = ob_get_contents();
fputs($fp,$html);


  } } ?>