Encode data in php and uncompress in Javascript (ajax)

In order to reduce the size of my json file, I wanted to zip it. Hence, I am trying to compress json data file sent from php server :

In order to reduce the size of my json file, I wanted to zip it. Hence, I am trying to compress json data file sent from php server :

header('Content-Encoding: gzip'); 
$output = gzencode(json_encode($data));     
echo $output;

And then, uncompress it in javascript (ajax methodd) :

    url: url,
    type: "GET",
    headers : {'Accept-Encoding': 'gzip '},
    async: true,
    success: function (data) {
        console.log("sucess !!");

I also modified apache server in order to uncompress it automagically :

LoadModule deflate_module modules/mod_deflate.so

And :

 <IfModule mod_headers.c>
  <FilesMatch ".(js|css|xml|gz|txt|json)$">
      Header append Vary: Accept-Encoding

However, I couldnt get the data properly (it stills compress).

Could you please let me know what I am doing wrong ?

Thank you

PHP variable to JavaScript In Laravel

PHP variable to JavaScript In Laravel

In PHP, there is always a limitation on pass PHP variable to the javascript file. Many PHP developers, face this issue. But Laravel has one package which is directly set the variable in js. So, you can use this package for passing a variable from controller to javascript.

In PHP, there is always a limitation on pass PHP variable to the javascript file. Many PHP developers, face this issue. But Laravel has one package which is directly set the variable in js. So, you can use this package for passing a variable from controller to javascript.

However, we know the Laravel framework is having the largest community. Similarly, Laravel having large package base. So, sometimes it is easy to use package rather use custom code. Moreover, you can use existing packages.

Pass PHP variable to JavaScript

Many times you often find the need to pass PHP variable or string to the javascript file. But for this, you can use the below package.

Install package

Just copy below package and paste into the composer.json file.

"laracasts/utilities": "^2.1"

Or similarly from command line or terminal run command:

composer require laracasts/utilities


Further, add the Service provider into the config/app.php file. Which is used for the binding. After this, you will get Javascript facade.

'providers' => [

Publish the Configuration:

Finally, publish the config using the below command.

php artisan vendor:publish --provider="Laracasts\Utilities\JavaScript\JavaScriptServiceProvider"

Further, it will copy the javascript.js file to the config folder. There are two variable you can assign the values. Firstly, you can set bind_js_vars_to_this_view. This will set the name of the view. Basically, this is a partial view. If more than one view then you can set in array. Secondly, js_namespace is where you can define the namespace of the js variable. By default, Laracasts is the variable but you can change it to something else.

Usage in controller

Import the Dependency

You can initialize the JavaScript variable in the controller. Initialize and import into the controller.

use Javascript;

Set Variable

Now, you can define the variable into the controller using Javascript. You can set the values in the key-value pair. Assign a value to the key.

$array = [
    'key' => value_here,

So, put your value into the JavaScript variable using the value of an array. Once you define into the array and assign to the variable you can access it into the js file.

Now, your controller will look like below.

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use JavaScript;
class VarController extends Controller
     * Display a listing of the resource.
     * @return \Illuminate\Http\Response
    public function index()
            'foo' => 'bar',
            'user' => 'user',
            'time' => '2019-04-29'
        return view('pages/home');

Access In JS file

Now, your blade file will look like below.

    <div style="text-align:center">
        <h1>PHP var to JavaScript</h1>
<script src='assets/app.js'></script>

In js file, you can access the set variable into the Laracasts namespace. Which you define in the javascript.js file.

console.log(Laracasts.foo); // access foo variable
console.log(Laracasts.user);// access user variable
console.log(Laracasts.time);// access time variable

In this way, you can directly access the set variable. This will give simple access for getting value into the js file. There is a limitation for getting the value into the js file. So this package will give you direct access into js file.

In many cases, this will give you the simplest solution. Many developers have to face this problem in developement. So, this post will give some relief from this problem. Let me know if you face any issue.

Thanks For Visiting, Keep Visiting. If you liked this post, share it with all of your programming buddies!

Message Encryption in JavaScript and PHP

Message Encryption in JavaScript and PHP

Just for fun, let's encrypt some stuff in client-side JavaScript and have a PHP server decrypt it. Note that **this [will never replace TLS (HTTPS)](https://stackoverflow.com/a/12327375/2224584)**. ## JavaScript Encryption with...

Just for fun, let's encrypt some stuff in client-side JavaScript and have a PHP server decrypt it. Note that this will never replace TLS (HTTPS).

JavaScript Encryption with Sodium-Plus

You'll want the latest release of sodium-plus for this. (As of this writing, it's version 0.4.0.)


Next, you'll want to write some JavaScript code to encrypt a message and send it to a server. I'll be using jQuery for this example, but you can easily adapt it to use a XMLHttpRequest object instead.

Let's define two functions. One loads a CryptographyKey object from a hard-coded string (n.b. you never want to actually do this, but for the sake of an easy, working example, we're using a hard-coded secret). The other actually encrypts a message.

 * Get the example key. In the real world, you want to generate these randomly.
async function getExampleKey() {
    if (!window.sodium) window.sodium = await SodiumPlus.auto();
    return CryptographyKey.from(
    // return await sodium.crypto_secretbox_keygen();

 * Encrypt a message under a given key.
async function encryptMessage(message, key) {
    if (!window.sodium) window.sodium = await SodiumPlus.auto();

    let nonce = await sodium.randombytes_buf(24);
    let encrypted = await sodium.crypto_secretbox(message, nonce, key);
    return nonce.toString('hex') + encrypted.toString('hex');

Next, you'll want to write a function that gathers user input, encrypts it, and sends it to a server.

async function sendEncryptedMessage() {
    let key = await getExampleKey();
    let message = $("#user-input").val();
    let encrypted = await encryptMessage(message, key);
    $.post("/send-message", {"message": encrypted}, function (response) {
        $("#output").append("<li><pre>" + response.message + "</pre></li>");

...and some supporting HTML:

<label for="user-input">Type a message to encrypt and send:</label>
<textarea id="user-input"></textarea>
<button id="send-it" type="button">Send Encrypted Message</button>
<hr />
<ol id="output"></ol>

<script type="text/javascript">
$("#send-it").on('click', sendEncryptedMessage);

PHP Decryption with Sodium

You're going to want paragonie/sodium_compat.

If you're using PHP 7.2, with overwhelming probability you can just use the built in sodium_* functions. However, some distros may incorrectly disable the sodium extension by default. So to play it safe, install sodium_compat anyway.

If you're using a framework (Symfony, Laravel), your code will look a lot cleaner, but for the sake of illustration, the decryption code will look like this:


require 'vendor/autoload.php'; // Composer

header('Content-Type: application/json');

$key = sodium_hex2bin('e9897cea109576c2f8088c277125d553e4f83afbc0abbb92cfb1f7b776b4fee0');

$encrypted = $_POST['message'] ?? null;
if (!$encrypted) {
    echo json_encode(
        ['message' => null, 'error' => 'no message provided'],

$nonce = sodium_hex2bin(substr($encrypted, 0, 48));
$ciphertext = sodium_hex2bin(substr($encrypted, 48));
$plaintext = sodium_crypto_secretbox_open($ciphertext, $nonce, $key);

echo json_encode(
    ['message' => $plaintext, 'original' => $encrypted],

Putting it Together

When you type in a message and press the button, it will encrypt it and send a hex-encoded string to the server.

The PHP code will then decrypt the message and return the plaintext in a JSON response.

The JavaScript code will then grab the plaintext from the JSON response and append it to the output field below the form.

Security Considerations

This is just a toy example to illustrate how to use sodium-plus (JavaScript) and libsodium (PHP) to encrypt/decrypt messages.

We took a lot of shortcuts that you won't want to take in a real system (for example: hard-coding the encryption keys, and eschewing error-checking in favor of brevity).

JavaScript vs PHP: What's the Difference?

JavaScript vs PHP: What's the Difference?

In this post, you'll see the difference between PHP and JavaScript, from which you choose the language that's right for you.

Originally published by https://www.guru99.com

Is not fair to compare PHP vs JavaScript, as they both have different purposes for web-site development. PHP is a server-side scripting language while JavaScript is a client-side scripting language. In fact, the most dynamic website is created when we use functions of both these languages together. If PHP is like a paint-brush to paint picture, then JavaScript is a paint-color.

PHP stands for "Hypertext Preprocessor", is a programming language embedded in HTML that does all sort of things like build custom web content, send and receive cookies, evaluate form data sent from a browser, etc. It is integrated with number of popular databases like PostgreSQL, Oracle, Sybase, SQL, and MySQL. PHP also supports major protocols like IMAP, POP3 and LDAP.

PHP can handle forms, save data to a file, return data to the user, gather data from files, etc.

Example: Let say a website that takes user to view the order status after logging in. By PHP coding, you would send a query to the database that would then output the specific user information based on what information is in the database


While, JavaScript is designed for creating network-centric applications. With JavaScript, web pages will no longer be static HTML and allows the program that interacts with the user, control the browser, and dynamically create the HTML content. The advantage of JavaScript is that it has less server interaction, allowing you to validate user input before sending the page off which means less load on your server and less server traffic. JavaScript allows immediate feedback to the visitors.

Example: When you hover over the menu tab on the web-page, the drop down effect is done through JavaScript.

Note: JavaScript now supports server side execution via NodeJS

JavaScript vs PHP


Trend of JavaScript vs PHP

Job trends from indeed.com shows millions of jobs search for Java-script and PHP from thousands of job sites. It relatively shows the growing and falling trend of the job for both languages in consecutive years. 

Likewise, regional interest of people for these two languages are also highlighted over-here. In graph, though we can see the fall of interest of PHP and JavaScript languages over the period of time due to introduction of new languages, JavaScript still remains on top of PHP. 

Thanks for reading

If you liked this post, please do share/like it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading

JavaScript Programming Tutorial - Full JavaScript Course for Beginners

JavaScript Basics Before You Learn React

Build a CMS with Laravel and Vue

Developing RESTful APIs with Lumen (A PHP Micro-framework)

Why I still use PHP in 2019 and why you should too.