php variables and sessions

<?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 ?
doctorbillTechAsked:
Who is Participating?
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.

Chris StanyonWebDevCommented:
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

0
Mark BradyPrincipal Data EngineerCommented:
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) . "')";
0
doctorbillTechAuthor 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" }
0
Powerful Yet Easy-to-Use Network Monitoring

Identify excessive bandwidth utilization or unexpected application traffic with SolarWinds Bandwidth Analyzer Pack.

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

No idea why
1
Chris StanyonWebDevCommented:
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?
0
Chris StanyonWebDevCommented:
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
0
doctorbillTechAuthor 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
0
Chris StanyonWebDevCommented:
Are you doing anything here with AJAX calls to different pages?
0
doctorbillTechAuthor 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
1
Mark BradyPrincipal Data EngineerCommented:
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.
0
doctorbillTechAuthor 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 ?
0
Chris StanyonWebDevCommented:
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
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
doctorbillTechAuthor Commented:
Perfect - that worked. Thing is, I still don't why was the echo statement was adding the session name to the $filepath variable
0
Chris StanyonWebDevCommented:
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
0
doctorbillTechAuthor Commented:
Ah
I thought that that would only happen if this was true:

echo $_SESSION['comp'].$filepath.$filename;
OR
echo $company.$filepath.$filename;
0
Chris StanyonWebDevCommented:
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

0
doctorbillTechAuthor Commented:
Ah I see
Makes sense now
0
doctorbillTechAuthor Commented:
Thanks all - sorry for, in effect,  asking 2 questions
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
Databases

From novice to tech pro — start learning today.