passing array from php to javascript - php

Hello
I'm trying to pass several arrays from php to javascript. For some of them it works, for others not. I get an array of filenames and an array which contains the content of several text files.
<?php
$album="./images/text_".$benutzerLang."_album1/";
$fileArray=lsRandom("./images/album1");
$listTextArray=initTexts($album,$fileArray);
$falseArray=lsRandom("./images/album2");
print $listTextArray[0];
?>
<script language="javascript" type="text/javascript">
var filesArray=new Array(5);
var falseArray=new Array(5);
var textListArray=new Array(5);
<?php
$i=0;
foreach($fileArray as $element){
print 'filesArray['.$i.']="'.$element.'";';
$i++;
}
$i=0;
foreach($falseArray as $element){
print 'falseArray['.$i.']="'.$element.'";';
$i++;
}
$i=0;
foreach($listTextArray as $element){
print 'textListArray['.$i.']="'.$element.'";';
$i++;
}
?>
function createText(){//...
</script>
<?php
function lsRandom($foldername){
$files = array();
$returnFiles=array();
$indexes=array();
$currentPath=getcwd();
chdir($foldername);
// Get the all files and folders in the given directory.
$files = glob("*", GLOB_BRACE + GLOB_MARK);
$indexes=(array_rand($files,5));
shuffle($indexes);
foreach($indexes as $in){
$returnFiles[$in]=$files[$in];
}
chdir($currentPath);
return $returnFiles;
}
function getFileText($fileName,$path){
$filePath=''.$path.''.$fileName.'';
//$file=fopen($filePath,'r');
//$text=fread($file,filesize($filePath));
$text=file_get_contents($filePath,false);
return $text;
}
function initTexts($album, $images){
$textArray1=array();
$i=0;
foreach($images as $im){
$nameArray=explode(".",$im);
$textName=''.$nameArray[0].'.txt';
$textArray1[$i]=getFileText($textName, $album);
$i++;
}
return $textArray1;
}
?>
The problem is the $listTextArray. In the 8th row I can print the whole array $listTextArray which contains the content of some small textfiles and it works. But further down in the 'foreach - loop'. It doesn't work anymore. As soon as I use the variable $listTextArray in the second php block the rest of my php code doesn't get executed anymore. I don't know why it can not access $listTextArray at that part. Because its no problem with the other arrays $fileArray and $falseArray.

Some general advice:
It's difficult to troubleshoot this kind of problem without the error message. If no error is being printed where you can see it, look for files named php.log, error.log, or httpd.log or ask your server admin(s).
Try using print_r() on your arrays to see if there's any difference in how they're structured. For example, just after setting the arrays in PHP:
print_r($fileArray);
print_r($listTextArray);
print_r($falseArray);
Rather than constructing the JS arrays via loops, try using the built-in json_encode() function instead. This both simplifies your PHP code and may cause more useful error messages when there are problems:
var filesArray=<?php json_encode($fileArray) ?>;
var falseArray=<?php json_encode($falseArray) ?>;
var textListArray=<?php json_encode($listTextArray) ?>;

you initiate
var textListArray=new Array(5);
but try to use
listTextArray
Use the same name and everything will be alright

The problem is already solved for you. Use json_encode instead.
print('filesArray = '.json_encode($filesArray));
Note that json_encode demands that your data is utf8 encoded. But you should do that already anyway.

Related

How to get variables from a different PHP file without executing the code?

I am trying to loop through all the php files listed in an array called $articleContents and extract the variables $articleTitle and $heroImage from each.
So far I have the following code:
$articleContents = array("article1.php", "article2.php"); // array of all file names
$articleInfo = [];
$size = count($articleContents);
for ($x = 0; $x <= $size; $x++) {
ob_start();
if (require_once('../articles/'.$articleContents[$x])) {
ob_end_clean();
$entry = array($articleContents[$x],$articleTitle,$heroImage);
array_push($articlesInfo, $entry);
}
The problem is, the php files visited in the loop have html, and I can't keep it from executing. I would like to get variables from each of these files without executing the html inside each one.
Also, the variables $articleTitle and $heroImage also exist at the top of the php file I'm working in, so I need to make sure the script knows I'm calling the variables in the external file and not the current one.
If this is not possible, can you please recommend an alternative method?
Thanks!
Don't do this.
Your PHP scripts should be for your application, not for your data. For your data, if you want to keep it file-based, use a separate file.
There are plenty of formats to choose from. JSON is quite popular. You can use PHP's built-in serialization as well, which has support for more PHP-native types but is not as portable to other frameworks.
A little hacky but seems to works:
$result = eval(
'return (function() {?>' .
file_get_contents('your_article.php') .
'return [\'articleTitle\' => $articleTitle, \'heroImage\' => $heroImage];})();'
);
Where your_article.php is something like:
<?php
$articleTitle = 'hola';
$heroImage = 'como te va';
The values are returned in the $result array.
Explanation:
Build a string of php code where the code in your article scripts are wrapped inside a function that returns an array with the values you want.
function() {
//code of your article.php
return ['articleTitle' => $articleTitle, 'heroImage' => $heroImage];
}
Maybe you must do some adaptations to the strings due <?php ?> tags placements.
Anyway, this stuff is ugly. I'm very sure that it can be refactored in some way.
Your problem (probably) comes down to using parentheses with require. See the example and note here.
Instead, format your code like this
$articlesInfo = []; // watch your spelling here
foreach ($articleContents as $file) {
ob_start();
if (require '../articles/' . $file) { // note, no parentheses around the path
$articlesInfo[] = [
$file,
$articleTitle,
$heroImage
];
}
ob_end_clean();
}
Update: I've tested this and it works just fine.

PHP replace {replace_me} with <?php include ?> in output buffer

I have a file like this
**buffer.php**
ob_start();
<h1>Welcome</h1>
{replace_me_with_working_php_include}
<h2>I got a problem..</h2>
ob_end_flush();
Everything inside the buffer is dynamically made with data from the database.
And inserting php into the database is not an option.
The issue is, I got my output buffer and i want to replace '{replace}' with a working php include, which includes a file that also has some html/php.
So my actual question is: How do i replace a string with working php-code in a output-buffer?
I hope you can help, have used way to much time on this.
Best regards - user2453885
EDIT - 25/11/14
I know wordpress or joomla is using some similar functions, you can write {rate} in your post, and it replaces it with a rating system(some rate-plugin). This is the secret knowledge I desire.
You can use preg_replace_callback and let the callback include the file you want to include and return the output. Or you could replace the placeholders with textual includes, save that as a file and include that file (sort of compile the thing)
For simple text you could do explode (though it's probably not the most efficient for large blocks of text):
function StringSwap($text ="", $rootdir ="", $begin = "{", $end = "}") {
// Explode beginning
$go = explode($begin,$text);
// Loop through the array
if(is_array($go)) {
foreach($go as $value) {
// Split ends if available
$value = explode($end,$value);
// If there is an end, key 0 should be the replacement
if(count($value) > 1) {
// Check if the file exists based on your root
if(is_file($rootdir . $value[0])) {
// If it is a real file, mark it and remove it
$new[]['file'] = $rootdir . $value[0];
unset($value[0]);
}
// All others set as text
$new[]['txt'] = implode($value);
}
else
// If not an array, not a file, just assign as text
$new[]['txt'] = $value;
}
}
// Loop through new array and handle each block as text or include
foreach($new as $block) {
if(isset($block['txt'])) {
echo (is_array($block['txt']))? implode(" ",$block['txt']): $block['txt']." ";
}
elseif(isset($block['file'])) {
include_once($block['file']);
}
}
}
// To use, drop your text in here as a string
// You need to set a root directory so it can map properly
StringSwap($text);
I might be misunderstanding something here, but something simple like this might work?
<?php
# Main page (retrieved from the database or wherever into a variable - output buffer example shown)
ob_start();
<h1>Welcome</h1>
{replace_me_with_working_php_include}
<h2>I got a problem..</h2>
$main = ob_get_clean();
# Replacement
ob_start();
include 'whatever.php';
$replacement = ob_get_clean();
echo str_replace('{replace_me_with_working_php_include}', $replacement, $main);
You can also use a return statement from within an include file if you wish to remove the output buffer from that task too.
Good luck!
Ty all for some lovely input.
I will try and anwser my own question as clear as I can.
problem: I first thought that I wanted to implement a php-function or include inside a buffer. This however is not what I wanted, and is not intended.
Solution: Callback function with my desired content. By using the function preg_replace_callback(), I could find the text I wanted to replace in my buffer and then replace it with whatever the callback(function) would return.
The callback then included the necessary files/.classes and used the functions with written content in it.
Tell me if you did not understand, or want to elaborate/tell more about my solution.

Removing last comma from out in PHP that is going into a javascript image pre-load script

Hi I have a javascript pre-load script that incorporates a php command to pre-load uploaded images for a future onClick action. Anyway I am having trouble removing the LAST comma from the last image the pre-load script pulls from.
Here is the script:
<div style="display:hidden">
<script type="text/javascript">
<!--//--><![CDATA[//><!--
var images = new Array()
function preload() {
for (i = 0; i < preload.arguments.length; i++) {
images[i] = new Image()
images[i].src = preload.arguments[i]
}
}
preload(
<?php
for ($i = 0; $i < 6; $i++) {
if (!empty($imgs[$i])) {
echo "'http://www.samplegallery.com/upload/image.php?img_source_url=" . $imgs[$i] . "&img_resize_to=500',";
}
}
?>
)
//--><!]]>
</script>
</div>
Anyway, I need to find out how to remove the last comma from the last image that is uploaded. Not sure how to do this. Please help me! BTW... the images don't have an extension since they are linking to a php image script that resizes them and places them into a watermark. Hope you guys can help me figure!
Think the other way! the comma could be at the start and then you remove it from the first one :)
if (!empty($imgs[$i])) {
$comma = $i == 0? '' : ',';
echo $comma."'http://www.samplegallery.com/upload/image.php?img_source_url=" . $imgs[$i] . "&img_resize_to=500'";
}
This way doesn't matter if $i is equal to 5, 8 or 139871!
The easiest way to do it is using the php build in implode() function
<?php echo implode(',', $imgs); ?>
And if you want just the first 6 images, you can make an array like so
$imgs = array_slice($imgs, 0, 6);
So the whole thing must look like that:
preload(
<?php
$imgs = array_slice($imgs, 0, 6);
echo implode(',', $imgs);
?>
)
to remove the last comma from a string, just use this:
$string = rtrim($string, ",");
May I suggest a slightly different approach to your problem? Whenever you want to pass data to JavaScript, JSON is probably the thing you want to generate. json_encode() helps you with that. Your script could look like:
var urls = <?php echo json_encode(array_values($imgs)); ?>;
var images = [];
function preload(urls) {
for (var i = 0; i < urls.length; i++) {
var url = 'http://www.samplegallery.com/upload/image.php?img_source_url='
+ encodeURIComponent(urls[i])
+ '&img_resize_to=500';
images[i] = new Image();
images[i].src = url;
}
}
preload(urls);
please note that I've taken the liberty of adding missing semicolons and var declarations to keep your variables local. I have added the array_values() call to make sure you're passing a numerically indexed array, rather than an associative array that would have resulted in an object literal { ... } rather than an array literl [ ... ].
I have also moved the URL building to JavaScript, as I didn't see a reason to keep it in PHP. If you need this to be in PHP and want to avoid the "manual" loop, look into array_map().
Please also note that I'm running your URL fragment through encodeURIComponent() to properly escape whatever it is you're passing in.
A note on security: should your script at /upload/image.php accept arbitrary URLs (and or "local file resources"), consider white-listing the allowed domains and paths.
You could use a foreach...
<?PHP
if ($count = count($imgs)) {
foreach ($imgs as $key=>$img) {
echo "http://www.samplegallery.com/upload/image.php?img_source_url="
. $img . "&img_resize_to=500";
if ($key < $count-1) echo ",";
}
}
?>

Assigning php POST array to Javascript array

I know this may sound similar to some past Q/As, I think mine is slightly different though.. I have a webpage which I want to dynamically load text file information. I upload the text file through an iframe and I want to save this information from php to Javascript. Whenever I try to save this as a regular variable it doesn't work so I have tried to do this by saving this information as a part of the $_POST array under a hidden form named $_POST['hidden_form']. Whenever I try to read the php into Javascript, I keep getting an error "Unexpected token ILLEGAL." I have tried the following two codes:
for($i=0;$i< count($_POST['hidden_form']) ;$i++)
{
echo "saved_form[$i]='" . $_POST['hidden_form'][$i]. "';\n";
}
and
saved_form = <?php echo json_encode($_POST['hidden_form']); ?>;
Assigning a php array into a javascript array
I think the error has to do with the " ' " needed to specify the array but not sure. I have no idea where to go from here so any help would be GREATLY appreciated. If there are better methods to do this please let me know. Thanks in advance!
saved_form = '<?php echo addslashes(json_encode($_POST['hidden_form'])); ?>';
Or
for($i=0;$i< count($_POST['hidden_form']) ;$i++)
{
echo "saved_form[$i]='" . addslashes($_POST['hidden_form'][$i]) . "';\n";
}
Both should work, probably had quotes breaking something?
the best way i have used is,
text/javascript
var saved_form = <?php echo json_encode($_POST['hidden_form']) ?>
Please note there are no Quotes around the php so your saved_form is an Object not a string json string witch would require you to to use var form_object = eval(saved_form)
#Lee might have meant this?
Just a note though i would not use the Raw $_POST pass it to a function that can loop though and addSlashes every value inside the post some thing like
<?php
function arr_addSlashes($array){
$ret = array();
foreach($array as $k => $v){
$ret[$k] = addSlashes($v);
}
return $ret;
}
?>

Is there any way to get all GET vars with javascript?

First off, I do not want what is in the URL query. I want what PHP see's in the$_GET array.
This is because the URL query will not show all the params if mod_rewrite has been used to make pretty URLs
So is there a way to get the query string that would match exactly what is in the php $_GET array?
--
I came up with a way myself using PHP and JavaScript like so:
function query_string()
{
<?php
function assoc_array_to_string ($arr)
{
$a = array();
foreach($arr as $key => $value)
{
$str = $key.'='.$value;
$a[] = $str;
}
return implode("&",$a);
}
?>
return '<?=urlencode(assoc_array_to_string($_GET))?>';
}
...but I need to do this with just javascript if possible because I can't put PHP code in a .js file.
Won't JavaScript "only see" the query string? How would client-side script know about any rewrite rules?
The only way I can think of is to use PHP -- echo it into a variable in an inline script in your main page rather than the JS file.
In your page <head>:
<script type="text/javascript">
var phpQueryParams = <?php print json_encode($_GET); ?>
</script>
Assuming at least PHP 5.2, otherwise use an external package
The query string is found in window.location.search, but that's the raw query string. So if you run something like this:
(function () {
QueryStr = {}
QueryStr.raw = window.location.search.substr(1);
var pairStrs = QueryStr.raw.split('&');
QueryStr.val = {}
for(var i=0,z=pairStrs.length; i < z; i++) {
var pair = pairStrs[i].split('=');
QueryStr.val[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
}
})();
You'd have something very much like $_GET in QueryStr.val.
Of course, you mention that you've mixed things up a bit using mod_rewrite, which is cool, but since we don't know your rewrite scheme, we can't help specifically with that.
However... you know your rewrite scheme, and you could probably modify the code I gave above to operate on some other part of window.location. My bet is that you'd want to split window.location.pathname on the / character instead of &.

Categories