[PHP] Re: More include issues

2007-06-06 Thread Jared Farrish


I try not to bother the list and figure things out by myself as much as I
can, but it's hard when I was volunteered to become the guinea pig to
convert some of our apps from ColdFusion to PHP...especially when nobody I
work with has ever touched PHP before.  I have nobody to turn to except
google/forums/this list.



I feel ya brotha! I think Stut might be having a bad day...

Coldfusion, MSSQL, Informix, PHP, oh my!

So once again, thank you, and thanks to everyone else that is helping this

novice become more familiar with PHP.



Don't let the b*st*rds get you down, man.

A note about include paths: Unless you want to drive yourself totally batty,
always try to use absolute document paths when include/require'ing. I use a
simple constant that I stick at the top of every path I put together:

code
// The @ kills an error that would be produced
// if already defined
// Leave 'www/' empty if root path
// to current file is not a subdirectory
@define('INCLUDE_PATH_SUBDIRECTORY','www/');
@define('INCLUDE_PATH',
   $_SERVER['DOCUMENT_ROOT'] .
   (strrpos($_SERVER['DOCUMENT_ROOT'],'/') !==
   (strlen($_SERVER['DOCUMENT_ROOT'])-1) ? '/' : '') .
   INCLUDE_PATH_SUBDIRECTORY)
);
// Usage
// I recommend always using
// include_once and require_once
// unless you know for sure you
// need multiple includes for that
// file
include_once INCLUDE_PATH . 'Connections/conn.php';
/code

This might output for INCLUDE_PATH:

/inetpub/www/virtual/www_example_com/

for example, which then becomes

/inetpub/www/virtual/www_example_com/Connections/conn.php

PHP will always know how to find that.

This works for me, but your usage or results may vary, and may not work on
all servers (IIS, for instance) or some Apache installations (I guess). Try
creating a test page and play around with it using echo and so on to see
what it outputs. You can contact me directly if the forum mungs it up on the
line-wrap.

Also try:

code
echo 'pre';
print_r($_SERVER);
echo '/pre';
/code

To see what server variables are available. Just remember, webroot (public)
and docroot (private) are different things.

--
Jared Farrish
Intermediate Web Developer
Denton, Tx

Abraham Maslow: If the only tool you have is a hammer, you tend to see
every problem as a nail. $$


Re: [PHP] Re: More include issues

2007-06-06 Thread Jared Farrish

On 6/6/07, Robert Cummings [EMAIL PROTECTED] wrote:


On Wed, 2007-06-06 at 17:21 -0500, Jared Farrish wrote:
 I feel ya brotha! I think Stut might be having a bad day...

Bad day?? Did you read the same posts I read?

Cheers,
Rob.



Sure I did. Let's not take this too seriously, ok?

--
Jared Farrish
Intermediate Web Developer
Denton, Tx

Abraham Maslow: If the only tool you have is a hammer, you tend to see
every problem as a nail. $$


Re: [PHP] Re: More include issues

2007-06-06 Thread Jared Farrish

On 6/6/07, Robert Cummings [EMAIL PROTECTED] wrote:


On Wed, 2007-06-06 at 20:26 -0500, Jared Farrish wrote:
 On 6/6/07, Robert Cummings [EMAIL PROTECTED] wrote:
 
  On Wed, 2007-06-06 at 17:21 -0500, Jared Farrish wrote:
   I feel ya brotha! I think Stut might be having a bad day...
 
  Bad day?? Did you read the same posts I read?

 Sure I did. Let's not take this too seriously, ok?

You forgot a winkie ;) :)

Cheers,
Rob.



Ach! YOU ARE S RIGHT!

Now I need a twinkie... ;)


--
Jared Farrish
Intermediate Web Developer
Denton, Tx

Abraham Maslow: If the only tool you have is a hammer, you tend to see
every problem as a nail. $$


[PHP] Re: local v remote

2007-05-31 Thread Jared Farrish

On my localhost this works fine

$result= mysql_query(SELECT date_format(date, '%d/%m/%Y') as date, title,



id, display FROM NEWS);
while ($row = mysql_fetch_assoc($result)) {

but on my remote i get a mysql_fetch_assoc(): supplied argument is not a
valid MySQL result resource

Can someone expalin the problem? PHP version problem?


Check your connection resource, as I think it's referring to the optional
second variable for mysql_query($sql, $resource).

How are you connecting? I assume if you're on your local machine, you're
probably connecting to a locally-hosted mysql installation.

Are you using the same connection string when you upload? Are you even
providing one (even a background, default connection)?

You should also always try to pass the resource to the mysql_query function
(in most but not all cases). By not passing it, you're telling PHP to use
any valid open connection it currently has associated with the script that
is running:

// Let's first get a connection to the database
$link_identifier = mysql_connect('localhost', 'mysql_user',
'mysql_password');

// Next, look at the second, *optional* $link_identifier
// This tells PHP which connection to use to perform the query
// And also tells it what connection to use to get the result
resource mysql_query ( string $query [, resource $link_identifier] )

If you don't provide the $link_identifier as a valid connection resource,
and there's none in the background already connected, you get an invalid
resource response like you received.

To test, you can

code
$result= mysql_query(SELECT date_format(date, '%d/%m/%Y') as date, title,
id, display FROM NEWS);
echo 'pTest: before query/p'
while ($row = mysql_fetch_assoc($result)) {
   // Do stuff
}
/code

Where you get the error output will clue you in to which function is causing
the error (_query() or _fetch())?

To check if a resource has connected, you can check the resource by type:

if (is_resource($link_identifier) === true) {
   // Do database stuff that needs a connection
}

IMPORTANT: Do not use mysql_pconnect() without first reading about it:

- http://us2.php.net/manual/en/features.persistent-connections.php

- http://us2.php.net/manual/en/function.mysql-connect.php
- http://us2.php.net/manual/en/function.mysql-query.php
- http://us2.php.net/manual/en/function.is-resource.php

--
Jared Farrish
Intermediate Web Developer
Denton, Tx

Abraham Maslow: If the only tool you have is a hammer, you tend to see
every problem as a nail. $$


[PHP] Re: Re: Re: Re: preg_match() returns false but no documentation why

2007-05-31 Thread Jared Farrish

Well, sure.  It often appears as .* meaning none or any number of
any characters.  Use it when you honestly don't care what it matches.


This is what I thought it meant. Your example more than clears it up.


Say you want to find out if the word frog occus in a text followed
by the word dog.  You could match on:

 /\bfrog\b(.*\b)?dog\b/i

/   pattern delimiter
\b  word boundary
frog1st word
\b  word boundary

(   begin subpattern
.*  zero or any characters
\b  word boundary
)   end subpattern
?   zero or one instance of the preceding subpattern

dog 2nd word
\b  word boundary
/   pattern delimiter
i   case-insensitive

This guarantees that both words are bounded by word boundaries and
allows any number of any characters to occur between them.  (There's
sort of an implicit .* before and after the pattern.  Because I
haven't used ^ and $ to define the beginning and end of the text,
regex looks for my pattern anywhere in the text.)


Very helpful! I still have questions, but a PHP mailing list probably isn't
the best place.


And why is it called full stop?

That's what the 'period' is called in British English.
http://google.ca/search?q=define%3Afull+stop

In English syntax period and full stop are synonymous, and the
RegEx manual is throwing dot into the same bag.


That's very confusing to call it 'Full Stop' when it doesn't seem to
actually correlate to the regex meaning it identifies, don't you think?
Maybe to a Brit or someone who understands Commonwealth English would know
(I was aware of what it meant in CE, I just woudn't have imagined to apply
it here, since it looks to be descriptive).

Kind've like an elephant trainer calling her elephant's trunk a boot.

--
Jared Farrish
Intermediate Web Developer
Denton, Tx

Abraham Maslow: If the only tool you have is a hammer, you tend to see
every problem as a nail. $$


[PHP] RE: Return or not to return, that is the question

2007-05-30 Thread Jared Farrish


Even the most simple function can have more than one failure point
within it. If you aren't handling the errors yourself within the
function, you're returning false all over the place and then having to
do the same checking from whatever called it - duplicated however many
times you call that function from your code.



I don't know if arbitrarily inserting a return true|false onto the end of a
function is going to make it future-proof; what if that changes from a
true|false to a 0|1, or you want/need to return null? Will you break all the
distributed procedural checks peppered all over the script? I posit, if
you're not experienced/bright enough to consider these factors when coding,
you will probably make a mistake anyways.

Code to what you need (be it functional, OO, whatever), but have high
standards... :D

I think putting return; at the end of every function is probably a healthy
practice, but is it best practice? If it's poorly written and/or poorly
factored code, it doesn't make any difference if they have returns on
everything, it's still junky code.

But I don't believe return true/false is a good practice, especially for
those who WOULD NOT normally use it due to inexperience. Putting an
artificial return value that is arbitrary isn't really all that useful, and
might in the future cause headaches (see above).

Do you put returns on __construct() and __destruct()? They are functions,
too.

And there are times when a true/false response is meaningless. For instance,
if you have a public value settor but you don't want the value to be seen
publicly, do you want to return it? Well, no. Would a boolean be useful?
Maybe, if you can regex against a pattern or something, or check for a null
or empty value.

Should those checks be contained in the codeblock or class BEFORE returning?
I think so. In OOP (less in functional/procedural), I would make a
checkState() or isValueSet() or isUsable() method that returns boolean if
necessary (for example, a dependant object check), or push the logic into a
class creation and check type on function call. I think this also makes the
code easier to understand and puts logic in it's place by type (functions,
methods, members, checks). You can also pool checks together to validate an
object member, meaning code reuse is in effect. Exceptions come in handy.

YMMV

But, y'know, I'm sure there are cases where this could be proven wrong, but
personally, I see them as edge-cases mostly, that must be known when the
code is written. Again, by paying close attention and refactoring (and
hopefully unit testing), this is a moot question anyways. PHP's soft-typing
complicates this further (0 == false == null == '' == ??). This makes a
whole lot more sense in C++ or something other strong-typed language.

Thus, code to what you need, but have high standards (by knowing what you
need)!

--
Jared Farrish
Intermediate Web Developer
Denton, Tx

Abraham Maslow: If the only tool you have is a hammer, you tend to see
every problem as a nail. $$


[PHP] Re: scheduling a script to check a directory for files

2007-05-30 Thread Jared Farrish

On linux


Our webmaster actually sets up a cron to call a Lynx browser that navigates
to the page. How he did this, I'm not sure (me windows, linux NO!), but at
the time, cron didn't cut it (for some reason), where Lynx worked perfectly.
Probably had something to do with not using CLI to handle the call, though.

http://en.wikipedia.org/wiki/Lynx_(web_browser)

--
Jared Farrish
Intermediate Web Developer
Denton, Tx

Abraham Maslow: If the only tool you have is a hammer, you tend to see
every problem as a nail. $$


[PHP] Re: RE: Return or not to return, that is the question

2007-05-30 Thread Jared Farrish

Hi Jared,


Hi Rich!


If you do put a return; at the end of all of your functions, I'm
curious as to why? If a function doesn't actually return a value
(which is highly possible) then it isn't /required/, but that doesn't
stop me from doing it. I *do* put 'return;' at the end of all
functions (my question to the list was - does anyone else?)


I went through a phase where I *did* make a point to put returns on all
functions and class methods. This helped for a little while, as it caused me
to slow down a little and think about my code (why is why I think it could
be a healthy practice, especially for someone who is less experienced).

Now, I don't worry at all about it all (meaningless returns, that is). The
way I do things supercedes in a lot of cases worrying about returning
values, and since I have many more experiences, I don't worry about it. When
putting together some code, having meaningless return;s inserted at the
end of every code block seems more wasteful than helpful in most cases, so I
don't by practice append returns when unnecessary, although at times I have
done it.

It really doesn't matter in PHP (AFAIK), it all has to do with coding
patterns and practice, and what and how that is impacted by appending
returns. Is it helpful to always stop and think about a return value? Sure!
If you've been coding for five years and you are now equipped with advanced
methods and factoring iterations that render it moot? Personal preference
and dogma I assume will rule the day here.


That is all my original thread was ever really asking - I was just
curious what other people thought about returning from functions that
don't actually require a return value. So far the responses have been
pretty varied, from the (somewhat blinkered) 'how can a function never
return something?', to 'yes I always return' to 'no I just let it run
out'.


Maybe someone can shed light on what happens when the parser encounters a
return;. Would there be anything useful to that (I don't think so, but I
don't know).


Based on the variety of replies it appears there is no 'standard' for
this. Just as with code structure and studly-caps it's obviously a bit
of a religious debate.


If bumpy/camel case zealots are the bedouins of programming, what are people
who insist on returns? Returnaholics?


I think perhaps it is a psychological thing actually, as if I don't
consider the function 'finished' until it hits a return;. Almost like
you're issuing an instruction to tell PHP yes, as the programmer I am
now happy for you to return to where-ever you were called from -
perhaps just a way of exerting our control :)


It can also be used to visually parse a page of code (returns at this tab
spacing means end of code block...). So it can make the code modestly
easier to read, maybe.

And no, I don't think programmers are ever control freaks. Ever. No, I said
EVER. You're wrong.


 Should those checks be contained in the codeblock or class BEFORE

returning?

 I think so.

I would agree (because it's how I do it ;), but this isn't an approach
everyone takes.


There are times when return; is meaningful, such as breaking out of loops
(and the function), switch statements, and whatnot. For all other times when
a return isn't expressly meaningful, I see it as a matter personal
preference, which is usually influenced by someone else's overarching
dogmatic philosophy being impressed on them.

Good thing there aren't folks like that in programming! Right?!?

--
Jared Farrish
Intermediate Web Developer
Denton, Tx

Abraham Maslow: If the only tool you have is a hammer, you tend to see
every problem as a nail. $$


[PHP] Re: RE: Return or not to return, that is the question

2007-05-30 Thread Jared Farrish

My rule is to write what you mean, and if you don't mean to return

anything

valid or worth anything, just don't.  If you explicitly put a return it
should be for a reason, whatever you return should be meaningful. If I

find

a 'return true' at the end of a piece of code, I will check if there is

any

condition where it returns false, because I will assume that the return

true

is significant and so should be its obvious alternative.  I would also
wonder why the caller doesn't use that return value or if it does, why is
there no 'else' part.

In a similar line, I use 'null' in databases when I mean 'I have no valid
information for this field'.  Basically, the idea is to be clear in what

you

mean.  If you put a return it should be because you mean to return
something.  If you mean you don't know, use 'null', don't default to zero

or

any other implausible value for that field.  This kind of arbitrary
conventions dilute the self-documenting value of well-written code, quite
the opposite, they would need to be documented themselves to avoid
missinterpretations.

Satyam


Great point! If you put an arbitrary value in (and yeah, people will put
return true if they don't know any better), will this make the code even
more confusing? return; of course, is different (and only meaningful if
used to break a function).

Does the parser insert a return; for you, like the parser puts a ? on the
end of a PHP script that doesn't have it (I heard it does, anyways; I, of
course, ALWAYS...).

Additionally, does anyone know if return; to close a code block out that
is exhausted (at the final }) was ever meaningful, such as in other
languages?

I think in a lot of cases using surrogates is a better, scalable solution,
but that only matters if you need a better, scalable solution. Depends on
coding style, preference, and the situational need.

--
Jared Farrish
Intermediate Web Developer
Denton, Tx

Abraham Maslow: If the only tool you have is a hammer, you tend to see
every problem as a nail. $$


[PHP] preg_match() returns false but no documentation why

2007-05-30 Thread Jared Farrish

Hi all,

Can anybody spot why this doesn't seem to be working right? The manual (
http://us2.php.net/preg_match) says it returns false on error, but
preg_last_error() returns 0, which I assume points to the PREG_NO_ERROR
error code.

code
preg_match(^ldap(s)?://[a-zA-Z0-9-]+\.[a-zA-Z.]{2,5}$,$this-server)
/code

I also tried ereg(), and have searched and gone through the comments. Why
would a regex operation return false?

That may be ugly, since I've not done a lot of regex's yet. I have checked
and $this-server does insert a valid string. What I am trying to do is
validate ldap://com.com and ldaps://com.com and all valid variations of. Is
there something wrong with the regex, or am I pumping an invalid format into
preg_match()?

Incidentally, I stole the last piece (after ldaps://) off a regex for email
addresses (from SitePoint,
http://www.sitepoint.com/article/regular-expressions-php).

Thanks!

--
Jared Farrish
Intermediate Web Developer
Denton, Tx

Abraham Maslow: If the only tool you have is a hammer, you tend to see
every problem as a nail. $$


Re: [PHP] Re: a question on session ID and security

2007-05-30 Thread Jared Farrish

On 5/30/07, Richard Lynch [EMAIL PROTECTED] wrote: If they can get the first
cookie, they can get the second just as easily.

I thought this said just as weasily at first, and I thought, Ain't that
the truth...

--
Jared Farrish
Intermediate Web Developer
Denton, Tx

Abraham Maslow: If the only tool you have is a hammer, you tend to see
every problem as a nail. $$


Re: [PHP] preg_match() returns false but no documentation why

2007-05-30 Thread Jared Farrish

On 5/30/07, Richard Lynch [EMAIL PROTECTED] wrote:

On Wed, May 30, 2007 12:33 pm, Jared Farrish wrote:

 preg_match(^ldap(s)?://[a-zA-Z0-9-]+\.[a-zA-Z.]{2,5}$,$this-server)

You are missing the start/end delimiters is your first problem...


Which ones? I've got the starter ^ and the closer $, so what else am I
missing?


would a regex operation return false?

It would return false if your string doesn't match the expression.



The manual claims it will return a 0 signaling 0 matches found. And then,
under Return Values, it's says very quickly:

*preg_match()* returns *FALSE* if an error occurred.

If it's not returning ANYTHING I'm assuming it's faulting, but the calling
the error function returns 0 (kind've ironic, really...).

--
Jared Farrish
Intermediate Web Developer
Denton, Tx

Abraham Maslow: If the only tool you have is a hammer, you tend to see
every problem as a nail. $$


Re: [PHP] preg_match() returns false but no documentation why

2007-05-30 Thread Jared Farrish

On 5/30/07, Stut [EMAIL PROTECTED] wrote:


You need delimiters around the regex, as stated in the documentation.

preg_match(/^ldap(s)?://[a-zA-Z0-9-]+\.[a-zA-Z.]{2,5}$/,$this-server)

Although you don't need to use slashes, you can use any character you
want but you must escape it in if it appears in the regex.



Oh! You know, I had looked over those a couple times already. Can't say why
I didn't see them.

It will return false on an error, such as not having matching delimiters

aroung the regex.

The error function may retuyrn 0, but which of the following constants
is defined as 0?

PREG_NO_ERROR
PREG_INTERNAL_ERROR
PREG_BACKTRACK_LIMIT_ERROR
PREG_RECURSION_LIMIT_ERROR
PREG_BAD_UTF8_ERROR



I don't know, I'm assuming it means no error... I couldn't see anywhere
where it mentioned what was what.

Now that I'm looking at it again, I see it's 5.2 or greater, and I think
we're on 5.1 or something. Although, it seems like it would have a fatal
error if I call a function that doesn't exist...


Use === to distinguish FALSE from 0, which are not the same.


I realize they're not the same. What I was saying was that false is not
the stated return value if it's not found. If it's not printing a zero,
shouldn't that mean it's returning false?

preg_match(/^ldap(s)?:\/\/([a-zA-Z0-9-])+\.[a-zA-Z.]{2,5}$/,$this-server)

Now when I add the slashes, I get zero, even though I give it a real value
that should return 1. *sigh*

--
Jared Farrish
Intermediate Web Developer
Denton, Tx

Abraham Maslow: If the only tool you have is a hammer, you tend to see
every problem as a nail. $$


[PHP] Re: find (matching) person in other table

2007-05-30 Thread Jared Farrish

I was thinking to assign points (percentage) to matching fields (last
name, first name, email, phone, city, zip, phone) and then list people
with more than 50%. e.g., if first and last name match - 75%, if only
email match - 85%, if first name, last name and email match - 100%, if
last name and phone match - 50%... etc.

does anybody have any experience with such a problem? or something

similar?

Although you should be able to do this with you SELECT (I guess, never
have), since you posted this to a PHP mailing, you get a PHP answer!

Look up Levinshtein in the php manual and start from there:

http://us2.php.net/manual/en/function.levenshtein.php

If you can do this on SELECT (using the db engine), I would suggest that, as
that way you don't have to return a giant list to poke through.

You can also use wildcards, and only select matches that have the first
three characters:

$lastname = strpos('Rogers',0,2);
$firstname = strpos('Timothy',0,2);
$select = SELECT `uid`,`LastName`,`FirstName`
   FROM `users`
   WHERE LastName='$lastname%'
   AND FirstName='$firstname%';

I haven't tested that, but I think it would work. You would need to work on
a way to LIMIT the matches effectively. If that doesn't work, hey, this is a
PHP list...

--
Jared Farrish
Intermediate Web Developer
Denton, Tx

Abraham Maslow: If the only tool you have is a hammer, you tend to see
every problem as a nail. $$


[PHP] Re: find (matching) person in other table

2007-05-30 Thread Jared Farrish

On 5/30/07, Jared Farrish [EMAIL PROTECTED] wrote:


$lastname = strpos('Rogers',0,2);
$firstname = strpos('Timothy',0,2);
$select = SELECT `uid`,`LastName`,`FirstName`
FROM `users`
WHERE LastName='$lastname%'
AND FirstName='$firstname%';



Strike the above and make it:

$lastname = substr('Rogers',0,3);
$firstname = substr('Timothy',0,3);
$select = SELECT `uid`,`LastName`,`FirstName`
  FROM `users`
  WHERE LastName='$lastname%'
  AND FirstName='$firstname%';

Foolisness!

--
Jared Farrish
Intermediate Web Developer
Denton, Tx

Abraham Maslow: If the only tool you have is a hammer, you tend to see
every problem as a nail. $$


Re: [PHP] preg_match() returns false but no documentation why

2007-05-30 Thread Jared Farrish

On 5/30/07, Richard Lynch [EMAIL PROTECTED] wrote:


If you can't find them documented, print them out:

echo PREG_NO_ERROR: ', PREG_NO_ERROR, ';



Doh!

PREG_NO_ERROR: 0
PREG_INTERNAL_ERROR: 1
PREG_BACKTRACK_LIMIT_ERROR: 2
PREG_RECURSION_LIMIT_ERROR: 3
PREG_BAD_UTF8_ERROR: 4

So apparently, PREG_NO_ERROR is synonymous for you need delimiters,
egghead.



preg_match(/^ldap(s)?:\/\/([a-zA-Z0-9-])+\.[a-zA-Z.]{2,5}$/,$this-server)

Try using | instead of / for your delimiter, so that you don't have to
dink around with escaping the / in the pattern...



You only have to escape / if  it's part if it's the pattern delimiter?

Makes the code less cluttered and more clear.


Fo' sho'.



 Now when I add the slashes, I get zero, even though I give it a real
 value
 that should return 1. *sigh*

You may want \\. for the . in dot com



Ok, I tried:

preg_match(|^ldap(s)?://([a-zA-Z0-9-])+\.[a-zA-Z.]{2,5}$|,$this-server)
preg_match(|^ldap(s)?://([a-zA-Z0-9-])+\\.[a-zA-Z.]{2,5}$|,$this-server)
preg_match(|^ldap(s)?:\/\/([a-zA-Z0-9-])+\\.[a-zA-Z.]{2,5}$|,$this-server)

using: $this-server = ldap://www.example.com;;

No luck. I'll the try tool you referred to; I have been using
regular-expressions.info for information.

Download and play with The Regex Coach


It does pretty color syntax highlighting of the target string and your
regex to show you what's going on, as well as a slow-motion instant
replay to step through it piece by piece.



Oooh, pretty colors! Stepping through sounds interesting. I'll have to check
it out.

Thanks!

--
Jared Farrish
Intermediate Web Developer
Denton, Tx

Abraham Maslow: If the only tool you have is a hammer, you tend to see
every problem as a nail. $$


Re: [PHP] Re: find (matching) person in other table

2007-05-30 Thread Jared Farrish

On 5/30/07, Afan Pasalic [EMAIL PROTECTED] wrote:


yes. in one hand it's more for mysql list. though, I was thinking more
if somebody had already something similar as a project. more as path I
have to follow.
e.g., in your example, in where  clause AND doesn't work because bob
could be robert too, right? and last name has to match 100%, right? (or
I'm wrong?)



You're right. Remember, that was an example of what you MIGHT do, not
necessarily what you SHOULD do.

You could also situationally check the returned fields and if it's greater
than, say, 25 or 50, re-run the query and change the letters matched to 4,
for instance, and then add a link to get the greater total.

You could also look at the search box suggestion code that's out there for
a way to implement this on the server side. Don't know if that code will be
optimized or not, but that's essentially what you're doing here.

how smart solution will be something like this:


$query = my_query(select id from members where last_name='$last_name');
while($result = mysql_fetch_array($query))
{
$MEMBERS[$result['id']] += 50;
}



Well, see, if the match isn't exact, it won't return anything. Unless you
know the exact name.

You also may have to deal with someone misstyping their name(s).

$query = my_query(select id from members where first_name='$first_name');

while($result = mysql_fetch_array($query))
{
$MEMBERS[$result['id']] += 10;
}

$query = my_query(select id from members where email='$email');
while($result = mysql_fetch_array($query))
{
$MEMBERS[$result['id']] += 85;
}



Why would you do that many SELECTs? (Also, if you cap the SQL commands, it's
easier to read.)

etc.


after last query I will have an array of people. and I'll list all
person with score more than 50.



This is a really roundabout way to do this. Look at the Levinshtein PHP
manual page for some suggestions on how to calculate similarities. I *think*
that should be better to do this:

for ($i = 0; $i  count($mysqlresultset); $i++) {
   $lev = levenshtein($mysqlresultset[$i][$firstname], $postedname);
   if ($lev  49) {
   $matches[] = $mysqlresultset[$i];
   }
}

or, since last name MUST match, I think it's better this way (just got

in my head):
$query = my_query(select id from members where last_name='$last_name');
while($result = mysql_fetch_array($query))
{
$query = my_query(select id from members where
first_name='$first_name');
while($result = mysql_fetch_array($query))
{
$MEMBERS[$result['id']] += 10;
}

$query = my_query(select id from members where email='$email');
while($result = mysql_fetch_array($query))
{
$MEMBERS[$result['id']] += 85;
}

etc.
}



There's a lot of unnecessary work you're making PHP and your database do.
This is quite inefficient code.

If you're trying to match the emails and whatnot, then combine all those
queries together. SELECT them all together. It looks like what you're doing
is weighting it by email address, which you can add to the SELECT I posted
(although you need to think about how you use your wildcards for email
addresses, such as maybe matching the beginning OR the end, for instance).
It's even better if the person has to activate the account with an email
link to activate, since then you'd know the email address existed (although
it doesn't mean it isn't someone in the database that isn't already in
there).

--
Jared Farrish
Intermediate Web Developer
Denton, Tx

Abraham Maslow: If the only tool you have is a hammer, you tend to see
every problem as a nail. $$


[PHP] Re: preg_match() returns false but no documentation why

2007-05-30 Thread Jared Farrish

On 5/30/07, Jim Lucas [EMAIL PROTECTED] wrote:


The op will need to use something other than forward slashes.



You mean the delimiters (a la Richard's suggestion about using '|')?

so, this is going to match:

ldap://testing123.com   TRUE
ldap://www.testing-123.com  FALSE
ldap://testing123.com.ukFALSE
ldap://testing123.or.us TRUE



Hmm. What makes them fail/not fail? The '//' in the pattern?

preg_match('|^ldap(s)?://[a-zA-Z0-9-]+\.[a-zA-Z.]{2,5}$|', $this-server )


I also recommend using single quotes instead of double quotes here.



Single Quotes: Noted. Any reason why? I guess you might be a little out of
luck putting $vars into a regex without . concatenating.


why is there a period in the second pattern?


The period comes from the original article on SitePoint (linked earlier). Is
it unnecessary? I can't say I'm real sure what this means for the '.' in
regex's:

Matches any single character except line break characters \r and \n. Most
regex flavors have an option to make the dot match line break characters
too.
- http://www.regular-expressions.info/reference.html


Also, why are you allowing for uppercase letters
when the RFC's don't allow them?


I hadn't gotten far enough to strtolower(), but that's a good point, I
hadn't actually considered it yet.

Just my thoughts


Hey, I appreciate it!

--
Jared Farrish
Intermediate Web Developer
Denton, Tx

Abraham Maslow: If the only tool you have is a hammer, you tend to see
every problem as a nail. $$


Re: [PHP] Re: find (matching) person in other table

2007-05-30 Thread Jared Farrish

On 5/30/07, Afan Pasalic [EMAIL PROTECTED] wrote:
email has to match in total. [EMAIL PROTECTED] and [EMAIL PROTECTED]

are NOT the same in my case.

thanks jared,


If you can match a person by their email, why not just SELECT by email only
(and return the persons information)?

Consider, as well, that each time you're calling a database, you're slowing
down the response of the page. So, while making a bunch of small calls might
not seem like that much, consider:

||| x |||
||| a |||
||| b |||

Versus

||| x, a, b |||

The letters represent the request/response data (what you're giving to get,
then get back), and the pipes (|) are the overhead to process, send, receive
(on DB), process (on DB), send (on DB), receive, process, return to code.

The overhead and latency used to complete one request makes it a quicker,
less heavy operation. If you did the first a couple hundred or thousand
times, I would bet your page would drag to a halt while it loads...

--
Jared Farrish
Intermediate Web Developer
Denton, Tx

Abraham Maslow: If the only tool you have is a hammer, you tend to see
every problem as a nail. $$


[PHP] Re: Re: preg_match() returns false but no documentation why

2007-05-30 Thread Jared Farrish

If the pattern delimiter character appears in the pattern it must be
escaped so that the regexp processor will correctly interpret it as a
pattern character and not as the end of the pattern.

This would produce a regexp error:

 /ldap://*/

but this is OK:

 /ldap:\/\/*/

Therefore if you choose another delimiter altogether you don't have
to escape the slashes:

 #ldap://*#

Cleaner and more clear.


Ok, that makes sense.


preg_match('|^ldap(s)?://[a-zA-Z0-9-]+\.[a-zA-Z.]{2,5}$|', $this-server

)


I also recommend using single quotes instead of double quotes here.

Single Quotes: Noted. Any reason why? I guess you might be a little out

of

luck putting $vars into a regex without . concatenating.

Both PHP and regexp use the backslash as an escape.  Inside double
quotes, PHP interprets \ as escape, while inside single quotes PHP
interprets \ as a simple backslash character.

When working with regexp in PHP you're dealing with two interpreters,
first PHP and then regexp.  To support PHP's interpretation with
double quotes, you have to escape the escapes:

Single quotes:  '/ldap:\/\/*/'
Double quotes:  /ldap:\\/\\/*/

PHP interprets \\/ as \/
RegExp interprets \/ as /


Oh. Duh! I wasn't even considering PHP parsing the string due to the double
quoted string.


So, for a pattern like this that contains slashes, it's best to use a
non-slash delimiter AND single quotes (unless, as you say, you need
to include PHP variables in the pattern):

 $pattern = '#ldap://*#';

Personally I favor heredoc syntax for such situations because I don't
have to worry about the quotes:

$regexp = _
#ldap://*$var#
_;


Yeah, I just wish there were some way heredoc could work on one line.


why is there a period in the second pattern?

The period comes from the original article on SitePoint (linked earlier).

Is

it unnecessary? I can't say I'm real sure what this means for the '.' in
regex's:

Matches any single character except line break characters \r and \n.

Most

regex flavors have an option to make the dot match line break characters
too.
- http://www.regular-expressions.info/reference.html

Inside of a bracketed character class, the dot means a literal period
character and not a wildcard.

All non-alphanumeric characters other than \, -, ^ (at the start)
and the terminating ] are non-special in character classes


So what does the definition I posted mean for non-bracketed periods? Does it
mean it will match anything but a line or return break character? How in
practice is this useful?


PHP PREG
Pattern Syntax
http://www.php.net/manual/en/reference.pcre.pattern.syntax.php
scroll down to 'Square brackets'


Also, why are you allowing for uppercase letters
when the RFC's don't allow them?

I hadn't gotten far enough to strtolower(), but that's a good point, I
hadn't actually considered it yet.

Perhaps it has to do with the source of the string: can you guarantee
that the URIs passed to this routine conform to spec?


I just prefer to use strtolower(). I have to use the server address
anyways...

Breaking News: I had a thought (surprise!). Are LDAP servers ever on
localhost? Or at least a non-dot-concatenated address
(ldap://directoryname)? The pattern we've been looking won't match that, I
think.


Another way to handle this would be to simply accept case-insensitive

strings:


 |^ldap(s)?://[a-z0-9-]+\.[a-z.]{2,5}$|i


I actually read about that a little while ago, I just didn't know where to
put the i. Thanks!


Pattern Modifiers
http://www.php.net/manual/en/reference.pcre.pattern.modifiers.php

i (PCRE_CASELESS)
If this modifier is set, letters in the pattern match both upper
and lower case letters.


How do you test regex's against any known variants? I suppose I need to
build a test function to make arbitrary strings and then test and print the
results. I just don't know if my regex is going to be that great in
practice.

This would be in addition to the program Richard alluded to in the code
checker.

Thanks!

--
Jared Farrish
Intermediate Web Developer
Denton, Tx

Abraham Maslow: If the only tool you have is a hammer, you tend to see
every problem as a nail. $$


[PHP] Re: Re: Re: preg_match() returns false but no documentation why

2007-05-30 Thread Jared Farrish

Read the manual:


All due respect, I did read it. It's just... a little dense and not
practically descriptive.

Maybe it's more practical to ask, When is it practical to use it?

It matches anything, so I assume that means you can use it to match, say, a
paragraph that you can't predict or match against? One that you're looking
for a pattern match on one or either end?

I just look at the definition and have a hard time fitting it in. I'm
looking at some examples, though, so I'm sure I'll get it.

And why is it called full stop? Ok, maybe the definition doesn't make any
kind of sense to me, ie, practical usage.

Does it mean match anything that, say, *starts* with a pattern but ends with
whatever (.)???

Thanks!

--
Jared Farrish
Intermediate Web Developer
Denton, Tx

Abraham Maslow: If the only tool you have is a hammer, you tend to see
every problem as a nail. $$


[PHP] Re: a question on session ID and security

2007-05-29 Thread Jared Farrish

On 5/29/07, Stut [EMAIL PROTECTED] wrote:


What utter crud. An SSL connection encrypts the whole HTTP conversation,
including headers and even the URL you are requesting. The response is
also encrypted. It doesn't matter whether you're doing a POST or a GET
request, it's all encrypted.



The URL string is encrypted in HTTPS? Well, I was certainly under a
different impression (same with headers). Since I can't say I know any
better beyond a shadow of a doubt, I'll take your word for it. : )

Cookies are no more secure than the session ID. The general conclusion

from many years of discussion in the web community is that the user
experience is diminished so much by not trusting a session ID that the
security improvements are not justified.



So by storing sensitive information in a SESSION, you're safer? Only if the
session doesn't get read... I don't know, I guess in the security sense, it
should be seen as a part of the conversation as you put it, so if you
can't trust SESSION, you probably shouldn't use it at all for secure
applications. I still don't see the sense in storing sensitive information
in a session, at least one that persists; if it is passed to a temp table in
a database and destroyed across calls, I can see that as a better solution,
as long as you have a strong database security configuration.

If you're really concerned then your best bet is to reduce the session

lifetime to 5-10 minutes. Another 'trick' people sometimes use is to
store the user agent in the session and expire it if a request tries to
use an existing session with a different user agent. Unfortunately you
cannot rely on the IP address remaining the same throughout a session,
so don't build that into your session validation.



Well, if you use COOKIES, you can pass a secondary hash key that can be used
to validate the actual key against a footprint for a visitor (from
$_SERVER). Salt in a date/timestamp and SHA1 or other, and I feel like
that's a pretty good way to check against a visitor. I just think it feels
flimsy to validate a user on a SESSION key only.

--
Jared Farrish
Intermediate Web Developer
Denton, Tx

Abraham Maslow: If the only tool you have is a hammer, you tend to see
every problem as a nail. $$


--
Jared Farrish
Intermediate Web Developer
Denton, Tx

Abraham Maslow: If the only tool you have is a hammer, you tend to see
every problem as a nail. $$


Re: [PHP] Re: a question on session ID and security

2007-05-29 Thread Jared Farrish

On 5/29/07, Stut [EMAIL PROTECTED] wrote:


The only part of an SSL connection that's not encrypted is the
handshaking that goes on to set it up in the first place. Everything
after that, the GET/POST line, headers and the body as well as the
entire response is encrypted.



One of these days I'm actually going to run some tests so I can see what is
actually happening.  I would sound completely ignorant speaking of packets
as if I knew them that well, so I won't!

I never said it was safer to store sensitive information in a session -

stop adding words! All I said was that the whole discussion of session
security has been done to death and the conclusion is that you put the
minimum possible on the client (the session ID) and store everything
else on the server. If security is a big enough issue that you worry
about data in the session being read then you need a dedicated server.

If on the other hand you mean credit card information when you say
sensitive data, there is no reason on earth why that should ever be
*stored* anywhere on your server(s), even a temp table.



I find the best way to advice people on SESSIONS is not to trust them, and
thus not store any kind of sensitive information within them (SSN, credit
card, even phone numbers and whatnot). Since I don't happen to use sessions
or cookies that often (for this reason), maybe my advice is a little biased.
I store user data in cookies...

One thing that makes this all completely irrevelent is that, for someone
with physical access to authenticated browser session (such as an
co-worker), no amount of security will prevent misuse of a session.

As far as the relative security of cookies against sessions, they are

basically as insecure as each other in most cases, but your cookies are
at the mercy of the users setup which is something I'm just not willing
to trust.



True. I should have a fallback to use SESSION if cookies are not available,
but if I'm doing that, why not go whole-hog?

The bottom line is that anything sent to or received from the user is

insecure, and any security that can be added beyond SSL is easily worked
around.



And SSL is rendered moot for users who gain browser access to an
authenticated session. Security, I believe, is a matter of pushing
vulnerabilities into a corner. You can't ever make any system completely
secure, as such a system would be virtually useless.


Well, if you use COOKIES, you can pass a secondary hash key that can be
 used
 to validate the actual key against a footprint for a visitor (from
 $_SERVER). Salt in a date/timestamp and SHA1 or other, and I feel like
 that's a pretty good way to check against a visitor. I just think it
feels
 flimsy to validate a user on a SESSION key only.

Indeed, you can validate a session by using certain information from the
$_SERVER array, but bear in mind that none of it is necessarily
persistant. I don't know of any examples, but I'm sure somewhere there
is a crappy browser that changes its user agent for every request.
However, of all the options I think the user agent is your best bet if
you really feel you need to worry about it.



What happens if someone is behind a proxy? Never tested that, but if someone
were to make a proxy sanitizer that purposefully skewed what it reports in
the headers, that approach could be difficult to troubleshoot.

In your comment above you seem to be suggesting passing that secondary

hash key between requests via a cookie. Why not just store that in the
session? Then it doesn't go outside your app. And as mentioned
previously you have a lot more control over the session data than you do
over cookie data.



The whole point of using a shared hash is to provide notional benefit by
providing a secondary key, that is stored on the browser, which is used to
build the authenticated token, which is then matched to the server token.
This is a type of security hash similar to the one you suggested above
(using $_SERVER variables), only stored in a cookie.

Different approach for different folks... : )

Here one final thought... if there was a reliable way to add security to

sessions don't you think that one of the multitude of web development
languages out there would have done it, including PHP?



I certainly don't think you're implying I thought I had given some new,
better way of doing sessions that nobody had given before? Curious
statement.

--
Jared Farrish
Intermediate Web Developer
Denton, Tx

Abraham Maslow: If the only tool you have is a hammer, you tend to see
every problem as a nail. $$


Fwd: [PHP] Re: a question on session ID and security

2007-05-29 Thread Jared Farrish

On 5/29/07, Stut [EMAIL PROTECTED] wrote:


Don't get me wrong, I don't want to discourage anyone from thinking
about ways to improve it, but personally I consider this issue done to
death.



Well, I think the difference is that you send one key (a session identifier)
and hash on user agent report, while I send an authentication key and a
secondary hash key stored in cookies. I'm sending only nominally more
information than you are, so I don't think there's THAT much difference
between what we're saying here. As a lot of users would store session id's
as cookies, and fall back to a query string id, like I said, I don't see
much of a difference in our approaches, except you don't seem to think mine
is acceptable since it's not a session id.

If you supply the salt (instead of relying on it being provided, vis a vis,
user agent report), and store that in a cookie on the client, and then that
client can't reproduce an accurate, unchanged version of that cookie, what
change in either the salt and/or the auth id would make this approach
unacceptable (and not break the authentication)? I see major web firms use
cookies all the time, so I'm not sure why there is a bias against cookies,
besides a user that doesn't support cookies in the first place (which is a
real concern, I admit).

I remember a poster on a wall of a tech dept my friend worked for that had a
faux-advert for a security dongle for a computer. Essentially, it was a
rubber stopper that was put on a power cable that provided a 100% secure
air gap.

Whether it's been settled or not, I'm not nearly as played out on discussing
it (especially if I'm not getting aspects correct) as I am about browser
bickering, OS wars, and all the other dispassionate discourse currently
enlightening the internet. At least with security, there's some known
benefit to discussing it!
--
Jared Farrish
Intermediate Web Developer
Denton, Tx

Abraham Maslow: If the only tool you have is a hammer, you tend to see
every problem as a nail. $$


--
Jared Farrish
Intermediate Web Developer
Denton, Tx

Abraham Maslow: If the only tool you have is a hammer, you tend to see
every problem as a nail. $$


Re: [PHP] Re: a question on session ID and security

2007-05-29 Thread Jared Farrish

That's not what I'm saying. My basic question is why send the secondary
hash key to the client when it doesn't need it? Use the authentication
key to identify the users data, then get the secondary hash key from
that data. The browser never needs to see the hash, and from a purist
security point of view it could potentially reveal more about your
security methods than you need to.


The idea is that the secondary hash key replaces the user agent sniff.


But the point here is that both pieces of information required to
authenticate that client are stored on the client. If someone can get
one of them they can get the other, so it's no more secure than just
accepting the one cookie without bothering to authenticate it in any way.


The token isn't any more secure than tokenizing a user agent and salting it
into a digest. The client still knows what their user agent string says, and
this string can also be guessed (how random can they be?), but at least you
can manipulate a secondary hash key per day/hour, week, whatever.


I have nothing against cookies at all, but I think the line between
cookies and session data is pretty clear.


I would just ask where? (No, really.) If it was clear, then a link to a
tutorial on PHP session security is helpful.


Cookies should be used to...

a) remember a user between sessions (but not authenticate them)
b) remember a session ID during a session
c) remember user preferences for anonymous users, or where there is no
such concept as users on the site


I agree 100% on everything except the logic on authentication. How would you
finish the following:

Sessions should be use to...

a) ?
b) ?
c) ?


Sessions should be used for everything else. If you're finding that
you're storing huge amounts of data in cookies, switch to using
sessions. If you find that you're storing so-called sensitive
information in cookies, switch to sessions.


I don't store anything in cookies that are meant to be useful on the
server-side, save an auth string and a corresponding generated salt. This
will probably change on my next big project, but for the moment, I'm not
much of a fan of SESSIONS that persist. This is based on limited experience
and anecdotal evidence, so opinions may very.


I'm more than happy to discuss it, but please tell me you got the point
about whatever extra security is possible is likely to have been added
by the majority of web application platforms, including PHP.


Of course. We're talking methodology (implementation of what is available),
so I'm not sure why you feel the above is necessary.


I'm all for talking about it and seeing if there is a better way, but I
also know that people far smarter than me have been talking about it for
over 20 years, and what we have is what they've come up with. Ignoring
the other possibilities like client certificates there's not really
anything more you can do without introducing the possibility or even
likelihood that the user experience will be shafted.


If it's an accepted methodology, please describe the entire methodology. If
you think it's obvious, it should be easy, and a link is beneficial.

I do think the stated best practice of SESSIONS, at this point, probably
does need to be described to be further useful as a topic of discussion.
I've been a little unclear in some things, so I get the feeling we've got
the same point of view, with one slight deviation (I think it's slight...).


Re: [PHP] Re: a question on session ID and security

2007-05-29 Thread Jared Farrish

On 5/29/07, Jared Farrish [EMAIL PROTECTED] wrote:


I do think the stated best practice of SESSIONS, at this point, probably
does need to be described to be further useful as a topic of discussion.
I've been a little unclear in some things, so I get the feeling we've got
the same point of view, with one slight deviation (I think it's slight...).



Just thought I'd post this:

Primer on PHP session security:
http://www.php-mag.net/itr/online_artikel/psecom,id,513,nodeid,114.html

--
Jared Farrish
Intermediate Web Developer
Denton, Tx

Abraham Maslow: If the only tool you have is a hammer, you tend to see
every problem as a nail. $$


Re: [PHP] Re: a question on session ID and security

2007-05-29 Thread Jared Farrish
 been around is a sore replacement
for referring directly to what they say (the best practices, that is...).


The first solution was cookies. The problem with cookies is that
they're very inefficient and insecure. Inefficient because they get
transferred with every request, and insecure because they get
transferred in the HTTP headers and get stored on the client over which
the web developer has no control.

The natural progression of this was to store the minimum required in a
cookie, and tie that cookie value to a chunk of data on the server. This
is what we now understand as a session.

Client certificates were created to allow a client to prove its identity
to a server in the same way that an SSL certificate can prove the
identity of a server. Unfortunately the management of client
certificates makes them uneconomical for most applications. I know of a
few banks that use them, but not many at all. In fact, the only place
I've used them lately was in a forex trading system where each terminal
cost over $12k which included the hardware and the software license. In
effect the client was as much in our control as the servers were.

Anyhoo, I digress. Sessions are the answer to storing data related to a
users visit to a website / web application between page requests in an
efficient and relatively secure manner. Through the use of SSL you can
add to the security my making it very very hard (but not impossible) to
read the session ID at any point during its transmission. However, you
are still left wide open at the client end, and this I think is where we
differ.


In all reality, I actually agree with you about sessions in my
heart-of-hearts (maybe a little more now after this thread), as they are the
simplest to implement, and the checks performed on authentication are as
robust as any involving cookies (which can become hopelessly bogged down in
checks, digests, and rechecks), although I posit the SAME thing can be
achieved with instances of cookies. However, simplicity should be the
operative word, and the complexity of the approach I have described is more
than a little troublesome.


You want to store 2 pieces of information in the browser which, when put
together, will allow a user to continue their visit in an authenticated
state.


When put together *with other data* unknown to the browser... This is a
small difference. The auth key is not generated exactly from the hash digest
(sha1($clienthash) !== $authkey).


I want to put 1 piece of information in the browser, and store the other
in the session. The bit stored in the browser will identify a particular
session on the server from which I will get the second bit.

It doesn't really matter whether that second bit comes from the user
agent, or is randomly generated on login. Storing the validation key in
the same place as the key is like writing your PIN code on the back of
your credit card.


Or is it like have the three numbers on the back that are supposed to
prove you have it physically in-hand? I think this is more accurately what I
am describing.


Do you now see why my way is more secure than yours?


Of course not. Mind telling me again?! :D

I appreciate that you posted the historical information on sessions and
cookies. Whether it's accurate to reality, I don't know, but it makes sense,
not lemons, so for now, it's good enough for me!

p.s. Maybe everyone wasn't around when that history occurred...

--
Jared Farrish
Intermediate Web Developer
Denton, Tx

Abraham Maslow: If the only tool you have is a hammer, you tend to see
every problem as a nail. $$


[PHP] Re: PHP5 oop question...

2007-05-28 Thread Jared Farrish

When in-scope and using static functions, use self:

code

class Static_Ex {
   private static $variable = 'This is a static variable';
   public static function tryStatic() {
   return self::$variable;
   }
}
echo Static_Ex::tryStatic();

/code

If you think about it, there is no $this in a static function. If static
functions do not need an instatiated object to access class code, you don't
refer to them the same, nor do you use $this internally inside the functions
that are static.

Using static functions and variables is quite tricky. Static methods and
variables make tasks like programming a singleton to point to a single
database connection for all database activities on a website simple and
easy. But if it has to interact with the internals of an instantiated object
within it's own class, then you need to either pass in all variables
(Static_Ex::method($this) when in scope to an instantiated object should
work), and/or make it work entirely on it's own without $this.

--
Jared Farrish
Intermediate Web Developer
Denton, Tx

Abraham Maslow: If the only tool you have is a hammer, you tend to see
every problem as a nail. $$


[PHP] Tracking exit links with php?

2007-05-28 Thread Jared Farrish

Any ideas on how to track that?


Two things:

1) This is probably going to have to some kind of javascript spy that
reports to a (php/asp/python/ruby) page for recording onUnload().
2) You might read the Google AdSense legalese to see if they allow it, or if
they provide it (maybe for a fee). What you want is access to their redirect
page log.

You also might look into Urchin and the ISP's that support it.

--
Jared Farrish
Intermediate Web Developer
Denton, Tx

Abraham Maslow: If the only tool you have is a hammer, you tend to see
every problem as a nail. $$


[PHP] Re: Upload a ppt file

2007-05-28 Thread Jared Farrish

Does any have any references or an example to show me?


Well, I think we need a description of the error or the invalid response
you're having. It could be a file-size issue (your php.ini configuration
won't allow file sizes  8mb's, for instance).

Have you googled it?

--
Jared Farrish
Intermediate Web Developer
Denton, Tx

Abraham Maslow: If the only tool you have is a hammer, you tend to see
every problem as a nail. $$


[PHP] Re: Unknown number of check boxes?

2007-05-28 Thread Jared Farrish

Stephen Neigaard wrote:

I would like to have a unknown number of generated check boxes like this:

input type=checkbox name=chk01 /
input type=checkbox name=chk02 /
input type=checkbox name=chk0X /

And the name will be generated chk01 to chk99, but how do I make the
receiving PHP script that scans for post variables that are sent, so
that I can work on this information?


Inspect this code example to see a way to handle this problem using magic
form variables in contained POST arrays:

code
h4Test of Multiple Checkboxes/h4
form method=post action=?php echo($_SERVER['PHP_SELF']); ?
?php

function getCheckboxes() {
   for ($i = 100; $i  0; $i--) {
   $tr = $i % 5 === 0 ? Array('','') : Array('tr','/tr');
   $str .= labelinput type=\checkbox\  .
   name=\form[checks][]\ value=\$i\ / Input
#$i/label\n;
   }
   return $str;
}
echo(getCheckBoxes());

?
pinput type=submit //p
/form
hr /
pre
?php

if (!empty($_POST)) {
   print_r($_POST);
}
?
/pre
h4Consuming of form post/h4
pAn example of inverting a posted checkbox array to support $checked[45]
=== true behavior, making it easier to access and test the posted
content/p
pre
?php

// This will return an array that has inverted the posted
// items that were in checkboxes and had a state of
// checked=true
function consumeFormChecks($arr) {
   $consume = Array();
   for ($i = 0; $i  count($arr); $i++) {
   $consume[$arr[$i]] = true;
   }
   return $consume;
}
if (!empty($_POST)) {
   print_r(consumeFormChecks($_POST['form']['checks']));
}else {
   echo('h4Please select some random checkboxes above' .
' and submit the form/h4');
}

?
/pre
/code
--
Jared Farrish
Intermediate Web Developer
Denton, Tx

Abraham Maslow: If the only tool you have is a hammer, you tend to see
every problem as a nail. $$


[PHP] Re: Unknown number of check boxes?

2007-05-28 Thread Jared Farrish

On 5/28/07, Jared Farrish [EMAIL PROTECTED] wrote:


$tr = $i % 5 === 0 ? Array('','') : Array('tr','/tr');



Ignore this line, it was from an earlier iteration of that function.

--
Jared Farrish
Intermediate Web Developer
Denton, Tx

Abraham Maslow: If the only tool you have is a hammer, you tend to see
every problem as a nail. $$


[PHP] Re: Web Application Design Literature

2007-05-28 Thread Jared Farrish

I'm looking for recommendations on literature which will give me ideas
on best practices for design and implementation of web applications,
with if possible, PHP as its core reference language.

Syntax has never been the challenge for me, like for most, it's always
been the most practical and intelligent way to break up an application
and focus on how to putting it all together for reusability and
maintaining the application.

Anyhow, suggestions are appreciated.


Check out www.opensourcecms.org and look for the type of app you need for
suggestions of different prebuilt php projects.

http://www.opensourcecms.com/

I like the Harry Fuecks books on sitepoint, as well as the O'Reilly books.
Professional PHP5 from Wrox is pretty good, too.

For a general framework-style, I like seagull:

http://www.seagullproject.org

If you're going to be doing object-oriented programming techniques, keep in
mind PHP is quite a bit different from other languages (such as C#) in the
way it implements some details of objects, and that PHP4 and PHP5 are quite
significantly different versions, vis-a-vis objects and classes.

Good luck!

--
Jared Farrish
Intermediate Web Developer
Denton, Tx

Abraham Maslow: If the only tool you have is a hammer, you tend to see
every problem as a nail. $$


[PHP] Re: a question on session ID and security

2007-05-28 Thread Jared Farrish

1. script for login process is located on a SSL-enabled server, so
usernames and passwords are encrypted.

https:// is an envelope encryption, so POST data, which is a part of the
packet data, not packet headers, is encrypted. As long as you POST or COOKIE
data that needs encryption, you're fine. GET is not secure.


2. upon successful login, user is relocated to a non-SSL-enabled server
which hosts the scripts that contain the authenticated-user-only features.

If this is what you're doing (header() or a meta-refresh html tag).


So, while usernames and passwords are protected by SSL, the PHPSESSID is
not. In other words, anyone who captures that HTTP GET packet can get
the session ID. Is that true?

There are a few different attack vectors with SESSION data. Needless to say,
never store or authenticate by a PHP SESSION id only; use cookies or encrypt
a page with script and include() the content per page, and force users to
login every page change.


Another question is while that session ID is valid only before an
unset() and a session_destroy(). So the attacker who has the session ID
must fake the session before the real user logout. Is that true?

Before the session is destroyed and the temp file where it is stored is
deleted from the harddrive. Do not store sensitive information or use a
SESSION id to authenticate a user.


--
Jared Farrish
Intermediate Web Developer
Denton, Tx

Abraham Maslow: If the only tool you have is a hammer, you tend to see
every problem as a nail. $$


[PHP] Re: $_GET strings seperation

2007-05-27 Thread Jared Farrish

On May 26, 5:39 pm, [EMAIL PROTECTED] (Navid Yar) wrote:

Thanks so much Jarred. It helps me learn more when there's an
explaination on how the code works. I'll play around with it, change
it a bit and give that a try. Take care...
P.S. -- I'm in Arlington, TX


I work with a guy from Arlington. Live near the new stadium?
Incidentally, ponder this:

code
function shortGetNewQueryString($arr,$merge) {
   return array_merge($arr,$merge);
}
echo('pre');

// Let's do one new cID, new GET key/value
$query = Array('cID'=42,'freudian'='slip');
$go = shortGetNewQueryString($_GET,$query);
print_r($go);

// Let's do one new cID, new GET key/value
$query = Array('cID'=9-002,'footloose'='fancy free');
$go = shortGetNewQueryString($go,$query);
print_r($go);

// Let's do one new cID, new GET key/value
$query = Array('cID'=493,'fugged'='dhaboutit');
$go = shortGetNewQueryString($go,$query);
print_r($go);

// Let's do one new cID, new GET key/value
$query = Array('cID'=A4,'longlongtimeago'='in a galaxy far, far
away');
$go = shortGetNewQueryString($go,$query);
print_r($go);

echo('/pre');
/code

By the way, when you run that code, pay special attention to the
second test. Very very tricky entry anomaly... Wuffuh!

Pay attention to how short that new code is
( shortGetNewQueryString() ). It's certainly arguable you don't even
need to wrap it in a function. Consider:

code
// This is the best version, I believe: brief and simple.
function mediumGetNewQueryString ($arr,$add) {
   foreach ($add as $key=$val) {
   $arr[$key] = $val;
   }
   return $arr;
}

echo('pre');
print_r( mediumGetNewQueryString($_GET,$query) );
echo('pre');
/code

And then, of course, a number of shortcuts may be used to obscurify and
mystify your code for later puzzling, head-scratchedness.

This is, of course, exactly comparable to all the other example
methods:

code
// Hard to read, ie, needless brevity
function annoyingGetNewQueryString ($arr,$add) {
   foreach ($add as $key=$val) $arr[$key] = $val;
   return $arr;
}

echo('pre');
print_r( annoyingGetNewQueryString($_GET, $query) );
echo('/pre');
/code

Caution: Using array_merge, though, will overwrite keynames, but NOT
numerical items. You can't auto-map over numerical keys with array_merge(),
apparently.

Consider:

code
$array = Array(
   [0] = 'moe'
   [1] = 'curly',
   [2] = 'larry'
);

// Is equivalent to ~
$array = Array();
$array[] 'moe';
$array[] 'curly';
$array[] 'larry';

// Is equivalent to ~
$array = Array();
array_push($array, 'moe');
array_push($array, 'curly');
array_push($array, 'larry');
/code

When you add a numerical array in php, it is added to the stack as a new
item, or push. Essentially,

$array = Array('item1')
$array[] = 'item2' eq ~ Array('item1','item2')

And then when you call on the array, it

{ get Array as Numerically-Indexed Set } eq ~ split($array,$token=',') eq ~
({ [0] = 'item' , [1] = 'item2' })

So an array on a stack can be represeted in memory as a comma-delimited
numerically-indexed list, eg, 'item','item2'

--
Jared Farrish
Intermediate Web Developer
Denton, Tx

Abraham Maslow: If the only tool you have is a hammer, you tend to see
every problem as a nail. $$


[PHP] Re: PHP debugger

2007-05-26 Thread Jared Farrish

Miles Thompson wrote:

 Suggestions will be most welcome. Also, I'm not married to this, so if
 anyone thinks there is a better debugger, please jump in.


The following assumes object-oriented programming paradigms are at least
somewhat applied. I would guess functional would be similar, but procedural
code, you might be on your own there...

I actually use two classes that I include at the bottom of all of my library
definitions (in if(!class_exists()){declare}format). One provides warning
and error message storage, the other type assertion. Between the two of
these, I have simple unit testing that I can perform as I am developing a
class, as well as pre-included simple error logging that, when I install
into the greater system, can be incorporated into the systemic error
catching routines without refactoring code, in most cases to weld-on
systemic error routines.

Thinking aloud, getting code to work correctly usually means testing it
against what you expect it to do, so doing that at a very localized level
first can be helpful. Once I started doing this, my implementation issues
somewhat went away. Results (and implementations) may very.


 PS Why are we doing this? Because we are getting tired of debugging
 with Javascript alert()  boxes. /mt


Firebug in Firefox is a very well-developed javascript debugger, featuring
console.log(), which allows you to stop using alert() for error checking.
Very nice! And I put this:

code
// Solve the firebug extension issue in IE by try/catching and creating a
blank object console.log();
try{console.log();}catch(e){var console=new
Object;console={log:function(){var k=0;}};};
/code

At the head of each js file to prevent errors in IE or other browsers
without Firebug installed.

Example: http://web3.unt.edu/riskman/JS/lem.json.js

--
Jared Farrish
Intermediate Web Developer
Denton, Tx

Abraham Maslow: If the only tool you have is a hammer, you tend to see
every problem as a nail. $$


[PHP] Re: installing error

2007-05-26 Thread Jared Farrish

Thank you very much for you answers!!! =), but Im trying to work with
PostgreSQL.


I have never installed PostgreSQL, but I have installed Apache and PHP
together. Three suggestions:

1. Forget the installers. They are worthless, since all you're doing is
adding or editing a few config file lines, plus adding a PATH variable.
2. Where and how you change those files is important, though, so you need to
google the version of php and apache you are installing and follow those
directions. It's tricky the first time, though. Be patient.
3. Start apache during your testing through a command-line. The error
reporting is much better on the command-line.

Also, really try not to put your PHP library in your System32 folder. This
is bad practice. Edit the PATH variable to point at where it should be
looking for the library.


So Im gonna review your suggestions in order to see which would be the

best

for me


WAMPP makes apache and php installation stupid easy (MySQL too, but you
don't seem to need it). Maybe, you might install WAMPP, uninstall MySQL, and
install PostgreSQL... Never done it, but with some fiddling, it should work.

--
Jared Farrish
Intermediate Web Developer
Denton, Tx

Abraham Maslow: If the only tool you have is a hammer, you tend to see
every problem as a nail. $$


[PHP] Re: $_GET strings seperation

2007-05-26 Thread Jared Farrish

On 5/26/07, Navid Yar [EMAIL PROTECTED] wrote:

Hello Everyone,

I have a problem with GET strings. I use
$_SERVER[REDIRECT_QUERY_STRING] to get the value-pairs in the URL.
The problem is that there is a cID variable that keeps appending itself
to the string continuously everytime someone clicks on a different
category link on the website. For example, instead of this:



http://www.someexample.com/admin/index.html?cID=42somevar=valuesomevar2=value2


it keeps appending another cID to it everytime it goes to a different
link, like this:



http://www.someexample.com/admin/index.html?cID=42cID=39cID=44cID=37somevar=valuesomevar2=value2


I know that this is happening because I'm appending it with the dot (.)
but is there a way to just inject a single cID and still have the rest
of the value-pairs available? Something built into PHP, maybe a different
predefined variable I don't know about? Or, do I have to make a
complex function to separate each out and then put it back together
again like humpty dumpty? Is there an easier way to do this and still
have a single cID variable in the GET string? Thanks in advance.


Is this what you're doing:

code
$cid = getCid(); // However you do set the new, included cid
$newlink = 'http://www.someexample.com/admin/index.html?'.$cid.
$_SERVER[REDIRECT_QUERY_STRING];
/code

???

If this is similar to what you're doing, this is a fairly problematic way
for you to insert a replacement property in a query string. An example of a
way to get a new query string:

code
function getNewQueryString($arr) {
   $store = Array();
   foreach ($_GET as $key=$val) {
   foreach ($arr as $k=$v) {
   if (isset($_GET[$k])) {
   $store[$key] = $v;
   }
   }
   if (!isset($store[$key])) {
   $store[$key] = $val;
   }
   }
   $i = 0;
   $str = '?';
   $count = count($store);
   foreach ($store as $key = $val) {
   $amp = $count-1 !== $i ? 'amp;' : '';
   $str .= {$key}={$val}{$amp};
   $i++;
   }
   return $str;
}
$query = Array('cID'=42);
$newlink = http://www.oompaloompa/land.php.getNewQueryString($query);
echo(p$newlink/p);
/code

What you need to do is transcribe your $_GET string to a new version,
replacing the current values that need replacing while retaining all other
values. To do this, loop through the $_GET global array, replace those that
match $_GET keynames with the new data, and then rebuild the query into a
string for inclusion in the link.

I'll leave it to you figure out how to add new values that are not replaced
($query=Array('cID'=51,'doesnotexistyet'='completelynewvalue'), for
instance). Also, the above is an example; there are certainly many other
ways to do what is done above (such as replacing the last foreach loop with
an implode() call). There are some strictly unnecessary things done above,
in other words, but I left them in to show what really is happening (and
needs to be done).

--
Jared Farrish
Intermediate Web Developer
Denton, Tx

Abraham Maslow: If the only tool you have is a hammer, you tend to see
every problem as a nail. $$


[PHP] Re: Too many records to display in one web page

2007-05-26 Thread Jared Farrish

I am developing a web site that interacts with a MySQL database. When I

run

a query and display the records in a web page, this can become a problem
because there might be too many records to be displayed in one single web
page so I am trying to divide the total number of records and display them



in multiple pages. Let's say, if the query returns 100 records then I

would

like to display the first 10 records and then put a navigation bar where I



can go to the next 10 or return to the previous 10 records

Is this done at a SQL or PHP level ? any experience on doing this ?


This is called pagination, and is well-discussed and documented on the web:

http://www.google.com/search?q=php+pagination

--
Jared Farrish
Intermediate Web Developer
Denton, Tx

Abraham Maslow: If the only tool you have is a hammer, you tend to see
every problem as a nail. $$


[PHP] Re: Re: help with multi dimensional arrays

2007-05-25 Thread Jared Farrish

Hello Everyone,

I have a problem with GET strings. I use
$_SERVER[REDIRECT_QUERY_STRING] to get the value-pairs in the URL.
The problem is that there is a cID variable that keeps amending itself
to the string continuously everytime someone clicks on a different
category link on the website. For example, instead of this:



http://www.someexample.com/admin/index.html?cID=42somevar=valuesomevar2=value2


it keeps amending another cID to it everytime it goes to a different
link, like this:



http://www.someexample.com/admin/index.html?cID=42cID=39cID=44cID=37somevar=valuesomevar2=value2


I know that this is happening because I'm amending it with the dot (.)
but is there a way to just inject a single cID and still have the rest
of the values available? Something built into PHP, maybe a different
predefined variable I don't know about? Or, do I have to make a
complex function to separate each out and then put it back together
again like humpty dumpty? Is there an easier way to do this and still
have a single cID variable in the GET string? Thanks in advance to
anyone that contributes, I really appreciate everyone's effort on this
list in the past.


Please start a new thread with a more appropriate title.

Thanks!

--
Jared Farrish
Intermediate Web Developer
Denton, Tx

Abraham Maslow: If the only tool you have is a hammer, you tend to see
every problem as a nail. $$


[PHP] Re: Protecting MySQL Injection from PHP form

2007-05-25 Thread Jared Farrish

On 5/25/07, Jason Pruim [EMAIL PROTECTED] wrote:


I apologize for posting the entire add script, but I wasn't sure what
was needed to check if I was doing it right or not. I figured in this
case it was better to give to much info rather then not enough. My
big main goal it to make this bit of software as secure/safe as
possible.



No apology necessary. As long as you're not posting 90 lines for a one-line
question, you're ok.

Regardless of what one person or another thinks, I find that it's often
useful to see how other people approach problems and get around them. For
instance, checking for character encoding is something I really have never
done. I happen to think it's a useful best practice to use unit testing
techniques to verify posted data, but some people (obviously) view this as
overkill. To each his own.

Now if only I could get a check box to show up so I can delete

multiple people at one time :) But I'm still learning about that.



I sure hope you're testing on test data, and not live data...
--
Jared Farrish
Intermediate Web Developer
Denton, Tx

Abraham Maslow: If the only tool you have is a hammer, you tend to see
every problem as a nail. $$


Re: [PHP] Re: Check if Record was Entered Today.

2007-05-25 Thread Jared Farrish

On 5/25/07, Rahul Sitaram Johari [EMAIL PROTECTED] wrote:

I guess one of the problems is that PHP has a limited number of dbase
functions and I'm not able to run SQL Queries on a dbf database. Basically

I

have to make-do with the few dbase() functions I have available in PHP.

But I do get your logic and it's pretty helpful. I did re-write the code
using Boolean (flags) as Richard had also suggested and it works fine now!

Still wish I could run SQL Queries or do more to a dbase database using

PHP.


Thanks!


If you have a database that is unchanging (archived), you can always
transribe it into another format (such as an array or object) if the data
doesn't change, or store it in an XML file, or insert it into a MySQL
database (per table, column names, then loop through each record, copying it
over as you go), and then use more robust queries offered by those
technologies.

I don't know how sophisticated you are with PHP, but the easiest (or at
least most well-documented) solution is to move it to a MySQL database if
the db is archived (and unchanging).

PHP5 supports xQuery, which is also compelling, but the xml classes are
alittle dense to figure out, I think, if you've never gone through
programmatic XML parsing and searching before.

If, though, the database is used by some other software and you're using it
as a bridge (meaning the data changes and transcription isn't a viable
alternative), you may be stuck using the method you're describing.

Although, another alternative may be to configure a command line interpreter
on the db host machine to handle a script that pushes the work to another
machine (db host), that then returns a plaintext-formatted array that can
then be searched using array functions or whatnot, and is then used as an
include() file. This way, the data is rebuilt each go around, but the
overhead is pushed to another machine, similar to a SOAP service (which is
another...). Pass a variable id to the CLI script...

--
Jared Farrish
Intermediate Web Developer
Denton, Tx

Abraham Maslow: If the only tool you have is a hammer, you tend to see
every problem as a nail. $$


[PHP] Re: Using PHP to retrieve and display file from MySQL database

2007-05-25 Thread Jared Farrish

a href=download.php?id=?=$id;??=$name;?/a br


Is there a valid $id being passed through a query ($_GET) variable, like
so?:

http://www.filecircus.com/somewhere/outthere/gimme.php?id=badphoto103

What happens when you click on that?

--
Jared Farrish
Intermediate Web Developer
Denton, Tx

Abraham Maslow: If the only tool you have is a hammer, you tend to see
every problem as a nail. $$


[PHP] Re: RE: Cannot access file on Network Drive (Windows 2003)

2007-05-24 Thread Jared Farrish

Well, I'll say you've dramatically upped the ante by having an Apache server
on a windows box attempt to mount and read a file on a MacOS machine. Yipes!

So let me get this straight:

* Apache is on Windows Server 2003.

* PHP is running on Apache.

* A folder containing scripts/data/both is on a MacOSX machine.

* A user from frontierland knocks on PHP's front host.com:80 door and says,
Please...

* PHP - Apache: Gimme gimme [resource P]

* Apache says, Ok, let me get the data from location X.

* Apache - location X: Pretty Please, gimme gimme.

* location X - Apache: [barf]

* Apache - PHP: No luck.



Can you, from the Windows 2003 machine, manually access the folder/file that
you're asking PHP (through Apache) to access? Unless the service that Apache
is running under has permissions to communicate with the share resource
(location X), this will always fail.

Steps:
1) From Win2003 box, open My Computer and attempt to physically navigate to
the remote network share you attempting to access. If at all possible, use
the exact user permission set that Apache runs under. To determine this,
right-click on the bottom, right corner of the Win2003 desktop above the
time and select Task Manager, Processes tab, click to sort on Image Name
tab, and look for Apache.exe. The user name associated with this executable
will be the permissions you will need to use.

2) If you cannot connect to the network resource, then at least you have a
permissions issue (it may be others, though). Get this working first.

3) If you can connect, open, read, write, and execute from this permission
set (user/group), then you're at least sure that the machines can talk.
Next, you will need to determine if the Apache UID permissions are acting up
(in Safe Mode, this is entirely possible, and a black art in itself...).

4) Once you've determine Win/Mac communications and Apache server
permissions aren't impeding the process, you can work on the actual script
issues which may be present.

Remember, the computers need to be able to communicate and interact, then
apache/IIS/other, then PHP. Verify the simplest potential problems first,
then work your way up into the place where the problem currently exists.
Getting Macs to be on speaking terms with Win machines, I would think, would
be a MAJOR headache if you've never done it before. One essentially speaks
Polish, while the other speaks Italian.

--
Jared Farrish
Intermediate Web Developer
Denton, Tx

Abraham Maslow: If the only tool you have is a hammer, you tend to see
every problem as a nail. $$


[PHP] Re: RE: Cannot access file on Network Drive (Windows 2003)

2007-05-24 Thread Jared Farrish

On 5/24/07, Rahul Sitaram Johari [EMAIL PROTECTED] wrote:


I think you got a little confused with a previous post of mine. Mac OS X
is
Not in this scenario at all!!! So completely Eradicate it from this
current
Scenario.

This is a complete PHP/Apache on Windows 2003 Scenario. That's it!

So what it is supposed to be is:

* PHP5 / Apache2.2 on Windows Server 2003
* Folder on another Windows Machine on the Network contains some files
(mapped as network drive X:\)
* PHP trying to read file on X:\ from Apache on Windows 2003.



Ok, I was under the impression this was one Win2003 machine in a Mac
network.

There's really nothing else to it.


Heh.


Can you, from the Windows 2003 machine, manually access the folder/file
that
 you're asking PHP (through Apache) to access? Unless the service that
Apache
 is running under has permissions to communicate with the share resource
 (location X), this will always fail.

Yes! Without any problems! I can easily navigate to the X: drive on that
Windows Machine, and do anything I want with files there. I have all
permissions.



Are you running Apache under a different (non-privileged) account on the
Win2003 machine? If Apache is running as a service with a different username
(with no extended access to network resources), you will need to get Apache
to run as a service under a user that can access the network resource. And I
still think you should use non-mapped addresses instead of mapped addresses,
since a mapping is just a localized version of a resource name alias.

If, after determing that Apache is running with the right permissions for
the owned processes to connect to and use a network shared resource, then
it's probably an Apache UID conflict (is PHP in safe mode?).
--
Jared Farrish
Intermediate Web Developer
Denton, Tx

Abraham Maslow: If the only tool you have is a hammer, you tend to see
every problem as a nail. $$


Re: [PHP] Re: RE: Cannot access file on Network Drive (Windows 2003)

2007-05-24 Thread Jared Farrish

On 5/24/07, Rahul Sitaram Johari [EMAIL PROTECTED] wrote:



You may have something here.
Problem is, I don't know how to mess with how  under what user Apache is
running – and no one else here does either so basically I have to figure
this one out! I would like to, as you suggested, try and get Apache to run
as a service under a user that can access the network resource.



Well, I have already described how to do this two posting ago (and the
advice from another user was to read the Apache documentation...):

1) Go to Win2003 desktop
2) Right-click on bottom, right part of desktop (right on top of the clock).
3) Select 'Task Manager', click Processes Tab, sort Image Name by clicking
tab.
4) Find 'apache.exe' or some variation of.
5) Look at the username associated with the process.

If this is 'System' or something type of special user (or a basic user
without network privileges extended to it), then you will need to modify
this by:

1) Locate the My Computer link on your desktop.
2) Right-click on top of the link, select Manage, choose 'Services and
Applications', and select Services.
3) Find the apache service, double click to open properties, click on the
'Log On' tab, and see what user it is setup to use.

If this is a system account, I would think you would need to change this to
a network account, preferably one for which the password will not expire...
If apache is not running as a service, then you will need to determine how
it is starting up, and modify that to run under a different process with
modified user permissions.

I definitely agree about using non-mapped addresses and using the actual

Server Name addresses.



For ease on the eyes, mappings are great, but they are not reliable for
programming purposes, IMHO.

For the advanced PHP gurus on the list, is it accurate to characterize PHP
as relying on Apache for file manipulation? Is it accurately described as:

Process Request-PHP-Apache-[File System Poof!]-Apache-PHP-Process

??? Just making sure I have this characterization correct.

--
Jared Farrish
Intermediate Web Developer
Denton, Tx

Abraham Maslow: If the only tool you have is a hammer, you tend to see
every problem as a nail. $$


[PHP] Re: Protecting MySQL Injection from PHP form

2007-05-24 Thread Jared Farrish

I'm not sure exactly what kind of sanitization you think you're doing, but
if all you do is check to see if it's empty (empty() implements isset(),
empty() checks to see if it's set, then if it evaluates to an empty
variable), that's not much sanitization.

What you need to do is check for SQL injections, which means you need to
sanitize GPC (GET, POST, COOKIES) to prevent the following (only a
demonstration):

SELECT `colname` FROM `tablename` WHERE id='$variable' LIMIT 0,10

What happens if $variable is equal to:

$variable = $_POST['somedata'];

And $_POST['somedata'] ~  'INSERT INTO users
VALUES('name','password','AdminGroup')' ;

This is an example of a possible SQL injection (which means unknown SQL code
is running through your script access). The way to prevent this is to escape
single quotes before insert/select, and also turn all html entities into
escaped values (so that someone cannot put a script/script block into
the signature for their user, for example).

The good thing is, there are numerous help sites online that describe how to
do this. Generally, you're better off wrapping your SQL commands into a
class or at least a series of functions, so that you can implement your
sanitization once and use it for all database interactions.

Google: http://www.google.com/search?q=php+sanitize+sql+statement
PHP.net: http://www.php.net/manual/en/security.database.sql-injection.php

--
Jared Farrish
Intermediate Web Developer
Denton, Tx

Abraham Maslow: If the only tool you have is a hammer, you tend to see
every problem as a nail. $$


[PHP] Re: Protecting MySQL Injection from PHP form

2007-05-24 Thread Jared Farrish

Also, you should be checking against type (expecting a number? a boolean
value? a string?) and then checking against expected length requirements
(such as firstname can only be 80 characters long max, so maybe check for

code
if (strlen($var)  80) {
   do something;
}
/code

In unit testing, you build your objects first against types and perform
object checks using type verification and expected element attributes (such
as length, non-null values, etc...). If someone is posting a string of 8000
letters into a field that is supposed to contain a number two letters long,
before it is stored, maybe you manage that...

On 5/24/07, Jared Farrish [EMAIL PROTECTED] wrote:


I'm not sure exactly what kind of sanitization you think you're doing, but
if all you do is check to see if it's empty (empty() implements isset(),
empty() checks to see if it's set, then if it evaluates to an empty
variable), that's not much sanitization.

What you need to do is check for SQL injections, which means you need to
sanitize GPC (GET, POST, COOKIES) to prevent the following (only a
demonstration):

SELECT `colname` FROM `tablename` WHERE id='$variable' LIMIT 0,10

What happens if $variable is equal to:

$variable = $_POST['somedata'];

And $_POST['somedata'] ~  'INSERT INTO users
VALUES('name','password','AdminGroup')' ;

This is an example of a possible SQL injection (which means unknown SQL
code is running through your script access). The way to prevent this is to
escape single quotes before insert/select, and also turn all html entities
into escaped values (so that someone cannot put a script/script block
into the signature for their user, for example).

The good thing is, there are numerous help sites online that describe how
to do this. Generally, you're better off wrapping your SQL commands into a
class or at least a series of functions, so that you can implement your
sanitization once and use it for all database interactions.

Google: http://www.google.com/search?q=php+sanitize+sql+statement
PHP.net: http://www.php.net/manual/en/security.database.sql-injection.php

--
Jared Farrish
Intermediate Web Developer
Denton, Tx

Abraham Maslow: If the only tool you have is a hammer, you tend to see
every problem as a nail. $$





--
Jared Farrish
Intermediate Web Developer
Denton, Tx

Abraham Maslow: If the only tool you have is a hammer, you tend to see
every problem as a nail. $$


[PHP] Re: php hosting-mediatemple/dreamhost

2007-05-24 Thread Jared Farrish

I use MediaTemple, and what I like is that it's a company geared towards a
category of developers, and not ANY person who wants a website. So the
services and support are commensurate for a company that offers services
primarily aimed at professional design-oriented firms and/or developers, and
not Joe Schmo Website Author. Service request responses have always been
quick, I've never lost data, had a website disappear altogether, etc...

The GRID server configuration is nice at a $20 pricepoint. With PHP5
supported and safe_mode turned off, I can't wait to get off the shared
server.

Shawn Inman is a modestly-famous web designer/developer who uses MediaTemple
for his website:

http://www.shauninman.com/

--
Jared Farrish
Intermediate Web Developer
Denton, Tx

Abraham Maslow: If the only tool you have is a hammer, you tend to see
every problem as a nail. $$


[PHP] Re: Check if Record was Entered Today.

2007-05-24 Thread Jared Farrish

I believe you need a while instead of an if.  The if will only run
until the first occurance is true.   Whereas a while will run to find

all

results that are true until it goes thru all of the result rows..


No, I think he's checking to make sure that $db contains a resource id and
not a boolean false (meaning the file did not load or contains no data).

Maybe a more descriptive way may be to say:

code
if ($db !== false  is_resource($db)) {
   doStuff();
}
/code

To the next problem:


'exit' terminates the script.  You should not be using exit there.


When you want a loop structure to stop and goto what flows next in the code,
use break:

code
for ($i = 0; $i  count($items); $i++) {
   if ($items[$i] == $arbitraryCondition) {
   echo 'I do not need to doStuff() anymore.';
   break;
   }
   doStuff();
}
/code

When you want a loop structure to skip over something but still continue to
loop, use continue:

code
for ($i = 0; $i  count($items); $i++) {
   if ($items[$i] == $arbitraryCondition) {
   echo 'I do not need to doStuff() on this item.';
   continue;
   }
   doStuff();
}
/code

When reading through values in an array or other structure, you can while or
do/while loop:

code
$db = getDb('location/db.dbf');
while($row = db_fetch_array($result)) {
   if ($row['AcctActivation'] != $date) {
   continue;
   } elseif ($row['AcctActivation'] == $date) {
   break;
   }
   doStuff();
}
/code

Isn't there a way to search for and select only the rows with the account
number though? If you're looking for needles in a (potentially large)
haystack, this sounds like an expensive process for something SQL or other
could do better/faster.



Incidentally, does this mean you solved the file access problems from this
thread:

http://news.php.net/php.general/255542

--
Jared Farrish
Intermediate Web Developer
Denton, Tx

Abraham Maslow: If the only tool you have is a hammer, you tend to see
every problem as a nail. $$


[PHP] Re: Developer / Client Documents

2007-05-24 Thread Jared Farrish


I am trying to start a small (Read: Tiny) web development company from
home,
which will handle only a few light contracts. I have been spending some
time
searching Google for common documents used by developers and their clients
to help layout all the goals and features the site might have.
Unfortunately
since I have not obtained any formal education, I am experiencing a slight
fish-out-of-water syndrome, and am not even sure of the names of the
documents I am seeking. I would be eternally grateful if some experienced
developers would point me in the right direction; any documents related to
planning the website, contracts, really anything would be considered
useful.



What you are looking for are project development and project management
books that describe how projects are organized, documented, etc...

First, google design patterns gang of four
Second, visit
http://trac.seagullproject.org/wiki/Standards/SoftwareBestPractices
Third, look at: http://trac.seagullproject.org/wiki/Standards
Fourth, visit: http://www.oreilly.com/pub/topic/projectmanagement
   and http://www.oreilly.com/pub/topic/designpatterns

Also, I might suggest:

http://www.oreilly.com/catalog/webdbapps2/

This will give you most of what you're looking for. Think XAMPP for a
localhost install to run tests, and MySQL for a database backend (part of
XAMPP):

http://www.apachefriends.org/en/xampp.html

It will take time. Good luck!

--
Jared Farrish
Intermediate Web Developer
Denton, Tx

Abraham Maslow: If the only tool you have is a hammer, you tend to see
every problem as a nail. $$


[PHP] Re: Re: RE: Cannot access file on Network Drive (Windows 2003)

2007-05-24 Thread Jared Farrish


This *might* be correct with PHP as an Apache Module, but I doubt it.

I think it's more like:

Whatever - PHP - stdio.h File System calls

Whatever will affect what user is running PHP and thus what
permissions they have, but that's about it.



Is it then:

Whatever['Apache.exe'] (owns) System Process (which) Requests (using)
stdio.h

How/what determines the active process that is requesting the directive (and
matches access privileges)?

If PHP is running in CLI, I could see how this might be seen as a different
process, but I'm fuzzy about file permissions extended through primary
processes (such as Apache using an executable)... The whole apache GUID mess
seems like cryptic middle ages eye gouging...

--
Jared Farrish
Intermediate Web Developer
Denton, Tx

Abraham Maslow: If the only tool you have is a hammer, you tend to see
every problem as a nail. $$


[PHP] Re: Include???

2007-05-24 Thread Jared Farrish


Perhaps there is some whitespace before/after the 'C'...

echo '$_POST[status_code]'br /\n;

You should then see some whitespace inside the '' so you'll know it's
there.

This is a VERY good debugging technique to adopt. :-)



My own methodology is to use one of the following to peer into an array (of
any sort):

code
echo 'pre';
print_r($_POST);
echo '/pre';

echo 'pre';
var_dump($_POST);
echo '/pre';
/code

Wrap one of those in a function or put it in a static class to call when
needed, and voila!, instant array introspection. Useful for $_GET, $_COOKIE,
$GLOBALS, $_SERVER, etc...

p.s.: Could you use descriptive subjects; include doesn't really say
much...

--
Jared Farrish
Intermediate Web Developer
Denton, Tx

Abraham Maslow: If the only tool you have is a hammer, you tend to see
every problem as a nail. $$


[PHP] Re: Scalable Site Architecture

2007-05-24 Thread Jared Farrish


On Wed, May 9, 2007 2:10 pm, bruce wrote:
 In looking for what's required fo a site, I'm trying to find
 docs/overview/mentors to talk to/etc,...

 Basically, I'm considering what's required in terms of
 hardware/apps/functionality for each server to be able to support a
 site/system of ~100,000/day


Not that this isn't entirely off-topic...

100,000 hits/day should be coordinated through a medium-sized hosting
service that promises multi-tier architecture and dynamic server arrays. At
3,000,000 hits/month, for perspective, Yahoo! and MySpace average about 15
times that, per day.

Google multi-tier architecture
Google dynamic server farm
Google server array
Google raid array

Much has been written about scalability of systems architecture.

Google scalable systems architecture

Web services push data from responder to caller.

Google n-tier web services
Google SOAP

If you're looking to implement something that you know will scale quickly
(like a porn site), hire someone. If you have months (or years or lead time)
and just feel a little masochistic, first read on server and raid arrays, to
get a good foundation. Different animals, but knowing how each works at
least superficially can help later.

What I suspect you need is a book on LAMP (www.oreilly.com).

--
Jared Farrish
Intermediate Web Developer
Denton, Tx

Abraham Maslow: If the only tool you have is a hammer, you tend to see
every problem as a nail. $$


[PHP] Re: Uploading Files into MySQL

2007-05-24 Thread Jared Farrish


I am working on a script to upload files into MySQL db.  The following
script uploads to a file system how do I go about uploading the file
into the DB?  Where do I put the SQL statement in the code below?



Let's see:

script upload file mysql database

Hmm, add php and you have

Google php script upload file mysql database

You can thank me later.

*snap*

--
Jared Farrish
Intermediate Web Developer
Denton, Tx

Abraham Maslow: If the only tool you have is a hammer, you tend to see
every problem as a nail. $$


[PHP] Re: help with multi dimensional arrays

2007-05-24 Thread Jared Farrish

Also, when I get PHP errors, if not obvious, I check the previous line
also... If says something like error on line 7 I will look at both
line six and seven.


I used the notepad-error-of-death method:

1. Use only notepad for php scripting (or some BASIC text editor, with
exactly ONE undo).
2. Author horrid script without thinking.
3. Upload and cringe on blank white screen effect of ill-advised code
manipulation.
4. Figure out how to change code by slowing down and using Notepad's undo
(remember, ONE undo, and then you undo the undo) to make less-stupid
mistakes or omissions.

Pretty impractical for professional programming, but sure helped me out. At
least I make deliberately bad decisions now, instead of wholly ignorant
ones. At least not a whole string of them at one time.


Of course, depends on error message. Yadda yadda... I still feel like a
dork for saying comma.


Well, I got a chuckle. :D

--
Jared Farrish
Intermediate Web Developer
Denton, Tx

Abraham Maslow: If the only tool you have is a hammer, you tend to see
every problem as a nail. $$


[PHP] Re: Form Validation Issues

2007-05-23 Thread Jared Farrish

Having a giant conditional statement such as the one you have posted is a
real problem for many different reasons. Below is a simple states class that
allows you to test for a state using a couple of different checks (such as
making both comparables lower or upper case). One major issue with the code
block you posted (which may or may not be a problem on your end, it could be
the email software), but these two are not comparable:

code
$v = New Hampshire;
$x = New
Hampshire;
if ($v === $x) {
   echo(pre$v is exactly equal to $x/pre);
} elseif ($v == $x) {
   echo(pre$v is loosely equal to $x/pre);
} else {
   echo(pre$v is not exactly equal to $x/pre);
}
/code
This will produce: New Hampshire is not exactly equal to New
Hampshire

A better way to test a conditional (whether complex and/or lengthy) is to
wrap it in either a function, or a class method, like so:

code
?php
class States {
   var $suggest = null;
   var $states = Array(
   'alabama'=true,'al'=true,
   'alaska'=true,'ak'=true,
   'arizona'=true,'az'=true,
   'arkansas'=true,'ar'=true,
   'california'=true,'ca'=true,
   'colorado'=true,'co'=true,
   'connecticut'=true,'ct'=true,
   'delaware'=true,'de'=true,
   'florida'=true,'fl'=true,
   'georgia'=true,'ga'=true,
   'hawaii'=true,'hi'=true,
   'idaho'=true,'id'=true,
   'illinois'=true,'il'=true,
   'indiana'=true,'in'=true,
   'iowa'=true,'ia'=true,
   'kansas'=true,'ks'=true,
   'kentucky'=true,'ky'=true,
   'louisiana'=true,'la'=true,
   'maine'=true,'me'=true,
   'maryland'=true,'md'=true,
   'massachusetts'=true,'ma'=true,
   'michigan'=true,'mi'=true,
   'minnesota'=true,'mn'=true,
   'mississippi'=true,'ms'=true,
   'missouri'=true,'mo'=true,
   'montana'=true,'mt'=true,
   'nebraska'=true,'ne'=true,
   'nevada'=true,'nv'=true,
   'new hampshire'=true,'nh'=true,
   'new jersey'=true,'nj'=true,
   'new mexico'=true,'nm'=true,
   'new york'=true,'ny'=true,
   'north carolina'=true,'nc'=true,
   'north dakota'=true,'nd'=true,
   'ohio'=true,'oh'=true,
   'oklahoma'=true,'ok'=true,
   'oregon'=true,'or'=true,
   'pennsylvania'=true,'pa'=true,
   'rhode island'=true,'ri'=true,
   'south carolina'=true,'sc'=true,
   'south dakota'=true,'sd'=true,
   'tennesee'=true,'tn'=true,
   'texas'=true,'tx'=true,
   'utah'=true,'ut'=true,
   'vermont'=true,'vt'=true,
   'virginia'=true,'va'=true,
   'washington'=true,'wa'=true,
   'west virginia'=true,'wv'=true,
   'wisconsin'=true,'wi'=true,
   'wyoming'=true,'wy'=true
   );
   function States() {
   }
   function isValid($str,$suggest) {
   if ($this-states[strtolower($str)] === true) {
   $this-suggest = null;
   return true;
   } elseif ($suggest === true  strlen($str)  3) {
   $this-doSuggest($str);
   return false;
   } else {
   $this-suggest = null;
   return false;
   }
   }
   function doSuggest($str) {
   foreach ($this-states as $state = $val) {
   similar_text(strtolower($state),strtolower($str),$result);
   if ($result  85) {
   $this-suggest = $state;
   }
   }
   if (empty($this-suggest)) {
   $this-suggest = null;
   }
   }
   function isSuggested() {
   return $this-suggest;
   }
}
$states = new States();
$state = 'Hawii';
if ($states-isValid($state,true) === true) {
   echo(p$state is a state./p);
} elseif ($suggest = $states-isSuggested()) {
   echo(pMay we suggest $suggest?/p);
} else {
   echo(pState not found./p);
}
?
/code
--
Jared Farrish
Intermediate Web Developer
Denton, Tx

Abraham Maslow: If the only tool you have is a hammer, you tend to see
every problem as a nail. $$


[PHP] Re: Form Validation Issues

2007-05-23 Thread Jared Farrish

Also, Indiana and Connecticut were misspelled.

--
Jared Farrish
Intermediate Web Developer
Denton, Tx

Abraham Maslow: If the only tool you have is a hammer, you tend to see
every problem as a nail. $$


[PHP] Re: problems in WHERE statment

2007-05-23 Thread Jared Farrish

Change the single quote to a double quote:

code
$query = SELECT * FROM `job listing` WHERE open = '$today' LIMIT 0 , 30
;
/code

This tells the PHP string parser to replace all declared, in-scope variables
that are detected in a string with the value of the variable (as a
toString() method, so a reference would not pass in the actual data, it
would print something like Resource id #3).

When you use single-quotes, you are telling the parser to keep it's hands
off the string, and use as-is.

Example:
code
var $a = 'test';
var $b = 'test2';
var $c = '$a$b';
var $d = $a$b;
var $e = $a.$b;
/code

$e is equivalent to $d, where c would print literally $a$b, since you told
the parser using the single quotes to leave the string alone.

Likewise, var $f = $a.-$b$c-.'$e'; would print test-test2$a$b-$e;

--
Jared Farrish
Intermediate Web Developer
Denton, Tx

Abraham Maslow: If the only tool you have is a hammer, you tend to see
every problem as a nail. $$


[PHP] RE: Cannot access file on Network Drive (Windows 2003)

2007-05-23 Thread Jared Farrish

Other than permissions, you might be referencing the folder by the local
network mapping drive initial, instead of the actual path:

X:\\offsite\db\test.dbf == \\compname-x\offsite\db\test.dbf

Generally, I like using the computer name and not a mapping. I find this
name-based address through the 'My Network Places' folder.

I'm not much of a windows networking person, but this might be the problem.
Results may vary, but in windows, I think the mappings are by machine only,
as mappings (I assume) are local aliases, and must be set or shared among
groups of machines to be known.

It's probably a permissions thing, though.

FWIW

--
Jared Farrish
Intermediate Web Developer
Denton, Tx

Abraham Maslow: If the only tool you have is a hammer, you tend to see
every problem as a nail. $$


[PHP] Re: Cannot access file on Network Drive (Windows 2003)

2007-05-23 Thread Jared Farrish

Oh yeah, and tijnema has a good point:

\\compname-x\\offsite\\db\\test.dbf

Btw, what does top post mean?

On 5/23/07, Jared Farrish [EMAIL PROTECTED] wrote:


Other than permissions, you might be referencing the folder by the local
network mapping drive initial, instead of the actual path:

X:\\offsite\db\test.dbf == \\compname-x\offsite\db\test.dbf

Generally, I like using the computer name and not a mapping. I find this
name-based address through the 'My Network Places' folder.

I'm not much of a windows networking person, but this might be the
problem. Results may vary, but in windows, I think the mappings are by
machine only, as mappings (I assume) are local aliases, and must be set or
shared among groups of machines to be known.

It's probably a permissions thing, though.

FWIW

--
Jared Farrish
Intermediate Web Developer
Denton, Tx

Abraham Maslow: If the only tool you have is a hammer, you tend to see
every problem as a nail. $$





--
Jared Farrish
Intermediate Web Developer
Denton, Tx

Abraham Maslow: If the only tool you have is a hammer, you tend to see
every problem as a nail. $$


Re: [PHP] RE: Cannot access file on Network Drive (Windows 2003)

2007-05-23 Thread Jared Farrish

Try to simply include() and var_dump() or something. Start from just
checking you can access the file first (I'd even start with a
test.txtfile), before you inflate the db...

Let us know what the error is exactly, as well. What happens? Error?
Warning? Blank page? What tells you the script doesn't work?

On 5/23/07, Rahul Sitaram Johari [EMAIL PROTECTED] wrote:



Tried that too. Used

\\Servername\sharename\test.dbf

Also used additional backslashes for the escape issue:

Servername\\sharename\\test.dbf

Still doesn't work!
I'm not getting a permissions related issue and I'm doubting it is a
permissions issue. I have Full Control given to the system all this is on.



--
Jared Farrish
Intermediate Web Developer
Denton, Tx

Abraham Maslow: If the only tool you have is a hammer, you tend to see
every problem as a nail. $$


[PHP] Re: [PEAR] PHP5 Static functions called through __call() that don't exist... yet

2007-05-22 Thread Jared Farrish

Ok, somehow I did this again (posted to pear-general instead of
php-general). pear-general and php-general look alike...

Thank everyone for their suggestion. I would like to see a __static()
version of __call(), but this is the wrong place to bring that feature
request up.

To answer Greg Beaver's observations, I would prefer to use static instances
in this case, to save myself the trouble (and overhead) of instantiating a
new object while developing classes. The utility is meant to provide unit
testing for individual classes or libraries, that can then be extended to a
specific class or library, and abstract the actually is_type() testing to
another class. It's a somewhat specific implementation meant more for unit
testing.

Below is the code I decided to implement (with a test below it to
demonstrate):

code
?php
if (!class_exists('TypeAssert')) {
   class TypeAssert {
   public static $a;
   public static $assert;
   private static $types = array(
   'array','bool','float','integer','null','numeric',
   'object','resource','scalar','string'
   );
   function __construct() {
   self::$assert = self::$a;
   }
   public static function __call($method,$arguments) {
   $obj = self::assertStandardTypes($arguments[0]);
   return $obj-$method;
   }
   public static function assertStandardTypes($para) {
   $r = TypeAssert::getTypesObject();
   foreach ($r as $type=$v) {
   $func = is_.strtolower($type);
   if (function_exists($func) === true) {
   if ($func($para) === true) {
   $r-$type = true;
   } else {
   $r-$type = false;
   }
   }
   }
   return $r;
   }
   public static function getTypesObject() {
   $obj = (object) '';
   for ($i = 0; $i  count(self::$types); $i++) {
   $obj-{self::$types[$i]} = (bool) false;
   }
   return $obj;
   }
   }
}
TypeAssert::$a = new TypeAssert();
echo(pre\n);
switch($_GET['type']) {
   case 'int':
   $test = 100;
   $_test = 100;
   break;
   case 'float':
   $test = 100.001;
   $_test = 100.001;
   break;
   case 'null':
   $test = null;
   $_test = 'null';
   break;
   case 'object':
   $test = TypeAssert::$a;
   $_test = '[object]';
   break;
   default:
   $test = 'string';
   $_test = 'string';
   break;
}
foreach (TypeAssert::getTypesObject() as $type = $v) {
   echo(divis_b style=\color: #00a;\$type/b(b$_test/b) === .
 (TypeAssert::$assert-$type($test)?
  'b style=color: #0a0;true/b':
  'b style=color: #a00;false/b').
  /div\n
   );
}
echo(/pre\n);
?
/code

Thanks!

On 5/22/07, Jared Farrish [EMAIL PROTECTED] wrote:


Thank everyone for their suggestion. I would like to see a __static()
version of __call(), but this is the wrong place to bring that feature
request up.

To answer Greg Beaver's observations, I would prefer to use static
instances in this case, to save myself the trouble (and overhead) of
instantiating a new object while developing classes. The utility is meant to
provide unit testing for individual classes or libraries, that can then be
extended to a specific class or library, and abstract the actually is_type()
testing to another class. It's a somewhat specific implementation meant more
for unit testing.

Below is the code I decided to implement (with a test below it to
demonstrate):

code
?php
if (!class_exists('TypeAssert')) {
class TypeAssert {
public static $a;
public static $assert;
private static $types = array(
'array','bool','float','integer','null','numeric',
'object','resource','scalar','string'
);
function __construct() {
self::$assert = self::$a;
}
public static function __call($method,$arguments) {
$obj = self::assertStandardTypes($arguments[0]);
return $obj-$method;
}
public static function assertStandardTypes($para) {
$r = TypeAssert::getTypesObject();
foreach ($r as $type=$v) {
$func = is_.strtolower($type);
if (function_exists($func) === true) {
if ($func($para) === true) {
$r-$type = true;
} else {
$r-$type = false;
}
}
}
return $r;
}
public static function getTypesObject() {
$obj = (object) '';
for ($i = 0; $i  count(self::$types); $i++) {
$obj-{self::$types[$i]} = (bool) false;
}
return $obj;
}
}
}
TypeAssert::$a = new TypeAssert();
echo(pre\n);
switch($_GET['type']) {
case 'int':
$test = 100

[PHP] PHP5 Static functions called through __call() that don't exist... yet

2007-05-18 Thread Jared Farrish

Hi all,

I am building an assertType object using static functions. What I want to
keep away from is the following:

code
public static function assertString($para){
   return $answer;
};
public static function assertBool($para){
   return $answer;
};
...
public static function assertArray($para){
   return $answer;
};
/code

What I would like to do is replace this with the following:

code
if (!class_exists('TypeAssert')) {
   class TypeAssert {
   private static $types = array(
   'array','bool','float','integer','null','numeric',
   'object','resource','scalar','string'
   );
   public static function __call($method,$arguments) {
   $obj = self::assertStandardTypes($arguments[0]);
   return $obj-$method;
   }
   public static function assertStandardTypes($para) {
   $r = TypeAssert::getTypesObject();
   if (is_array($para))$r-array = true;
   if (is_bool($para)) $r-bool = true;
   if (is_float($para))$r-float = true;
   if (is_integer($para))  $r-integer = true;
   if (is_null($para)) $r-null = true;
   if (is_numeric($para))  $r-numeric = true;
   if (is_object($para))   $r-object = true;
   if (is_resource($para)) $r-resource = true;
   if (is_scalar($para))   $r-scalar = true;
   if (is_string($para))   $r-string = true;
   return $r;
   }
   public static function getTypesObject() {
   $obj = (object) '';
   for ($i = 0; $i  count(self::$types); $i++) {
   $obj-{self::$types[$i]} = (bool) false;
   }
   return $obj;
   }
   }
}
echo('pre');
echo(TypeAssert::string('test'));
echo('/pre');
/code

I don't think this is possible (see
http://marc.info/?l=php-generalm=114558851102060w=2
). But I would LIKE for it to work (currently, the above code doesn't).

Anybody have any insight on how I might get this to work?

Thanks!

--
Jared Farrish
Intermediate Web Developer
Denton, Tx

Abraham Maslow: If the only tool you have is a hammer, you tend to see
every problem as a nail. $$


[PHP] Re: PHP5 Static functions called through __call() that don't exist... yet

2007-05-18 Thread Jared Farrish

Hi all,

Here is more code, with a test case included. What I would prefer to do is
call TypeAssist::$string(), instead of TypeAssist::$a-string(). Or at least
__construct() the $a object.

code
?php
if (!class_exists('TypeAssert')) {
   class TypeAssert {
   public static $a;
   public static $assert;
   private static $types = array(
   'array','bool','float','integer','null','numeric',
   'object','resource','scalar','string'
   );
   function __construct() {
   self::$assert = self::$a;
   }
   public static function __call($method,$arguments) {
   $obj = self::assertStandardTypes($arguments[0]);
   return $obj-$method;
   }
   public static function assertStandardTypes($para) {
   $r = TypeAssert::getTypesObject();
   foreach ($r as $type=$v) {
   $func = is_.strtolower($type);
   if (function_exists($func) === true) {
   if ($func($para) === true) {
   $r-$type = true;
   } else {
   $r-$type = false;
   }
   }
   }
   return $r;
   }
   public static function getTypesObject() {
   $obj = (object) '';
   for ($i = 0; $i  count(self::$types); $i++) {
   $obj-{self::$types[$i]} = (bool) false;
   }
   return $obj;
   }
   }
}
TypeAssert::$a = new TypeAssert();
echo(pre\n);
switch($_GET['type']) {
   case 'int':
   $test = 100;
   $_test = 100;
   break;
   case 'float':
   $test = 100.001;
   $_test = 100.001;
   break;
   case 'null':
   $test = null;
   $_test = 'null';
   break;
   case 'object':
   $test = TypeAssert::$a;
   $_test = '[object]';
   break;
   default:
   $test = 'string';
   $_test = 'string';
   break;
}
foreach (TypeAssert::getTypesObject() as $type = $v) {
   echo(divis_b style=\color: #00a;\$type/b(b$_test/b) === .
 (TypeAssert::$assert-$type($test)?
  'b style=color: #0a0;true/b':
  'b style=color: #a00;false/b').
  /div\n
   );
}
echo(/pre\n);
?
/code

Original Message Text


Hi all,

I am building an assertType object using static functions. What I want to
keep away from is the following:

code
public static function assertString($para){
return $answer;
};
public static function assertBool($para){
return $answer;
};
...
public static function assertArray($para){
return $answer;
};
/code

What I would like to do is replace this with the following:

code
if (!class_exists('TypeAssert')) {
class TypeAssert {
private static $types = array(
'array','bool','float','integer','null','numeric',
'object','resource','scalar','string'
);
public static function __call($method,$arguments) {
$obj = self::assertStandardTypes($arguments[0]);
return $obj-$method;
}
public static function assertStandardTypes($para) {
$r = TypeAssert::getTypesObject();
if (is_array($para))$r-array = true;
if (is_bool($para)) $r-bool = true;
if (is_float($para))$r-float = true;
if (is_integer($para))  $r-integer = true;
if (is_null($para)) $r-null = true;
if (is_numeric($para))  $r-numeric = true;
if (is_object($para))   $r-object = true;
if (is_resource($para)) $r-resource = true;
if (is_scalar($para))   $r-scalar = true;
if (is_string($para))   $r-string = true;
return $r;
}
public static function getTypesObject() {
$obj = (object) '';
for ($i = 0; $i  count(self::$types); $i++) {
$obj-{self::$types[$i]} = (bool) false;
}
return $obj;
}
}
}
echo('pre');
echo(TypeAssert::string('test'));
echo('/pre');
/code

I don't think this is possible (see 
http://marc.info/?l=php-generalm=114558851102060w=2
). But I would LIKE for it to work (currently, the above code doesn't).

Anybody have any insight on how I might get this to work?

Thanks!

--
Jared Farrish
Intermediate Web Developer
Denton, Tx

Abraham Maslow: If the only tool you have is a hammer, you tend to see
every problem as a nail. $$





--
Jared Farrish
Intermediate Web Developer
Denton, Tx

Abraham Maslow: If the only tool you have is a hammer, you tend to see
every problem as a nail. $$