Having trouble getting a session variable sest in php.

I've never worked with sessions before. I found a small piece of code when I searched on it, but it doesn't seem to be actually saving what I'm trying to set. I must be doing it wrong. Could I get some help with this please?

Here's the code I've been trying:
	if (!isset($_SESSION['csvmerger_session'])) {
		$temp_sess = random_folder_name(10);
		$temp_folder = $upload_dir.'/'.$temp_sess;
		session_start();
		$_SESSION['csvmerger_session'] = $temp_sess;
	} else {
		$temp_sess = $_SESSION['csvmerger_session'];
		$temp_folder = $upload_dir.'/'.$temp_sess;
	}

Open in new window


And the upload_dir variable is just set to the regular wordpress uploads folder path + another folder inside of it - which is all working fine. But when I reload the page, the session info previously assigned changes again. I'm not using a form or anything, just loading the script onto the page right now.
LVL 14
DzynitAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

COBOLdinosaurCommented:
The session_start() should be the first instruction and come before the if.

I can't tell if there is continuity if you are just firing a script from a page.

Cd&
0
DzynitAuthor Commented:
I tried moving it before the if, but it still keeps changing every time I reload the page. Here's the full script if it would be more helpful.
The file writing stuff is just stuck there temporarily for testing. I'll actually be adding an upload feature for multiple files into those temp folders. The working with those and deleting them when finished.

function csvmerger_function() {
	session_start();
	$upload_dir = wp_upload_dir();
	$upload_dir = $upload_dir['path'].'/csv-merger';
	if (!isset($_SESSION['csvmerger_session'])) {
		$temp_sess = random_folder_name(10);
		$temp_folder = $upload_dir.'/'.$temp_sess;
		$_SESSION['csvmerger_session'] = $temp_sess;
	} else {
		$temp_sess = $_SESSION['csvmerger_session'];
		$temp_folder = $upload_dir.'/'.$temp_sess;
	}

	if (!file_exists($upload_dir)) {
		if (!mkdir($upload_dir, 0766, true)) {
		    echo('Failed to create main directory. You\'ll need to manually create it in your uploads folder with the name csv-merger and set your permissions to writable using 766 or 777.<br />');
		}
	}
	
	if (!file_exists($temp_folder)) {
		if (!mkdir($temp_folder, 0766, true)) {
		    echo('Failed to create temp directory. If you\'re sure the permissions are correct on the main directory and this still fails, you most likely cannot use this tool. It requires the ability to dynamically create and delete temp folders and files.');
		}
	}
	
	$upload_dir = $upload_dir.'/';

	$temp_folder = $upload_dir.$_SESSION['csvmerger_session'].'/';
	
	// Here we define the file path and name
	$target_file = $temp_folder."test-file.txt";
	// Here we define the string data that is to be placed into the file
	$target_file_data = "This is the string data or code I want to place in the newly created file.";
	// Here we are creating a file(since it does not yet exist) and adding data to it
	$handle = fopen($target_file, "w");
	fwrite($handle, $target_file_data); // write it
	fclose($handle);
	// Here we are opening and appending to the file
	$handle = fopen($target_file, "a");
	// Here we define the string data that is to be appended to the data already in file
	$target_file_data = "Here is more data I want to append to the file.";
	fwrite($handle, $target_file_data); // write it
	fclose($handle);

	// Here we display the file contents by including it
	include($target_file); 
	
	echo $temp_folder;
}	

function random_folder_name($length) {
    $key = '';
    $keys = array_merge(range(0, 9), range('a', 'z'));

    for ($i = 0; $i < $length; $i++) {
        $key .= $keys[array_rand($keys)];
    }

    return $key;
}

add_shortcode( 'csvmerger', 'csvmerger_function' );

Open in new window


The reason I need to get a random folder name assigned for a while is because there will be more than one person using at the same time so I need to be sure it's working with only each person's files that's using it and not mixing multiple people's files.

This is where I'm testing it, but likely viewing that isn't helpful: http://www.dzynit.net/csv-merger/

If you have thoughts on a better way to temporarily store that random folder name I'd be happy to try it.
The point of this is to have a simple online tool that allows uploading a group of csv files then just "stack" combine them all in one csv. It's to be a free tool so it doesn't have to be real fancy - just working correctly so it's not jumbling different people's files together.
0
COBOLdinosaurCommented:
The only thing that comes to mind is that somehow it appears like you are coming from another domain, then where you started; maybe the lack of a form is the problem, though I don't think it should be.

Cd&
0
Starting with Angular 5

Learn the essential features and functions of the popular JavaScript framework for building mobile, desktop and web applications.

Dave BaldwinFixer of ProblemsCommented:
session_start(); needs to be the first thing on the page.  The only thing that I put before it is 'error_reporting().  Putting it in a function means that it likely won't get called until it is too late.  Like this...
<?php
error_reporting(E_ALL);
// Create a unique session ID
session_start(); 

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
DzynitAuthor Commented:
Dave that worked putting it outside the function.
With it being outside the function, since it's a plugin - do you think that could cause any other problems? conflicts, etc.
0
COBOLdinosaurCommented:
I just noticed that it is a Wordpress site.  That can be problematic for sessions because WP does not like them.  You might find this helpful:
http://www.myguysolutions.com/2010/04/14/how-to-enable-the-use-of-sessions-on-your-wordpress-blog/

Cd&
0
DzynitAuthor Commented:
Cd, I don't really think that will be much of an issue. Maybe on very outdated wordpress versions? But most shopping cart plugins use sessions and I've not had any issues with any of those. My main concern is having the session_start outside the shortcode function, the plugin always loads regardless of if you're on the page with the shortcode. So wondering if I might end up having conflicts or anything with other plugins.
0
Dave BaldwinFixer of ProblemsCommented:
I don't know, I don't use Wordpress very much.  But my example is the way I use session_start on many sites.  You should click on "Request Attention" above and get the Wordpress topic area added to your question.
0
DzynitAuthor Commented:
I can just start another question on that. I'm thinking it will be fine, but since I've never really had to work with sessions before I'd like some other opinions. I've worked with sites that simply had way too many plugins and I know more than one use the sessions and I've not seen problems. It's mostly that I'd like the knowledge on it if there were to be any support issues down the road.
0
DzynitAuthor Commented:
I split the points up because Cd answered before seeing the entire code or he might have specified that in his first answer. Thank you both for your help!
0
Dave BaldwinFixer of ProblemsCommented:
You're welcome.  'session_start' can actually be on the page multiple times because the first thing it does is check to see if a current session has already been set up.  If it has, it does nothing.  The only conflict might be if two routines or plugins used the same names for $_SESSION variables.
0
DzynitAuthor Commented:
Thanks Dave - that would definitely be the answer on that question. I did read on being sure the variable name was unique - so I used the name of the plugin with the addition of _session. So that should be very safe to stay unique.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.