PHP Beginner: How to pass PHP variable from one PHP code segment to another?
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 PH开发者_开发百科P code in main.js.php ?
@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;
}
...
?>
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']++;
}
?>
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
?>
精彩评论