Include javascript files content in ob_start buffer - javascript

I am currently working on the translation of a website.
To perform this translation easily, I created a .csv file containing the matches between the two languages (japanese->english).
Then, this file is parsed with PHP, and ob_start() is called on the page in order to replace wanted strings.
Here is the script :
function lang_modify($buffer){
require('get_messages.php');
for($i=0; $i<count($messages); $i++){
$buffer = str_replace($messages[$i][0], $messages[$i][1], $buffer);
}
return $buffer;
}
$buffer = ob_start('lang_modify');
This script works perfectly on php/html files. However, ob_start does not read javascript files so I was wondering if someone knows a way to include javascript files into the output buffer so that the ob_start() function will replace the words found in javascript as well.
Someone adviced me to do search something with the AddFile statement (.htaccess), but I don't know at all how could I use this to do what I want.
Does anyone have a clue ?

What you are facing here, is a Separation of Concerns issue.
Your translation is generated from PHP.
And yet, your javascript displays and (sometimes) generates those messages.
How do i fix this?
1) Make sure your translations comes from one single source, ideally from PHP
2) Use an i18n js library to process your translations. I suggest: https://airbnb.github.io/polyglot.js/
3) If you are using Polyglot, make sure that your PHP translations are being generated into a js file, which is then loaded based on localisation.
Polygot will translate your default messages into internationalized ones.
In short:
Enable Modularity - Administer(CRUD) all your translations in PHP. Storing them in a database
would be ideal
Decouple JS from translation - Polygot will only provide the translated messages to your views(HTML).

Related

Load Random Image From Directory on Page Load Without a Listed Array of File Names

I've done some looking around on the site and every time I pull up a solution to this problem, one of the requirements is to have a naming convention and a list of every image to pull from the directory (example: image1.jpg, image2.jpg, etc.) All of the file names are different and there are thousands of them to pick from (so listing each one as a random opportunity in an array is not going to work).
I typically use CMS services and I'm writing this webpage from scratch in Notepad in an attempt to better my coding skills... and I'm not sure where to begin. I'm decent with HTML and CSS, but j Query and JavaScript are not my friends haha.
Thank you for any help! (Even if it's just pointing me to a tutorial or a solution I could not find!!!)
Are all file names image1 image2 image3 etc? Then you could try to generate a random number, create a new img element and have it's source pointing to image+randomnumber.jpg and append it to the DOM
One of the main problems your facing here is about your thinking when it comes to how content is delivered, in a standalone static website you do not have access to the file system. This means that if we want to query things outside of the browsers context we are not allowed, obviously without being able to access directories we can not generate a list of file names which can be loaded.
If your wondering why we can't access the file system directly from say the JavaScript it's because of the sandbox that most modern browsers live in, otherwise people could attack your native directories from the front end languages. Your question is interesting as electron removes this sandboxing in a sophisticated esk manner, which is necessary as it's used for building desktop apps with chromium.
These days the most obvious solution would be to use some form of back end language and to create a web server that has direct access to the native directories around it. Node, PhP, GoLang and many other populatr backend languages can parse a directory of files and then interpolate those into the frontend code which is the most common method.
The other popular method at the moment is to create API's which is just a fancy web server with a queryable end point that then executes code against our web server and provides back a list of such items. You could then for instance take the items and then print those out using javascript.
Reference directories method in php:
http://php.net/manual/en/ref.dir.php
List contents of directory in nodejs:
https://code-maven.com/list-content-of-directory-with-nodejs
The best place to really start with the easiest route to understand more would be to start a backend language in either node or php, with php being the simpler of the two.
https://www.w3schools.com/php/
First you need to get your file list from server side. then you can use a code like following:
var imageList = //your image list as an array of urls;
var imageNumber = Math.random() * imageList.length; //gives you a random number in the range of imageList's size
var imageToLoad = new Image();
imageToLoad.addEventListener("load", function(){
console.log( "image is loading" );
$('#my-container').append(this); //in this case this will return image dom
});
imageToLoad.src = imageList[imageNumber];
this will add image to a container with id 'my-container' its just an example you can do anything you want using 'this'
So after much help and guidance from the community, I have figured out the answer! To clarify my process in extreme detail, here is what I did to achieve the desired outcome:
Create the page as a .php file instead of a .html file (in my case, index.php). If you are using notepad to create the file, make sure you change the file extension to .php, the encoding to UTF-8, and save file type as "All Files". As I understand it, PHP can pick the file at random but cannot pass this info to a static HTML page.
Place this block of code into the webpage where the image should show. Currently, it is set up to reference a folder named, "images" out of the root directory (aka mysite.com/images/). This can be changed by modifying the text between the apostrophes after $imagesDir. All other html markup on the page will work correctly if it is outside of the php code block.
Code Block:
<?php
$imagesDir = 'images/';
$images = glob($imagesDir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);
$randomImage = $images[array_rand($images)];
echo "<img src='$randomImage'>";
?>
Thank you #bardizba for the code! Although there may be less resource intensive ways to write this, my situation was a bit different because the file names in the directory did not follow a naming convention and there was a mix of file types (jpg, gif, etc.)
Thanks again to everyone that helped me out!

Remove javascript comments within php file

I have a javascript file, myjs.php, that is generated on the server and delivered to the browser with a header.
Header("content-type: application/x-javascript; charset=utf-8");
The file is large and contains a lot of comments that are echoed within the js sections:
echo " // comments /* comments */ etc.
I appreciate that, if necessary, I could rewrite the php so that all comments were within php sections.
Is there a way, within PHP, to remove these comments at runtime so that they are not part of the file that is delivered to the browser, either by minifying or by some other means?
You can use tool such as UglifyJS from a PHP wrapper. There are packages to handle it, like UglifyPHP. After your file is generated, run the minifier on it, which will also strip comments:
use UglifyPHP\JS;
$js = new JS(['myjs.php']);
$js->minify('myjs.js', [
'comments' => false,
]);
In combination with ob_start(), ob_get_contents(), ob_end_clean() and using raw file stream as input you can achieve desired result.
Update:
Added this on demand by OP, if one haven't got possibility to use anything other than pure LAMP stack.
Here's a reference on how to remove single- and multiline PHP comments from a file:
Regex to strip comments and multi-line comments and empty lines
And here's working universal solution:
Best way to automatically remove comments from PHP code
This do the trick.

how to get the whole laravel language(localization) data onto view?

I want to use the laravel language data at the frontend part in the browser.
So I can use sprintf in js to show the same translation in frontend part.
I wish it could be an big javascript object. It would be very easy and nice to use.
Thanks in advance.
This is a situation I've dealt with myself and the answer is a bit awkward.
You can use Lang::get('file') to output the entire file as an array, which you can use with json_encode to do exactly what you want. But, as far as I know, you cannot get all language files. This probably has to do with the fact that Laravel cannot scan the directory for all file names without consuming a lot of disk resources, and does not do so normally. Language is handled with lazy loading in all applicable cases.
But! What you can do, is put all your JavaScript-related language in one file. I called mine widgets.php, and then do json_encode( Lang::get('widget') ) to get your JavaScript relevant language in one object.
Or, if you really do need all of it, you can build it manually.
$lang = ['auth', 'validation', 'etc'];
for ($files as $file)
{
$lang[$file] = Lang::get($file);
}
return json_encode($lang);
I guess easiest way to do that is to use cookies. Set coockie with Laravel:
$cookie = Cookie::make($name, $value);
Then read and parse it with JS:
var x = document.cookie;

JS, PHP, Html File Conventions

I have 3 questions, but I think the first 2 are very simple, so I'll ask them all here.
I normally work in C++ with SQL (and sometimes with VBA), and I'm trying to figure out the basics of JS, PHP & HTML (I've mostly got the jist of HTML and CSS).
I have 5 different reference books plus the net, but one thing I can't seem to find anything about are the file exts (.js, .php, .html).
From my tests I have come to realize that you can usually run JS scripts in other file types, but PHP seems to require the .php ext.
So the questions are:
Do I always have to use *.php for PHP scripting?
In a SINGLE file, can I delay PHP execution by simply putting the code into a function?
eg
<?php
function test() {echo "hello world";}
//as opposed to:
echo "hello world";
?>
When using multiple files, are there any compelling reasons to (or not to) always put scripts in their corresponding file types (e.g. JS in *.js). Obviously this would make it easier to understand / read, especially as it grows BUT can this create problems?
No, you can use any extension you want. Even if you want, don't use extension at all. But then, tell your server what interpreter to use when he founds he has to parse a *.wtf file. I mean, you're running a the script "file.wtf" from the command line you can do it like this:
$>php file.wtf
but if the script is to be parsed by your favorite web server (like Apache) because it is part of (say) a web page, then you have to configure it to interpret .wtf files with the PHP library.
By simply putting it in a function:no. But you really want to delay execution, use the sleep function
Just what you said: You can mix html and javascript code in your php files, but that is very messy.

PhpStorm Inject PHP language into JavaScript files

How can I add automatic language injection for PHP into JavaScript files?
When I add some PHP code into JavaScript the whole syntax highlighting messes up and I got a ton of errors.
I tried to add language injection with ALT+ENTER but I don't get PHP in my list of injections:
This won't work. The reason that it cannot be done is that when you load the javascript file in your browser, the PHP code will just appear as plain text, rather than actually be ran to produce the result that you want.
Just to reiterate, you cannot inject PHP code into Javascript files, what you can do however, is have inline javascript, within a file that can handle PHP. For example, if you want the variable contents, you'd have your JS file like follows:
$(function() {
loadSomething(varNameHere);
});
Then somewhere in the main body of the main, file somewhere that PHP can be ran, you can have this.
?>
<script> var varNameHere = "<?=$somePhp;?>"; </script>
<?php
While not ideal, this is a base example of how it'd work. Hope that helped.

Categories

Resources