How to add elements to an array ?

HI

I have declared the following session variable:

session_start();
$_SESSION['articulos'] = array();

And this code adds an element in the array, but it only keeps the last element and not all of them:
$indice = $_GET["codigo"];
$_SESSION['articulos'] = array($indice => 1);

The idea is to store in session all selected products.
dimensionavAsked:
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.

StingRaYCommented:
$_SESSION['articulos'][$indice] = 1;

Open in new window

0
dimensionavAuthor Commented:
I tried your code but I still watching the last element, this is the code I use to get the array elements:

                            foreach ($_SESSION['articulos'] as $key => $value) {
                            echo("<td><div align=\"center\"></div>".$value."</td>");
                            echo("<td><div align=\"center\">".$key."</div></td>");
                            echo("<td><div align=\"right\"></div></td>");
                            echo("<td><div align=\"right\"></div></td>");
                            echo("<td><div align=\"center\">Eliminar</div></td>");
                            }
0
youssefomarCommented:
All data need to be serialized before saved into sessions.
<?
    session_start();
    
    $arr = array();
    // reading the array from a session
    if(isset($_SESSION['articulos'])){
        $arr = unserialize($_SESSION['articulos']);
        foreach ($arr as $key => $value){
            echo $value;
        }
    }
    
    // adding new item to the array then wirting the array to a session
    $arr[] = "xxx";
    $_SESSION['articulos'] = serialize($arr);
    
?>

Open in new window

0
Cloud Class® Course: Amazon Web Services - Basic

Are you thinking about creating an Amazon Web Services account for your business? Not sure where to start? In this course you’ll get an overview of the history of AWS and take a tour of their user interface.

Ray PaseurCommented:
Let me try to deconstruct this little piece of code and show you what is happening.

1. $indice = $_GET["codigo"];
2. $_SESSION['articulos'] = array($indice => 1);

Here is what you need to know:

It is not clear if the session_start() statement was executed before the logic flow came here.  Without that, PHP will not start the session handler.  Unfortunately the variable $_SESSION can be created and used by your PHP script even if the session_start() function has not been called.  What happens?  Nothing -- it is a silent error.  The information you put into the $_SESSION array will simply be lost and PHP will not tell you about it.  Hardly a recipe for success!

PHP session handling is documented here.  Take some time to read the man pages carefully and learn what happens.  In particular, you need to be aware that if there has been any browser output at all, even invisible whitespace, the session_start() function cannot work.  It must come first.
http://us.php.net/manual/en/features.sessions.php
http://us.php.net/manual/en/function.session-start.php

A wise practice is to begin every script with these statements in this order:

// TELL PHP TO REPORT MY ERRORS
ini_set('display_errors', TRUE);
error_reporting(E_ALL);
// ALWAYS START THE SESSION, UNCONDITIONALLY, ON EVERY PAGE
session_start();

Statement #1
$indice = $_GET["codigo"];

This statement assumes that there is a URL parameter argument named "codigo=" like this:
<a href="path/to/script.php?codigo=X+Y">link</a>

In this URL and in the PHP script, "codigo" is case sensitive, so "Codigo" is a different variable name or array index.  If there is no such URL parameter, $indice will be made to exist in the namespace or scope of your script, and it will contain the NULL value.  If there is a URL parameter named "codigo" its structure and value will be copied into $indice.  Probably it will be a string, and it may also be an array.  PHP loose typecasting may change the data type.

Statement #2
$_SESSION['articulos'] = array($indice => 1);

This statement creates an array.  The array has one key-value pair.  Array keys are case-sensitive and loosely typecast.  The value is an integer 1.  The key is what?  We do not know because we do not know what data, if any, was presented by the client in the GET request!  If we are lucky, and the client URL said "?codigo=X+Y", then the $indice variable would now contain a string of three characters with "X Y" and the created array would look like this:
array: "X Y" => 1

What if the client omitted "codigo" from the URL argument?  What will this statement do with a NULL array key?  Good question!  I have never tried to do anything like that.  You might want to test it and see what happens.  You can use var_dump() to look at the data in $_SESSION.  You want to be careful that you never write programming that could depend on an unset or invalid variable.   Since information in $_GET is external data, it is by definition tainted and therefore to be considered an attack vector.  It is wise to set default values and filter external data carefully, using the philosophy, "Accept Only Known Good Values."  

After the array is created, it will be assigned to the array position named 'articulos' in the variable $_SESSION.  Thus you will have a two-dimensional array in $_SESSION.  Taken together, these two lines of code have done nothing more than copy an unfiltered (and possibly nonexistent) URL parameter into a local variable and into an array key of a super-global variable.  A third copy of this variable will appear in $key in this iterator, where $value will contain integer 1.
foreach ($_SESSION['articulos'] as $key => $value)

At this point the script has three unfiltered copies of the potential attack vector.  This is not healthy!

You might enjoy this book.  Very readable with great examples.  Now in its fourth printing, it has been a permanent member of my professional library since Edition One.
http://www.sitepoint.com/books/phpmysql4/

Happy New Year and best of luck with your project, ~Ray
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
Ray PaseurCommented:
The assertion at ID:37349319 that all data must be serialized is factually inaccurate.  Data may be serialized, but it is not required.

See http://www.laprbass.com/RAY_temp_youssefomar.php and refresh the browser a few times.
<?php // RAY_temp_youssefomar.php
error_reporting(E_ALL);


// PHP SESSION HANDLING
session_start();

// MAKE THE OUTPUT EASY TO READ
echo "<pre>";

// SHOW THE STATE OF THE SESSION NOW
echo "BEFORE: ";
var_dump($_SESSION);

// SET  OR INCREMENT SOME VARS
if (empty($_SESSION["cheese"])) $_SESSION["cheese"] = "Cheddar";
if (!isset($_SESSION["array"]))
{
    $_SESSION["array"] = array( 'X' => 1 );
}
else
{
    $_SESSION["array"]['X']++;
}

echo "AFTER: ";
var_dump($_SESSION);

Open in new window

0
youssefomarCommented:
@Ray
I think you are right, serialize is not important for arrays but it's for objects, see serialze() help on php.net

 dimensionav, in the code you submitted in the question, you just need to add empty brackets [] after $_SESSION['articulos']
<?

session_start();
$_SESSION['articulos'] = array();

// And this code adds an element in the array, but it only keeps the last element and not all of them:
$indice = $_GET["codigo"];
$_SESSION['articulos'][] = array($indice => 1);

?>

Open in new window

0
eriksmtkaCommented:
@youssefomar: you don't need to serialize an array or even an object stored in a session variable.. but you DO have to define the class (include it from the file, whatever) BEFORE you start the session... if you don't it will choke.
0
youssefomarCommented:
@eriksmtka: according to http://www.php.net/manual/en/function.serialize.php, serialize() " is useful for storing or passing PHP values around without losing their type and structure. "

and I just found out that PHP serializes all objects, when saved into a session, automatically so you do not have to do it yourself: http://php.net/manual/en/oop4.serialization.php

thank you, I learned something new.
0
dimensionavAuthor Commented:
Wow guys what a really good explanation about this!

Ray_Paseur: I will take some time to read what you give, meanwhile, I would like to give you some more information.
I call start_session at the top of every script of all pages but, the script is not placed at the very top of the pages, I wonder if that is a problem.
The GET variable is generated by a script so the user never iteracts with that data but I consider that in some cases could be possible to lost it, should be a good idea to protect that part of the code.

youssefomar:
I have tried your code and now I just get as Key Array the word "Array" and as value "0".
0
Ray PaseurCommented:
the script is not placed at the very top of the pages - I would be highly suspicious of that.  Consider this example:

<?php $x = 3; ?>
<?php session_start(); ?>

The session will not be started because there is an invisible whitespace character (the newline character) and that qualifies as browser output.  The session uses cookies, and cookies are headers.  It is a law of HTTP that headers must come before and be complete before any browser output.
0
dimensionavAuthor Commented:
Guys, I did this:

At the very top of each script I have a require instruction that gets the connection to the database, something like this:

SOME HTML
HEADER
BODY
...SOME TABLE
      <?php
    require("conndb.php");
    SOME MORE PHP CODE.....
   ...
   ...    
   ?>
....
FINAL HTML


And this is conndb.php file:

<?php
session_start();
$prefijo = "";
$servidor="localhost";
$usuario=$prefijo."user";
$pass="pass";
$conn=mysql_connect($servidor,$usuario,$pass);
$db=$prefijo."db";
mysql_select_db($db,$conn);
?>

Now the array is working but I got in each page this error:

Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent........
0
youssefomarCommented:
Make the include of conndb.php 1st line:


<?php
       require("conndb.php");
?>
SOME HTML
HEADER
BODY
...SOME TABLE
      <?php
    SOME MORE PHP CODE.....
   ...
   ...    
   ?>
....
FINAL HTML
0
Ray PaseurCommented:
Agree with youssefomar.  Here is a sample "common" script from one of my apps.  Every script starts with

<?php
require_once("common.php");


As you can see, in one statement I bring in all of my initialization and housekeeping routines, I load my classes and functions, etc.  Whenever I find that my web site or application has two scripts that might need the same processing, it goes into the common script, so I can avoid repeating myself.

Now to a little more important design pattern, and that is the separation of logic and presentation. The usual method I use when I prepare a web page is to do all of the PHP processing and set up all of the variables before I think about presentation of HTML.  Only after all the work is done do I begin the presentation layer.  This means I can concentrate on the logic in one section of the script and the presentation in the other section.  Just because PHP allows you to intersperse logic with echo statements does not mean it is a good idea to do so.  In fact the programmer's best hope is exactly one echo statement at the end of the script!  You can do that effectively if you use HEREDOC syntax.
http://us.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc

Anyway, it looks like you're getting the idea and that your sessions will be working from now on, so I will sign off.  Best regards, and Happy New Year, ~Ray
<?php // common.php
error_reporting(E_ALL);
date_default_timezone_set('America/Chicago');

// LIVE DATABASE CREDENTIALS
require_once('/path/to/live_data.php');


// OPEN A CONNECTION TO THE DATA BASE SERVER
// MAN PAGE: http://us2.php.net/manual/en/function.mysql-connect.php
if (!$db_connection = mysql_connect("$db_host", "$db_user", "$db_word"))
{
    $errmsg = mysql_errno() . ' ' . mysql_error();
    echo "<br/>NO DB CONNECTION: ";
    echo "<br/> $errmsg <br/>";
}

// SELECT THE MYSQL DATA BASE
// MAN PAGE: http://us2.php.net/manual/en/function.mysql-select-db.php
if (!$db_sel = mysql_select_db($db_name, $db_connection))
{
    $errmsg = mysql_errno() . ' ' . mysql_error();
    echo "<br/>NO DB SELECTION: ";
    echo "<br/> $errmsg <br/>";
    die('NO DATA BASE');
}
// IF WE GOT THIS FAR WE CAN DO QUERIES


Class States
{

    protected $states;
    protected $abbrs;

    public function __construct( $canada=TRUE )
    {
        $this->states['AK'] = 'Alaska';
        $this->states['AL'] = 'Alabama';
        $this->states['AR'] = 'Arkansas';
        $this->states['AZ'] = 'Arizona';
        $this->states['CA'] = 'California';
        $this->states['CO'] = 'Colorado';
        $this->states['CT'] = 'Connecticut';
        $this->states['DC'] = 'Washington DC';
        $this->states['DE'] = 'Delaware';
        $this->states['FL'] = 'Florida';
        $this->states['GA'] = 'Georgia';
        $this->states['HI'] = 'Hawaii';
        $this->states['IA'] = 'Iowa';
        $this->states['ID'] = 'Idaho';
        $this->states['IL'] = 'Illinois';
        $this->states['IN'] = 'Indiana';
        $this->states['KS'] = 'Kansas';
        $this->states['KY'] = 'Kentucky';
        $this->states['LA'] = 'Louisiana';
        $this->states['MA'] = 'Massachusetts';
        $this->states['MD'] = 'Maryland';
        $this->states['ME'] = 'Maine';
        $this->states['MI'] = 'Michigan';
        $this->states['MN'] = 'Minnesota';
        $this->states['MO'] = 'Missouri';
        $this->states['MS'] = 'Mississippi';
        $this->states['MT'] = 'Montana';
        $this->states['NC'] = 'North Carolina';
        $this->states['ND'] = 'North Dakota';
        $this->states['NE'] = 'Nebraska';
        $this->states['NH'] = 'New Hampshire';
        $this->states['NJ'] = 'New Jersey';
        $this->states['NM'] = 'New Mexico';
        $this->states['NV'] = 'Nevada';
        $this->states['NY'] = 'New York';
        $this->states['OH'] = 'Ohio';
        $this->states['OK'] = 'Oklahoma';
        $this->states['OR'] = 'Oregon';
        $this->states['PA'] = 'Pennsylvania';
        $this->states['RI'] = 'Rhode Island';
        $this->states['SC'] = 'South Carolina';
        $this->states['SD'] = 'South Dakota';
        $this->states['TN'] = 'Tennessee';
        $this->states['TX'] = 'Texas';
        $this->states['UT'] = 'Utah';
        $this->states['VA'] = 'Virginia';
        $this->states['VT'] = 'Vermont';
        $this->states['WA'] = 'Washington';
        $this->states['WI'] = 'Wisconsin';
        $this->states['WV'] = 'West Virginia';
        $this->states['WY'] = 'Wyoming';

        if ($canada)
        {
            $this->states['AB'] = 'Alberta';
            $this->states['BC'] = 'British Columbia';
            $this->states['MB'] = 'Manitoba';
            $this->states['NB'] = 'New Brunswick';
            $this->states['NL'] = 'Newfoundland and Labrador';
            $this->states['NS'] = 'Nova Scotia';
            $this->states['NT'] = 'Northwest Territories';
            $this->states['NU'] = 'Nunavut';
            $this->states['ON'] = 'Ontario';
            $this->states['PE'] = 'Prince Edward Island';
            $this->states['QC'] = 'Quebec';
            $this->states['SK'] = 'Saskatchewan';
            $this->states['YT'] = 'Yukon Territory';
        }

        $this->abbrs = array_keys($this->states);
    }

    // GET NAME FROM STATE ABBREVIATION
    public function getName($abbr)
    {
        $abbr = trim(strtoupper($abbr));
        if (!isset($this->states[$abbr])) return FALSE;
        return $this->states[$abbr];
    }

    // GET ALL NAMES FROM STATE ABBREVIATIONS
    public function getAllNames()
    {
        return $this->states;
    }

    // GET STATE ABBREVIATIONS
    public function getAllAbbrs()
    {
        return $this->abbrs;
    }

} // END CLASS STATES



// DEFINE THE GOOGLE STATIC MAPPING CLASS
class GSM
{
    // THE MAP CENTER GEOCODE, ADDRESS OR LANDMARK
    protected $center;

    // MARKER DATA ARRAY
    protected $markers;
    protected $default_icon;

    // OUR VARIABLES FOR THE MAP DISPLAY
    protected $maptype;
    protected $width;
    protected $height;
    protected $zoom;
    protected $format;

    // OUR VARIABLES FOR THE GOOGLE URL AND IMAGE TAG
    protected $alt;
    protected $title;
    protected $class;
    protected $id;
    protected $usemap;
    protected $sensor;
    protected $url;
    private $img;

    // A CONSTRUCTOR TO SET THE DEFAULT VALUES
    public function __construct()
    {
        // THE URL AND IMG TAG PARAMETERS
        $this->alt    = FALSE;
        $this->class  = FALSE;
        $this->id     = FALSE;
        $this->usemap = FALSE;
        $this->sensor = FALSE;
        $this->title  = TRUE;
        $this->url    = '';
        $this->img    = '';

        // THE CENTER AND ZOOM SCALE OF THE MAP (IF OMITTED, GOOGLE WILL CALCULATE)
        $this->center  = NULL;
        $this->zoom    = NULL;

        // THE CHARACTERISTICS OF THE MAP IMAGE
        $this->maptype = 'hybrid';    // CHOOSE
        $this->maptype = 'terrain';   // AMONG
        $this->maptype = 'satellite'; // THESE
        $this->maptype = 'roadmap';   // OPTIONS
        $this->width   = '640';
        $this->height  = '640';
        $this->format  = 'png';

        // THE DEFAULT ICON
        $this->default_icon = 'http://maps.google.com/mapfiles/ms/micons/question.png';

        // AN ARRAY OF MARKER ARRAYS
        $this->clearMarkers();

    } // END CONSTRUCTOR

    // A METHOD TO CLEAR THE MARKERS
    public function clearMarkers()
    {
        $this->markers = array();
    }

    // A SETTER TO ADD MARKERS TO THE MAP
    public function setMarker($geocode, $color='blue', $size='normal', $label='X')
    {
        $this->markers[]
        = array
        ( 'color'   => $color
        , 'label'   => $label
        , 'geocode' => $geocode
        , 'size'    => $size
        , 'icon'    => FALSE
        )
        ;
    }

    // A SETTER TO ADD ICONS TO THE MAP - VIEW SOURCE HERE: http://www.visual-case.it/cgi-bin/vc/GMapsIcons.pl
    public function setIcon($geocode, $icon=FALSE)
    {
        if (!$icon) $icon = $this->default_icon;
        $this->markers[]
        = array
        ( 'color'   => FALSE
        , 'label'   => FALSE
        , 'geocode' => $geocode
        , 'icon'    => $icon
        )
        ;
    }

    // A SETTER TO OVERRIDE EACH OF THE DEFAULT VALUES
    public function setCenter($geocode=NULL)
    {
        $this->center = $geocode;
    }
    public function setMaptype($x)
    {
        $this->maptype = $x;
    }
    public function setFormat($x)
    {
        $this->format = $x;
    }
    public function setWidth($x)
    {
        $this->width = $x;
    }
    public function setHeight($x)
    {
        $this->height = $x;
    }
    public function setZoom($x=NULL)
    {
        $this->zoom = $x;
    }
    public function setAlt($x=FALSE)
    {
        $this->alt = $x;
    }
    public function setTitle($x=TRUE)
    {
        $this->title = $x;
    }
    public function setClass($x=FALSE)
    {
        $this->class = $x;
    }
    public function setId($x=FALSE)
    {
        $this->id = $x;
    }
    public function setUsemap($x=FALSE)
    {
        $this->usemap = $x;
    }
    public function setSensor($x=FALSE)
    {
        $this->sensor = $x;
    }

    // A METHOD TO PREPARE AND RETRIEVE THE MAPPING URL
    public function asURL()
    {
        $s = 'false'; // SEE http://code.google.com/apis/maps/documentation/staticmaps/#Sensor
        if ($this->sensor) $s = 'true';

        // IF ICONS OR MARKERS ARE ON THE MAP, 'IMPLODE' THE DATA INTO THE URL
        $marker_string = '';
        foreach ($this->markers as $marker)
        {
            // PROCESS FOR CUSTOM ICONS
            if ($marker['icon'])
            {
                $marker_string
                = $marker_string
                . '&markers='
                . 'icon:'
                . urlencode($marker['icon'])
                . '|'
                . $marker['geocode']
                ;
                continue;
            }
            // PROCESS FOR STANDARD MARKERS
            $marker_string
            = $marker_string
            . '&markers='
            . 'color:'
            . $marker['color']
            . '|'
            . 'label:'
            . $marker['label']
            . '|'
            . 'size:'
            . $marker['size']
            . '|'
            . $marker['geocode']
            ;
        }

        // SET CENTER AND ZOOM, IF PRESENT
        $c = '';
        if ($this->center) $c = "&center=$this->center";
        $z = '';
        if ($this->zoom)   $z = "&zoom=$this->zoom";

        // MAKE THE URL
        $this->url
        = "http://maps.google.com/maps/api/staticmap?sensor=$s"
        . $c
        . $z
        . "&size=$this->width" . 'x' . "$this->height"
        . "&format=$this->format"
        . "&maptype=$this->maptype"
        . "$marker_string"
        ;
        return $this->url;
    }

    // A METHOD TO PREPARE AND RETRIEVE THE HTML IMAGE TAG
    public function asIMG()
    {
        // GET THE URL
        if (!$this->url) $this->url = $this->asURL();

        // GET THE ALT TEXT
        $a = "$this->maptype" . ' centered ' . "$this->center";
        if ($this->alt !== FALSE) $a = $this->alt;

        // REQUIRED FIELDS
        $this->img = '<img src="' . $this->url . '" alt="' . $a . '"';

        // OPTIONAL FIELDS - PROVIDE A DEFAULT TITLE
        $t = "$this->maptype" . ' centered ' . "$this->center";
        if     ($this->title  === TRUE ) { $this->img .= ' title="' . $t .           '"'; }
        elseif ($this->title !== FALSE)  { $this->img .= ' title="' . $this->title . '"'; }

        // OPTIONAL FIELDS MAY BE OMITTED
        if ($this->class  !== FALSE) { $this->img .= ' class="'  . $this->class  . '"'; }
        if ($this->id     !== FALSE) { $this->img .= ' id="'     . $this->id     . '"'; }
        if ($this->usemap !== FALSE) { $this->img .= ' usemap="' . $this->usemap . '"'; }

        // CLOSE THE IMAGE TAG AND CLEAR THE CONSUMED URL
        $this->img .= ' />';
        $this->url = FALSE;
        return $this->img;
    }
} // END CLASS GSM



// SIMPLE GEOCODER CLASS
class SimpleGeoCoder
{

    // DECLARE THE INPUT DATA
    public $location; // USE THIS FOR A FREEFORM QUERY, OR USE THESE PARTS
    public $address;
    public $city;
    public $state;
    public $zip;

    // DECLARE THE OUTPUT DATA
    public $latitude;
    public $longitude;
    public $precision;
    public $warning;
    public $geocoder;

    // DECLARE THE CONSTRUCTOR
    public function __construct()
    {
        $this->latitude  = 0.0;
        $this->longitude = 0.0;
        $this->precision = 0;   // HIGHER IS BETTER, BUT Y AND G USE DIFFERENT SCALES
        $this->warning   = '';
        $this->geocoder  = '';
    }

    // DECLARE THE YAHOO! VERSION OF THE WORKHORSE
    public function geocodeYahoo()
    {
        $this->geocoder = 'Yahoo!';
        $yahooUrl       = "http://where.yahooapis.com/geocode?gflags=Q&appid=";
        if (defined("YAHOO_API"))
        {
            $yahooUrl .= YAHOO_API;
        }

        // YOU CAN ASK FOR A FREEFORM QUERY
        if ($this->location != '')
        {
            $yahooUrl .= "&location=" . urlencode($this->location);
        }

        // YOU CAN ASK FOR INDIVIDUAL PIECES OF AN ADDRESS
        else
        {
            $loc = urlencode
            ( trim($this->address)
            . ', '
            . trim($this->city)
            . ', '
            . trim($this->state)
            . ' '
            . trim($this->zip)
            )
            ;
            $yahooUrl .= "&location=" . $loc;
        }

        // EXECUTE YAHOO GEOCODER QUERY SEE http://developer.yahoo.com/geo/placefinder/guide/requests.html
        // NOTE - USE ERROR SUPPRESSION OR IT WILL BARK OUT THE YAHOO API KEY - ON FAILURE RETURNS HTTP 400 BAD REQUEST
        if ($yfp = @fopen($yahooUrl, 'r'))
        {
            $yahooResponse = '';
            while (!feof($yfp)) { $yahooResponse .= fgets($yfp); }
            fclose($yfp);
        }
        else
        {
            return FALSE;
        }

        // EXAMINE THE RESULT
        if ($yahooResponse != '') // NOT EMPTY, WE GOT DATA
        {
            $ydata    = new SimpleXMLElement($yahooResponse);
            // echo "<pre>";var_dump($ydata);

            // CHECK FOR ANY ERROR MESSAGE, IF NONE, EXTRACT THE DATA POINTS
            $y_err    = (string)$ydata->Error;
            if ($y_err)
            {
                $this->warning   = $ydata->ErrorMessage;
                return FALSE;
            }
            else
            {
                $this->precision = (string)$ydata->Result->quality;
                $this->latitude  = (string)$ydata->Result->latitude;
                $this->longitude = (string)$ydata->Result->longitude;
                $this->address   = (string)$ydata->Result->line1;
                $this->city      = (string)$ydata->Result->city;
                $this->state     = (string)$ydata->Result->statecode;
                $this->zip       = (string)$ydata->Result->postal;

                $this->location
                = (string)$ydata->Result->line1
                . ', '
                . (string)$ydata->Result->line2
                . ' '
                . (string)$ydata->Result->line3
                ;
            }
        }

        // NO RESULT - SOMETHING IS SICK AT YAHOO
        else
        {
            return FALSE;
        }
        return TRUE;
    } // END function geocodeYahoo



    // DECLARE THE GOOGLE VERSION OF THE WORKHORSE
    public function geocodeGoogle()
    {
        $this->geocoder = 'Google';
        $googleUrl      = "http://maps.google.com/maps/geo?output=csv";
        $googleUrl      = "http://maps.googleapis.com/maps/api/geocode/xml?sensor=false";
        if (defined("GOOGLE_API"))
        {
            $googleUrl .= "&key=" . GOOGLE_API;
        }

        // YOU CAN ASK FOR A FREEFORM QUERY
        if ($this->location != '')
        {
            $googleUrl .= "&address=" . urlencode(trim($this->location));
        }

        // YOU CAN ASK FOR INDIVIDUAL PIECES OF AN ADDRESS
        else
        {
            $loc = urlencode
            ( trim($this->address)
            . ', '
            . trim($this->city)
            . ', '
            . trim($this->state)
            . ' '
            . trim($this->zip)
            )
            ;
            $googleUrl .= "&address=$loc";
        }

        // EXECUTE GOOGLE GEOCODER QUERY SEE http://code.google.com/apis/maps/documentation/geocoding/
        if ($gfp = @fopen($googleUrl, 'r'))
        {
            $googleResponse = '';
            while (!feof($gfp)) { $googleResponse .= fgets($gfp); }
            fclose($gfp);
        }
        else
        {
            return FALSE;
        }

        // EXTRACT THE DATA
        $gdata    = new SimpleXMLElement($googleResponse);

        // ON FAILURE
        if ($gdata->status != 'OK') return FALSE;

        // GEOCODE ACCURACY IS A TEXT STRING NOW
        $this->location  = (string)$gdata->result->formatted_address;
        $this->precision = (string)$gdata->result->type;
        $this->latitude  = (string)$gdata->result->geometry->location->lat;
        $this->longitude = (string)$gdata->result->geometry->location->lng;
        return TRUE;
    } // END function geocodeGoogle

} // END class SimpleGeocoder



class ResponseObject
{
    public function __construct()
    {
        $this->response = array();
    }
    public function setResponse($jso)
    {
        // AN ARRAY OF OBJECTS
        $this->response[] = $jso;
    }
    public function getResponse()
    {
        return $this->response;
    }
    public function getJSON()
    {
        $jso = json_encode($this->response);
        $jso = str_replace('\\', NULL, $jso);
        return $jso;
    }
}


class ErrorObject
{
    public function __construct($err)
    {
        $this->xml = "<error>$err</error>";
        $this->obj = SimpleXML_Load_String($this->xml);
    }
    public function getJSON()
    {
        return json_encode($this->obj);
    }
}



// MAN PAGE: http://en.wikipedia.org/wiki/Haversine_formula
function compute_distance($from_lat, $from_lon, $to_lat, $to_lon, $units='KM')
{
    // CHOOSE A UNIT OF MEASURE BY THE FIRST CHARACTER
    $units = strtoupper(substr(trim($units),0,1));

    // ENSURE THAT ALL COORDINATES ARE FLOATING POINT VALUES
    $from_lat = floatval($from_lat);
    $from_lon = floatval($from_lon);
    $to_lat   = floatval($to_lat);
    $to_lon   = floatval($to_lon);

    // IF THE SAME POINT THE DISTANCE IS ZERO AND HAVERSINE IS NOT NEEDED
    if ( ($from_lat == $to_lat) && ($from_lon == $to_lon) )
    {
        return 0.0;
    }

    // COMPUTE THE DISTANCE WITH THE HAVERSINE FORMULA
    $distance
    = acos
    ( sin(deg2rad($from_lat))
    * sin(deg2rad($to_lat))
    + cos(deg2rad($from_lat))
    * cos(deg2rad($to_lat))
    * cos(deg2rad($from_lon - $to_lon))
    )
    ;
    $distance = rad2deg($distance);

    // DISTANCE IN MILES AND KM - ADD OTHER MEASURES IF NEEDED
    $miles = (float) $distance * 69.0;
    $km    = (float) $miles * 1.61;

    // RETURN MILES
    if ($units == 'M') return round($miles,1);

    // RETURN KILOMETERS
    if ($units == 'K') return round($km,2);

    // UNITS NOT UNDERSTOOD
    return('INVALID FIFTH ARGUMENT - USE MILES OR KM');
}



// A NOMINAL DATA CLEAN-UP FUNCTION
function get_clean_text_string($s)
{
    return preg_replace('/[^A-Z 0-9_,\.\-#]/i', NULL, $s);
}



function elapsed($now, $then, $wdhms='WDHMS', $return_array=FALSE)
{
    // TIME CONSTANT VALUES (MONTHS AND YEARS ARE OMITTED - NOT FIXED VALUES)
    $seconds_per["W"] = 60*60*24*7;
    $seconds_per["D"] = 60*60*24;
    $seconds_per["H"] = 60*60;
    $seconds_per["M"] = 60;
    $seconds_per["S"] = 1;

    // TIME DESCRIPTIVE TERMS - YOU CAN USE SOME OR ALL OF THESE
    $terms["W"] = 'week';
    $terms["D"] = 'day';
    $terms["H"] = 'hour';
    $terms["M"] = 'minute';
    $terms["S"] = 'second';

    // SET THE FLAGS FOR OUTPUT
    if (empty($wdhms)) $wdhms = 'WDHMS';
    $wdhms = strtoupper($wdhms);
    $wdhms = str_split($wdhms);
    $wdhms = array_combine($wdhms, $wdhms);

    // SET THE FUTURE/PAST TIMESTAMP OR FAIL ON ERROR
    if (!$other_timestamp = strtotime($then)) return FALSE;

    // SET THE CURRENT TIMESTAMP
    if (!empty($now))
    {
        $current_timestamp = strtotime($now);
    }
    else $current_timestamp = time();

    // COMPUTE THE DIFFERENCE IN SECONDS
    $lapsed_seconds    = $other_timestamp - $current_timestamp;
    if ($lapsed_seconds == 0) return 'RIGHT NOW!';

    // DETERMINE FUTURE OR PAST
    $since_until = "until";
    if ($lapsed_seconds < 0)
    {
        $since_until = "since";
        $lapsed_seconds = abs($lapsed_seconds);
    }

    // COMPUTE THE INCREMENTS
    foreach ($seconds_per as $key => $secs)
    {
        if (array_key_exists($key, $wdhms))
        {
            $lapsed_time    = floor($lapsed_seconds / $secs);
            $lapsed_seconds = $lapsed_seconds - ($lapsed_time * $secs);
            $wdhms[$key]    = (int)$lapsed_time;
        }
    }

    // RETURN AN ARRAY
    if ($return_array) return $wdhms;

    // RETURN A RESPONSE STRING
    $s = NULL;
    foreach ($terms as $key => $str)
    {
        // RETURN ONLY THE UNITS THAT WERE REQUESTED IN $wdhms
        if (!array_key_exists($key, $wdhms)) continue;
        $s
        .= ' '
        . $wdhms[$key]
        . ' '
        . $str
        ;
        if ($wdhms[$key] != 1) $s .= 's';
        $s .= ',';
    }

    // TIDY UP THE RETURN STRING AND SHOW UNTIL OR SINCE
    $s = rtrim($s, ',');
    $s .= " $since_until $then";
    $s = trim($s);
    return $s;
}

Open in new window

0
Ray PaseurCommented:
PS... I just noticed that there was no session_start() in the script I posted.  D'OH! (slaps forehead).  But you know that it needs to come at the top of the common script.
0
dimensionavAuthor Commented:
Happy new year!
0
Ray PaseurCommented:
Thanks for the points -- Happy New Year to you, too!
0
youssefomarCommented:
Thank you for the points -- HaPPy New Year
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.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.