Jump to content

Passing Session Var to called file


aleX_hill

Recommended Posts

Hi All,

 

I am using the uploadify script available at http://uploadify.com/

 

Now I can get the file uploads working fine with the script below:

<?php
session_start();
?>

<link href="/uploadify/uploadify.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="/uploadify/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="/uploadify/swfobject.js"></script>
<script type="text/javascript" src="/uploadify/jquery.uploadify.v2.1.0.min.js"></script>

<input id="fileInput" name="fileInput" type="file" />
<script type="text/javascript">// <![CDATA[
    $(document).ready(function() {
    $('#fileInput').uploadify({
    'uploader'  : '/uploadify/uploadify.swf',
    'script'    : '/uploadify/uploadify.php',
    'cancelImg' : '/uploadify/cancel.png',
    'auto'      : true,
    'folder'    : '<?php echo $_SESSION['filepath']."/downloads/"; ?>',
'multi'     : true
    });
    });
    // ]]></script>

 

The problem that I am having is that I also store the mysql connection details in session vars (they change depending on who logs in). I have tried a number of ways of "passing" these session vars to the uploadify.php file which does the grunt work of the uploading, but I can never seem to access them. I obviously dont want to pass them to the uploadify.php script through the js because that will show my credentials in the source code.

 

So, the question is, how can I access these session vars in the called file. I assume its a combination of session_write_end() and session_start() but I havent got the right combination yet.

Link to comment
Share on other sites

sadr: The contents of the uploadify file are not displayed, so what I did was hard code in some mysql connection details, and try and write the session var to the db (to see what the session var contained), i got blank (although the write to db worked)

 

ohdang888: yes they are. When the user logs in I include a particular file based on their user group, this included file sets the session vars or db_user, db_server, db_table etc. I cant see a way of hardcoding into the file at the moment.

Link to comment
Share on other sites

I'm now looking at your code and I think.

Accidentally your code isn't loking somethink like this

<!DOCTYPE >
<html>
<head>
<?php
session_start();
?>
<link href="/uploadify/uploadify.css" rel="stylesheet" type="text/css" /><script type="text/javascript" src="/uploadify/jquery-1.3.2.min.js"></script><script type="text/javascript" src="/uploadify/swfobject.js"></script>
//etc

 

if so then here's your problem u must strat session before any output even white space before "<?php" can mess up everythink

 

here's right way to do it:

<?php
session_start();
?>
<!DOCTYPE>
<html>
<head>
<link>
<script>
</head>
<body>
//....

Link to comment
Share on other sites

before i begin, i think this is off topic from what you wanted, but it is nevertheless an issue in your security (storing that data in $_SESSION)

 

yes they are. When the user logs in I include a particular file based on their user group, this included file sets the session vars or db_user, db_server, db_table etc. I cant see a way of hardcoding into the file at the moment.

ok, the solution i'm thinking of is very inefficient, and i wouldn't advise this on a large scale, but then again i wouldn't advise your current setup.

 

anyways, here goes:

hardcore a mysql connect into the files with a generic username, database, etc. Have a table that includes the new table, database names, usernames, etc. (passwords too, i guess. theres a way around doing this, but thats even more innefficient).. and have the column "setting_id" or something, and assign the user a setting id from one of the possible tablesets, etc. Store THAT setting id in $_SESSION, and again, hardcore a mysql query that selects their new tablesets, and use mysql fetch array to get that information into variables that you will use from then on. Run another mysql connect, db_select, all with your new information

 

I'm not sure what you're trying to protect and whatnot, but unless its particularly important or sensitive data, this method (in my opinion) is not worth the extra time and CPU load on the server

Link to comment
Share on other sites

That file is called in an iframe, so I havnet bothered putting <html> or <DOCTYPE> tags etc.

 

The $_SESSION vars work well in the code I showed you and i get:

 

'folder'    : 'my/path/to/downloads/',

 

fine. But when I upload a file, this info is passed to uploadify.php (which I have put a cut down version below):

<?php
session_start();
$connection = mysql_connect($_SESSION['server'], 
        $_SESSION['user'], 
        $_SESSION['password']); 

    mysql_select_db($_SESSION['database'], $connection); 

if (!empty($_FILES)) {
$tempFile = $_FILES['Filedata']['tmp_name'];
//$targetPath = $_SERVER['DOCUMENT_ROOT'] . $_REQUEST['folder'] . '/';
$targetPath = $_REQUEST['folder'];
//$targetFile =  str_replace('//','/',$targetPath) . $_FILES['Filedata']['name'];
$targetFile =  $targetPath . $_FILES['Filedata']['name'];

// $fileTypes  = str_replace('*.','',$_REQUEST['fileext']);
// $fileTypes  = str_replace(';','|',$fileTypes);
// $typesArray = split('\|',$fileTypes);
// $fileParts  = pathinfo($_FILES['Filedata']['name']);

// if (in_array($fileParts['extension'],$typesArray)) {
	// Uncomment the following line if you want to make the directory if it doesn't exist
	// mkdir(str_replace('//','/',$targetPath), 0755, true);

//Check to see if I got my session vars through (I hard code values when using this bit)
	$title = $_FILES['Filedata']['name'];
	$file = $_FILES['Filedata']['name'];
	$query = "INSERT INTO photos (title, file) VALUES ('$title', '$_SESSION[db_server]')";
	$result = mysql_query($query);

	move_uploaded_file($tempFile,$targetFile);
	echo $result; //nothing is ever echoed as it is called in the background
// } else {
// 	echo 'Invalid file type.';
// }
}
?>


 

Link to comment
Share on other sites

ohdang888: I will look into that in the future, still in a dev stage at the moment.

 

The setup I use is:

 

login form -> login.php which includes a file similar to "/profiles/$_POST['username'].php" - there are very few users so I dont have 500 profile files

then header.php (on all site pages) calls sqlConnect.php which uses the $_SESSION vars to connect to the db.

 

I might put a user_id into the session var then put a switch in the sqlConnect.php file.

 

Either way, I will need to get the session var of the user id through to the uploadify.php file

 

Link to comment
Share on other sites

Your upload script seems fine. And your $_SESSION vars are fine too. So, whats the problem? Is it returning errors? just blank?

 

Another side note:

includes a file similar to "/profiles/$_POST['username'].php" - there are very few users so I dont have 500 profile files

You're not truly understanding the reason PHP was built. Imagine how long that would take to update even 50 files. With all due respect, that setup is ridicolous, even for a dev app. Its impossible to build a decently good system with that. You need to, VERY soon, make a single "profile.php" page, where it takes the $_GET['username']... so instead of dozens of files of usernames... you would have a url like profile.php?username=$_POST['username']

Link to comment
Share on other sites

I just get nothing in mysql. So if i use the session var, nothing is written to the db.

 

If I use hard coded and run the query to put the $_SESSION var into the db, then I get a row added to the db, with the $title var going in fine, but the "file" item in the db row is blank.

 

And the structure of setting the sesison vars is irrelevant at the moment. the main reason i did it this way was it was easier for me to troubleshoot at the beginning (there is only 3 profile pages). The login really asks for username, password and website (from select box). Each "website" has its own db, hence the different session vars. Like I said, i will change this in the future.

Link to comment
Share on other sites

Not really that setup.

 

The site is a CMS which connects to a different db depending on the login, used by a couple of primary schools in my area. So when they hit the login page, they choose their school from the drop down, then enter their username/password. This way I know which db to connect to so that I can properly authenticate them. The session vars also get used to connect to the db each time I run a query. So same source code for the cms for all schools, except it is operating on a different db.

 

If I need to add a school, my thoughts were just to duplicate the profiles/schoolname.php file and put in the new db details, but after this thread I will probably change the way I am doing things.

 

Either way, I want to be able to read the session vars in the uploadify.php file rather then pass them through as a parameter to the iframe, so people cant just call the upload script, pass in a "user_id" or similar and connect to the db. (ie <iframe src="uploadScript.php?user_id=2"> )

 

I will keep working on it and see what I come up with.

Link to comment
Share on other sites

page.php has an iframe with source upload.php, which loads a flash object to handle uploads. this then calls uploadify.php with the $_FILES details.

 

I could get the session vars into the iframe fine, but just not into uploadify.php . The same would have happened whether upload.php was in an iframe or standalone.

Link to comment
Share on other sites

  • 7 months later...

It's likely that either the host-name (sub-domain, even the www. vs no-www being used) or the path part of the URL changed from where the session id cookie was set at and the session id cookie settings are not set to match all sub domains or paths on your domain.

 

All HTTP requests that the browser makes, even if it is due to a flash object on a page, sends all the matching cookies to the server with that request, so, if your session is not working because the session id is not sent, it is likely because the URL being requested does not match the cookie and you would need to set up the cookie so that it will match all variations of your domain.

 

You should start a new thread for your problem (it's unlikely it is identical.)

Link to comment
Share on other sites

This is how I got the session variable into the flash uploader:

<input id="fileInput" name="fileInput" type="file" />
<script type="text/javascript">// <![CDATA[
    $(document).ready(function() {
    $('#fileInput').uploadify({
    'uploader'  : '/uploadify/uploadify.swf',
    'script'    : '/uploadify/uploadify.php',
    'cancelImg' : '/uploadify/cancel.png',
    'auto'      : true,
    'folder'    : 'uploads/',
'multi'     : true,
'sizeLimit' : '800000',
'fileDesc'  : 'Image Files',
'fileExt'   : '*.jpg;*.gif;*.png;*.bmp',
scriptData: { <?php echo session_name(); ?>: '<?php echo session_id();?>',
albumID : <?php echo $_GET['albumID']; ?>}
    });
    });
    // ]]></script>

 

The obvious change is the scriptData being passed in.

 

With the corresponding session_start() called at the beginning of the file.

 

Then I had this in the file which loads the uploadify.php:

 

$x = $_POST; // your method type
$session_name = session_name();

if (!isset($x[$session_name])) {
// not logged
   exit;
}
else {
      session_id($x[$session_name]);
      session_start();
}

 

Hope this is what you were after.

 

Link to comment
Share on other sites

That is what I'm after but I still can't get it working. Here is what i'm working with:

 

I have a form that the ADMIN fills out to register a user:

once the form is submitted, I do the following to capture the user's email address that I JUST registered:

 

$currentemail=$_REQUEST['Email'];
$_SESSION['current_email']=$currentemail;
header('Location:/upload');

 

As you can see the above also redirects the ADMIN to upload/index.php (which is the front end of uploadify - where you can select files to upload):

 

index.php looks like this:

 

<?php
  session_start();
  if ($_SESSION['level']=="1"){
        echo "<b>Welcome, ".$_SESSION['firstname']."!</b><br><br>";
        echo "<a href='/register'>Home</a> | <a href='/logout/index.php'>Log Out</a><br /><hr width='100%'></hr><br>";
}else{
        die("Access Denied.");
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Shots by Shell Pictures Upload</title>
<link href="/scripts/default.css" rel="stylesheet" type="text/css" />
<link href="/scripts/uploadify.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="/scripts/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="/scripts/swfobject.js"></script>
<script type="text/javascript" src="/scripts/jquery.uploadify.v2.1.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
        $("#uploadify").uploadify({
                'uploader'       : '/scripts/uploadify.swf',
                'script'         : 'upload.php',
                'cancelImg'      : '/images/cancel.png',
                'folder'         : 'uploads',
                'queueID'        : 'fileQueue',
                'auto'           : true,
                'multi'          : true,
                'scriptData'     :{'current_email':'<?php echo session_id();?>'}
        });                                                                                                                     
});
</script>
</head>

<body>
<div id="fileQueue"></div>
<input type="file" name="uploadify" id="uploadify" />
<p><a href="javascript:jQuery('#uploadify').uploadifyClearQueue()">Cancel All Uploads</a></p>
</body>
</html>

 

 

'scriptData'    :{'current_email':'<?php echo session_id();?>'}  is the line I can't figure out how to set in order to get $_SESSION['current_email'] to pass to uploadify.php. This is necessary, because i need to get that user's email into a database as shown below in my upload.php:

 

<?php
session_start();
//	var_dump($_SESSION);

if (!empty($_FILES)) {
$con = mysql_connect("localhost", "xxx", "xxx") or die("cannot connect");
	 mysql_select_db("xxx", $con) or die("cannot select DB");
$tempFile = $_FILES["Filedata"]["tmp_name"];
$name = $_FILES["Filedata"]["name"];
$targetPath = "uploads/";
$targetFile =  str_replace('//','/',$targetPath) . $_FILES["Filedata"]['name'];
      	$size = $_FILES["Filedata"]["size"];
        $oext = getExtension($name);
        $ext = strtolower($oext);
$whois = $_SERVER['REMOTE_ADDR'];
// THIS ISN'T GETTING PASSED $email = $_SESSION['current_email'];

          if ($ext == "jpg" || $ext == "jpeg" || $ext == "bmp" || $ext == "gif") {
              if ($size < 1024 * 1024) {
                  if (file_exists("uploads/" . $name)) {
                      move_uploaded_file($tempFile, "uploads/" . $name);
                      $qry = "select id from pictures where path='$targetFile' and type='$ext'";
                      $res = mysql_fetch_array(mysql_query($qry));
                      $id = $res['id'];
                      $qry = "UPDATE pictures SET path='$targetFile', type='$ext', size='$size', whois='$whois', date=NOW() where id=$id";
                      mysql_query($qry);
                      echo "1";
                      ?><div style="float:right; text-align:left; width:400px;"><?php echo "Image '$name' <font color='blue'>updated</font><br />";
                  } else {
                      move_uploaded_file($tempFile, "uploads/" . $name);
                      $qry = "INSERT INTO pictures(id, path, type, size, email, whois, date) VALUES ('', '$targetFile', '$ext', '$size', '$email', '$whois', NOW())";

                      mysql_query($qry, $con);
		echo "1";
                      ?><div style="float:right; text-align:left; width:400px;"><?php echo "Image '$name' <font color='green'>uploaded</font><br />";
                  }
              } else { 
                  ?><div style="float:right; text-align:left width:400px;"><?php echo "<font color='red'><B>Image size excedded.<br />File size should be less than 1Mb</B></font><br />";
              }
          } else {
              ?><div style="float:right; text-align:left; width:400px;"><?php  echo "<font color='red'><B>Invalid file extension '.$oext'</B></font><br />";
          }
      }
  
  function getExtension($image_name)
  {
      return substr($image_name, strrpos($image_name, '.') + 1);
  }

?>

 

I appreciate you helping me out! - especially on this old of thread :P

 

 

Link to comment
Share on other sites

I am a bit out of touch with this code, havent touched it since the original post, but try using exactly this:

 

scriptData: { <?php echo session_name(); ?>: '<?php echo session_id();?>'}

 

And then:

$session_name = session_name();
session_id($_POST[$session_name]);
session_start();

 

From memory this will set the entire $_SESSION variable.

 

Or try editing your line to match this:

scriptData     :{current_email:'<?php echo $_SESSION['current_email']; ?>'} //removed some quotes as well as changed session var

 

Then in the processing see what $_POST['current_email'] holds...

Link to comment
Share on other sites

@aleX_hill,

 

You may or may not want to revisit this, but your problem reads like the session id is not being passed because the uploadify.php file is in a different folder and the session.cookie_path is not set to the default of / to get the session cookie to match all paths of your domain.

 

Are all these websites using the same domain name? What does a phpinfo(); statement show for the session.cookie_path?

 

Another reason you might want to revisit this is because getting the destination folder for the uploaded file from the client will allow someone to overwrite any of your site's files with his own by specifying any path they want. Your uploadify.php code should set or determine the destination path independent of any data the script receives from the client.

Link to comment
Share on other sites

Hmmm... I played with the uploadify code and it does not cause the session id cookie to be sent for some reason, so passing the session name/session id through the uploadify code is probably the simplest solution.

 

@dschuett, if you pass the session id into the uploadify.php file the way aleX_hill has shown, your $_SESSION variables will exist. You don't need to do anything else.

Link to comment
Share on other sites

@PFMaBiSmAd

 

I still can't get it to work.

 

I have a session called $_SESSION['current_email'] which is created when a form is submitted. (This holds a users email).

 

I have done this to my uploadify index.php:

 

<?php  session_start();  if ($_SESSION['level']=="1"){echo "<b>Welcome, ".$_SESSION['firstname']."!</b><br><br>";echo "<a href='http://sbslogin.ath.cx:8080/register'>Home</a> | <a href='/logout/index.php'>Log Out</a><br /><hr width='100%'></hr><br>";}else{        die("Access Denied.");}?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>Shots by Shell Pictures Upload</title><link href="/scripts/default.css" rel="stylesheet" type="text/css" /><link href="/scripts/uploadify.css" rel="stylesheet" type="text/css" /><script type="text/javascript" src="/scripts/jquery-1.3.2.min.js"></script><script type="text/javascript" src="/scripts/swfobject.js"></script><script type="text/javascript" src="/scripts/jquery.uploadify.v2.1.0.min.js"></script><script type="text/javascript">$(document).ready(function() {$("#uploadify").uploadify({	'uploader'       : '/scripts/uploadify.swf',	'script'         : 'uploadify.php',	'cancelImg'      : '/images/cancel.png',	'folder'         : 'uploads',	'queueID'        : 'fileQueue',	'auto'           : true,	'multi'          : true,	scriptData   : { <?php echo session_name(); ?>: '<?php echo session_id();?>'}	});});</script></head><body><div id="upload_wrapper"><div id="fileQueue"></div><input type="file" name="uploadify" id="uploadify" /><p><a href="javascript:jQuery('#uploadify').uploadifyClearQueue()">Cancel All Uploads</a></p></div></body></html>

 

 

I have this in uploadify.php (just for testing purposes as of now):

 

<?php$session_name = session_name();session_id($_GET[$session_name]);session_start();ob_start(); //Start bufferingvar_dump($_GET); //print the result$output = ob_get_contents(); //get the result from bufferob_end_clean(); //close buffer$h = fopen('log.txt', 'w+'); //open a filefwrite($h, $output); //write the output textfclose($h); //close file?>

 

 

log.txt shows:

 

array(0) {

}

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.