Same Javascript code, unique outputs with PHP

381

I have the following Javascript:

<script>
function myFunction() { 
    document.write("Hello StackOverFlow users!");
}
myFunction();
</script>

Is any recommended/fast way to encode/encrypt/minify/pack the JavaScript using PHP so the output be different every time (using a random string to pack the js or anything similar)?
I just want the same function, that would do the same thing every time but with different JavaScript code each time.

518

Answer

Solution:

As most packers/compressors always use the same algorithm without any seed you might try to add some random js garbage before and after the function itself.

<?php
function getRandomGarbage(){
  return "\nfunction " . uniqid() . "(){}\n";
}
$myJsFunction = "... put your js here ";
//You can send the following to a php js compressor or pack it yourself
echo getRandomGarbage() . $myJsFunction . getRandomGarbage();
29

Answer

Solution:

Create random string function in PHP

<?php
/*
 * Create a random string
 * @author  XEWeb <>
 * @param $length the length of the string to create
 * @return $str the string
 */
function randomString($length = 6) {
    $str = "";
    $characters = array_merge(range('A','Z'), range('a','z'), range('0','9'));
    $max = count($characters) - 1;
    for ($i = 0; $i < $length; $i++) {
        $rand = mt_rand(0, $max);
        $str .= $characters[$rand];
    }
    return $str;
}
?>

Then modify your js function as follow

 <script>
    //assign php variable to js variable
    function myFunction() { 
        var randomString=<?php echo randomString(10);?>
        document.write(randomString);
    }
    myFunction();
 </script>

This will allow you to write random string each time JS function is called

[PHP function taken from 'https://www.xeweb.net/2011/02/11/generate-a-random-string-a-z-0-9-in-php/']

People are also looking for solutions to the problem: php - Update user table on login without touching vendors folder laravel 5.1

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.