Thursday, November 10, 2022

Loop object best approches

combine Object.keys() and Array.prototype.forEach():

var obj = { first: "John", last: "Doe" };

Option One: 

Object.keys(obj).forEach(function(key) {
    console.log(key, obj[key]);
});

Option Two: 


for (const key of Object.keys(obj)) {
    console.log(key, obj[key]);
}

Option Three: 

Object.entries(obj).forEach(
    ([key, value]) => console.log(key, value)
);


Option Four: 

for (const [key, value] of Object.entries(obj)) {
    console.log(key, value);
}

Vue.js — Three common approaches to organize your API calls

 When building a single page application, it is very common to make API calls to communicate with the server side, such as fetching data, submitting form, etc. Yet, Vue doesn’t provide an official practice for making API calls. Hence, I have summarized three common ways people are using to organize their APIs.

Concept of Programming and Software Development — by Andrey Suslov

1. Centralize all API calls in Vuex action

This approach is heavily inspired by the React-Redux model. Instead of having separated API calls in different components, you keep everything in Vuex action. Components know only actions but not endpoints. After the API call is returned, you do some data massage and business logic. After that, you update the state and notify components about the state change.

export default new Vuex.store({
state: {
account: null
},
mutations: {
setAccount(state, account) {
state.account = account;
}
},
actions: {
async signin({ commit }, { username, password }) {
let data = await axios.get('/api/signin', {
username,
password
});
commit('setAccount', data)
}
}
}

Then somewhere in your component:

export default {
computed: {
account() {
return this.$store.state.account
}
},
...
methods: {
submit(username, password) {
this.$store.dispatch('signin', { username, password })
},
...
},
...
}

The major advantage is that this is probably one of the most organized approach so far. You encapsulate not only the endpoints, but also the logic. It is extremely clean for components as they only need to care about the state change. Yet, the drawback is also quite obvious. It relies on the model of single direction of data flow from the store to components. It works well on project with concurrent and shared data. Yet, for application that is consisted of many different pages with totally different functionalities and local states, you may find this approach a bit crunky.

2. Manage API calls with plain JavaScript objects

This approach is more straight forward comparing with the previous one. You just make a file with one or more objects, and put all your API calls there. Here is a simplest example:

const signin = async (username, password) => {
let data = await axios.get('/api/signin', {
username,
password
});
let massageData = .... //Some data massage
return massageData
}
export {
signin
}

Then somewhere in your component:

import { signin } from '@/api';export default {
...
methods: {
submit(username, password) {
signin(username, password).then(account => {
...do something
})
},
...
},
...
}

The major pros of this approach is that it is not coupled with any data model. It is easy to learn and flexible enough to work in almost any application. It provides good readability without a great impact on your application architecture. The drawback is things happen outside the Vue instance. It can be quite messy when you need to trigger some Vue actions inside your isolated objects instead of the components, such as changing states, pushing routes, etc.

3. Keep APIs in components with boilerplate caller

This is the most casual one. You define some boilerplate callers and keep the endpoints in your components. You may use a separated file to store those callers:

const postForm = (url, params = {}) => {
let formData = new FormData();
Object.entries(params).forEach(([key, value]) => {
formData.set(key, value);
});
return axios({
method: 'post',
url: url,
data: formData,
headers: {'Content-Type': 'multipart/form-data' }
})
}
export default { postForm };

And somewhere in your component:

import { postForm } from '@/api';export default {
...
methods: {
submit(username, password) {
postForm('/api/signin', { username, password })
.then(account => {
...do something
})
},
...
},
...
}

Or you may even use a mixin:

export default {
methods: {
$_apiCaller_postForm(url, params = {}) => {
...
})
}
}

The rationale behind is that scalability is not always the major concern. Sometimes you know you are working on a short term project, and the endpoints are very unlikely to have change. This approach suits best for these kind of one-off developments.

This article aims to provide a short introduction on some common approaches people use to make API calls in Vue. There is no right or wrong answer. No approach is definitely better than the others. It totally depends on the situation. Also, I believe there are many other approaches that are not listed in this article. Please feel free to leave a comment and let me know if you know something interesting. :)

Sunday, August 28, 2022

How to Install or Upgrade PHP 8.1 on Ubuntu 20.04

 PHP 8.1 is the latest PHP version released on 2021. In this guide you are going to learn how to install the latest PHP version which is currently 8.1 on your Ubuntu 20.04 system or server and configure it with Apache and Nginx. You will also learn how to upgrade your PHP version to latest.

This tutorial guides you to configure PHP INI settings, FPM settings, Pools, etc which is more useful for your application to run smooth.

This installation is tested on Google Cloud Platform with a Compute Compute Engine VM Instance. This set up will work on all Linux servers.

Prerequisites

Basic knowledge of using SSH Terminal on Linux.

Getting Started

Make sure your Ubuntu server is having the latest packages by running the following command.

sudo apt update
sudo apt upgrade

This will update the package index and update the installed packages to the latest version.

Add PPA for PHP 8.1

Add the ondrej/php which has PHP 8.1 package and other required PHP extensions.

sudo apt install software-properties-common
sudo add-apt-repository ppa:ondrej/php
sudo apt update

Once you have added the PPA you can install PHP 8.1.

Install PHP 8.1 for Apache

Execute the following command to install PHP 8.1

sudo apt install php8.1

After the installation has completed, you can confirm the installation using the following command

php -v

Install PHP 8.1 FPM for Nginx

For Nginx you need to install FPM. Execute the following command to install PHP 8.1 FPM

sudo apt install php8.1-fpm

After the installation has completed, confirm that PHP 8.1 FPM has installed correctly with this command

php-fpm8.1 -v

Install PHP 8.1 Extensions

Installing PHP extensions are simple with the following syntax.

sudo apt install php8.1-extension_name

Now, install some commonly used php-extensions with the following command.

sudo apt install php8.1-common php8.1-mysql php8.1-xml php8.1-xmlrpc php8.1-curl php8.1-gd php8.1-imagick php8.1-cli php8.1-dev php8.1-imap php8.1-mbstring php8.1-opcache php8.1-soap php8.1-zip php8.1-redis php8.1-intl -y

Configure PHP 8.1

Now we configure PHP for Web Applications by changing some values in php.ini file.

For PHP 8.1 with Apache the php.ini location will be in following directory.

sudo nano /etc/php/8.1/apache2/php.ini

For PHP 8.1 FPM with Nginx the php.ini location will be in following directory.

sudo nano /etc/php/8.1/fpm/php.ini

Hit F6 for search inside the editor and update the following values for better performance.

upload_max_filesize = 32M 
post_max_size = 48M
memory_limit = 256M
max_execution_time = 600
max_input_vars = 3000
max_input_time = 1000

Once you have modified your PHP settings you need to restart your Apache for the changes to take effect.

For users with Nginx to who use PHP-FPM, you need to restart PHP-FPM.

sudo service php8.1-fpm restart

Configure PHP 8.1 FPM Pools

PHP-FPM allows you to configure the user and group that the service will run under. You can modify these with these commands

sudo nano /etc/php/8.1/fpm/pool.d/www.conf

If you want to change the username name you can change the following lines by replacing the www-data with your username.

user = username 
group = username 
listen.owner = username
listen.group = username

Hit CTRL+X and Y to save the configuration and check if the configuration is correct and restart PHP.

Restart PHP 8.1 FPM

Once you have updated your PHP FPM settings you need to restart it to apply the changes.

sudo php-fpm8.1 -t 
sudo service php8.1-fpm restart

Now you are having PHP 8.1 Installed and configured.

Prepare yourself for a role working as an Information Technology Professional with Linux operating system

Upgrade to PHP 8.1 for Apache

Once you have installed PHP 8.1 you need to upgrade to the latest installed version of PHP.

You need to tell Apache to use the PHP 8.1version we installed right now. Disable the old PHP module (below I have mentioned php7.4, you need to use your current php version used by Apache) and enable the new PHP module using the following command.

Replace the current enabled PHP version with your version.

sudo a2dismod php7.4
sudo a2enmod php8.1

Restart Apache for the changes to take effect.

sudo service apache2 restart

Upgrade PHP 8.1 for Nginx

For Nginx you need to update the PHP-FPM socket in your Nginx configration located inside the sites-available directory. This will be located inside the location block location ~ \.php$

Edit your configuration…

sudo nano /etc/nginx/sites-available/your.conf

The line you need to modify will look like this…

fastcgi_pass unix:/run/php/php7.4-fpm.sock; 

You need to replace the old PHP version with the new version.

fastcgi_pass unix:/run/php/php8.1-fpm.sock; 

Test your configration.

sudo nginx -t

Save the file and exit the editor and restart Nginx for the changes to take effect.

sudo service nginx restart

Conclusion

Now you have learned how to install PHP 8.1 on your Ubuntu server for Apache and Nginx and also how to upgrade to latest version.

Thanks for your time. If you face any problem or any feedback, please leave a comment below.

Link: https://www.cloudbooklet.com/how-to-install-or-upgrade-php-8-1-on-ubuntu-20-04/

Saturday, August 27, 2022

Increasing File Upload Size Limit In Nginx

 A common problem while running nginx as a frond end to php based Apache+mod_fastcgi server is the size that nginx allows you to upload. Sometimes the app allows user upload images up to 2MB in size. Other times when users try to upload 1.5MB or larger in size while using nginx reverse proxy, they are getting the following error on screen: “Nginx 413 Request Entity Too Large”. The question arises: how am I going to fix this problem and allow for image upload up to 2MB in size using nginx web-server working in reverse proxy, or by stand-alone mode on Unix like operating systems?

The error that you see, “413 – Request Entity Too Large”, notates that the web server is organized to restrict large file size. Nginx is able to be set to allow the maximum size of the client request body using the client_max_body_size directive. If the size of a request surpasses the configured value, the “413 error” is returned to the client.

Thus, you need to configure both nginx and php to allow an increase in upload size.

Increase file upload size limit in PHP-Nginx

If Nginx terminates your connection when uploading large files, you will see something like below in Nginx’s error logs:

[error] 25556#0: *52 client intended to send too large body:

This error message means that you must increase PHP file-upload size limit. Following steps given below will help you troubleshoot this common problem.

  1. Changes in php.ini: to modify the max file upload size to 100MB, edit:

vim /etc/php7/fpm/php.ini

Then, set:

upload_max_filesize = 100M
post_max_size = 100M

Additional Notes:

As a rule of thumb, post_max_size must always be bigger than upload_max_filesize except for large numbers like 100M (which can safely make them equal).

Another variable is max_input_time which can potentially limit upload size. If your application allows uploads of file-size in GBs, you may need to adjust for this. If utilizing PHP-FPM behind Nginx, this setup has Nginx uploading files and then Nginx copies it to PHP. As Nginx to PHP copying will be the local operation max_input_time and may never create issue. Also, Nginx may not copy the file but may simply hand-over the location of file or descriptor records to PHP.

  1. Change in Nginx config: Add following line to http{..} block in nginx config:

http {
#…
client_max_body_size 100m;
#…
}

Note: For very large files, it may be helpful to change the value of client_body_timeout parameter. The default is 60s.

Also, be sure to reload PHP-FPM & Nginx. This can be done with the following command:

Service php7-fpm reload

service nginx reload

  1. Changes in WordPress-Multisite: When running WordPress Multisite setup, be sure to make one more change at the WordPress end.

Go to: Network Admin Dashboard >> Settings. Look for Upload Settings. Also change value for Max upload file size.


service --status-all


https://www.digitalocean.com/community/questions/increase-file-upload-size-doesn-t-work-nginx-conf-php-ini


Monday, June 27, 2022

How to install Nginx and apache HTTP server on Ubuntu

Nginx is an open source HTTP web server that is often used as reverse proxy or HTTP cache. Nginx is popular for high-performance, speed, stability and low resource consumption.

In this article, we will walk through installing and setting up NginX server on Ubuntu. Follow these steps to install and setup NginX on your ubuntu.

Requirement

You need to be logged in non-root user with sudo permission. 

Installing Nginx

Nginx is available Ubuntu's default repository, so you can directly install with below command.

sudo apt-get update
sudo apt-get install nginx

After installing it, open your browser and run your server IP address. If you see this page, then you have successfully installed Nginx on your Ubuntu. This default page placed at /var/www/html/ location.

Configure Nginx

Check ufw application list with below command.

sudo ufw app list

Add Nginx to use port 80.

sudo ufw allow 'Nginx HTTP'

If you want to check Nginx server status, then you can run following command.

sudo systemctl status nginx

Add websites to Nginx

When using multiple websites, you need to add your websites to Nginx configuration. For that first create a new Nginx configration file.

sudo nano /etc/nginx/sites-available/website

And put the site details in it.

server {
    listen 80;
    listen [::]:80;

    root /var/www/html/website;
    index index.html index.htm index.nginx-debian.html;

    server_name website www.website.com;

    location / {
            try_files $uri $uri/ =404;
    }
}

Now create a website folder /var/www/html/website. And also give 755 permission.

sudo mkdir /var/www/html/website
sudo chmod -R 7555 /var/www/html/website

Now create simple page for website homepage.

sudo nano /var/www/html/website/index.html

And put any HTML code to check.

<!DOCTYPE html>
<html>
<head>
    <title>Hello World!</title>
</head>
<body>
    <h1>Hello World!</h1>
    <p>Welcome to Website.com</p>
</body>
</html>

Save this file. And now restart the Nginx server.

sudo systemctl restart nginx

Now open your and open your website. you should get your page.



Apache is open-source and most widely used web server in the world. It provides dynamic modules, and powerful support to website.

In this article, we will go through on how to install Apache web server in your Ubuntu 20.04 system.

Prerequisites:

You should have non-root user account logged in with sudo privileges to install Apache server.

Install apache2 server

Apache is already included in Ubuntu's repository, So you can directly install apache server from the Terminal command.

First update the repository index with bellow command.

sudo apt-get update

Install Apache server:

sudo apt-get install apache2

Configure apache server

First check the Apache in ufw application list.

sudo ufw app list

And allow the Apache server

sudo ufw allow 'Apache'

You can also check the ufw status

sudo ufw status

Apache server status

You can check the apache server status with the command:

sudo systemctl status apache2

Start the Apache server

sudo service apache2 start

Or stop the server

sudo service apache2 stop

This way, you can also restart the server

sudo service apache2 restart

This way you can setup your Apache to your server. If you have any suggestions or query, please let us know in the bellow comment section.