how to convert php script to javascript - javascript

we have construct the one secret URL for my application.i have PHP script how to change java script any one help me to solve the issue
Below mentioned script how to change java script in c# application
i have php script this to change javascript
<html>
<title>Live</title>
<head>
<script src="http://content.jwplatform.com/libraries/Y09dkRGs.js"></script>
<script>jwplayer.key = "ti8UU55KNdJCPX+oWrJhLJNjkZYGiX13KS7yhlM7Ok/wmU3R";</script>
</head>
<body>
<?php
function bg_gen_secure_uri($file, $directory, $secret, $expiry=0, $allowed_countries='',
$disallowed_countries='', $allowed_ip='', $allowed_useragent='',
$allowed_metros='', $disallowed_metros='',
$progressive_start='', $progressive_end='',
$extra_params='') {
if ($file==''||$secret=='') {
return false;
}
// Construct the values for the MD5 salt ...
if (substr($expiry,0,1)=='=') {
$timestamp=substr($expiry,1);
} else if ($expiry > 0) {
$now=time(); // use UTC time since the server does
$timestamp=$now+$expiry;
} else {
$timestamp=0;
}
if ($allowed_countries) {
$allowed_countries='&a='.$allowed_countries;
}
if ($disallowed_countries) {
$disallowed_countries='&d='.$disallowed_countries;
}
if ($allowed_ip) {
$allowed_ip='&i='.$allowed_ip;
}
if ($allowed_useragent) {
$allowed_useragent='&u='.$allowed_useragent;
}
if ($progressive_start!='') {
$progressive_start='&start='.$progressive_start;
}
if ($progressive_end) {
$progressive_end='&end='.$progressive_end;
}
if ($allowed_metros) {
$allowed_metros='&am='.$allowed_metros;
}
if ($disallowed_metros) {
$disallowed_metros='&dm='.$disallowed_metros;
}
if ($extra_params) {
$extra_params=urldecode($extra_params);
}
// Generate the MD5 salt ...
if ($directory == '') {
$salt = $secret . $file . '?e=' . $timestamp . $allowed_countries .
$disallowed_countries . $allowed_metros . $disallowed_metros . $allowed_ip .
$allowed_useragent . $progressive_start . $progressive_end;
} else {
$salt = $secret . $directory . '?e=' . $timestamp . $allowed_countries .
$disallowed_countries . $allowed_metros . $disallowed_metros . $allowed_ip .
$allowed_useragent . $progressive_start . $progressive_end;
}
// Generate the MD5 hash ...
$hash_code = md5($salt);
// Generate the link ...
$url = $file . '?e=' . $timestamp . $allowed_countries . $disallowed_countries .
$allowed_metros . $disallowed_metros . $allowed_ip . $allowed_useragent .
$progressive_start . $progressive_end . '&h=' . $hash_code . $extra_params;
return $url;
}
function get_secure_url($file,$directory,$secret) {
$expiry=3600;
$allowed_countries='';
$disallowed_countries='';
$allowed_ip='';
$allowed_useragent='';
$allowed_metros='';
$disallowed_metros='';
$progressive_start='';
$progressive_end='';
$extra_params='&bgsecuredir=1';
return bg_gen_secure_uri($file, $directory, $secret, $expiry, $allowed_countries, $disallowed_countries, $allowed_ip, $allowed_useragent, $allowed_metros, $disallowed_metros, $progressive_start, $progressive_end, $extra_params);
}
$url = 'http://tv.live-s.cdn.bitgravity.com/cdn-live/_definst_/tv'.get_secure_url('/secure/live/tv/playlist.m3u8','/tv/secure/','kkkfdashfsdiads');
?>
<div>
<div id="player">
<div id="myElement"> </div>
<script type="text/javascript">
jwplayer("myElement").setup({
file: '<?=$url?>',
width: '100%',
aspectratio: '16:9',
stretching:'exactfit',
autostart: false,
androidhls: true,
skin: 'vapor',
primary: 'html5'
});
</script>
</div>
</div>

Install Composer from http://getcomposer.org/
Add the "base-reality/php-to-javascript": ">=0.0.3" to your project's
composer.json file:
"require":{ "base-reality/php-to-javascript": "0.1.16" }
Or the latest tagged version. The dev master should only be used for
development, not production.\
Include the Composer SPL autoload file in your project:
require_once('../vendor/autoload.php');
Call the converter:
$phpToJavascript = new PHPToJavascript\PHPToJavascript();
$phpToJavascript->addFromFile($inputFilename); $jsOutput =
$phpToJavascript->toJavascript();
$jsOutput will now contain an auto-generated Javascript version of
the PHP source file.
Hope this helps!
Thanks

You can convert PHP syntax to JS with https://gitlab.com/kornelski/babel-preset-php

Related

Combine Javascript files without erasing inline js

I have finally managed to combine all my WordPress Javascript from my theme and plugins into a single bundle using the function below:
function merge_all_scripts() {
global $wp_scripts;
$wp_scripts -> all_deps($wp_scripts -> queue);
$merged_file_location = get_stylesheet_directory() . DIRECTORY_SEPARATOR . 'merged-script.js';
$merged_script = '';
foreach( $wp_scripts->to_do as $handle) {
$src = strtok($wp_scripts->registered[$handle]->src, '?');
if (strpos($src, 'http') !== false) {
$site_url = site_url();
if (strpos($src, $site_url) !== false) $js_file_path = str_replace($site_url, '', $src);
else $js_file_path = $src;
$js_file_path = ltrim($js_file_path, '/');
} else {
$js_file_path = ltrim($src, '/');
}
if (file_exists($js_file_path)) {
$localize = '';
if (#key_exists('data', $wp_scripts->registered[$handle]->extra)) {
$localize = $obj->extra['data'] . ';';
}
$merged_script .= $localize . file_get_contents($js_file_path) . ';';
}
}
file_put_contents ( $merged_file_location , $merged_script);
wp_enqueue_script('merged-script', get_stylesheet_directory_uri() . '/merged-script.js', array(), '1.0', false );
foreach( $wp_scripts->to_do as $handle ) {
wp_deregister_script($handle);
}
}
add_action( 'wp_enqueue_scripts', 'merge_all_scripts', 99 );
Problem is it erases all inline woocommerce js defined in the "get_script_data" woocommerce function. I want it to include that aswell.
Otherwise content such as this will not get injected into the DOM, and therefore prevent the site from working properly:
var wc_add_to_cart_params = {"ajax_url":"\/wp-admin\/admin-ajax.php","wc_ajax_url":"\/?wc-ajax=%%endpoint%%","i18n_view_cart":"Se kurv","cart_url":"https:\/\/lawrence.dk\/bag\/","is_cart":"","cart_redirect_after_add":"no"};

php variable pass to javascript using getJSON()

i want to pass a php variable to javascript
on php(getStatus.php) i'm using json_encode like this
$resultFin = array();
if (strpos($status,'Scan is complete') === true){
$resultFin[] = 1;
}
else{
$resultFin[] = 0;
}
echo json_encode($resultFin);
echo "$status";
and i want get resultFin value on javascript so i wrote below code
echo '<script type="text/javascript">
$(document).ready(function() {
$.post("scanner/getStatus.php", {testId:' . "$testId" . ',chkCnt:' . "$chkCount" . ',rxss:' . "$rxss" . ',sxss:' . "$sxss" . ',sqli:' . "$sqli" . ',basqli:' . "$basqli" . ',autoc:' . "$autoc" . ',idor:' . "$idor" . ',dirlist:' . "$dirlist" . ',bannerdis:' . "$bannerdis" . ',sslcert:' . "$sslcert" . ',unredir:' . "$unredir" . ',clamav:' . "$clamav" . '}, function(data){$("#status").html(data)});
var refreshId = setInterval(function() {
$.post("scanner/getStatus.php", {testId:' . "$testId" . ',chkCnt:' . "$chkCount" . ',rxss:' . "$rxss" . ',sxss:' . "$sxss" . ',sqli:' . "$sqli" . ',basqli:' . "$basqli" . ',autoc:' . "$autoc" . ',idor:' . "$idor" . ',dirlist:' . "$dirlist" . ',bannerdis:' . "$bannerdis" . ',sslcert:' . "$sslcert" . ',unredir:' . "$unredir" . ',clamav:' . "$clamav" . '}, function(data){$("#status").html(data)});
console.log("dfdfdf");
$.getJSON("scanner/getStatus.php", function(data){
var fini;
fini = data;
console.log(fini);
if( fini == 1){
clearInterval(refreshId);
}
});
}, 500);
$.ajaxSetup({ cache: false });
});</script>';
i have checked it using brakepoint console.log("dfdfd");
but not getting into getJSON method and don't get resultFin value
how to fix this code?
i want resultFin value using in javascript
Your getStatus.php should look like:
$resultFin = array();
if (strpos($status,'Scan is complete') === true){
$resultFin['scan_completed'] = true;
}
else{
$resultFin['scan_completed'] = false;
}
echo json_encode($resultFin);
So on frontend you can use fini.scan_completed which will be true or false.

How to link Javascript files to HTML recursively

I'm trying to recursively link some Javascript files in a directory into a HTML page:
<?php
$dir = '/opt/lampp/htdocs/my_project/js';
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir), RecursiveIteratorIterator::SELF_FIRST );
foreach ( $iterator as $path ) {
if ($path->isDir()) {
print('dir >>> ' . $path->__toString() . PHP_EOL . '\n');
} else {
print($path->__toString() . PHP_EOL . '\n\n\n');
echo("<script src='$path->__toString() . PHP_EOL>\</script>");
}
}
?>
This, however, doesn't seem to work. How can I go about adding all the files in the directory and sub-directories recursively? Any working recursive approach will do. It doesn't have to be the way I'm trying it above.
Thank you all in advance.
Try changing your foreach block to below code and see if that helps?
foreach ( $iterator as $path ) {
if ($path->isDir()) {
print('dir >>> ' . $path . PHP_EOL);
} else {
print($path . PHP_EOL);
echo("<script src='$path'></script>".PHP_EOL);
}
}
The issue was with the syntax of "<script src='$path->__toString() . PHP_EOL>\</script>" changing this line to "<script src='$path'></script>" will help.

Dynamically include JavaScript from external file - PHP

Thanks in advance for your help. I am having a hard time keeping my codebase clean. I want to avoid intermixing PHP, HTML, and CSS.
Currently, my main site is broken down into numerous smaller tabs. The PHP code for these tabs is dynamically included after an ajax call is made.
elseif (file_exists('templates/custom/'.$center."/".$section."/".$tab.".php")) {
include 'templates/custom/'.$center."/".$section."/".$tab.".php";
}
It works great but I would also like to dynamically include JavaScript from an external file. In my mind it would work like this,
elseif (file_exists('templates/custom/'.$center."/".$section."/".$tab.".php")) {
include 'templates/custom/'.$center."/".$section."/".$tab.".php";
include 'templates/custom/'.$center."/".$section."/".$tab.".js";
}
How can I dynamically include javascript based on what tab the user wants to go to while still keeping the javascript separated by tab in individual files.
I have spent the entire day looking into this issue and keep coming across examples that look like this,
echo "<script language='javascript' type='text/javascript'>";
echo "alert('hello worldio');";
echo "</script>";
$URL="page.php";
echo "<script>location.href='$URL'</script>";
This site is a single page application. THanks again!
Just print the <script> tag to include it:
print '<script src="templates/custom/'.$center.'/'.$section.'/'.$tab.'.js'" type="text/javascript"></script>';
Javascript files cannot be included by php function. Use the below code
elseif (file_exists('templates/custom/'.$center."/".$section."/".$tab.".php")) {
include 'templates/custom/'.$center."/".$section."/".$tab.".php";
$file_path = "javascript external file path"; // replace with correct file path
?>
<script language="JavaScript" type="text/javascript" src="<?php echo $file_path;?>"></script>
<?php } ?>
hi in my case i use module base template that seprated to smaller parts.i have 3 main UI part in my site
1.public site js for all templates jquery,bootstrap ,... that use in all templates must put here
2.each style or template has a js folder that all public js file of this templates must be there
3.each module in template has js folder that js special for that module must be there
i do it for css too.in fact when i load a module check all of this folders by
array_slice(scandir($st_css_style_public_path), 2)
and create css link or js script and print final string of addresses in my page.
but some times you need to inject a peace of code directly into your page i use a folder and a file with name of plugins->plugins.php put all piece of script there get it's content and print it into my page
`$st_plugins .= (file_exists($st_plugin_style_public_path) ) ? file_get_contents($st_plugin_style_public_path) : ' ';
all of my render method in my view is this :
public function render($address, $data = '', $cache = 1, $showstyle = 1) {
$data['LINKPREFIX'] = '/' . $this->current_holding_unique_name
. '/'
. $this->current_lang;
if (isset($address)) {
$path = explode('/', $address);
$path[0] = $path[0];
$path[1] = $path[1];
}
$template = $this->twig->loadTemplate($path[0] . DS . $path[1] . '.twig');
if ($showstyle) {
$css_links = '';
$js_links = '';
$st_plugins = '';
//##################################################
//########################## CREATING CSS,JS ADDRESS
//##################################################
//####### SITE PUBLIC CSS & JS FILES
$st_js_public_path = '.' . DS . PUBLIC_DIR . DS . $this->set_address($path[0]) . 'js';
$st_css_public_path = '.' . DS . PUBLIC_DIR . DS . $this->set_address($path[0]) . 'css';
if (file_exists($st_js_public_path) && is_dir($st_js_public_path)) {
$ar_public_jsfile_list = array_slice(scandir($st_js_public_path), 2);
foreach ($ar_public_jsfile_list as $js_file_name) {
$js_links .= $this->create_css_js_link($st_js_public_path . DS . $js_file_name, 'js');
}
}
if (file_exists($st_css_public_path) && is_dir($st_css_public_path)) {
$ar_public_cssfile_list = array_slice(scandir($st_css_public_path), 2);
foreach ($ar_public_cssfile_list as $css_file_name) {
$css_links .= $this->create_css_js_link($st_css_public_path . DS . $css_file_name, 'css');
}
}
//####### STYLE PUBLIC CSS & JS & PLUGINS FILES
$st_js_style_public_path = '.' . DS . VIEW_DIR . DS . $this->current_style . DS . 'public' . DS . $this->current_direction . DS . 'js';
$st_css_style_public_path = '.' . DS . VIEW_DIR . DS . $this->current_style . DS . 'public' . DS . $this->current_direction . DS . 'css';
$st_plugin_style_public_path = '.' . DS . VIEW_DIR . DS . $this->current_style . DS . 'public' . DS . $this->current_direction . DS . 'plugins' . DS . 'plugins.php';
if (file_exists($st_css_style_public_path) && is_dir($st_css_style_public_path)) {
$ar_cssfile_list = array_slice(scandir($st_css_style_public_path), 2);
foreach ($ar_cssfile_list as $css_file_name) {
$css_links .= $this->create_css_js_link($st_css_style_public_path . DS . $css_file_name, 'css');
}
}
if (file_exists($st_js_style_public_path) && is_dir($st_js_style_public_path)) {
$ar_jsfile_list = array_slice(scandir($st_js_style_public_path), 2);
foreach ($ar_jsfile_list as $js_file_name) {
$js_links .= $this->create_css_js_link($st_js_style_public_path . DS . $js_file_name, 'js');
}
}
$st_plugins .= (file_exists($st_plugin_style_public_path) ) ? file_get_contents($st_plugin_style_public_path) : ' ';
//####### MODULE CSS & JS FILES
$st_js_style_path = '.' . DS . VIEW_DIR . DS . $this->current_style . DS . $path[0] . DS . $this->current_direction . DS . 'js';
$st_css_style_path = '.' . DS . VIEW_DIR . DS . $this->current_style . DS . $path[0] . DS . $this->current_direction . DS . 'css';
$st_plugin_path = '.' . DS . VIEW_DIR . DS . $this->current_style . DS . $path[0] . DS . $this->current_direction . DS . 'plugins' . DS . 'plugins.php';
if (file_exists($st_css_style_path) && is_dir($st_css_style_path)) {
$ar_cssfile_list = array_slice(scandir($st_css_style_path), 2);
foreach ($ar_cssfile_list as $css_file_name) {
$css_links .= $this->create_css_js_link($st_css_style_path . DS . $css_file_name, 'css');
}
}
if (file_exists($st_js_style_path) && is_dir($st_js_style_path)) {
$ar_jsfile_list = array_slice(scandir($st_js_style_path), 2);
foreach ($ar_jsfile_list as $js_file_name) {
$js_links .= $this->create_css_js_link($st_js_style_path . DS . $js_file_name, 'js');
}
}
$st_plugins .= (file_exists($st_plugin_path) && $showstyle ) ? file_get_contents($st_plugin_path) : ' ';
//################################################
//################################################
//################################################
//################################################
//# # # CREATING CSS,JS ADDRESS
$data['VARCSSADDR'] = $css_links;
$data['VARJSADDR'] = $js_links . $st_plugins;
$data['VARURL'] = '/';
$data = array_merge($data, lang_translate::$lang);
$template->display($data);
} else {
//$ar_langpropr = language::$ar_lanuage[session::get('current_lang')];
//$data['lang_code'] = $ar_langpropr['lang_code'];
$data = array_merge($data, lang_translate::$lang);
return $this->twig->render($address . '.twig', $data);
}
}
i am using twig template engine so there are some unrelated code to your question here;else part is for ajax call.
conclusion:
1-you can use this structure to add or delete file from a module as easy as copy or delete a file from it's folder.
2- you can use it to create correct js or css to create address by ajax and print it in your code
i hope it helped you and don't hesitate to as more question if you need
PHP include()'s are server-side.
JavaScript is client-side.
Therefore, you cannot use include() on a JavaScript.
However, if you would like to load a JavaScript with a URL that you want, use this:
$url = "JAVASCRIPT URL HERE";
echo('<script src="'. $url .'"></script>');

Passing variable from ajax to php fails

I am very new to javascript and ajax and I would like to do the folowing:
I have got a page where you can select the name of the person you want to upload a file. Then, through javascript you get that name in a variable and through ajax you pass the variable to a .php file where the upload takes place. The problem is that no name is passed and the file is upload in the same folder where all the names of the people are, not inside one of them. Here is the code I have got for the moment:
SOME NEW EDITS IN THE CODE
html
<select id="cuadro" name="op-cliente">
<option>bbraun</option>
<option>biosystems</option>
<option>seat</option>
<option>tradsp</option>
<option>tradin</option>
<option>vanderlande</option>
</select>
<script type="text/javascript">
$(function() {
// Setup html5 version
$("#uploader").pluploadQueue({
// General settings
runtimes : 'html5,flash,silverlight,html4',
url : 'plupload/examples/upload.php',
multipart_params: {'valor' : $('#cuadro').val()},
chunk_size: '5mb',
rename : true,
dragdrop: true,
filters : {
// Maximum file size
max_file_size : '500mb',
// Specify what files to browse for
mime_types: [
]
},
flash_swf_url : 'plupload/js/Moxie.swf',
silverlight_xap_url : 'plupload/js/Moxie.xap'
});
});
</script>
php
$valor = $_REQUEST['valor'];
$targetDir = ".." . DIRECTORY_SEPARATOR . ".." . DIRECTORY_SEPARATOR . "uploads" . DIRECTORY_SEPARATOR . $valor;
$cleanupTargetDir = true; // Remove old files
$maxFileAge = 7 * 24 * 3600; // Temp file age in seconds
// Create target dir
if (!file_exists($targetDir)) {
#mkdir($targetDir);
}
// Get a file name
if (isset($_REQUEST["name"])) {
$fileName = $_REQUEST["name"];
} elseif (!empty($_FILES)) {
$fileName = $_FILES["file"]["name"];
} else {
$fileName = uniqid("file_");
}
$filePath = $targetDir . DIRECTORY_SEPARATOR . $fileName;
// Chunking might be enabled
$chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
$chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 0;
// Remove old temp files
if ($cleanupTargetDir) {
if (!is_dir($targetDir) || !$dir = opendir($targetDir)) {
die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}');
}
while (($file = readdir($dir)) !== false) {
$tmpfilePath = $targetDir . DIRECTORY_SEPARATOR . $file;
// If temp file is current file proceed to the next
if ($tmpfilePath == "{$filePath}.part") {
continue;
}
// Remove temp file if it is older than the max age and is not the current file
if (preg_match('/\.part$/', $file) && (filemtime($tmpfilePath) < time() - $maxFileAge)) {
#unlink($tmpfilePath);
}
}
closedir($dir);
}
And this last time I got something that could be revealing: if I change this: multipart_params: {'valor' : $('#cuadro').val()}, to this: multipart_params: {'valor' : '5'}, it works and creates a folder called "5"....
Thank you very much for your time
I see you're passing it as a GET value. Therefore the variable is not in the POST.
Change
$_POST['valor']; to $_GET['valor'];
An Alternative
<select id="cuadro" name="op-cliente">
<option>bbraun</option>
<option>biosystems</option>
<option>seat</option>
<option>tradsp</option>
<option>tradin</option>
<option>vanderlande</option>
</select>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script type="text/javascript">
$('#cuadro').change(function(){
var selectedValue = $("#cuadro").val();
$.ajax({url:"plupload/examples/upload.php?valor="+selectedValue,cache:false,success:function(result){
alert("success");
}});
});
</script>
upload.php (For this way, use $_GET to get valor.)
$targetDir = ".." . DIRECTORY_SEPARATOR . ".." . DIRECTORY_SEPARATOR .
"uploads" . DIRECTORY_SEPARATOR . $_GET['valor'];
the problem i think you face is because you send the name of the person in one request and the file in an other request but if you send them in the same request you will get the wanted result i have tested this and it works for me.
this is index.php
<html>
<head>
<script type="text/javascript" src="jquery-1.12.0.js"></script>
<script type="text/javascript">
$(function(){
$('#my_Form').on('submit',function(e){
e.preventDefault();
var $form=$(this);
var fd = (window.FormData)? new FormData($form[0]) : null;
var data=(fd !==null)? fd : $form.serialize();
$.ajax($form.attr('action'),{
type:$form.attr('method'),
contentType:false,
processData:false,
dataType:'json',
data:data,
success:function(response){alert("sucess");},
error:function(response){alert("update failre");}
});
});
});
</script>
</head>
<body>
<form id="my_Form" action="upload.php" method="POST" enctype="multipart/form-data">
<fieldset>
<select name="person" >
<option value="jhon">jhnon</option>
<option value="albert">albert</option>
<option value="achabahe">achabahe</option>
<option value="Tom">Tom</option>
</select>
<input type="file" name="myFile"/>
<input type="submit" value="Upload"/>
</fieldset>
</form>
</body>
</html>
and this is upload.php
<?php
$tempFile=$_FILES['myFile']['tmp_name'];
$targetDir = ".." . DIRECTORY_SEPARATOR . ".." . DIRECTORY_SEPARATOR . "uploads" . DIRECTORY_SEPARATOR . $_POST['person'];
$uploadedFileName= $_FILES['myFile']['name'];
$maxFileAge=7*24*3600;
$cleanUpTargetDir=true;
if(!file_exists($targetDir)){
#mkdir($targetDir);
}
if($dir=opendir($targetDir)){
while($file=readdir($dir)) {
$file=$targetDir.DIRECTORY_SEPARATOR.$file;
if(filemtime($file)<(time() - $maxFileAge )){
#unlink($file);
}
}
}else{
die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}');
}
$filePath= $targetDir . DIRECTORY_SEPARATOR .$uploadedFileName;
move_uploaded_file($tempFile,$filePath);
?>

Categories