Solved

strange $_SESSION behaivor

Posted on 2016-08-23
43
63 Views
Last Modified: 2016-08-29
I have a site I am developing; relies heavily on $_SESSION variables.

I have it working fine at my development site. Zero issues with the $_SESSION vars

Transferred to customer hosting at GoDaddy. Odd problems. At least one (maybe more) of the session vars just disappears. Maybe the name, I use $_SESSION['user'], the one disappearing? I put a whole bunch of echo's in to find out where it disappears, finally I used a query string var ($_GET) to pass it from one script to another, where I reset the $_SESSION['user']. So far that works, but I am skeptical down the road.

Is 'user' as a session var name reserved (or used for other purposes by php)?

Can anyone shed any light on this, I don't want to post a bunch of code, etc.?
0
Comment
Question by:Richard Korts
  • 18
  • 9
  • 8
  • +2
43 Comments
 
LVL 42

Expert Comment

by:zephyr_hex
Comment Utility
If you aren't using named sessions, then one unset session in any app will blow all sessions.  Moreover, if you have more than one app using the same session variables, you could have collision if you aren't using named sessions.
0
 
LVL 82

Expert Comment

by:Dave Baldwin
Comment Utility
More details will be needed.  I am using PHP SESSIONs on a number of different hosting plans on Godaddy and in the last 7 years, I have not had that problem.  This includes shopping carts and Paypal code with 50+ $_SESSION variables on  both Linux and Windows.  I haven't had that problem on any other hosting either.
0
 
LVL 82

Expert Comment

by:Dave Baldwin
Comment Utility
Are you using the same version of PHP in both places?
0
 

Author Comment

by:Richard Korts
Comment Utility
Dave,

On the development host (where everything works), php version 5.5.38.

At Godaddy, php version 5.2.17.

I will send code later.

Thanks
0
 

Author Comment

by:Richard Korts
Comment Utility
Dave,

Where is the "code" window. Ray said I have to use that for submitting code. Of course, it's not evident where it is.

Thanks,

Richard
0
 
LVL 42

Expert Comment

by:zephyr_hex
Comment Utility
You'll want to highlight your code and then select the CODE button:

code
0
 
LVL 82

Expert Comment

by:Dave Baldwin
Comment Utility
If you look in the "Write Comment" box below, you will see the word CODE.  When you click on it, it will put [ code ]tags[ /code ] where you can put your code in between them.

The difference in PHP versions may be too great.  A lot has changed since PHP 5.2.17.  That also tells me that you are probably using Windows hosting at Godaddy with IIS7 for a web server.  I do know that AJAX calls in that environment returned an extra \r\n that I had to get rid of.  Is your development box also Windows?
0
 
LVL 42

Expert Comment

by:zephyr_hex
Comment Utility
I really don't think this could be a PHP version issue, especially if it's intermittent.  In my opinion, this smells of session conflict, which is the entire purpose for using named sessions.
0
 

Author Comment

by:Richard Korts
Comment Utility
The development is linux / apache, for sure. I was almost sure Godady was linux/apache too, I'll have to check.
0
 
LVL 42

Expert Comment

by:zephyr_hex
Comment Utility
Actually, the idea scenario would be to spin up a dev site using the same version of PHP as production, and enable PHP error reporting.  I suppose there could be an instance where you have a code bomb and a session variable isn't being set as you expect it to be.
0
 

Author Comment

by:Richard Korts
Comment Utility
To zephyr_hex,

It is NOT intermittent on Godaddy. It occurs in one specific place, only (as far as I know) for $_SESSION['user']. It is there in one php program, gone in the next.

I'll post code.
0
 
LVL 42

Expert Comment

by:zephyr_hex
Comment Utility
Aha, ok.  Then it's probably an error that's causing the variable to not get set.
0
 

Author Comment

by:Richard Korts
Comment Utility
zephyr_hex,

Of course, but why does it wok on the dev server?
0
 
LVL 42

Expert Comment

by:zephyr_hex
Comment Utility
Because of the differing PHP versions.  I originally thought the problem was intermittent, which led me to think session conflict and not code error.  But you've since clarified that this is not intermittent.  It's entirely possible that there is an error in production that is not occurring in dev, due to differing PHP versions.
0
 

Author Comment

by:Richard Korts
Comment Utility
OK, here is some source.

In the first of these, choose_cust.php, $_SESSION['user'] exists, I know this from commented out echos I did.

In the second, get_form.php, $_SESSION['user'] is empty.

<?php
session_start();
include "db_connect.php";
function conv_date($x) {
		$d = split("-", $x);
		$r = $d[1] . "/" . $d[2] . "/" . $d[0];
		return $r;
	}
if(! empty($_SERVER['HTTP_USER_AGENT'])){
		$useragent = $_SERVER['HTTP_USER_AGENT'];
		if( preg_match('@(iPad|iPod|iPhone|Android|BlackBerry|SymbianOS|SCH-M\d+|Opera Mini|Windows CE|Nokia|SonyEricsson|webOS|PalmOS)@', $useragent) ){
			$loc = "phone.php";
		} else {
			$loc = "form.php";
	}
} 	
$qry = "SELECT * from form_data where user = " . $_SESSION['user'] . " order by prop_city, prop_zip, prop_addr";
//echo "qry = " . $qry;
$res = mysqli_query($link, $qry);
$nr = mysqli_num_rows($res);
$_SESSION['nr'] = $nr;
if ($nr == 0) {
	header("Location: " . $loc);	
}	
//echo "session user = " . $_SESSION['user'] . "<br>";
?>

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
    <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>

    <script src="//code.jquery.com/jquery-1.10.2.js"></script>
    <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
    <link rel="stylesheet" href="/resources/demos/style.css">

    <title>City of Houston Backflow Assembly & Test Report Form</title>
    <style>
        .nopadding {
            padding: 0 !important;
            margin: 0 !important;
        }
        
        .wrapper {
            max-width: 767px;
            min-width: 480px;
            margin: 0 auto;
        }
    </style>
	<script>
	ac = "";
	function chk_vals() {
		if (ac == "n") {
			document.st.action = "clear_sess.php";
			return true;
		}
		if (document.st.sprop.value == "") {
			alert("Please select a property.");	
			return false;
		}
		if (ac == "e") {
			document.st.action="get_form.php?u=" + document.st.sprop.value + "&usr=<? print $_SESSION['user']; ?>";
			return true;
		}
		if (ac == "d") {
			document.st.action = "delete_prop.php?u=" + document.st.sprop.value; 
			return true;	
		}	
	}
	</script>
</head>	
<body>
<div class="wrapper">
<form method="POST" name="st" action="form.php" onSubmit="return chk_vals();">
<div class="container-fluid" style="background-color: #F3D9AF;">
<div class="row">
    <div class="col-xs-8 text-center"><img src="images/bfp_logo_sm.jpg"></div>
</div>
<div class="row">
       <div class="col-xs-8 text-center" style="font-size:18px;"><b>City of Houston - Backflow Assembly & Test Report Form - Choose Property</b></div>
 </div>
 <? if ($err != "") { ?>
	<div class="row">
         <div class="col-xs-8 text-center" style="font-color:red;"><? print $msg; ?></div>
    </div>
<? } ?>	
<div class="row">
        <div class="col-xs-8 text-right" style="padding-top:10px;">
            <input type="submit" onMousedown= "ac='n';" value="New Property">
        </div>
</div>
<div class="row">
        <div class="col-xs-8" style="padding-top:10px;">	
		<select name="sprop">
			<option value="">--- Select a Property ---</option>
		<? for ($i = 0; $i < $nr; $i++) { 
			$fd = mysqli_fetch_array($res,MYSQLI_ASSOC);
			if ($fd['test_date'] == 0000-00-00) {
				$tdstr = "No Test Date";
			} else {
				$tdstr = conv_date($fd['test_date']);
			}	
			$val = $fd['prop_city'] . ", " . $fd['prop_zip'] . ", " . $fd['prop_addr'] . ", test date " . $tdstr;?>
			<option value="<? print $fd['uid']; ?>"><? print $val; ?></option>
		<? } ?>	
		</select></div>
</div>
<div class="row">
        <div class="col-xs-4 text-center" style="padding-top:10px;">	
				<input type="submit" value="Edit" onMousedown="ac='e';">
		</div>
		<div class="col-xs-4 text-center" style="padding-top:10px;">	
				<input type="submit" value="Delete" onMousedown="ac='d';">
		</div>
</div>		

            </div>
        </form>
    </div>
</body>

</html>	

Open in new window

<?php
	$u = $_GET['u'];
	session_start();
	$_SESSION['uid'] = $u;
	//echo "get usr = " . $_GET['usr'] . "<br>";
	$_SESSION['user'] = $_GET['usr'];
	//echo "session user = " . $_SESSION['user'] . "<br>";
	include "db_connect.php";
	//echo "entered get_form<br>";
	function conv_date($x) {
		$d = explode("-", $x);
		$r = $d[1] . "/" . $d[2] . "/" . $d[0];
		return $r;
	}
	$qry = "SELECT * from form_data where uid = " . $u;
	$res = mysqli_query($link, $qry);
	$fd = mysqli_fetch_array($res,MYSQLI_ASSOC);
	$_SESSION['pn'] = $fd['property'];
	$_SESSION['padr'] = $fd['prop_addr'];
	$_SESSION['city'] = $fd['prop_city'];
	$_SESSION['state'] = $fd['prop_state'];
	$_SESSION['zip'] = $fd['prop_zip'];
	$_SESSION['keymap1'] = $fd['keymap1'];
	$_SESSION['keymap2'] = $fd['keymap2'];
	$_SESSION['phac'] = $fd['phac'];
	$_SESSION['phex'] = $fd['phex'];
	$_SESSION['phl4'] = $fd['phl4'];
	$_SESSION['madr'] = $fd['mailing_addr'];
	$_SESSION['ckmasa'] = $fd['ckmasa'];
	$_SESSION['conname'] = $fd['prop_contact'];
	$_SESSION['anr'] = $fd['assembly'];
	$_SESSION['rsn'] = $fd['ass_replaced'];
	$_SESSION['asstyp'] = $fd['ass_type'];
	$_SESSION['mfg'] = $fd['ass_mfg'];
	$_SESSION['model'] = $fd['ass_model'];
	$_SESSION['size'] = $fd['ass_size'];
	$_SESSION['serno'] = $fd['ass_serno'];
	$_SESSION['sloc'] = $fd['serving_loc'];
	$_SESSION['instdate'] = conv_date($fd['date_installed']);
	if ($fd['dina'] == "Y") {
		$_SESSION['dina'] = 'on';
		$_SESSION['instdate'] = "";
	}	
	$_SESSION['cupc'] = $fd['cupc'];
	// test values
	// get proper record based on ass_typ
	//echo "asstyp = " . $_SESSION['asstyp'] . "<br>";
	//echo "session asstyp = " . $_SESSION['asstyp'] . "<br>";
	switch($_SESSION['asstyp']) {
			case "DVD":
			case "DCD":
				$qrytd = "SELECT * from test_data_dvc_dvd where uid = " . $u; 
				//echo "test data qry = " . $qrytd . "<br>";
				$restd = mysqli_query($link, $qrytd);
				break;
			case "RP":
			case "RPD":
				$qrytd = "SELECT * from test_data_rp_rpd where uid = " . $u;  
				$restd = mysqli_query($link, $qrytd);
				break;
			case "PVB":
			case "SVB":	
				$qrytd = "SELECT * from test_data_pvb_svb where uid = " . $u;  
				$restd = mysqli_query($link, $qrytd);
				//echo "insert pvb test data = " . $qryit . "<br>";
				break;
	}
	$td = mysqli_fetch_array($restd,MYSQLI_ASSOC);	
	$_SESSION['itcv1ct'] = "";
	$_SESSION['itcv2ct'] = "";
	$_SESSION['itcv1l'] = "";
	$_SESSION['itcv2l'] = "";
	$_SESSION['ftcv1ct'] = "";
	$_SESSION['ftcv2ct'] = "";
	$_SESSION['ftcv1l'] = "";
	$_SESSION['ftcv2l'] = "";
	$_SESSION['itrvdno'] = "";
	$_SESSION['itaidno'] = "";
	$_SESSION['itcvl'] = "";
	if ($td['itcv1ct'] == "Y") {
		$_SESSION['itcv1ct'] = "on";
	}
	if ($td['itcv2ct'] == "Y") {
		$_SESSION['itcv2ct'] = "on";
	}
	if ($td['itcv1l'] == "Y") {
		$_SESSION['itcv1l'] = "on";
	}
	if ($td['itcv2l'] == "Y") {
		$_SESSION['itcv2l'] = "on";
	}
	if ($td['itrvdno'] == "Y") {
		$_SESSION['itrvdno'] = "on";
	}
	if ($td['itaidno'] == "Y") {
		$_SESSION['itaidno'] = "on";
	}
	if ($td['ftcv1ct'] == "Y") {
		$_SESSION['ftcv1ct'] = "on";
	}
	if ($td['ftcv2ct'] == "Y") {
		$_SESSION['ftcv2ct'] = "on";
	}
	if ($td['ftcv1l'] == "Y") {
		$_SESSION['ftcv1l'] = "on";
	}
	if ($td['ftcv2l'] == "Y") {
		$_SESSION['ftcv2l'] = "on";
	}
	$_SESSION['itcv1psi'] = $td['itcv1psi'];
	//echo "itcv1psi = " . $td['itcv1psi'] . "<br>";
	$_SESSION['itcv2psi'] = $td['itcv2psi'];
	$_SESSION['itrvpsi'] = $td['itrvpsi'];
	$_SESSION['rmucv1'] = $td['rmucv1'];
	$_SESSION['rmucv2'] = $td['rmucv2'];
	$_SESSION['rmurv'] = $td['rmurv'];
	$_SESSION['ftcv1psi'] = $td['ftcv1psi'];
	$_SESSION['ftcv2psi'] = $td['ftcv2psi'];
	$_SESSION['ftrvpsi'] = $td['ftrvpsi'];
	$_SESSION['itaipsi'] = $td['itaipsi'];
	$_SESSION['itcvpsi'] = $td['itcvpsi'];
	$_SESSION['rmuai'] = $td['rmuai'];
	$_SESSION['rmucv'] = $td['rmucv'];
	$_SESSION['ftaipsi'] = $td['ftaipsi'];
	$_SESSION['ftcvpsi'] = $td['ftcvpsi'];
// form bottom part
	$_SESSION['testdate'] = conv_date($fd['test_date']);
	$_SESSION['witness'] = $fd['witness'];	
	$_SESSION['remarks'] = $fd['remarks'];
	$_SESSION['passfail'] = $fd['pass_fail'];
	//echo "user = " . $_SESSION['user'] . "<br>";
	$loc = "form.php";
	if(! empty($_SERVER['HTTP_USER_AGENT'])){
		$useragent = $_SERVER['HTTP_USER_AGENT'];
		if( preg_match('@(iPad|iPod|iPhone|Android|BlackBerry|SymbianOS|SCH-M\d+|Opera Mini|Windows CE|Nokia|SonyEricsson|webOS|PalmOS)@', $useragent) ){
			$loc = "phone.php";
		}
	}
	header("Location: " . $loc . "?t=" . $_SESSION['asstyp']);
	//echo "session uid in get form = " . $_SESSION['uid'] . "<br>";
	exit;

Open in new window


This code thing is absurd, you cannot see line numbers, but in the first one, in the Javascript function chk_vals(), see this line: document.st.action="get_form.php?u=" + document.st.sprop.value + "&usr=<? print $_SESSION['user']; ?>";

Here a pass $_SESSION['user'] to get_form.php as a $_GET variable.

In the 2nd one, jus from the top, I do $_SESSION['user'] = $_GET['usr'];

The $_SESSION['user'] is set.

Any help appreciated.

Thanks
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
At Godaddy, php version 5.2.17.
PHP version 5.2 has been obsolete for a decade.  Get off PHP 5.2.  Do not listen to anyone who tells you that you need PHP 5.2.  Instead, look at http://php.net.  Look in the upper right-hand corner for the current releases.  Find a hosting company that can give you a platform with a current release.

This article tells how to use the PHP session.
https://www.experts-exchange.com/articles/11909/PHP-Sessions-Simpler-Than-You-May-Think.html

Try installing this script and running it.  I have never seen a properly configured PHP installation that did not run this script correctly.
<?php // demo/session_test.php
/**
 * Demonstrate how PHP sessions work
 *
 * Ref: http://php.net/manual/en/book.session.php
 * Ref: http://php.net/manual/en/function.session-start.php
 * Ref: http://www.experts-exchange.com/articles/11909/PHP-Sessions-Simpler-Than-You-May-Think.html
 */
error_reporting(E_ALL);

// START THE SESSION (DO THIS FIRST, UNCONDITIONALLY, IN EVERY PHP SCRIPT ON EVERY PAGE)
session_start();

// INITIALIZE THE SESSION ARRAY TO SET A DEFAULT VALUE
if (!isset($_SESSION["counter"])) $_SESSION["counter"] = 0;

// SEE IF THE INCREMENT SUBMIT BUTTON WAS CLICKED
if (isset($_POST['bump']))
{
    // ADD ONE TO THE COUNTER
    $_SESSION['counter']++;
}

// SEE IF THE DECREMENT SUBMIT BUTTON WAS CLICKED
if (isset($_POST['dump']))
{
    // TAKE ONE FROM THE COUNTER
    $_SESSION['counter']--;
}

// RECOVER THE CURRENT VALUE FROM THE SESSION ARRAY
$counter = $_SESSION['counter'];


// END OF PROCESSING SCRIPT - CREATE THE FORM USING HEREDOC NOTATION
$form = <<<ENDFORM
<html>
<head>
<title>Session Test</title>
</head>
<body>
Currently, SESSION["counter"] contains: $counter<br/>
<form method="post">
<input type="submit" value="decrement this counter" name="dump" />
<input type="submit" value="leave my counter alone" name="keep" />
<input type="submit" value="increment this counter" name="bump" />
</form>
</body>
</html>
ENDFORM;

echo $form;

Open in new window

0
 

Author Comment

by:Richard Korts
Comment Utility
Ray, thanks for that insight.

It's not quite as simple as 'get off GoDaddy. My customer has 260 domains there. You see the magnitude.

Maybe I got it wrong, but I  wrote a one 1
Line script phpinfo() & ran it at the site root. That's what I got.

Fyi, my dev server is Chihost, recommended by you years ago. I have hosted 10 or 15 sites with them. Their service is the best I have ever encountered.
0
 
LVL 42

Assisted Solution

by:zephyr_hex
zephyr_hex earned 125 total points
Comment Utility
The PHP version on GoDaddy is configurable.  That being said, you can't just change the PHP version in a production environment without extensive testing.

The better option, until testing and upgrade is possible, is to fix whatever is causing the error in your current code.  As I mentioned earlier, you can spin up a dev environment that matches the production PHP version.  If you're doing any extensive work for a client, you'll want to have dev match production anyway.  There are plenty of free hosts you can use just for testing.  Get a dev environment set up, copy your php files over, and turn on PHP error reporting to see where the problem is.

Or, if you know the block of code that's causing a problem, post it here.
0
 
LVL 82

Expert Comment

by:Dave Baldwin
Comment Utility
Error reporting is not turned on on either script above.  You have been told Many times to do that and you almost never do.  How would you know what errors are occurring without doing that?
0
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 250 total points
Comment Utility
get off GoDaddy
I didn't say that (at least not this time).  Instead I said "Get off PHP 5.2."

You should be able to get adequate error_reporting()* without disrupting the client browser output.  The errors can be written to the error_log file.  They do not have to be put on the browser viewport.

Here are my PHP settings for E_ALL and no error display.
display_errors         Off
display_startup_errors Off

error_append_string    no value
error_log              error_log // <-- This is a File Name
error_prepend_string   no value
error_reporting        32767

log_errors             On
log_errors_max_len     1024

Open in new window


Here is a script that will recursively search all the directories and display the contents of the error_log files.  For obvious reasons you might want to password-protect such a script.  You might want to trigger this sort of script with a cron  job.  The cron job could send you an email or SMS alert when an error_log file appears.
<?php // demo/find_error_log.php
/**
 * Traverse all directories in the web tree
 * Show and optionally delete the error log files
 *
 * http://php.net/manual/en/class.recursivedirectoryiterator.php#85805
 */
ob_start();
error_reporting( E_ALL );
ini_set( 'display_errors', TRUE );
ini_set( 'log_errors',     TRUE );


// PUT THIS SCRIPT IN THE WEB ROOT DIRECTORY
$path = realpath(getcwd());
$plen = strlen($path);

// THE ERROR LOG FILE NAME
$signal = strrev(ini_get('error_log'));

// IF THERE IS A POST-METHOD REQUEST TO DELETE THIS ERROR LOG
if (!empty($_POST['log']))
{
    // MAKE SURE WE ONLY UNLINK THE ERROR LOG FILE
    $test = strrev($_POST['log']);
    if (strpos($test, $signal) === 0)
    {
        @unlink($path . $_POST['log']);
        echo '<h3>' . $_POST['log'] . ' Discarded</h3>';
    }
}


// COLLECT THE DIRECTORY INFORMATION OBJECTS
$objs = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST);


// ITERATE OVER THE OBJECTS
foreach($objs as $name => $obj)
{
    // PROCESS THE ERROR LOG ONLY
    $test = strrev($name);
    if (strpos($test, $signal) === 0)
    {
        $name = substr($name, $plen);
        $form = <<<EOD
<form method="post" style="margin:0; padding:0; display:inline;!important">
<b>$name</b>
<input type="submit" value="Discard?" />
<input type="hidden" name="log" value="$name" />
</form>
EOD;
        echo $form;

        // SHOW THE CONTENTS OF THE ERROR LOG
        echo '<pre>';
        print_r(file_get_contents($path . $name));
        echo PHP_EOL . '********** EOF **********';
        echo '</pre>' . PHP_EOL;
    }
}

$out = ob_get_contents();
if (empty($out)) echo '<h3>Good News! No error_log found.</h3>';


// SHOW THE GIT BRANCH
$root = '.git/HEAD';
$text = @file_get_contents($root);
if ($text)
{
    $text = explode(DIRECTORY_SEPARATOR, $text);
    $text = array_slice($text, 2);
    $name = implode(DIRECTORY_SEPARATOR, $text);
    echo PHP_EOL . "On Git branch: $name" . PHP_EOL;
}
else
{
    echo PHP_EOL . "On Git branch: UNKNOWN" . PHP_EOL;
}

echo '<a href="' . $_SERVER['REQUEST_URI'] . '">Run Again</a>?' . PHP_EOL;

Open in new window

* Read the Changelog!
0
 
LVL 7

Expert Comment

by:Scobber
Comment Utility
I'm thinking some sort of register globals mismatch between the dev computer and godaddy
1
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
@Scobber: agreed - register globals is evil.  With severely backlevel versions of PHP (like 5.2) those old bugaboos can still bite someone.

Apologies in advance -- E-E keeps messing with the article publishing system, so this article may be improperly formatted.  But hopefully the content will be clear.
https://www.experts-exchange.com/articles/7317/Register-Globals-a-bad-idea-from-day-one.html
0
 
LVL 42

Expert Comment

by:zephyr_hex
Comment Utility
In the first block of code, you set $_GET['usr'] here:

document.st.action="get_form.php?u=" + document.st.sprop.value + "&usr=<? print $_SESSION['user']; ?>";

Open in new window


Have you verified the result of this line?

In the second block of code, you attempt to access $_GET['usr'] and set $_SESSION['user']:

$_SESSION['user'] = $_GET['usr'];

Open in new window


What is the url (and parameters) at this point?

As a complete side note, this is vulnerable to SQL Injection, and other hackery:
$u = $_GET['u'];
$qry = "SELECT * from form_data where uid = " . $u;

Open in new window


It is never a good idea to use get variables in a database query.  It's an even worse idea to directly concatenate those to formulate a database query.  For example, a user could easily modify the url parameter to :

u=someValue; DROP TABLE form_data

Open in new window


And then you can say goodbye to your table.
You should be using prepared statements instead of your current approach.  And it would be a step in the right direction to use POST instead of GET for these types of interactions.
0
 

Author Comment

by:Richard Korts
Comment Utility
zephyr_hex,

I recognize the issues with $_GET. I used that as a temporary solution since $_SESSION['user'] was being dropped between these two scripts. This was a quick & dirty to test, it's much easier than creating a form with a hidden variable to then post, etc.

The real question, that seems to have been COMPLETELY lost in all the ensuing discussions about how I am doing everything wrong, is WHY is the $SESSION variable being dropped in the first place?

I am going to try the suggestion of making GoDaddy use a later version of php and then run Ray's test to see if that works. My intent all along was $_SESSION vars for ALL of this.
0
 
LVL 82

Assisted Solution

by:Dave Baldwin
Dave Baldwin earned 125 total points
Comment Utility
Here is a little utility program to show you what $_SESSION data you actually have.  Open this in a second window or tab and refresh it after every new page in the first window.  It will show you what $_SESSION variables you have and when they change.
<?php 
session_start();  // This joins the current session

 ?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
 "http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<title>$_SESSION data</title>
</head>
<body>
<h1>$_SESSION data</h1>
<?php 

foreach($_SESSION as $key => $value) {
	echo "$key => $value<br>";
	}

 ?>
</body>
</html>

Open in new window

0
 

Author Comment

by:Richard Korts
Comment Utility
Dave,

Excellent, I'll try it.

Richard
0
 
LVL 42

Expert Comment

by:zephyr_hex
Comment Utility
@Richard Korts - I mentioned my comment about $_GET insecurity as a side comment.  Sorry if that felt like a complete turn from the main topic.  I think it's important for everyone to be aware of security risks in code.

P.S.  Once you get $_SESSION working, you still have a security risk in concatenating variables to form a sql query.  You should always use prepared statement.  Again, side comment.
1
 

Author Comment

by:Richard Korts
Comment Utility
Update

(1) I upgraded php on GoDaddy to 5.4. That was the highest version they had available.

(2) I ran the latest version (it's undergoing changes all the time) at the dev site, it works fine.

(3) Uploaded all latest versions to the (going to be, probably not now) live site at GoDaddy.

(4) Same single $_SESSION variable disappears between two programs. Code of both later. EXACTLY the same error as before.

(5) Ran Ray's Session test program, works perfect.

(6) Put these lines into tops of the two subject programs:

      error_reporting(E_ALL);
      ini_set('display_errors', 1);

(7) Put echos into the "from" & "to" programs to show, specifically, the values of $_SESSION['user']. The "from" program displays the correct value. The "to" program displays null.

(8) Did text search on both "from" & "to" programs for $_SESSION['user']. Found only at the expected places. NOWHERE is it set to null or blank.

From program:

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();
include "db_connect.php";
function conv_date($x) {
		$d = explode("-", $x);
		$r = $d[1] . "/" . $d[2] . "/" . $d[0];
		return $r;
	}
if(! empty($_SERVER['HTTP_USER_AGENT'])){
		$useragent = $_SERVER['HTTP_USER_AGENT'];
		if( preg_match('@(iPad|iPod|iPhone|Android|BlackBerry|SymbianOS|SCH-M\d+|Opera Mini|Windows CE|Nokia|SonyEricsson|webOS|PalmOS)@', $useragent) ){
			$loc = "phone.php";
		} else {
			$loc = "form.php";
	}
} 	
$qry = "SELECT * from form_data where user = " . $_SESSION['user'] . " order by prop_city, prop_zip, prop_addr";
//echo "qry = " . $qry;
$res = mysqli_query($link, $qry);
$nr = mysqli_num_rows($res);
$_SESSION['nr'] = $nr;
if ($nr == 0) {
	header("Location: " . $loc);	
}	
echo "session user = " . $_SESSION['user'] . "<br>";
?>

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
    <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>

    <script src="//code.jquery.com/jquery-1.10.2.js"></script>
    <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
    <link rel="stylesheet" href="/resources/demos/style.css">

    <title>Backflow Assembly & Test Report Form</title>
    <style>
        .nopadding {
            padding: 0 !important;
            margin: 0 !important;
        }
        
        .wrapper {
            max-width: 767px;
            min-width: 480px;
            margin: 0 auto;
        }
    </style>
	<script>
	ac = "";
	function chk_vals() {
		if (ac == "n") {
			document.st.action = "clear_sess.php";
			return true;
		}
		if (document.st.sprop.value == "") {
			alert("Please select a property.");	
			return false;
		}
		if (ac == "e") {
			document.st.action="http://backflowtestreport.com/get_form.php?u=" + document.st.sprop.value + "&usr=<? print $_SESSION['user']; ?>";
			return true;
		}
		if (ac == "p") {
			document.st.action="get_form.php?u=" + document.st.sprop.value + "&p=Y";
			return true;
		}
		if (ac == "d") {
			document.st.action = "delete_prop.php?u=" + document.st.sprop.value; 
			return true;	
		}	
	}
	</script>
</head>	
<body>
<div class="wrapper">
<form method="POST" name="st" action="form.php" onSubmit="return chk_vals();">
<div class="container-fluid" style="background-color: #F3D9AF;">
<div class="row">
    <div class="col-xs-8 text-center"><img src="images/bfp_logo_sm.jpg"></div>
</div>
<div class="row">
       <div class="col-xs-8 text-center" style="font-size:18px;"><b>Backflow Assembly & Test Report Form<br>Choose Property</b></div>
 </div>
<div class="row">
        <div class="col-xs-8 text-right" style="padding-top:10px;">
            <input type="submit" onMousedown= "ac='n';" value="New Property">
        </div>
</div>
<div class="row">
        <div class="col-xs-8" style="padding-top:10px;">	
		<select name="sprop">
			<option value="">--- Select a Property ---</option>
		<? for ($i = 0; $i < $nr; $i++) { 
			$fd = mysqli_fetch_array($res,MYSQLI_ASSOC);
			if ($fd['test_date'] == 0000-00-00) {
				$tdstr = "No Test Date";
			} else {
				$tdstr = conv_date($fd['test_date']);
			}	
			$val = $fd['prop_city'] . ", " . $fd['prop_zip'] . ", " . $fd['prop_addr'] . ", test date " . $tdstr;?>
			<option value="<? print $fd['uid']; ?>"><? print $val; ?></option>
		<? } ?>	
		</select></div>
</div>
<div class="row">
        <div class="col-xs-4 text-center" style="padding-top:10px;">	
				<input type="submit" value="Edit" onMousedown="ac='e';">
		</div>
		<div class="col-xs-4 text-center" style="padding-top:10px;">	
				<input type="submit" value="Delete" onMousedown="ac='d';">
		</div>
</div>
<div class="row">
        <div class="col-xs-8 text-center" style="padding-top:10px;">
            <input type="submit" onMousedown= "ac='p';" value="Print Form">
        </div>
</div>
<div class="row">
    <div class="col-xs-8 text-center" style="padding-top:10px;"></div>
</div>
		

            </div>
        </form>
    </div>
</body>

</html>	

Open in new window


To Program:

<?php
	error_reporting(E_ALL);
	ini_set('display_errors', 1);
	$u = $_GET['u'];
	session_start();
	$_SESSION['uid'] = $u;
	$prt = $_GET['p'];
	//echo "get usr = " . $_GET['usr'] . "<br>";
	echo "session user = " . $_SESSION['user'] . "<br>";
	include "db_connect.php";
	//echo "entered get_form<br>";
	function conv_date($x) {
		$d = explode("-", $x);
		$r = $d[1] . "/" . $d[2] . "/" . $d[0];
		return $r;
	}
	$qry = "SELECT * from form_data where uid = " . $u;
	$res = mysqli_query($link, $qry);
	$fd = mysqli_fetch_array($res,MYSQLI_ASSOC);
	$_SESSION['pn'] = $fd['property'];
	$_SESSION['padr'] = $fd['prop_addr'];
	$_SESSION['city'] = $fd['prop_city'];
	$_SESSION['state'] = $fd['prop_state'];
	$_SESSION['zip'] = $fd['prop_zip'];
	$_SESSION['keymap1'] = $fd['keymap1'];
	$_SESSION['keymap2'] = $fd['keymap2'];
	$_SESSION['phac'] = $fd['phac'];
	$_SESSION['phex'] = $fd['phex'];
	$_SESSION['phl4'] = $fd['phl4'];
	$_SESSION['madr'] = $fd['mailing_addr'];
	$_SESSION['ckmasa'] = $fd['ckmasa'];
	$_SESSION['conname'] = $fd['prop_contact'];
	$_SESSION['anr'] = $fd['assembly'];
	$_SESSION['rsn'] = $fd['ass_replaced'];
	$_SESSION['asstyp'] = $fd['ass_type'];
	$_SESSION['mfg'] = $fd['ass_mfg'];
	$_SESSION['model'] = $fd['ass_model'];
	$_SESSION['size'] = $fd['ass_size'];
	$_SESSION['serno'] = $fd['ass_serno'];
	$_SESSION['sloc'] = $fd['serving_loc'];
	$_SESSION['instdate'] = conv_date($fd['date_installed']);
	if ($fd['dina'] == "Y") {
		$_SESSION['dina'] = 'on';
		$_SESSION['instdate'] = "";
	}	
	$_SESSION['cupc'] = $fd['cupc'];
	if ($fd['initpass'] == "Y") {
		$_SESSION['initpass'] = "on";
	}	
	// test values
	// get proper record based on ass_typ
	//echo "asstyp = " . $_SESSION['asstyp'] . "<br>";
	//echo "session asstyp = " . $_SESSION['asstyp'] . "<br>";
	switch($_SESSION['asstyp']) {
			case "DVD":
			case "DCD":
				$qrytd = "SELECT * from test_data_dvc_dvd where uid = " . $u; 
				//echo "test data qry = " . $qrytd . "<br>";
				$restd = mysqli_query($link, $qrytd);
				break;
			case "RP":
			case "RPD":
				$qrytd = "SELECT * from test_data_rp_rpd where uid = " . $u;  
				$restd = mysqli_query($link, $qrytd);
				break;
			case "PVB":
			case "SVB":	
				$qrytd = "SELECT * from test_data_pvb_svb where uid = " . $u;  
				$restd = mysqli_query($link, $qrytd);
				//echo "insert pvb test data = " . $qryit . "<br>";
				break;
	}
	$td = mysqli_fetch_array($restd,MYSQLI_ASSOC);	
	$_SESSION['itcv1ct'] = "";
	$_SESSION['itcv2ct'] = "";
	$_SESSION['itcv1l'] = "";
	$_SESSION['itcv2l'] = "";
	$_SESSION['ftcv1ct'] = "";
	$_SESSION['ftcv2ct'] = "";
	$_SESSION['ftcv1l'] = "";
	$_SESSION['ftcv2l'] = "";
	$_SESSION['itrvdno'] = "";
	$_SESSION['itaidno'] = "";
	$_SESSION['itcvl'] = "";
	if ($td['itcv1ct'] == "Y") {
		$_SESSION['itcv1ct'] = "on";
	}
	if ($td['itcv2ct'] == "Y") {
		$_SESSION['itcv2ct'] = "on";
	}
	if ($td['itcv1l'] == "Y") {
		$_SESSION['itcv1l'] = "on";
	}
	if ($td['itcv2l'] == "Y") {
		$_SESSION['itcv2l'] = "on";
	}
	if ($td['itrvdno'] == "Y") {
		$_SESSION['itrvdno'] = "on";
	}
	if ($td['itaidno'] == "Y") {
		$_SESSION['itaidno'] = "on";
	}
	if ($td['ftcv1ct'] == "Y") {
		$_SESSION['ftcv1ct'] = "on";
	}
	if ($td['ftcv2ct'] == "Y") {
		$_SESSION['ftcv2ct'] = "on";
	}
	if ($td['ftcv1l'] == "Y") {
		$_SESSION['ftcv1l'] = "on";
	}
	if ($td['ftcv2l'] == "Y") {
		$_SESSION['ftcv2l'] = "on";
	}
	$_SESSION['itcv1psi'] = $td['itcv1psi'];
	//echo "itcv1psi = " . $td['itcv1psi'] . "<br>";
	$_SESSION['itcv2psi'] = $td['itcv2psi'];
	$_SESSION['itrvpsi'] = $td['itrvpsi'];
	$_SESSION['rmucv1'] = $td['rmucv1'];
	$_SESSION['rmucv2'] = $td['rmucv2'];
	$_SESSION['rmurv'] = $td['rmurv'];
	$_SESSION['ftcv1psi'] = $td['ftcv1psi'];
	$_SESSION['ftcv2psi'] = $td['ftcv2psi'];
	$_SESSION['ftrvpsi'] = $td['ftrvpsi'];
	$_SESSION['itaipsi'] = $td['itaipsi'];
	$_SESSION['itcvpsi'] = $td['itcvpsi'];
	$_SESSION['rmuai'] = $td['rmuai'];
	$_SESSION['rmucv'] = $td['rmucv'];
	$_SESSION['ftaipsi'] = $td['ftaipsi'];
	$_SESSION['ftcvpsi'] = $td['ftcvpsi'];

// form bottom part
	$_SESSION['testdate'] = conv_date($fd['test_date']);
	$_SESSION['witness'] = $fd['witness'];	
	$_SESSION['remarks'] = $fd['remarks'];
	$_SESSION['passfail'] = $fd['pass_fail'];
	//echo "user = " . $_SESSION['user'] . "<br>";
	if ($prt == "Y") {
		$loc = "print_form.php";
	} else {	
		$loc = "form.php";
		if(! empty($_SERVER['HTTP_USER_AGENT'])){
		$useragent = $_SERVER['HTTP_USER_AGENT'];
			if( preg_match('@(iPad|iPod|iPhone|Android|BlackBerry|SymbianOS|SCH-M\d+|Opera Mini|Windows CE|Nokia|SonyEricsson|webOS|PalmOS)@', $useragent) ){
			$loc = "phone.php";
			}
		}
	}	
	header("Location: " . $loc . "?t=" . $_SESSION['asstyp']);
	//echo "session uid in get form = " . $_SESSION['uid'] . "<br>";
	exit;

Open in new window


Notes: The "from" program displays a pulldown & several buttons. Near the bottom of the from program are the buttons. I select one of the pulldown "properties" & click "Edit". Note that goes to the Javascript function chk_vals, the js variable ac is set to 'e', so the action goes to get_form.php, the "to" program, upon whence $_SESSION['user'] is undefined.

The attached jpg is the screen shot of the php errors shown by the "to" program (get_form.php). The 2nd one is the disappearance of $_SESSION['user'].

Any help appreciated.
0
 
LVL 7

Expert Comment

by:Scobber
Comment Utility
Create a file as
<?php
phpinfo();
?>

On both servers, paste the output here feel free to generalise up addresses or server names.

Do not omit any other detail

Perhaps that will help someone resolve your problem
0
 

Author Comment

by:Richard Korts
Comment Utility
Scobber,

The output, as I'm sure you know is MANY pages long, I don't see an easy way to convey it; I'm not too imclined to save 25 pages of images for EACH server.

I could post the html each produces as "code", would that work?

Thanks
0
 

Author Comment

by:Richard Korts
Comment Utility
To all,

I suspect I'm just missing something obvious, I can't see the forest for the trees, that's where I'm hoping your eyes come in.

Richard
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
Here's an idea that may be helpful: SSCCE

Basically it teaches us to step away from the complexity that obscures the central issues and make smaller, more succinct examples that illustrate the problem we're having.  As we add layers of detail back into the succinct examples, we can see when the problem appears.  Then we have laser-targeting on the part of our application that causes the problem.
0
 
LVL 7

Expert Comment

by:Scobber
Comment Utility
output it as a pdf for each server and attach.

there is a peculiar difference between the two servers,

Id be happy to tee up a time on http://www.experts-exchange.com/live if you would like.

Unless you can provide some facts about both configurations, phpinfo is probably the best avenue for this,

Without it you may not get an answer that your happy with,
0
 

Author Comment

by:Richard Korts
Comment Utility
Ray,

I am aware of that technique, or variations of it.

I generally do it like this.

Cut the size of the offending program in half. try the first half, if it works, issue is in 2nd half. Cut 2nd half in half, etc.

Eventually you find it.

It just in this case it is not clear WHICH of the two programs is the issue. It appears that the $_SESSION variable is cleared inbetween the programs.

But I see a way to start.

Thanks, I didn't think of that.

I'll just cut both down to basically nothing except session start, echo the variable go to the next one, same.

Build from there
0
 

Author Comment

by:Richard Korts
Comment Utility
Scobber,

I don't see how to output it as a pdf.

Can you advise?

Thanks
0
 
LVL 7

Expert Comment

by:Scobber
Comment Utility
If you are on Windows 10 you just use the print utility to make a pdf, otherwise xps is ok

Failing that copy and paste it to word. Word pad. Notepad and upload it
0
 

Author Comment

by:Richard Korts
Comment Utility
Scobber,

See attached.

dev_server is where it works. godaddy is where it DOES NOT work.
phpinfo_dev_server.pdf
phpinfo_godaddy.pdf
0
 

Author Comment

by:Richard Korts
Comment Utility
To All,

Unless Scobber (or someone else) finds something in the php_info files, I give up.

I spent about 1 1/2 hours today trying to pare it down to a tiny program, still produces unpredictable results, insists on dropping just that ONE $_SESSION['user'] at various places. I'm almost convinced that $_SESSION['user'], the name user, is the issue but I can find nothing to corroborate that.

Just so you are all PERFECTLY clear, the programming & $_SESSION variables work PERFECTLY at my dev host.

So I am going to recommend to my customer getting hosting there so I don't have to waste any more time with this nonsense any more. If it then fails there, since it's working there now, I'm sure the tech support there will assist me in finding it.

If someone solves it before Sunday (8/28), they get the points. Otherwise, I will award points based on effort.

Thanks,

Richard
0
 
LVL 82

Expert Comment

by:Dave Baldwin
Comment Utility
You can check it by changing the name from 'user' to something similar like 'buser' and see what happens.
0
 

Author Comment

by:Richard Korts
Comment Utility
Dave,

I changed it to user1, made no difference. Same issue.
0
 
LVL 82

Expert Comment

by:Dave Baldwin
Comment Utility
I would have made a bigger change but still, that tells it is Not some peculiarity or reserved word in PHP.  It is something in your code that doesn't work the same on the two versions of PHP and the hosting setups.
0
 

Author Closing Comment

by:Richard Korts
Comment Utility
The problem is not solved.

I think we are going to host at Chihost, where it is being developed & it works.

I'm thinking of asking GoDaddy why this is but the dev is in flux, hard to pin down a test version, & they will say "you need to get a developer". Duh. They have told me that before.
0
 
LVL 82

Expert Comment

by:Dave Baldwin
Comment Utility
Probably a good decision to host it where it is working.  Godaddy won't look at any code.
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Suggested Solutions

Both Easy and Powerful How easy is PHP? http://lmgtfy.com?q=how+easy+is+php (http://lmgtfy.com?q=how+easy+is+php)  Very easy.  It has been described as "a programming language even my grandmother can use." How powerful is PHP?  http://en.wikiped…
Developers of all skill levels should learn to use current best practices when developing websites. However many developers, new and old, fall into the trap of using deprecated features because this is what so many tutorials and books tell them to u…
The viewer will learn how to count occurrences of each item in an array.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

743 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now