Jump to content

PHP 5 Session


zimmo

Recommended Posts

Hi People, I am on a deadline and finding that my code does not work in php5 and I have to change it to work. Just wonder if anyone can spot the obvious within my code. This all worked in php4 but now I have to rewrite it. Basically its a little order system.

 


<?
include("inc/connect.php");

// Continue start session.
// We need to first check to see if an item with the SID and cat and product_code exists in the database, 
// if it does then we need to update that item, if not then we need to add the item

// clean out any malicious data
foreach ($_REQUEST as $k => $v) {
$_REQUEST[$k] = (get_magic_quotes_gpc() ? strip_tags($v) : strip_tags(addslashes($v)));
}

session_start();
{

$sql = "SELECT * FROM orders WHERE sid = '$PHPSESSID' AND product_id = '$product_id' "; 
$sql_result = mysql_query($sql); 

if (mysql_num_rows($sql_result) ==0)
{
        # setup SQL statement
        $SQL = " INSERT INTO orders (sid,product_id,product_title,qty,standard_price,deluxe_price) VALUES ('$PHPSESSID','$product_id','$product_title','$qty','$standard_price','$deluxe_price')";

        #execute SQL statement
        $result = mysql_db_query( azflowers,"$SQL",$connection );

        # check for error
        if (!$result) { echo("ERROR: " . mysql_error() . "\n$SQL\n");    }
}
else
{
      # setup SQL statement
        $SQL = " UPDATE orders SET qty = qty +1 WHERE sid = '$PHPSESSID' AND product_id = '$product_id' ";

        #execute SQL statement
        $result = mysql_db_query( azflowers,"$SQL",$connection );

        # check for error
        if (!$result) { echo("ERROR: " . mysql_error() . "\n$SQL\n");    }
}

header("Location: http://www.site.com/site/cart.php?sid=$PHPSESSID");
exit;
}
?>

Link to comment
Share on other sites

There are very few incompatible differences between php4 and php5. Most php4 code will work as is under php5, given the same php.ini configuration. Most problems are due to code that is using old outdated/depreciated php features, such as register_globals.

 

Are you debugging your code on a system with error_reporting set to E_ALL and display_errors set to ON in your master php.ini so that all the php detected errors will be reported and displayed to help you find problems in your code? You will save a ton of time.

 

What kind of things have you needed to change so far, as that would narrow down the possible problems and help us to tell you what might need to be changed in the code you posted.

 

Also, what symptoms or errors are you getting, as that would narrow down the possible problems and help us tell you what might need to be changed in the code you posted.

 

Short-answer: Don't just post code that 'does not work' without also stating what problem, error, or symptom it exhibits when you tried it.

 

Most of the variables in your code don't have any code setting them and will be undefined. Your code is likely relying on register_globals, which were turned off by default over 8 years ago. Your code should have been updated to current php standards a long time ago and this has nothing to do with php4 vs php5.

Link to comment
Share on other sites

Seeing as I dont know what the errors are this may be as good as I can get it without actually running the code also, try using OOP, it helps the layout immensly for you and anyone that you want help from.

 

 

 

Also, read my comments. Some of them require changing for your needs.

 

<?php
require_once 'inc/connect.php';
//include("inc/connect.php");

// Continue start session.
// We need to first check to see if an item with the SID and cat and product_code exists in the database, 
// if it does then we need to update that item, if not then we need to add the item

// clean out any malicious data
//You cannot clean any malicious data when using an exploitable global variable. Try and use POST/GET but still SANITIZE
foreach ($_REQUEST as $k => $v) {
    $_REQUEST[$k] = (get_magic_quotes_gpc() ? strip_tags($v) : strip_tags(addslashes($v)));
}

session_start();

$sql = "SELECT * FROM `orders` WHERE `sid` = '{$PHPSESSID}' AND `product_id` = '{$product_id}' "; 
$sql_result = mysql_query($sql); 

if(mysql_num_rows($sql_result) ==0){
        # setup SQL statement
        $SQL = " INSERT INTO `orders` (`sid`,`product_id`,`product_title`,`qty`,`standard_price`,`deluxe_price`) VALUES ('{$PHPSESSID}','{$product_id}','{$product_title}','{$qty}','{$standard_price}','{$deluxe_price}')";

        #execute SQL statement
        
        #CHANGE ACCORDINGLY
        $SQLConnect = mysql_connect('[sERVER]','USER', 'PASS');
        
        if($SQLConnect !== TRUE){
            #Not good practice to put HTML in PHP but I dont know whether your using a Template System
            echo 'Sorry Something went wrong! <br />' . mysql_error();
        }else{
            
            $result = mysql_query("$SQL");
            if (!$result){
                echo 'ERROR: ' . mysql_error() . "\n$SQL\n";    
            }
        }
        
        
        //speed things up
        unset($result, $SQLConnect);



}else{
    # setup SQL statement
        $SQL = " UPDATE orders SET qty = qty +1 WHERE sid = '$PHPSESSID' AND product_id = '$product_id' ";    

        #CHANGE ACCORDINGLY
        $SQLConnect = mysql_connect('[sERVER]','USER', 'PASS');
        
        if($SQLConnect !== TRUE){
            #Not good practice to put HTML in PHP but I dont know whether your using a Template System
            echo 'Sorry Something went wrong! <br />' . mysql_error();
        }else{
            
            $result = mysql_query("$SQL");
            if (!$result){
                echo 'ERROR: ' . mysql_error() . "\n$SQL\n";    
            }
        }
}
header("Location: http://www.site.com/site/cart.php?sid=$PHPSESSID");


//speed things up
unset($SQLConnect, $SQL, $result);
?>

 

 

Best Regards,

Mantyy

 

Link to comment
Share on other sites

After reading the post above mine, I agree with him.

 

The only thing I did was made it more readable and changed a few functions from PHPv4 to PHPv5.

 

But you must make sure that you have got everything in your php.ini set up correctly for your needs. This would probably be more useful than my previous post.

Link to comment
Share on other sites

Thanks for the advice. I posted the code up too soon. I then had a look and realised, yes it was very old code. One that did work some time ago.

 

I am now understanding the differences, yes register globals was on for the old code, I have this off now by default, so will change things.

 

Will report back with how I get on. Thanks for the tips etc..

Link to comment
Share on other sites

Hi there Zimmo,

 

Firstly: use of short tags (<??>) is a bad idea as not all servers support the use of short style tags, for cross server compatibility always use full tags (<?php?>) this will make sure that you hard work will run on any server, and will save headaches later on should you come to migrate servers...

 

Secondly: $_REQUEST; global has know security issues, replace this with the actual global that you are trying to access ($_POST/$_GET/$_COOKIE) this will make you script more secure.

 

Session_start() should be set at the top of the file too, also a good idea to have error_reporting(E_ALL|E_DEPRECATED); on just underneath it so that you can see any errors being flagged up by php. I use deprecated so that any functions (like ereg & eregi) can be flagged up, because now preg is now favoured in php5

 

Cheers,

Rw

EDIT: I should learn to type quicker!!

Link to comment
Share on other sites

Thanks again people. I have noted all comments and will take note.

 

Now DarkMantis thanks for the code tips. I have altered my code now using some of the code you gave me, but for some reason when I add to basket and it executes this script it is hanging for a very long time? Would there be a reason for this?

 

Also, its not giving me a phpsession id or inserting anything into the database now?

Link to comment
Share on other sites

Also I forgot to mention how the data is added to the cart.

 

It is appended through a URL.

 

Here is an example:

addcart.php?action=add&product_title=Product&product_id=10&qty=1&standard_price=22.00&deluxe_price=0.00

 

Also, would my php ini file tell me more? Below is the settings for the session within the ini file.

 

 

session.auto_start	Off	Off
session.bug_compat_42	Off	Off
session.bug_compat_warn	On	On
session.cache_expire	180	180
session.cache_limiter	nocache	nocache
session.cookie_domain	no value	no value
session.cookie_lifetime	0	0
session.cookie_path	/	/
session.cookie_secure	Off	Off
session.entropy_file	no value	no value
session.entropy_length	0	0
session.gc_divisor	1000	1000
session.gc_maxlifetime	1440	1440
session.gc_probability	1	1
session.hash_bits_per_character	5	5
session.hash_function	0	0
session.name	PHPSESSID	PHPSESSID
session.referer_check	no value	no value
session.save_handler	files	files
session.save_path	/var/lib/php/session	/var/lib/php/session
session.serialize_handler	php	php
session.use_cookies	On	On
session.use_only_cookies	Off	Off
session.use_trans_sid	0	0

Link to comment
Share on other sites

Thanks Mantyy appreciate your support

 

It is still taking alot longer than before to process. Its taking a good few seconds. Before the way I had it written it was instant.

 

Also, for some reason the data is not going in the database, I just checked and it is not entering anything into the db? but still processing although taking ages.

Link to comment
Share on other sites

Here is my code now as it stands with help from this great forum.

 

<?php
session_start();
require_once 'inc/connect.php';
error_reporting(E_ALL|E_DEPRECATED);
//include("inc/connect.php");

// Continue start session.
// We need to first check to see if an item with the SID and cat and product_code exists in the database, 
// if it does then we need to update that item, if not then we need to add the item

// clean out any malicious data
  foreach ($_POST as $key => $value) { 
  $_POST[$key] = mysql_real_escape_string($value); 
  }


$sql = "SELECT * FROM orders WHERE sid = '{$PHPSESSID}' AND product_id = '{$product_id}' "; 
$sql_result = mysql_query($sql); 

if(mysql_num_rows($sql_result) ==0){
	# setup SQL statement
	$SQL = "INSERT INTO orders (sid,product_id,product_title,qty,standard_price,deluxe_price) VALUES ('{$PHPSESSID}','{$product_id}','{$product_title}','{$qty}','{$standard_price}','{$deluxe_price}')";

	#execute SQL statement

	#CHANGE ACCORDINGLY
	$SQLConnect = mysql_connect('*****','*****', '*****');

	if($SQLConnect !== TRUE){
		#Not good practice to put HTML in PHP but I dont know whether your using a Template System
		echo 'Sorry Something went wrong! <br />' . mysql_error();
	}else{

		$result = mysql_query("$SQL");
		if (!$result){
			echo 'ERROR: ' . mysql_error() . "\n$SQL\n";	
		}
	}

	//speed things up
	unset($result, $SQLConnect);

}else{
# setup SQL statement
	$SQL = "UPDATE orders SET qty = qty +1 WHERE sid = '{$PHPSESSID}' AND product_id = '{$product_id}'";	

	#CHANGE ACCORDINGLY
	$SQLConnect = mysql_connect('*****','*****', '*****');

	if($SQLConnect !== TRUE){
		#Not good practice to put HTML in PHP but I dont know whether your using a Template System
		echo 'Sorry Something went wrong! <br />' . mysql_error();
	}else{

		$result = mysql_query("$SQL");
		if (!$result){
			echo 'ERROR: ' . mysql_error() . "\n$SQL\n";	
		}
	}
}
header("Location: http://www.site.com/site/cart.php?sid='{$PHPSESSID}'");
exit;

//speed things up
unset($SQLConnect, $SQL, $result);
?>

 

What is happening now is:

1: The script is taking a long time to execute. As though it is hanging.

2: The session id is still not given

3: The data is NOT going into the database.

 

Can anyone see why? I am stuck.

Link to comment
Share on other sites

You need to add the following -

ini_set("display_errors", "1");

 

The error_reporting/display_errors should be set immediately after your first opening <?php tag (so that session_start and errors due to your connect.php will be reported.)

 

I had hoped that you had not used the mysql_connect() code that had been posted, for a couple of reasons - you are already apparently making a connection in connect.php (for your initial query on the page) and since the posted code didn't select a database, it would be producing more problems.

Link to comment
Share on other sites

Hi there,

 

I am still learning, so thank you for the comments. I have gone back to my original code and modified that to see if that will work. I have also placed the error code at the very top as well. I am getting no errors, an entry is getting created in the db but without the information that is being sent. So a blank entry.

 

Still not getting any session id at all?

 

Here is the code now

<?
ini_set("display_errors", "1");
session_start();
include("inc/connect.php");

// Continue start session.
// We need to first check to see if an item with the SID and product id exists in the database, 
// if it does then we need to update that item, if not then we need to add the item

//This stops SQL Injection in POST vars 
  foreach ($_POST as $key => $value) { 
  $_POST[$key] = mysql_real_escape_string($value); 
  }

{

$sql = "SELECT * FROM orders WHERE sid = '{$PHPSESSID}' AND product_id = '{$product_id}' "; 
$sql_result = mysql_query($sql); 

if (mysql_num_rows($sql_result) ==0)
{
        # setup SQL statement
	$SQL = " INSERT INTO orders (sid,product_id,product_title,qty,standard_price,deluxe_price) VALUES ('{$PHPSESSID}','{$product_id}','{$product_title}','{$qty}','{$standard_price}','{$deluxe_price}')";

        #execute SQL statement
        $result = mysql_db_query( azflowers,"$SQL",$connection );

        # check for error
        if (!$result) { echo("ERROR: " . mysql_error() . "\n$SQL\n");    }
}
else
{
      # setup SQL statement
	$SQL = " UPDATE orders SET qty = qty +1 WHERE sid = '{$PHPSESSID}' AND product_id = '{$product_id}' ";	

        #execute SQL statement
        $result = mysql_db_query( azflowers,"$SQL",$connection );

        # check for error
        if (!$result) { echo("ERROR: " . mysql_error() . "\n$SQL\n");    }
}

header("Location: http://www.atozofflowers.com/site/cart.php?sid=$_GET[phpSESSID]");
exit;
}
?>

 

 

Link to comment
Share on other sites

sorry, I thought what you said was to replace that. Just tested now: Here is the top of the code now:

 

ini_set("display_errors", "1");

error_reporting(E_ALL|E_DEPRECATED);

session_start();

include("inc/connect.php");

 

Just tried the link again and nothing is getting mentioned, should I see errors?

Link to comment
Share on other sites

Sorry to bother people again... spending hours on this and driving me insane. I am not sure if it is my code with the issue or my server, as I cannot get the session id..... is the syntax correct for entering into the database as the data is not entering but seems as though it is attempting to?

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.