php-general Digest 9 Jan 2005 22:58:06 -0000 Issue 3218

Topics (messages 205897 through 205920):

Re: From Poland
        205897 by: Manoj Kumar
        205899 by: tr

Re: How do I start at a specific position in an array? Is there a function?
        205898 by: tr

Re: where can i find some tutorials aout sockets ?
        205900 by: tr

Re: how to read the path of the current document's url
        205901 by: Torsten Roehr
        205906 by: Curt Zirzow

Re: Need a Calender class that can access a DB
        205902 by: Manuel Lemos

Re: How do I start at a specific position in an array? Is there
        205903 by: M. Sokolewicz
        205917 by: Thomas Goyne
        205920 by: M. Sokolewicz

Re: imagecreatefromjpeg
        205904 by: Alex Greg

Re: Problem with WHILE using MYSQL database
        205905 by: Curt Zirzow

"*** glibc detected *** double free or corruption:" error
        205907 by: Alex Greg

Re: Persistent PHP web application?
        205908 by: Xuefer Tinys

DOM or DOM XML ?
        205909 by: Chris
        205916 by: Yann Larriv�e

Global class instances mysteriously set to NULL
        205910 by: James \(IFMS\)
        205913 by: Jason Wong
        205914 by: Greg Beaver
        205915 by: James \(IFMS\)
        205918 by: James \(IFMS\)

Re: making FORM dissapear when successful login
        205911 by: Will Merrell
        205912 by: JHollis

$_ENV vars
        205919 by: Charly Tango

Administrivia:

To subscribe to the digest, e-mail:
        [EMAIL PROTECTED]

To unsubscribe from the digest, e-mail:
        [EMAIL PROTECTED]

To post to the list, e-mail:
        [email protected]


----------------------------------------------------------------------
--- Begin Message ---
What the mean to spend time  of a group for this type of off topics. 


--mksheoran


-----Original Message-----
From: Ewa Rubach Wardawy [mailto:[EMAIL PROTECTED] 
Sent: Saturday, January 08, 2005 11:59 PM
To: [email protected]
Subject: [PHP] From Poland 

Dear Greg! 

This is Jarek.Wardawy. It's not a joke I promisse! This is my real name.
Some time ago I found your name in internet I wrote an e-mail to you. No
answer. Maybe this time.

I' m from Poland, living in a city Ostrow Wielkopolski. I'm working as a
journalist, and that's the reason why I spend so much time in internet. 

I'm oopen minded person, 40 years old. I'll be happy o write you more about
me and my family. At least, we have the family name. I'm interested of your
background, probably it comes from Poland. Is interesting for you? If so,
write me back, also for [EMAIL PROTECTED]  Just put the name wardawy in
google, and you'll see, that it's not a stupid joke. 

 

Best regards

Jarek Wardawy 

>From Poland 

 

--- End Message ---
--- Begin Message ---
Ewa Rubach Wardawy  wrote / nap�sal (a):

Dear Greg!

This is Jarek.Wardawy. It's not a joke I promisse! This is my real name.
Some time ago I found your name in internet I wrote an e-mail to you. No
answer. Maybe this time.

I' m from Poland, living in a city Ostrow Wielkopolski. I'm working as a
journalist, and that's the reason why I spend so much time in internet.

I'm oopen minded person, 40 years old. I'll be happy o write you more about
me and my family. At least, we have the family name. I'm interested of your
background, probably it comes from Poland. Is interesting for you? If so,
write me back, also for [EMAIL PROTECTED] Just put the name wardawy in
google, and you'll see, that it's not a stupid joke.



Best regards

Jarek Wardawy

From Poland

Do not spam this php mailing list, we are not interested about your family.


trobi





--- End Message ---
--- Begin Message ---
Brent Clements  wrote / nap�sal (a):

I know this is a simple question because I could easily write a loop
to move to the specific position in the array, but I want to know is
there a function to move the array pointer position to a specific
position in the array?

Thanks,
Brent



next($array)
prev($array)
current($array)

trobi
--- End Message ---
--- Begin Message ---
Serban Nicolae  wrote / nap�sal (a):

where can i find some tutorials aout sockets ?



get a good book
or
search

www.google.com

trobi
--- End Message ---
--- Begin Message ---
"Tim Burgan" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> Hello,
>
> I have a page where the URL is along the lines of
> http://www.example.com/test.php
>
> I've tried using the parse_url() function without success.. I'm trying
> to just get "test.php" returned as a string.
>
> Can someone please point me in the right direction with this.
>
> Thank you for your time.
>
> Tim

http://de3.php.net/manual/en/function.basename.php

Regards, Torsten Roehr

--- End Message ---
--- Begin Message ---
* Thus wrote Tim Burgan:
> Hello,
> 
> I have a page where the URL is along the lines of 
> http://www.example.com/test.php
> 
> I've tried using the parse_url() function without success.. I'm trying 
> to just get "test.php" returned as a string.

How are you using parse_url()?  $_SERVER['REQUEST_URI'] will have
exactly what you need.



Curt
-- 
Quoth the Raven, "Nevermore."

--- End Message ---
--- Begin Message ---
Hello,

on 01/07/2005 08:41 PM Phillip S. Baker said the following:
Greetings All,

I have the need to find a calender class/script. What I am trying to do is
have a view by month calender that lists all classes for the month. People
can see the names of the classes in the month display and then click on the
link and get the detailed information about the class through this view.

We have a custom look for the class descriptions and such so I do not need
the whole standard calendar stuff that is often out there. Just the main
calendar feature that will allow me to pull records from a MySQL DB and let
me create links to the appropiate pages that I am coding.

The database with the classes is already in place. So I am just looking for
a view events by month class or script that I can use and plug into the DB I
already without having to build this thig from scratch.

Is there anyone that already has something that I can use or can you point
me to something on sourceforge or phpbuilder or some other site I am not
aware of.

If you are looking for ready to use PHP components, you need to look in the right place: PHP Classes repository.

Here you may find a generic calendar class. You just need to create a subclass to customize it to present any events in the month calendar table cells. An example of customization subclass is provided to demonstrate how to do it.

http://www.phpclasses.org/calendargenerator


Here you also find another calendar solution with separate scripts for customizing the presentation of events detailed in a MySQL table:

http://www.phpclasses.org/jcal

--

Regards,
Manuel Lemos

PHP Classes - Free ready to use OOP components written in PHP
http://www.phpclasses.org/

PHP Reviews - Reviews of PHP books and other products
http://www.phpclasses.org/reviews/

Metastorage - Data object relational mapping layer generator
http://www.meta-language.net/metastorage.html

--- End Message ---
--- Begin Message --- Tr wrote:
Brent Clements  wrote / nap�sal (a):

I know this is a simple question because I could easily write a loop
to move to the specific position in the array, but I want to know is
there a function to move the array pointer position to a specific
position in the array?

Thanks,
Brent



next($array)
prev($array)
current($array)

trobi
that's not a SPECIFIC place in the array, that's just current, next and previous. AFAIK there is no way to explicitly set the internal pointer of the array to a spcified place. I used a function which basically looped trough the array until it got to the correct depth, and then returned it by reference....but it's not very efficient :S
--- End Message ---
--- Begin Message ---
On Sun, 09 Jan 2005 15:59:43 +0100, M. Sokolewicz <[EMAIL PROTECTED]> wrote:

that's not a SPECIFIC place in the array, that's just current, next and previous. AFAIK there is no way to explicitly set the internal pointer of the array to a spcified place. I used a function which basically looped trough the array until it got to the correct depth, and then returned it by reference....but it's not very efficient :S


Why would you ever want to do that other than to waste cycles?
--- End Message ---
--- Begin Message --- Thomas Goyne wrote:
On Sun, 09 Jan 2005 15:59:43 +0100, M. Sokolewicz <[EMAIL PROTECTED]> wrote:

that's not a SPECIFIC place in the array, that's just current, next and previous. AFAIK there is no way to explicitly set the internal pointer of the array to a spcified place. I used a function which basically looped trough the array until it got to the correct depth, and then returned it by reference....but it's not very efficient :S


Why would you ever want to do that other than to waste cycles?
can't recall what it was exactly, but I believe it was a case where I didn't know the key of the array, nor the value, but knew the "place" in the array.
Can't exactly remember what it was... I am now thinking that what I'm saying in my last line can be done easily by using array_values and using a numeric key....

But... as I said, I can't recall what it was. In the end I simply rewrote whatever it was to use a more efficient way of handling things
--- End Message ---
--- Begin Message ---
On Sun, 9 Jan 2005 21:37:33 +1100, Juergen Rehberger
<[EMAIL PROTECTED]> wrote:
> i have a problem with my resizing image script.
> 
> It all works fine on my localhost server, but once i upload the whole thing 
> on my webhost, the script allows resizing of images not bigger than 600kb or 
> something aournd that size. so my question. does that problem depend on 
> settings from my webhost. i uploaded (without resizing) images with a 
> filesize of 1.2mb and it was working. but once i try to add the resizing 
> function i get following error message
> 
> Fatal error: Allowed memory size of 8388608 bytes exhausted at (null):0 
> (tried to allocate 1632 bytes) in /var/www/html/familie/cms/addimage.php on 
> line 39

It looks like your script has tried to allocate more than the default
8MB memory limit in php.ini.

Is the default on your offline server different? Try:

grep memory_limit /usr/local/lib/php.ini

(or wherever your php.ini lives) to find out.


Regards,


-- Alex

--- End Message ---
--- Begin Message ---
* Thus wrote Labunski:
> 
> $data = mysql_query("SELECT * FROM firt_table WHERE cat='sweaters' ORDER BY
> `id` ASC ") or die("can't find DB!");
> while($line = mysql_fetch_array($data)){
> echo' <tr><td width="225" height="19"'.$line['product'].'</td></tr>';
> }
> 
> for example, there are 3 records in the "first_table", so script will output
> only 3 records:
> <tr><td width="225" height="19"'.$line['product'].'</td></tr>
> <tr><td width="225" height="19"'.$line['product'].'</td></tr>
> <tr><td width="225" height="19"'.$line['product'].'</td></tr>
> 
> It's ok. But I need to output 10 records always, even if there are less than
> 10 records in the database.

Just keep a counter for your while loop then output however meany
are left:

$i = 0;
while ($line = ...) {
  $i++;
}

echo str_repeat('<tr><td>&nbsp;</td></tr>', 10 - $i);

or something to that effect.

Curt
-- 
Quoth the Raven, "Nevermore."

--- End Message ---
--- Begin Message ---
(apologies if this reaches the list twice - the first time I sent it,
it didn't arrive within 12 hours)

Hi,

Recently I migrated the front-end of our bulletin board (running
phpBB, patched against the recently highlight vulnerability) to a pair
of servers running Fedora Core 3. I compiled Apache 1.3.33 and PHP
4.3.10 from source. The MySQL database is running on a separate machine.

This morning, the servers slowed down to the point that they were
almost completely unresponsive. After a while I managed to SSH into
the machines and saw that the httpd processes had grown to 35MB each
and were using up all the swap and RAM on the machines (they have 1GB
RAM, 1GB swap). I then set MaxClients to 30 and restarted Apache, but
the slowdown happened again:

top - 18:18:51 up 32 days,  4:51,  1 user,  load average: 15.22, 41.62, 39.75
Tasks:  90 total,   1 running,  89 sleeping,   0 stopped,   0 zombie
Cpu(s):  0.2% us,  0.0% sy,  0.0% ni, 99.7% id,  0.2% wa,  0.0% hi,  0.0% si
Mem:   1033484k total,   898000k used,   135484k free,     1268k buffers
Swap:  1052248k total,   896880k used,   155368k free,    10896k cached

PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND
19305 nobody    16   0 41892  35m 5732 S  0.0  3.5   0:38.49 /www/bin/httpd
19219 nobody    18   0 41940  29m 5732 S  0.0  3.0   0:20.87 /www/bin/httpd
19290 nobody    18   0 41940  29m 5732 S  0.0  3.0   0:42.64 /www/bin/httpd
19217 nobody    18   0 48780  29m 5736 S  0.0  2.9   0:51.25 /www/bin/httpd
19252 nobody    16   0 41916  29m 5732 S  0.0  2.9   0:45.81 /www/bin/httpd
19298 nobody    18   0 41940  29m 5732 S  0.0  2.9   0:16.61 /www/bin/httpd
19296 nobody    18   0 44052  25m 5732 S  0.0  2.6   0:42.79 /www/bin/httpd
19294 nobody    18   0 41796  25m 5732 S  0.0  2.5   0:11.85 /www/bin/httpd
19215 nobody    17   0 41892  25m 5732 S  0.0  2.5   0:22.84 /www/bin/httpd
19218 nobody    17   0 41940  25m 5732 S  0.0  2.5   0:17.84 /www/bin/httpd
19221 nobody    16   0 41900  24m 5732 S  0.0  2.5   0:45.56 /www/bin/httpd
19299 nobody    17   0 41796  24m 5732 S  0.0  2.5   0:11.63 /www/bin/httpd
19302 nobody    17   0 41796  24m 5732 S  0.0  2.5   0:13.46 /www/bin/httpd
19220 nobody    16   0 42300  24m 5732 S  0.0  2.4   0:24.97 /www/bin/httpd
19292 nobody    16   0 41796  21m 5732 S  0.0  2.1   0:37.17 /www/bin/httpd
19303 nobody    16   0 43736  19m 5732 S  0.0  1.9   0:45.86 /www/bin/httpd
19300 nobody    18   0 42184  16m 5732 S  0.0  1.6   0:31.80 /www/bin/httpd
19222 nobody    18   0 42264  14m 5732 S  0.0  1.4   0:16.17 /www/bin/httpd
19291 nobody    16   0 41904  13m 5732 S  0.0  1.4   0:12.57 /www/bin/httpd
19293 nobody    16   0 41796  12m 5732 S  0.0  1.3   0:33.04 /www/bin/httpd
19295 nobody    18   0 44040  11m 5732 S  0.0  1.1   0:35.78 /www/bin/httpd
19224 nobody    17   0 42292 8600 5732 S  0.0  0.8   0:15.22 /www/bin/httpd
19304 nobody    16   0 43804 7908 5732 S  0.0  0.8   0:37.06 /www/bin/httpd
19301 nobody    16   0 43736 7316 5732 S  0.0  0.7   0:40.19 /www/bin/httpd
19537 nobody    18   0 21112 7020 5732 S  0.0  0.7   0:05.79 /www/bin/httpd
19250 nobody    16   0 42272 5712 5732 S  0.0  0.6   0:15.20 /www/bin/httpd
19223 nobody    16   0 41940 5248 5732 S  0.0  0.5   0:45.97 /www/bin/httpd
19216 nobody    16   0 41892 4828 5732 S  0.0  0.5   0:42.77 /www/bin/httpd
19287 nobody    18   0 41892 4312 5732 S  0.0  0.4   0:38.22 /www/bin/httpd
19288 nobody    18   0 41892 4096 5732 S  0.0  0.4   0:08.98 /www/bin/httpd

I then checked the error log and found this:

*** glibc detected *** double free or corruption: 0x097ec7e8 ***
*** glibc detected *** double free or corruption: 0x097ec7e8 ***
*** glibc detected *** double free or corruption: 0x097e6d58 ***
*** glibc detected *** double free or corruption: 0x096ec7b8 ***
*** glibc detected *** double free or corruption: 0x09723188 ***
*** glibc detected *** double free or corruption: 0x097ed3b8 ***
*** glibc detected *** double free or corruption: 0x097e8870 ***
*** glibc detected *** double free or corruption: 0x097ffe88 ***
*** glibc detected *** double free or corruption: 0x096ee320 ***
*** glibc detected *** double free or corruption: 0x08f147e8 ***
*** glibc detected *** double free or corruption: 0x08f147f8 ***
*** glibc detected *** double free or corruption: 0x08f147f8 ***

and the same on the other server:

*** glibc detected *** double free or corruption: 0x09957ac0 ***
*** glibc detected *** double free or corruption: 0x09a50710 ***
*** glibc detected *** double free or corruption: 0x09a622e0 ***
*** glibc detected *** double free or corruption: 0x09978768 ***
*** glibc detected *** double free or corruption: 0x099df900 ***
*** glibc detected *** double free or corruption: 0x0993ca08 ***
*** glibc detected *** double free or corruption: 0x0992b6d8 ***
*** glibc detected *** double free or corruption: 0x0992b6d8 ***
*** glibc detected *** double free or corruption: 0x0992b5f8 ***

This bulletin board application has been running fine for a month or
so on a pair of Fedora Core 1 servers running PHP 4.3.9 (which I've
recently upgraded to 4.3.10), and they didn't have the above problem.

Any advice would be much appreciated.


Regards,


-- Alex

--- End Message ---
--- Begin Message ---
On Sat, 08 Jan 2005 12:03:10 -0800, Rasmus Lerdorf <[EMAIL PROTECTED]> wrote:
> 
> You greatly underestimate how slow unserialize is.
> 
> -Rasmus
> 
> 
you're right, but php-devs seems going to rewrite it.

--- End Message ---
--- Begin Message --- I'm currently compiling (at the ./configure step at the moment) 5.03 on Redhat 9 and ran into something that confused me. I got the error message included below.

[EMAIL PROTECTED] ./configure --with-apxs2=/usr/local/apache2/bin/apxs --with-gd --with-mysql=/usr/local/mysql41 --with-mysqli=/usr/local/mysql41/bin/mysql_config
. . .
Configuring extensions
checking whether to enable LIBXML support... yes
checking libxml2 install dir... no
configure: error: xml2-config not found. Please check your libxml2 installation.


That, in itself, isn't too confusing, it's looking for something that's not there. Simple. I've been trying to figure out a few things though, and could use outside help:

1) Why is it trying to enable LIBXML support?
2) Which extension is it trying to load? DOM? DOM XML? Something else?

Upon review I think I'd like to compile in DOM, but the manual ( http://www.php.net/dom ) doesn't mention anything about how to compile it in.

Thanks,
Chris

--- End Message ---
--- Begin Message ---
Hello

If you don't wish to have XML support please use.

--disable-simplexml --disable-libxml  --disable-xml

By Default, libxml is needed to compile PHP5.
It tries to load DOM. DOMXML is history :)

Hop this helps.

Yann


On January 9, 2005 13:35, Chris wrote:
> I'm currently compiling (at the ./configure step at the moment) 5.03 on
> Redhat 9 and ran into something that confused me. I got the error
> message included below.
>
> [EMAIL PROTECTED] ./configure --with-apxs2=/usr/local/apache2/bin/apxs
> --with-gd --with-mysql=/usr/local/mysql41
> --with-mysqli=/usr/local/mysql41/bin/mysql_config
> . . .
> Configuring extensions
> checking whether to enable LIBXML support... yes
> checking libxml2 install dir... no
> configure: error: xml2-config not found. Please check your libxml2
> installation.
>
>
> That, in itself, isn't too confusing, it's looking for something that's
> not there. Simple. I've been trying to figure out a few things though,
> and could use outside help:
>
> 1) Why is it trying to enable LIBXML support?
> 2) Which extension is it trying to load? DOM? DOM XML? Something else?
>
> Upon review I think I'd like to compile in DOM, but the manual (
> http://www.php.net/dom ) doesn't mention anything about how to compile
> it in.
>
> Thanks,
> Chris

Attachment: pgpY2X2rEsaU1.pgp
Description: signature


--- End Message ---
--- Begin Message --- I'm struggling to narrow this down, and am chasing my tail to figure this out. I apologise for the imprecise nature.

PHP: 4.3.2 (latest RHEL 3 version; php-4.3.2-19.ent.src.rpm)
OS: Linux kernel 2.4.21-15.0.3.EL
Distro: RHEL 3, all updates

I have an app that defines two global class instances, one for the database connection, the other for handling user authentication. The first is instantiated in uDatabase.php the other in uAuthenticate.php.

In building a page, there are several files that call require_once with one or the other file, e.g.

require_once 'uAuthenticate.php';

Which creates an a global instance of a class defined in another file, performs some checks, &c.

I'm using require_once with the understanding that once this file has been included, that any subsequent require_once call to the same file will be ignored.

My problem is that it appreas that in some cases require_once destroys the instance, i.e. var_dump($Auth); or var_dump($Database) displays NULL.

I'm currently trying to determine rhyme or reason for the problem, but haven't found any pattern. It comes and goes depending on which file first calls require_once and the order, but makes no sense.

ANY ideas apreciated. :-)

Thanks,

James
--- End Message ---
--- Begin Message ---
On Monday 10 January 2005 03:34, James (IFMS) wrote:

> I'm currently trying to determine rhyme or reason for the problem, but
> haven't found any pattern. 

OK, but ...

> It comes and goes depending on which file 
> first calls require_once and the order, 

... doesn't this contradict the above?

Is there or is there not a pattern? Can you make it fail/work consistently by 
changing the order of the require_once()?

> but makes no sense. 

As long as you've got something that is consistent and reproducible then 
eventually some sense can be made out of it. But if you're saying that 
running the same code without changes repeatedly will give random results 
then *that* doesn't make sense.

-- 
Jason Wong -> Gremlins Associates -> www.gremlins.biz
Open Source Software Systems Integrators
* Web Design & Hosting * Internet & Intranet Applications Development *
------------------------------------------
Search the list archives before you post
http://marc.theaimsgroup.com/?l=php-general
------------------------------------------
New Year Resolution: Ignore top posted posts

--- End Message ---
--- Begin Message --- James wrote:
I'm struggling to narrow this down, and am chasing my tail to figure this out. I apologise for the imprecise nature.

PHP: 4.3.2 (latest RHEL 3 version; php-4.3.2-19.ent.src.rpm)
OS: Linux kernel 2.4.21-15.0.3.EL
Distro: RHEL 3, all updates

I have an app that defines two global class instances, one for the database connection, the other for handling user authentication. The first is instantiated in uDatabase.php the other in uAuthenticate.php.

In building a page, there are several files that call require_once with one or the other file, e.g.

require_once 'uAuthenticate.php';

Which creates an a global instance of a class defined in another file, performs some checks, &c.

I'm using require_once with the understanding that once this file has been included, that any subsequent require_once call to the same file will be ignored.

My problem is that it appreas that in some cases require_once destroys the instance, i.e. var_dump($Auth); or var_dump($Database) displays NULL.

I'm currently trying to determine rhyme or reason for the problem, but haven't found any pattern. It comes and goes depending on which file first calls require_once and the order, but makes no sense.

ANY ideas apreciated. :-)

Since you are using relative includes (require_once 'uAuthenticate.php';)

You must make sure that there is only *1* uAuthenticate.php file being included. To verify that this is the case, try this code at the end of the main file:

<?php
var_dump(get_included_files());
?>

If you switch the ordering of inclusion and get a different listing, there's your answer.

Greg
--- End Message ---
--- Begin Message ---
Since you are using relative includes (require_once 'uAuthenticate.php';)

You must make sure that there is only *1* uAuthenticate.php file being included. To verify that this is the case,

I didn't think about this.

I did follow up on your suggestion to no avail, then made *really* sure there is only *one* file by running "updatedb" and "locate uAuthenticate" as root.
--- End Message ---
--- Begin Message ---
As long as you've got something that is consistent and reproducible then eventually some sense can be made out of it. But if you're saying that running the same code without changes repeatedly will give random results then *that* doesn't make sense.

Very true. I wasn't too clear.

Switching around (and removing) require_once in different source files does cause different results *consistently*.

If I have "require_once 'uAuthenticate.php'" in one source file it causes the problem, but if remove it, or add/remove it from another source file the problem goes away.

What I mean by "no rhyme or reason" is that even though I get consistent results of problem/no problem, I see no pattern to what causes the problem and what does not. It's really screwy, at least from my understanding of how require_once should work. (It's possible of course that I simply may be misinterpreting the documentation.)

While I would like to understand the problem so that I know "don't do that you fool," I also am short on time.

I was able to find a work-around thus:

1) In the source file that's the #1 problem child I changed

require_once 'uAuthenticate.php';

to

require 'uAuthenticate.php';

2) in uAuthenticate.php I changed

$Auth = new TAuthenticate;

to

if(!isset($Auth))
  $Auth = new TAuthenticate;


This doesn't seem to nuke the global $Auth.
--- End Message ---
--- Begin Message ---
On Tuesday, January 04, 2005 9:05 PM, JHollis wrote:

> I had this code working the way i wanted it to (as far as
> correct username and password allowing successful login)
> ...but what i want to happen now is when a user
> successfully logs it it will make the login
> form disappear and just say successfully logged in or
> welcome user and a link below it so they can log off and
> make the form re-appear.
> [and then he included some sample code]


I am working on something similar, so I was intrigued at your question. I
took the liberty of looking at your code and rewritting it somewhat. Here
are my thoughts and my version.

First, as someone else noted, it is best to do the login/logout logic at the
top of the code because a lot of things in PHP require that they be done
before any output is sent. So I find it is best to resolve all of that
before I send any HTML.

Second, I don't like to rely on side effects and data outside my control to
determine my code logic. I perfer to figure out what I need and then set a
variable of my own to use to steer my logic. So in this case I want to
determine if I have a valid user and then set a variable to hold the state
of the user. Then I can use that variable to steer my logic later in the
code.

Below is my version of your code. I have added session management so a user
can stay logged on over multiple pages. This is demonstrated by the Reload
button in the Content section.

<!-- -------- Snippet ----------- -->
<?php

  // cleanup_text() protects against malicious users
  // using POST values to insert dangerous code into
  // your sql calls. All user supplied data should
  // be filtered before being trusted.
  function cleanup_text ($value)
  {
    return htmlspecialchars(strip_tags($value));
  }

  // logout closes a logged in user session. It is
  // in a function because it is called in several
  // places
  function logout()
  {
    global $user;
    global $userid;

    unset($user);
    $userid = 0;
    session_destroy();
  }


  $userid = 0;        // contains the sql record id of
                      // the logged in user. It can be
                      // used to test if a user is
                      // logged in. This assumes that
                      // no valid record has an id of 0.

  // Database connection code:
  // Asumptions:
  //    1) Using MySQL
  //    2) user login info is contained in a table
  //       called 'users'
  //    3) 'users' contains a unique identifier field
  //       called 'id' and it is numeric
  //    4) 'users' contains a unique field
  //       called 'username' and it is string type
  //       (that is, each user has only one record
  //       per'username' entry)
  //    5) 'users' contains a string field called
  //       'password'
  //    6) the 'password' field contains the password
  //       data encoded in md5 form. This is for added
  //       security.

  $db_username="root";
  $db_password="";
  $db="teamtrack";
  $server="localhost";

  $connect = mysql_connect($server,$db_username,$db_password);
  if (!$connect)
  {
    die ("Error: could not connect to database<br />\n");
  }
  $select = mysql_select_db($db,$connect);
  if (!$select)
  {
    die ("Error: could not select database $db<br />\n");
  }

  session_start();  // Start the session.

  // Check to see if we are already logged in from some previous session.
  if( isset($_SESSION['userid']) && $_SESSION['userid'] > 0 )
  {
    // Check to see if we are logging out.
    if ( isset($_POST['login']) && $_POST['login'] == "Log Out" )
    {
      logout();
    }
    else
    {
      // if we were previously logged in and we are not
      // logging out then set up the user's data
      $userid = $_SESSION['userid'];
      $sql = "select * from users where id=$userid";
      $result = mysql_query($sql);
      $user = mysql_fetch_object($result);
      if (isset($user->id))
      {
        // The specified user was found in the database
        $userid = $user->id;
        $_SESSION['userid'] = $userid;
      }
      else
      {
        // The specified user was NOT found in the database
        logout();
      }
    }
  }
  else
  {
    // We were NOT previously logged in, so check if this is a
    // login request
    if ( isset($_POST['login']) && $_POST['login'] == "Login" )
    {
      $sql = "select * from users where username='" .
        cleanup_text ($_POST['username']) . "' and password=md5('" .
        cleanup_text ($_POST['password']) . "')";
      $result = mysql_query($sql);
      $user = mysql_fetch_object($result);
      if (isset($user->id))
      {
        // The specified user was found in the database
        $userid = $user->id;
        $_SESSION['userid'] = $userid;
      }
      else
      {
        // The specified user was NOT found in the database
        logout();
      }
    }
  }

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
          "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd";>
<html>
  <head>
    <title>Test</title>
    <link href="style.css" rel="stylesheet" type="text/css" />
  </head>
  <body>
    <div id="container">
      <div id="top">
        <h1>Header</h1>
      </div>
      <div id="leftnav">
        <p>Left Nav Box</p>
        <p>
<?php
        // Check to see if we are logged in.
        // Note: The logout button is put into a form so that it will
        // be sent to the next page as a $_POST variable.
        if ($userid > 0)
        {
?>
          Welcome, <b><?php echo $user->first_name; ?></b><br />
          Your email address is: <b><?php echo $user->email_address;
?></b><br />
          <form action="<?php $_SERVER['PHP_SELF'] ?>" method="post">
            <input type="submit" name="login" value="Log Out">
          </form>

<?php
        }
        else
        {
          // Since we are not logged in, present the log in form.
?>
          <form action="<?php $_SERVER['PHP_SELF'] ?>" method="post">
            <input type="hidden" name="id">
            <table border="1">
              <tr>
                <td>Username:</td>
                <td><input class="input" size="20" type="text"
name="username" value="<?php echo $username ?>"></td>
              </tr>
              <tr>
                <td>Password:</td>
                <td><input class="input" size="20" type="password"
name="password"></td>
              </tr>
              <tr>
                <td>&nbsp;</td>
                <td><input type="submit" name="login" value="Login"></td>
            </table>
          </form>
<?php
        }
?>
        </p>
      </div>
<?php
      if ($userid > 0)
      {
?>
      <div id="rightnav" class="box">
        <p>Right Nav Box</p>
      </div>
<?php
      }
?>
      <div id="content">
        <h2>Page Content</h2>
        <p>Blah, Blah, Blah</p>
        <a href="<?php $_SERVER['PHP_SELF'] ?>">Reload</a>
        <p>Blah, Blah, Blah</p>
      </div>
      <div id="footer">
        <p>Today is <?php  echo( date("F dS Y.")); ?></p>
      </div>
    </div>
  </body>
</html>
<!-- ------ end snippet --------- -->

-- Will

--- End Message ---
--- Begin Message ---
Will,

Thanks so much for all the time and effort you have put into making my code better. I dont have time right now to really test all of this out, but when i do, if i have any questions about your modified code, i will be sure to ask you.

Again thanks!
Jason

Will Merrell wrote:
On Tuesday, January 04, 2005 9:05 PM, JHollis wrote:


I had this code working the way i wanted it to (as far as
correct username and password allowing successful login)
...but what i want to happen now is when a user
successfully logs it it will make the login
form disappear and just say successfully logged in or
welcome user and a link below it so they can log off and
make the form re-appear.
[and then he included some sample code]



I am working on something similar, so I was intrigued at your question. I took the liberty of looking at your code and rewritting it somewhat. Here are my thoughts and my version.

First, as someone else noted, it is best to do the login/logout logic at the
top of the code because a lot of things in PHP require that they be done
before any output is sent. So I find it is best to resolve all of that
before I send any HTML.

Second, I don't like to rely on side effects and data outside my control to
determine my code logic. I perfer to figure out what I need and then set a
variable of my own to use to steer my logic. So in this case I want to
determine if I have a valid user and then set a variable to hold the state
of the user. Then I can use that variable to steer my logic later in the
code.

Below is my version of your code. I have added session management so a user
can stay logged on over multiple pages. This is demonstrated by the Reload
button in the Content section.

<!-- -------- Snippet ----------- -->
<?php

  // cleanup_text() protects against malicious users
  // using POST values to insert dangerous code into
  // your sql calls. All user supplied data should
  // be filtered before being trusted.
  function cleanup_text ($value)
  {
    return htmlspecialchars(strip_tags($value));
  }

  // logout closes a logged in user session. It is
  // in a function because it is called in several
  // places
  function logout()
  {
    global $user;
    global $userid;

    unset($user);
    $userid = 0;
    session_destroy();
  }


$userid = 0; // contains the sql record id of // the logged in user. It can be // used to test if a user is // logged in. This assumes that // no valid record has an id of 0.

  // Database connection code:
  // Asumptions:
  //    1) Using MySQL
  //    2) user login info is contained in a table
  //       called 'users'
  //    3) 'users' contains a unique identifier field
  //       called 'id' and it is numeric
  //    4) 'users' contains a unique field
  //       called 'username' and it is string type
  //       (that is, each user has only one record
  //       per'username' entry)
  //    5) 'users' contains a string field called
  //       'password'
  //    6) the 'password' field contains the password
  //       data encoded in md5 form. This is for added
  //       security.

  $db_username="root";
  $db_password="";
  $db="teamtrack";
  $server="localhost";

  $connect = mysql_connect($server,$db_username,$db_password);
  if (!$connect)
  {
    die ("Error: could not connect to database<br />\n");
  }
  $select = mysql_select_db($db,$connect);
  if (!$select)
  {
    die ("Error: could not select database $db<br />\n");
  }

  session_start();  // Start the session.

  // Check to see if we are already logged in from some previous session.
  if( isset($_SESSION['userid']) && $_SESSION['userid'] > 0 )
  {
    // Check to see if we are logging out.
    if ( isset($_POST['login']) && $_POST['login'] == "Log Out" )
    {
      logout();
    }
    else
    {
      // if we were previously logged in and we are not
      // logging out then set up the user's data
      $userid = $_SESSION['userid'];
      $sql = "select * from users where id=$userid";
      $result = mysql_query($sql);
      $user = mysql_fetch_object($result);
      if (isset($user->id))
      {
        // The specified user was found in the database
        $userid = $user->id;
        $_SESSION['userid'] = $userid;
      }
      else
      {
        // The specified user was NOT found in the database
        logout();
      }
    }
  }
  else
  {
    // We were NOT previously logged in, so check if this is a
    // login request
    if ( isset($_POST['login']) && $_POST['login'] == "Login" )
    {
      $sql = "select * from users where username='" .
        cleanup_text ($_POST['username']) . "' and password=md5('" .
        cleanup_text ($_POST['password']) . "')";
      $result = mysql_query($sql);
      $user = mysql_fetch_object($result);
      if (isset($user->id))
      {
        // The specified user was found in the database
        $userid = $user->id;
        $_SESSION['userid'] = $userid;
      }
      else
      {
        // The specified user was NOT found in the database
        logout();
      }
    }
  }

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
          "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd";>
<html>
  <head>
    <title>Test</title>
    <link href="style.css" rel="stylesheet" type="text/css" />
  </head>
  <body>
    <div id="container">
      <div id="top">
        <h1>Header</h1>
      </div>
      <div id="leftnav">
        <p>Left Nav Box</p>
        <p>
<?php
        // Check to see if we are logged in.
        // Note: The logout button is put into a form so that it will
        // be sent to the next page as a $_POST variable.
        if ($userid > 0)
        {
?>
          Welcome, <b><?php echo $user->first_name; ?></b><br />
          Your email address is: <b><?php echo $user->email_address;
?></b><br />
          <form action="<?php $_SERVER['PHP_SELF'] ?>" method="post">
            <input type="submit" name="login" value="Log Out">
          </form>

<?php
        }
        else
        {
          // Since we are not logged in, present the log in form.
?>
          <form action="<?php $_SERVER['PHP_SELF'] ?>" method="post">
            <input type="hidden" name="id">
            <table border="1">
              <tr>
                <td>Username:</td>
                <td><input class="input" size="20" type="text"
name="username" value="<?php echo $username ?>"></td>
              </tr>
              <tr>
                <td>Password:</td>
                <td><input class="input" size="20" type="password"
name="password"></td>
              </tr>
              <tr>
                <td>&nbsp;</td>
                <td><input type="submit" name="login" value="Login"></td>
            </table>
          </form>
<?php
        }
?>
        </p>
      </div>
<?php
      if ($userid > 0)
      {
?>
      <div id="rightnav" class="box">
        <p>Right Nav Box</p>
      </div>
<?php
      }
?>
      <div id="content">
        <h2>Page Content</h2>
        <p>Blah, Blah, Blah</p>
        <a href="<?php $_SERVER['PHP_SELF'] ?>">Reload</a>
        <p>Blah, Blah, Blah</p>
      </div>
      <div id="footer">
        <p>Today is <?php  echo( date("F dS Y.")); ?></p>
      </div>
    </div>
  </body>
</html>
<!-- ------ end snippet --------- -->

-- Will

--- End Message ---
--- Begin Message ---
I have an Ultra5 (sparc64) running kernel 2.4.27 and Apache 2.0.52 with
mod_php 4.3.9.
The problem is that when i try to list all environment vars (mostly i need
to see Operating System's vars), PHP can see only $_ENV["PATH"], and can't
see any other $_ENV[] var.
phpinfo() lists only "PATH" environment variable under _ENV
Is this a new PHP's security restriction?

Thanks.

--- End Message ---

Reply via email to