views:

66

answers:

3

I have index.php which uploads a file to server and sets several PHP variables (like $target_folder_and_file_name).

index.php also has the following line (it was originally index.html):

<script language="JavaScript" src="main.js.php"></script>

After index.php returned to the browser, the browsers asks for main.js.php from the server (right?).

Can I access somehow $target_folder_and_file_name from the PHP code in main.js.php ?

A: 

The easiest way to accomplish this is to put the information in the PHP session. Sessions last beyond one round trip. You can also add your information to a database, cache, external store, or to the URL of the javascript. As I mentioned, sessions are the easiest.

http://www.php.net/manual/en/session.examples.basic.php

<?php
session_start();
// Use $HTTP_SESSION_VARS with PHP 4.0.6 or less
if (!isset($_SESSION['count'])) {
  $_SESSION['count'] = 0;
} else {
  $_SESSION['count']++;
}
?>
TheJacobTaylor
I should also warn you to be very careful. If you allow people to upload files, do not let them control where the files go, what the files are named, or place the files in a web server document folder. There are many tools and people out there that love exploiting this kind of security hole. This may prove to be a valuable reference: http://php.net/manual/en/features.file-upload.php
TheJacobTaylor
A: 

If you don't want everything to be session dependent, you could pass a parameter to the script when fetching it.

index.php

<?
 //get filename in whatever manner you currently do
?>
<script language="JavaScript" src="main.js.php?t=<?= urlencode($filename); ?>"></script>

main.js.php

<?php
$filename = urldecode($_GET['t']);
//do whatever you need to with the filename
?>
Jeriko
+1  A: 

@TheJacobTaylor is right, sessions are the best, but if you dont want to keep "$target_folder_and_file_name" secret, you can also use: (index.php)

<script type="text/javascript" src="main.js.php<?php echo '?target='.urlencode($target_folder_and_file_name); ?>"></script>

and in your main.js.php

<?php
$target_folder_and_file_name = htmlspecialchars(urldecode($_GET['target']));
...
?>

with SESSIONS this would look something like this:

in your index.php

<?php
session_start();
$_SESSION['target'] = $target_folder_and_file_name;

...
echo '<script type="text/javascript" src="main.js.php"></script>';
...
?>

and in your main.js.php:

<?php
session_start();
if( isset( $_SESSION['target'] ) )
{
    $target_folder_and_file_name = $_SESSION['target'];
}
else
{
    $target_folder_and_file_name = FALSE;
}
...
?>
ahmet2106
Thank you very much for the code ! I have one more question: when does the session actually ends ?
Misha Moroshko
by default a session lasts until the user closes their browser. but you can use session_destroy() to make this manually.
ahmet2106
OK, thanks a lot !
Misha Moroshko