php variables and sessions

doctorbill
doctorbill used Ask the Experts™
on
<?php
session_start();
echo $_SESSION['comp'];

 $company = $_SESSION['comp'];
//set random name for the image, used time() for uniqueness
require_once('db.php'); 
$filename =  time() . '.jpg';
$filepath = 'uploads/';
if(!is_dir($filepath))
	mkdir($filepath);
if(isset($_FILES['webcam'])){	
	move_uploaded_file($_FILES['webcam']['tmp_name'], $filepath.$filename);
	$sql="Insert into webcam_images(companyName, imgpath) values('$company','$filename')";
	$result=mysqli_query($con,$sql);
	echo $filepath.$filename;
}
?>

Open in new window


The above code works if I substitute the '$company' variable with, for example 'testname'
Both values are entered into the database
It looks as if the '$company' variable is not being recognised even though it is set (I have tested this with an echo command)

Any ideas ?
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2018
Distinguished Expert 2018

Commented:
Hi Bill,

What do you get if you echo out $company. Is there any chance that the value stored in $company has some quotes or other odd characters in there.

You should at the very least escape your data or better yet, use a prepared statement:

$sql = $con->prepare("INSERT INTO webcam_images (companyName, imgpath) VALUES (?, ?)");
$sql->bind_param("ss", $company, $filename);
$sql->execute();

Open in new window

Mark BradyPrincipal Data Engineer

Commented:
Firstly, I would advise you to always test what is in $_SESSION before trying to use it but in the above case, you should dump the contents of $_SESSION like this right after your session_start();
var_dump($_SESSION);

Before doing queries with $_SESSION results test they exist.

$company = isset($_SESSION['comp']) ? $_SESSION['comp'] : null;

// now test for the expected value
if(is_null($session)) {
    // do something here - the comp value is not set!
}

As for the query I would (after opening the db connection) escape them like so:
$sql="INSERT INTO webcam_images (companyName, imgpath) values ('". mysqli_real_escape_string($company) ."', '" . mysqli_real_escape_string($filename) . "')";

Author

Commented:
Tried the var_dump and got the following:
No idea where this is coming from:

array(8) { ["entry_uri"]=> string(23) "/ticktock_int/index.php" ["jcart"]=> object(__PHP_Incomplete_Class)#1 (9) { ["__PHP_Incomplete_Class_Name"]=> string(5) "Jcart" ["config"]=> array(2) { ["currencyCode"]=> string(3) "GBP" ["text"]=> array(14) { ["cartTitle"]=> string(13) "Shopping Cart" ["singleItem"]=> string(4) "Item" ["multipleItems"]=> string(5) "Items" ["subtotal"]=> string(8) "Subtotal" ["update"]=> string(6) "update" ["checkout"]=> string(8) "checkout" ["checkoutPaypal"]=> string(20) "Checkout with PayPal" ["removeLink"]=> string(6) "remove" ["emptyButton"]=> string(5) "empty" ["emptyMessage"]=> string(19) "Your cart is empty!" ["itemAdded"]=> string(11) "Item added!" ["priceError"]=> string(21) "Invalid price format!" ["quantityError"]=> string(38) "Item quantities must be whole numbers!" ["checkoutError"]=> string(34) "Your order could not be processed!" } } ["items":"Jcart":private]=> array(0) { } ["names":"Jcart":private]=> array(0) { } ["prices":"Jcart":private]=> array(0) { } ["qtys":"Jcart":private]=> array(0) { } ["urls":"Jcart":private]=> array(0) { } ["subtotal":"Jcart":private]=> int(0) ["itemCount":"Jcart":private]=> int(0) } ["jcartToken"]=> string(32) "ab41aff7dd53be5c6e73d484a891bdb7" ["uid"]=> string(5) "admin" ["loggedin"]=> string(33) "(Administrator Logged In)" ["comp"]=> NULL ["Type"]=> string(4) "BACS" ["Type_paid"]=> string(6) "Cheque" }
Ensure you’re charging the right price for your IT

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden using our free interactive tool and use it to determine the right price for your IT services. Start calculating Now!

Author

Commented:
Looks like the session has no value:
["comp"]=> NULL

No idea why
Most Valuable Expert 2018
Distinguished Expert 2018

Commented:
Well there you go - $_SESSION['comp'] is NULL. You said in your opening question that you'd tested it with an echo. Where and how did you test that?
Most Valuable Expert 2018
Distinguished Expert 2018

Commented:
Sorry - cross-posted !

The session looks like it's being manipulated elsewhere in your app, so you'll need to look for that, or check the code that is supposed to be setting it in the first place

Author

Commented:
When I set the SESSION on another page I get the following using var_dump:
["comp"]=> string(21) "The Apartment Service"

So the session is being set but not being seen by the page to enter into the database
Most Valuable Expert 2018
Distinguished Expert 2018

Commented:
Are you doing anything here with AJAX calls to different pages?

Author

Commented:
I think I have got to the bottom of it. I now set the session in the page I am using by using a form to submit a name back to the page with a GET command and set the SESSION to this. The correct data is now being entered into the database
Mark BradyPrincipal Data Engineer

Commented:
Nice job!  Yes you have to be careful using sessions across multiple pages where one page could wipe out what the other page has set. You have it now.

Author

Commented:
<?php
session_start();
echo $_SESSION['comp'];

//set random name for the image, used time() for uniqueness
require_once('db.php');
$company = $_SESSION['comp'];
$filename =  time() . '.jpg';
$filepath = 'uploads/';
if(!is_dir($filepath))
	mkdir($filepath);
if(isset($_FILES['webcam'])){	
	move_uploaded_file($_FILES['webcam']['tmp_name'], $filepath.$filename);
	$sql="Insert into webcam_images(companyName, imgpath) values('$company','$filename')";
	$result=mysqli_query($con,$sql);
	echo $filepath.$filename;
}
?>

Open in new window


The SESSION is now being set correctly but the problem is as follows:
This string "echo $filepath.$filename;" is producing the following:
companyname (This is the set SESSION value name) uploads/imagename.jpg
ie
http://localhost:888/inventassites/Downloaded/Webcam/WebcamImage-1.0.0/The%20Apartment%20Serviceuploads/1536258098.jpg
It should be:
http://localhost:888/inventassites/Downloaded/Webcam/WebcamImage-1.0.0/uploads/1536258098.jpg
ie /uploads/imagename.jpg
The companyname is being added to the $filepath name which is not what I want
The path would then be able to show the uploaded image on the webpage whereas the first does not because it is referencing the wrong path
Any ideas ?
Most Valuable Expert 2018
Distinguished Expert 2018
Commented:
If you look at your code, you're echoing out the company name at the start of your script:

echo $_SESSION['comp'];

I'm guessing you shouldn't be

Author

Commented:
Perfect - that worked. Thing is, I still don't why was the echo statement was adding the session name to the $filepath variable
Most Valuable Expert 2018
Distinguished Expert 2018

Commented:
It wasn't - you had 2 echo statements :

echo $_SESSION['comp'];
...
echo $filepath.$filename;

The first one echoed the company name and the second one echoed the filepath and filename so your output ends up looking like:

CompanyFilepathFilename

Author

Commented:
Ah
I thought that that would only happen if this was true:

echo $_SESSION['comp'].$filepath.$filename;
OR
echo $company.$filepath.$filename;
Most Valuable Expert 2018
Distinguished Expert 2018

Commented:
Nope. In PHP, output is buffered until the script ends (normally). Pretty sure you already use this a lot (probably in most scripts you write):

<h1>Users</h1>

<?php while ( $user = $db->getUsers() ): ?>

Username : <?php echo $user->username ?>
Email : <?php echo $user->email ?>

<?php endwhile; ?>

Open in new window

When you see it like that, it's plainly obvious that each output (whether direct HTML or with an echo statement) just get's buffered together until the script ends, and then the whole lot is dumped out.

echo "This ";
echo "is ";
echo "a ";
echo "sentence!";

Open in new window

Author

Commented:
Ah I see
Makes sense now

Author

Commented:
Thanks all - sorry for, in effect,  asking 2 questions

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial