Re: [PHP] FILTER_VALIDATE_INT - newbie question

2009-10-07 Thread Ben Dunlap
 If I put 0 filter_var() will return false.

Actually it returns the integer 0, not the boolean FALSE. Here's an
illustration of the difference:

http://codepad.org/73wff2u0

The integer value 0 can masquerade as false in an if() statement, of
course, as Ash pointed out above.

 If I put 0342352 filter_var() will also return false.

How is 0342352 being assigned to the variable that you're filtering?
If PHP thinks it's a string, then the filter will fail. If PHP thinks
it's a number, it seems to convert it internally to the number 115946,
before you get to the filter.  Not sure what's going on there. At any
rate it will then pass FILTER_VALIDATE_INT, but the value's not going
to be what you expect. You can see it happening here:

http://codepad.org/tw2qlpC1

Ben

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] FILTER_VALIDATE_INT - newbie question

2009-10-07 Thread Ben Dunlap
 How is 0342352 being assigned to the variable that you're filtering?
 If PHP thinks it's a string, then the filter will fail. If PHP thinks
 it's a number, it seems to convert it internally to the number 115946,
 before you get to the filter.  Not sure what's going on there. At any

Sorry, brain fart. In PHP, a leading 0 in an integer indicates an
octal number (thanks, Martin). PHP immediately converts it to decimal
internally. Hence 0342352 becomes 115946. But it's a bit of a fluke
that the example you used happened to be a valid octal number. Try
something that starts with 0 and has an 8 or a 9 in it; you'll end up
with plain old 0 (presumably because PHP's internal attempt to convert
from octal, fails):

http://codepad.org/KBUgAZWJ

Which, of course, leads to the apparent-false discussed above.

Ben

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] FILTER_VALIDATE_INT - newbie question

2009-10-07 Thread Ben Dunlap
 How is 0342352 being assigned to the variable that you're filtering?
 If PHP thinks it's a string, then the filter will fail. If PHP thinks

Oops, potentially bad information there as well, sorry. In general, a
string representation of a decimal number /will/ pass
FILTER_VALIDATE_INT. But your particular string (0342352) will only
fail FILTER_VALIDATE_INT in the filter's default configuration; set
the ALLOW_OCTAL flag and it will pass:

http://codepad.org/RNE5LZMr

You'll still end up with an unexpected value in your final variable, though.

Ben

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] FILTER_VALIDATE_INT - newbie question

2009-10-07 Thread Ben Dunlap
 Also, I think you're getting confused over the zero with exactly what
 you are asking PHP to do. filter_var() returns true if the filter
 matches. If the 0 match is returned as a false, then filter_var() will

filter_var() actually returns the filtered data if the filter matches,
and FALSE if it doesn't. That's the whole point of the filter_XXX
functions; to pass a tainted value through a filter and get a clean,
safe value out the other end:

$tainted = get_user_input();
$clean = filter_var($tainted, [FILTER_CONSTANT]);
// now use $clean and never touch $tainted again

From the original code above, it looks like the OP was
misunderstanding the use of filter_var() and expecting it to return a
boolean.

Ben

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Self-Process php forms or not?

2009-10-02 Thread Ben Dunlap
 Yes. But since I don't want to display a success information + form fields,
 but only the success information,
 I believe the only way we have to do this is by either use javascript and
 update a div or similar, or using only php, by redirecting to another page.

 Is this correct?

Whether or not it's the only way, redirecting to a success page is
probably the best way, from a user-experience perspective. It keeps
the browser history sane and avoids possible trouble with
page-refreshes.

Google for post redirect get and you'll find all sorts of
discussions of this pattern. Here's one of the clearer articles that
came up on the first page of results, when I ran that search:

http://www.andypemberton.com/engineering/the-post-redirect-get-pattern/

Ben

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Whacky increment/assignment logic with $foo++ vs ++$foo

2009-10-02 Thread Ben Dunlap
 Can someone PLEASE explain why the developers of PHP chose this seemingly
 whacky logic?

It mimicks C.

Ben

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Whacky increment/assignment logic with $foo++ vs ++$foo

2009-10-02 Thread Ben Dunlap
 My issue is that I see no reason to do the ASSIGNMENT FIRST and THEN
 INCREMENT.

 That's just counter intuitive. In the case of $foo = $num++, everything to
 the right of the = should be computed FIRST and THEN handed off to the left
 side. This particular expression (and I'm unaware of any other PHP
 expression that works this way) chooses to do some FM (f'n magic) and do
 an assignment FIRST and THEN increment.

It's not the expression that works that way -- it's the operator. The
post-increment operator /always/ does its work after the expression
that it's in has been evaluated.

Are you thinking it would be more intuitive if that operator departed
from its normal behavior in this one special case?

Ben

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Whacky increment/assignment logic with $foo++ vs ++$foo

2009-10-02 Thread Ben Dunlap
On Fri, Oct 2, 2009 at 2:37 PM, Ben Dunlap bdun...@agentintellect.com wrote:
 My issue is that I see no reason to do the ASSIGNMENT FIRST and THEN
 INCREMENT.

 That's just counter intuitive. In the case of $foo = $num++, everything to
 the right of the = should be computed FIRST and THEN handed off to the left
 side. This particular expression (and I'm unaware of any other PHP
 expression that works this way) chooses to do some FM (f'n magic) and do
 an assignment FIRST and THEN increment.

 It's not the expression that works that way -- it's the operator. The
 post-increment operator /always/ does its work after the expression
 that it's in has been evaluated.

 Are you thinking it would be more intuitive if that operator departed
 from its normal behavior in this one special case?

On further thought I do see why this one special case is a little
mind-blowing. What the heck /is/ supposed to happen when you do this:

$a = 2;
$a = $a++;
echo $a;

Seems like any way you slice it the output should be 3. I guess what's
revealed here is that, as far as PHP is concerned, the $a on the right
side of the assignment expression is something like a temporary copy
of the variable in the current scope. So the assignment gets
evaluated, and then ++ operates on that copy and the result is
discarded.

Honestly I think the only reason anyone would write an expression like
that is either to fake out the compiler or because they don't properly
understand the use of a unary operator. Or rather, of the
increment/decrement operators, because no other unary operator
actually changes the thing it operates on (AFAIK), which makes ++ and
-- doubly weird.

Ben

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Whacky increment/assignment logic with $foo++ vs ++$foo

2009-10-02 Thread Ben Dunlap
        int a = 2;
        b = a++;
        printf(b = [%d]\n, b);

 b would be 2 when printed.  However, after the second line (b = a++;)
 finished executing, a would then be 3.

Sure, but that code is perfectly clear. It's the odd special case
where you assign the variable to itself, that's ambiguous. Like Daevid
said, academic at this point -- but it might shed light on some
compiler-design decisions that I don't have the vocabulary for.

OTOH it could just a be a unique case with unpredictable results.

Ben

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] POST without POSTing

2009-10-01 Thread Ben Dunlap
 to make sure the user has properly filled out this form. So I have to
 validate it. That's done in the background on the server, naturally. But
 once the validating is done, it's time to send the user off to the
 secure site with a payload of POST variables. At that point, the user
 will enter credit card info and such, and continue the transaction.

You're describing what a 307 redirect is supposed to accomplish:

header(Location: $secure_url, TRUE, 307);

But I've heard that not all browsers comply with the HTTP spec on this
point. Might be worth testing a bit, though -- maybe your typical
audience doesn't tend to use non-compliant browsers.

 So I need to find a way to direct the user's browser to the secure site
 with their payload of POST variables. The more I look at this, the more
 it looks like cURL won't do it, and Javascript has the obvious down
 side.

 I'm afraid the only way to do this may be to validate everything, pass
 the values off to a confirmation page, where the user has to hit
 Proceed, and *that* page goes directly to the secure server with its
 POST payload.

That might actually be the best solution because it's the most
transparent, from the user's point-of-view. A 307 is going to cause
many browsers to pop up a confirmation dialog, which will freak some
users out -- and will break people's flow a lot more than would a
smoothly-executed two-stage submit.

Ben

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Parse Question Using list()

2009-10-01 Thread Ben Dunlap
 $line = fgets($handle);

 list($col1, $col2, $col3) = $line;
[8]
 echo c1 is $col1 and c2 is $col2 and c3 is $col3.'br'; // this shows
 just 1st char of each field

That's odd, I would have expected $col1, $col2, and $col3 to be NULL.
That's what I get when I try to assign a string to list(). It expects
a PHP array.

You could tackle this in a couple of different ways. Either split your
string into an array first:

$line = fgets($handle);
$columns = explode(,, trim($line));
list($col1,$col2,$col3) = $columns;

Or look at using fgetcsv(), which will save you a step or two:

http://php.net/manual/en/function.fgetcsv.php

Ben

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Re: Does anyone here use TCPDF?

2009-09-24 Thread Ben Dunlap
 I attempted to use the same functions as FPDI/FPDF, but they did not
 work in TCPDF.

Which functions did you use in FPDF?

Ben

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Re: session.gc_maxlifetime

2009-09-24 Thread Ben Dunlap
 php not but perhaps the client its not clear and commonly defined what
 clients do with cookies on reconnect and stuff or long idle times.

Maybe not, but I'd be really surprised. An HTTP client is supposed to
decide whether to send a cookie by looking at the domain name and path
of the URL it's requesting. These things are at a totally different
layer from IP addresses -- and even if they weren't, in most cases I
would think a browser is going to be ignorant of public IP address
changes because it's going to be behind a NAT device.

 I would expect as source the new browsers where more and more users use
 subwindows to have concurrent sessions, does anybody know how they handle ip
 changes? I'm not.

What specific situation do you have in mind in which a browser would
even be aware of an IP change on the client side? Maybe there are
common cases I'm not thinking of.

Ben

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] variable

2009-09-24 Thread Ben Dunlap
 Suppose I have a variable $i = 0 or 1 or 2
 and I have variables $item0, $item1 and $item2
 how do I print the variable $item0 using a combination of variable $item and
 variable $i?
 or with this code it gives me an error:
 $i = 0;
 $item0 = test;
 echo $item$i; #how do I properly use this variable $item with $i?

   $var = item$i;
   echo $$var;

Note the two dollar-signs in the second line.

I wonder if a basic array would make for easier-to-read code, though:

$items = array( test );
$i = 0;
echo $items[$i];

Ben

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] html email showing br instead of line breaks

2009-09-24 Thread Ben Dunlap
 \r\n should be between double quotes: \r\n

I think you'll still see the literal brs in your final email,
though because htmlspecialchars() is converting the angle-brackets in
the tag to their respective HTML entities (lt; for  and gt;
for ).

A bit of a thorny problem because you probably do want to escape
HTML-characters in the message for security purposes. I suppose you
could call str_replace() after htmlspecialchars(), instead of before
it as you currently do.

OTOH, why not just send your email as plain text, instead of HTML?

Thanks,

Ben

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Re: How to take output from an include, and embed it into a variable?

2009-09-23 Thread Ben Dunlap
 $file = 'invoicetable_bottom.php';
 fopen(http://yoursite.com/folder/$file,r;);

 http://tr.php.net/function.fopen

 worth trying. Easier than output buffering

Easier in what sense? It would end up requiring more code than
output-buffering because you'd have to read from the file after
calling fopen(), check for end-of-file, etc., and it seems needlessly
inefficient because it:

- uses a function, fopen(), instead of a language construct, include()
- generates a superfluous HTTP request

I think it's also counter-intuitive. I ran across a similar technique
in some code I was reviewing and I had to really scratch my head and
wonder why the original author of the code did that, instead of just
getting at the file via the local file system.

Finally, it would require the OP to store an include()-ed file inside
of DocumentRoot -- which I personally prefer not to do when I can
avoid it (although that approach is debatable).

Ben

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] PHP Header issue

2009-09-18 Thread Ben Dunlap
 if ... you have
 output_buffering option enabled in the php configuration.

Which is probably the case on the OP's local machine, and would
explain why the code doesn't fail for him there.

Ben

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] ie6 memory could not be read help!

2009-09-17 Thread Ben Dunlap
 have IE 6 for whatever reason. If you block them then you are blocking
 possible clients. There is still a large percentage that still use it.

I think that percentage depends on the target audience. There was a
kerfuffle several months back (maybe a year ago now?) when 37signals
announced that they would no longer work around IE6's limitations in
Basecamp. A lot of people presented the above argument in the support
forums and they said, We've analyzed our logs and we know how many of
our users run IE6, and it's not very many.

My preference is to make sure my stuff is functional in IE6, but to
forget about pixel-perfect. But I tend to go light on Javascript in
general, so it's not that big of a deal usually.

Ben

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] APC - Upload progress problem. apc

2009-09-17 Thread Ben Dunlap
 I was afraid it was a bug. I have generally just used whatever is at
 whatever host, until this project, and didn't really think something so
 glaring could be in there. WTF!

I wonder if massive uploads, like the ones you're coding for, really
aren't that common. I can imagine hard-coding that 3600 myself, and
thinking, no way someone's going to be uploading a single file for
longer than an hour, or even close to it.

 So, it seems like it would be pretty straight forward to fix this, if I was
 willing to run on a custom version until this fix is released. Do people do
 that? What do you think?

After looking at it bit more, I found another PECL bug, same basic
underlying problem, that was fixed almost a year ago:
http://pecl.php.net/bugs/bug.php?id=14198

That's when the config option apc.rfc1867_ttl was introduced to APC --
but some of that hardcoded 3600 remained until a few weeks ago.

The older bug (14198) sounds exactly like your problem, so if I were
you I'd start by trying any of the official versions that include the
fix for 14198. That fix was committed on August 29 of 2008:
http://svn.php.net/viewvc?view=revisionrevision=265595

So the next version up (3.1.1) from what you're currently using will
include it. I guess 3.1.1 is still in beta but I'd personally go for
beta over a custom build, at least on a first pass.

Ben

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] ie6 memory could not be read help!

2009-09-17 Thread Ben Dunlap
 I bought a Windows XP PC about three years ago with IE6 on it (I
 normally do all my work in Linux). I haven't upgraded it, and I can't
 imagine why the average user would. If it ain't broke (and most users
 wouldn't consider IE6 broken), don't fix it.

I agree in general, but eventually Microsoft will stop releasing
security updates for IE6. It's hard to tell exactly, but right now it
seems like that may happen next July:
http://support.microsoft.com/gp/lifesupsps/#Internet_Explorer

At that point I would consider IE6 broke.

Ben

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] APC - Upload progress problem. apc

2009-09-16 Thread Ben Dunlap
 upload keys, and any keys created via apc_add(). This listing includes a
 Timeout value, which is none for the apc_add keys and 3600 for the upload
 keys. Somewhat suspicious, I'd say, since the keys stop being working after
 1 hour of use.

 APC lets you set a number of timeout values: apc.gc_ttl, apc.user_ttl,
 apc.ttl. I have set all of these to be gianormous, but the upload key
 timeout value never changes.

 I can't believe that this is an inherent limitation, or nobody would be
 using this. The Google claims people are using this for big uploads, so I

I've just had my first glance at the APC source code, so I could be
misreading something, but it appears that 3600 was hardcoded in until
about 3 weeks ago.

Here's the trunk commit that seems to have made that value configurable:

http://svn.php.net/viewvc?view=revisionrevision=287534

And there's a reference to a PECL bug in the commit message:

http://pecl.php.net/bugs/bug.php?id=16717

I have no idea when this change will trickle through to a production
build -- or if it already has, but I suspect not, because the
hardcoded 3600 was still present in the latest available source code
tarball at http://pecl.php.net/get/APC

Ben

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Creating alphanumeric id for a table

2009-09-14 Thread Ben Dunlap
 1. user A insert into table (get id = 1 from auto increment value)
 2. user B insert into table (get id = 2 from auto increment value)
 3. user A get value from $id = LAST_INSERT_ID() (id = 2)
 4. user B get value from $id = LAST_INSERT_ID() (id =2)
[8]
 How can we make sure that those 3 processes are atomic operation (insert
 table - get id from LAST_INSERT_ID() - update table) ??

From the MySQL 5.0 manual (20.9.10.3):

For LAST_INSERT_ID(), the most recently generated ID is maintained in
the server on a per-connection basis. It is not changed by another
client. ... Using LAST_INSERT_ID() and AUTO_INCREMENT columns
simultaneously from multiple clients is perfectly valid. Each client
will receive the last inserted ID for the last statement /that/ client
executed.

http://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html

Ben

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] User Account Management

2009-09-11 Thread Ben Dunlap
 Honestly, whipping up a security scheme the way I have done it is a
 couple of days' work (including login and management screens). I'm not
 sure why people seem to be averse to it. You just work up your screens,

I suppose it does depend on the use case. If you're building a system
for internal use, and you know your users, and the data is potentially
exposed by other avenues (as is the case with all the internal-use
systems I've built), that's one thing.

But if the site is public, indexed by Google, and gets even a small
amount of traffic -- or even if it's an unpublicized site but it's on
a dedicated IP that belongs to a prominent hosting company -- it's
going to be hammered daily by script-kiddies and PC-based malware. If
it gets a lot of traffic it's probably going to be targeted by
sophisticated attackers.

At that point I'd personally be much more at ease knowing that
session-management, authentication, password-storage, etc. were
handled by a system that several more-experienced programmers have
worked on, which has gotten a good deal of production use in diverse
contexts, not to mention possible analysis by professional security
experts.

Security is complicated and it's very easy to get wrong. What hashing
algorithm do you use (in the general sense of you) to store your
passwords?  Do you salt your passwords; if so, do you salt them
correctly? How do you handle password-resets? What's your PRNG, and is
it random enough, and how do you know?

I just reviewed the code for a scratch-built system that seemed to
have reasonably-intelligent authentication and password management --
but /completely left out/ access-control! All I had to do was enter a
different uid in the URL of the my account page and I could get to
anyone's account, even the admin's, as long as I was authenticated.

Dumb mistake? Sure. Easy to make? Probably more so than one would like to think.

Ben

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Hoping for a hand with a login script

2009-09-10 Thread Ben Dunlap
 So I'm trying to set up a small website that includes a store (
 www.rareintaglio.com), i have all of my HTML hammed out and now I'm working
 on creating an admin login for the sites owner to input data from a back

I would really strongly advise against building your own
authentication system. I'm currently regretting the fact that I did
the same, a few years ago, for a couple of systems I still support.
There are just too many things that can go wrong, especially if you're
new to PHP and MySQL in general. Just to begin with, the code you
posted currently suffers from a really basic SQL injection
vulnerability and your database is likely be compromised within hours
of your site getting any kind of significant traffic. That's
completely distinct from the more basic syntax trouble.

Perhaps paradoxically, the more experience you gain with these things,
the less inclined you will be, most likely, to try to roll your own
AAA.

There are lots of open-source PHP frameworks out there that should be
able to take care of authentication and access-control for you --
CodeIgniter, Zend Framework, and Solar come immediately to mind as
packages that I've either heard good things about, or suspect are
solid because of the authors involved. I'm sure there are several
other good ones also.

http://codeigniter.com/
http://framework.zend.com/
http://www.solarphp.com/

Ben

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Hoping for a hand with a login script

2009-09-10 Thread Ben Dunlap
 several packages available to provide it. But I believe that telling
 someone to adopt a complete portal system like CI just to get basic
 authentication is gross overkill. There has to be a better way to
 provide this core functionality without installing a monster package
 that will be 95% superfluous to their needs.

I mentioned CI because it got the second-most votes on a very popular
Stack Overflow question asking for PHP-framework recommendations. The
most-upvoted answer discussed Zend Framework, although it's hard to
tell whether it was a good review of ZF, or a negative one, on
balance:

http://stackoverflow.com/questions/2648/what-php-framework-would-you-choose-for-a-new-application-and-why

Without knowing more about the OP's requirements, it's hard to say
whether CI's other functionality would be largely superfluous. You
might be right, though, and I guess my point was just to recommend
that the OP look at existing, mature, free, open-source solutions
before possibly reinventing the wheel.

I would recommend this to anyone looking to build any sort of web app.
Could be that nothing out there will end up serving your purposes, but
just the experience of looking at existing frameworks, seeing how
they're structured, reviewing some of their code, etc., is still
likely to be valuable.

Ben

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Hoping for a hand with a login script

2009-09-10 Thread Ben Dunlap
 I would recommend this to anyone looking to build any sort of web app.
 Could be that nothing out there will end up serving your purposes, but

... and, on further investigation, it looks like CI, surprisingly
enough, doesn't actually have pre-built authentication and access
control (although it does do session management). Solar and ZF do seem
to have their own auth/access-control, though.

Ben

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Creating alphanumeric id for a table

2009-09-10 Thread Ben Dunlap
 I assume that I can get increment value/sequence from db  (I used harcoded
 increment value  in the code above (generate_id(1))),
 but I don't know how I can get this incremental value from db.I use mysql
 5.0.

If you're thinking of retrieving the newest value of an AUTO_INCREMENT
column, immediately after inserting a row, there are different ways to
do this depending on how you're connecting to MySQL.

PDO, for example, has a method called lastInsertId():
http://us2.php.net/manual/en/pdo.lastinsertid.php

And the mysql_* family of functions has mysql_insert_id(), etc.

Ben

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] script failing at same line

2009-09-09 Thread Ben Dunlap

 My solution was to add a table to my database, and add an insert job id
 into the table after the line that is causing the problem. When I submit the
 script I use setTimeout to run an AJAX query of the table 5 seconds later.
 If the line has failed the job id will not be in the table and I alert the
 user. It works - and some day I hope to fix the software problem and make
 this unnecessary.


Thanks for the update -- that's about how I would have approached it too.

I wonder, in general, if fixing the underlying problem is even practical or
worth the investment of time. IIRC the problem was in third-party code --
and it seems to me that making your own code robust enough to handle
failures in third-party libraries (as you just did) is a really fruitful use
of your time; fixing the library itself, maybe not so much. I guess it
depends on how it all affects your end users.

Ben


Re: [PHP] Re: Class variable value lost

2009-09-09 Thread Ben Dunlap
 The object only exists for that instance of the script, so when the user
 navigates to the next page, the object is freed up from the memory.
 There are a couple of ways you could get round this:

      * don't navigate away from the page, and use AJAX calls to update
        parts of the page for the user (bad imho, as it relies on
        Javascript)

I think any AJAX-based approached would run into the same difficulty,
because each AJAX call is a separate HTTP request from the one that
originally loaded the page (and from every other AJAX call).

Ben

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Encrypt then decrypt yields extra dots at end

2009-09-09 Thread Ben Dunlap
 I thought this code:

 $enc=mcrypt_ecb(MCRYPT_RIJNDAEL_256,salt123,encrypt_me,MCRYPT_ENCRYPT);
 $dec=mcrypt_ecb(MCRYPT_RIJNDAEL_256,salt123,$enc,MCRYPT_DECRYPT);
 echo $dec;

 would yield encrypt_me. The actual result is
 encrypt_me.. (bunch of extra dots).

 Why, and how do I fix it?

The manual says that mcrypt_ecb() is deprecated and recommends
mcrypt_generic() instead. Its page mentions that the input string will
be padded to the next-highest multiple of the current block size, and
points out:

'Note the string returned by mdecrypt_generic() will be [padded] as
well...use rtrim($str, \0) to remove the padding'

http://us3.php.net/manual/en/function.mcrypt-generic.php

So I would guess that mcrypt_ecb() operates in a similar way, which
can be solved with rtrim(). Does your script actually echo .
characters (ASCII 0x2E), or is that your terminal's way of
representing some non-printable character? It would surprise me if
mcrypt_ecb() used the . character as its pad, but maybe it does.

Ben

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] dns lookups only half working in chroot

2009-09-09 Thread Ben Dunlap
 ?php
 echo gethostbyname('www.google.de').\n;
 print_r(dns_get_record('www.google.de', DNS_A)).\n;
 ?
[8]
 I don't understand why the first lookup fails, but the second one succeeds.
 Unfortunately thinks like fsockopen() seem to use the same technique as
 gethostbyname(), so they don't work either.
 Any pointers would be appreciated!

PHP's gethostbyname() is a wrapper for the system call of the same
name, which may attempt to resolve the name using local mechanisms
(/etc/hosts, perhaps an internal cache, etc.) before resorting to a
DNS query. I've never studied any particular implementation of
gethostbyname(), but I wouldn't be surprised to find that in some
implementations it doesn't actually query DNS at all, but simply hands
off the name to another mechanism that queries DNS.

PHP's dns_get_record(), on the other hand, queries DNS using the
resolver(3) system calls. All it needs is a network connection and a
valid DNS server address.

So that should help explain why one can work while the other doesn't.
Not sure why gethostbyname() fails in your chroot environment, though.
I've seen situations where this has happened on my internal network,
but only fake hostnames that ended in .local were affected.

Ben

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] new php script and sqlite

2009-09-09 Thread Ben Dunlap
 I was under the impression that sqlite2 was supported widely by PHP,
 but sqlite3 seems only to be enabled on php 5.3.0 by default.

 My concern now is actually that users may find that their hosting
 service providers don't provide sqlite3 out of the box.

PDO seems to support both versions:
http://us.php.net/manual/en/ref.pdo-sqlite.connection.php

So if it's practical to restrict yourself to features that are
available in both versions, you could probably do something like this:

$db_file = 'filename';
$dbh = null;

try {
  // prefer sqlite3 if available
  $dbh = new PDO('sqlite:$db_file');
} catch (PDOException $e) {
   // verify that error occurred because sqlite3 is not supported
   try {
       $dbh = new PDO('sqlite2:$db_file');
   } catch (PDOException $e) {
       // bail out gracefully
   }
}

Ben

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] new php script and sqlite

2009-09-09 Thread Ben Dunlap
   $dbh = new PDO('sqlite:$db_file');
[8]
        $dbh = new PDO('sqlite2:$db_file');

But with double-quotes, not single-quotes. ;-)

Ben

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Performance of while(true) loop

2009-09-09 Thread Ben Dunlap
 I have a php cli script that listens on a UDP socket and, when data is
[8]
 So I think the the MSG_WAITALL is causing it to block until incoming
 data connection is closed (it never reaches the 512 byte mark before
[8]
 your clients are not maintaining an open connection to the socket,
 so it'll output as soon as the remote client disconnects from your
 server.
[8]
 if you will) on the socket until a connection is made and it reads 512
 bytes / the client disconnects, which seems to be doing well for your
 usage.

Sorry if I'm missing something obvious, but do the concepts of
connection, close, and disconnect even apply in this case, since
it's a UDP socket?

Ben

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] script failing at same line

2009-09-04 Thread Ben Dunlap
 $map = ms_newMapObj($mapfile);

 The command creates a new mapscript object.


And PHP is hanging somewhere inside that constructor? Is this in a web
context or a command-line context? Or both?


Re: [PHP] script failing at same line

2009-09-04 Thread Ben Dunlap
On Fri, Sep 4, 2009 at 2:38 PM, jim white jbw2...@earthlink.net wrote:

 It's a web app that draws maps in a browser. Sometime it will generate a
 seg fault. The command should not take long, so if there is some script
 construct that will throw an exception after a few seconds if the command
 has not completed I could signal the user that the map will not draw and to
 reload the page.


There's a pecl extension called Libevent that can apparently trigger an
action to occur after a certain amount of time has elapsed:

http://us3.php.net/manual/en/ref.libevent.php

I've not used it and have no idea how mature or reliable it is. I'm also
wondering whether any solution will work that relies on the same script
that's about to trigger a segfault.

I think I'd be inclined to build an XHR-based monitor to run in the user's
browser. Even simpler would be to start the map-building process
asynchronously with XHR and then just alert the user, or automatically
refresh the browser, if a certain amount of time elapses before you get a
response from the map-building script. But I don't know how much you'd have
to alter your existing client-side code to use the latter method.

Either way it's creeping away from PHP so maybe I should leave it at that.

Ben


Re: [PHP] Searching on AlphaNumeric Content Only

2009-09-03 Thread Ben Dunlap
 Excuse me? Somebody suggested a PHP loop to solve a query problem and you are 
 saying that REGEXP should not be used?
 MySQL caches queries and 100 SELECT with a REGEXP will cost zero after the 
 first one if nothing changed inside the table.

Even if the REGEXP has to change with every query?

Performance aside, I think REGEXP() could be used here, but not in the
way you've suggested. As the OP has described his table, your regex
(^[a-zA-Z0-9]+$) won't match any rows, because all of his product
IDs have non-alphanumeric characters in them.

Suppose this table:

pk  | prod_id
1   | 07-ABCD-98
2   | 98-ZCXQ-21

And now suppose the OP's scenario, where a user tries to search on
product id, but enters 07ABCD98.

If the aim is to use REGEXP() to return row 1, I suppose you could
intersperse the search string with .? sequences and end up with this
query:

SELECT * FROM table WHERE prod_id REGEXP '^0.?7.?A.?B.?C.?D.?9.?8$'

I think just stripping the alphanumeric characters would end up being
more flexible, though.

-Ben

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Searching on AlphaNumeric Content Only

2009-09-03 Thread Ben Dunlap
 What's wrong with using the wildcards that are built into most SQL
 variants?

 SELECT * FROM table WHERE item_id LIKE '%#abcdef'

 Will select all records where the item_id field ends in '#abcdef'

That works if you know the user is always going to enter the last 7
characters of the product id, but that's not how the OP characterized
the problem. The OP talked about search strings where multiple
characters had been omitted from different parts of the product id.

Ben

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Magento shows blank page.

2009-09-03 Thread Ben Dunlap
 I followed this thread:
 
 http://spikomoko.wordpress.com/2009/08/19/magento-not-working-on-php-5-3/
 .

 But then, I'm bounched on this error in my webbrowser for visitting my
 magento on my production server desktop:
 
 .:
 Fatal error: Call to a member function createDirIfNotExists() on a
 non-object in /var/www/html/magento/app/Mage.php on line 644

Sounds like your version of Magento isn't compatible with PHP 5.3 (and
perhaps less-recent releases also?).

Is there a newer version of Magento available?

Ben

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Searching on AlphaNumeric Content Only

2009-09-03 Thread Ben Dunlap

 stripping, stemming, spelling corrections ?
  ... uhm, that's probably why they invented regular expressions, isn't it?

 As I said, at the end of the day, this will be a manual slow, potentially 
 wrong implementation of what we already have and use on daily basis.

If you've got a regular-expression-based method in mind that simply
nails the OP's problem, please share. I'm still not seeing how
regular expressions is a sufficient answer to the OP's problem,
which is basically fuzzy search.

My sense is that regular expressions are for situations where you
basically know just what you're searching for, but don't really know
where it falls in your search space.

The OP, on the other hand, is building a system where he won't know
just what he's searching for -- all he'll know is that his search key
is sort of like the thing he actually needs to find.

You might be able to squeeze this problem, or at least some part of
it, into a regex-based solution, but I don't think it's a natural fit.

Ben

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] CodeWorks 09

2009-09-02 Thread Ben Dunlap
 What I would do for UK PHP events :-(

Something like this perhaps?

http://conference.phpnw.org.uk/phpnw09/

Ben

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Generic decorators and type hinting

2009-09-02 Thread Ben Dunlap
 Is there another way to cleanly wrap method calls for timing/logging
 purposes?

I have a possibly-evil idea that gets around type-hinting by
dynamically declaring decorator classes as children of the real
classes that need to be timed. You end up with as many decorators as
you have classes that need to be timed, but if this is for dev/QA
purposes only, that might not be a problem.

This method can't have the conceptual simplicity of yours,
unfortunately, because __call() will never be invoked in a child
class. The original parent's methods will just be called instead. But
you can still override the parent's methods with wrapper methods in
the child class.

I've got some sample code written that first calls get_class_methods()
to list the names of all the visible methods of the parent object,
then constructs code to declare a child class that overrides those
methods with wrapper methods, and finally eval()s the declaration and
instantiates an object of the new class.

The basic concept seems to work and to get along fine with
type-hinting. I'm happy to share the test code if you're interested.
Not sure how it would end up working in real life, and I'm guessing
there are more sophisticated ways to achieve the same concept, perhaps
using the Reflection API. I suspect it also needs some refining to
handle protected methods. But it might be a start.

Ben

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Generic decorators and type hinting

2009-09-02 Thread Ben Dunlap
 code.  Instead, just use interfaces.  The only real downside is that
 all the classes you want to decorate would need to implement them and
 that would cause a wee bit of ugliness in the code/class declaration.

Can you explain a bit more? As I understood the OP, the challenge was
to take a large, already-built code base that relies on Zend Framework
(which itself has 1600 classes), and wrap arbitrary existing methods
with timing logic -- without significant code changes.

As I understand your solution, it would require all pre-existing
classes to be modified to implement the iDecorator interface -- and
even then, pre-existing methods in those pre-existing classes would
not actually be affected. So those would have to be modified also.

But maybe I'm totally missing something?

Ben

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Searching on AlphaNumeric Content Only

2009-09-02 Thread Ben Dunlap
        Is there is a way to search only for the alphanumeric content of
 field in a db?  I have an itemID field that contains item #'s that include
 dashes, forward slashes, etc, and I want people to be able to search for an
 item # even if they don't enter the punctuation exactly.

Not sure if there's anything specifically PHP-ish that will help you
here, but I would be inclined to start by storing a stripped-down
version of the item ID (alphanumeric characters only) in a separate
column in the database table.

Then, when a user enters some search data, I would remove
non-alphanumeric characters, if any, from the user's input, and then
search the stripped column with this normalized version of the input.

If you want even fuzzier matching (inadvertent transpositions or an
omitted character or two OK, for example), you might read about
Levenshtein distance:

http://en.wikipedia.org/wiki/Levenshtein_distance

PHP has a levenshtein function but you'll have to figure out a way to
use it efficiently with your data set. Or, if Levenshtein isn't quite
right for your needs, the article above might at least point you in a
useful direction.

Ben

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] safe_mode and inclusion of files don't work as documented

2009-09-01 Thread Ben Dunlap
 Safe mode is a bad idea. :) It's not safe; it may only have the effect
 of making you think you're safe. If you have a particular reason to
 use it then maybe it's OK, but just be aware that it will not exist in
 future versions of PHP and relying on it is not a good idea. Security,
 unfortunately, is not as simple as toggling a configuration variable.

Yes -- and I always look askance at shared-hosting providers who rely
on safe_mode and call it a security measure. Then when I'm done
looking askance, I take my business elsewhere.

Ben

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] I'm not crazy I swear it... IE vs Safari and Firefox - The impossible!

2009-08-31 Thread Ben Dunlap
 I would set up Wireshark to capture and compare the http sequences from
 each browser. After you capture each stream, use the Follow TCP Stream
 option to look at the raw HTTP. If it is the browsers, there should be
 some obvious differences in the sequence of requests from them.

This is a good idea, although the Net panel in Firebug would be a very
quick preliminary step to this more systematic approach. And it might
be all you need.

Firebug will parse out the HTTP very nicely for you and the best of it
is that you can watch the requests as the browser sends them, without
even looking aside to another window.

Ben

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Error when execute header('location: otherpage.php') after email been sent out. Any Workaround?

2009-08-28 Thread Ben Dunlap
 Which format should I used for log file? *.log or *.txt?

Doesn't matter to PHP -- but you do need to provide a local path, not a URL.

 [http://domain.com/log/logfile.*] or

No...

 [C:\some_path\domain.com\log\logfile.*] or just

Yes!

Ben

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Re: Best way to test for form submission?

2009-08-28 Thread Ben Dunlap
I was surprised when no one recommended this:

   if ($_SERVER['REQUEST_METHOD'] == 'POST')

So now I'm wondering if there's a pitfall to this method that I'm not
aware of...

Thanks,

Ben

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Re: Best way to test for form submission?

2009-08-28 Thread Ben Dunlap
 Well, as far as I'm aware $_SERVER isn't reliable from server to server.
 That said, I've never had a problem using it.

Thanks -- I just looked it up and the manual says: There is no
guarantee that every web server will provide any of these; servers may
omit some, or provide others not listed here. That said, a large
number of these variables are accounted for in the » CGI 1.1
specification, so you should be able to expect those.

So I guess it wouldn't make sense to rely on anything in $_SERVER if
you're building an app for widespread use; e.g., CodeIgniter, as
mentioned above.

 tend to use the $_REQUEST array instead of $_POST or $_GET. You get the
 benefit of being able to work with both arrays (as well as $_SESSION and
 $_COOKIE) without any drawbacks.

For now I'm inclined against $_REQUEST, since it's not yet supported
by filter_input(). I think filter_input() is the bee's knees and I've
stopped touching $_POST or $_GET directly since I discovered it.

Ben

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Re: unset() something that doesn't exist

2009-08-27 Thread Ben Dunlap
 ISTR the Royal Air Force has a Specialist Aircrew track where the really 
 good
 pilots, who wanted to fly planes rather than desks, could be promoted to
 management ranks but avoid the management duties.

They had a position like this at the first big company I worked for --
Member of the Technical Staff. These folks were very good at what
they did, but again, not interested in, or perhaps not suited for,
management.

Ben

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] phpmailer send() always return true even the emailaddress is invalid

2009-08-27 Thread Ben Dunlap
 another change in the email admin best practices discussion. For a short
 while the network became clogged in bounce messages sent to both valid
 and invalid addresses. Some of the invalid addresses even triggered
 infinite loops of error messages. None of the servers I am familiar with
 send bounce messages reporting invalid addresses any more. Our own
 servers won't even tell us internally when they discard incoming
 messages. SPAM quarantine is a thing of the past.

Seems like there's another possible way to handle messages to invalid
addresses, though; the receiving SMTP server can simply reject the
RCPT TO command with a 5xx error. This avoids backscatter but also
lets well-behaved clients know that the destination address is
invalid. AFAIK this is how Rackspace Email works (if you don't have a
catch-all address configured).

Ben

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] phpmailer send() always return true even the emailaddress is invalid

2009-08-27 Thread Ben Dunlap
 The second problem is that it still forces the originating SMTP server
 to pass on the 5xx error as a bounce message to the originator.

Yeah, I guess this would be a problem in cases where the originating
server is an open relay that's being exploited by a spammer. I wonder
what proportion of spam is sent in this manner -- and and how much, on
the other hand, comes from a direct SMTP conversation between a
malicious client and the MX server of the recipient's domain.

Ben

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] vote package

2009-08-27 Thread Ben Dunlap
 You might try to use the reported IP of the submitter, again unique, but
 that can be forged -- so again anyone can vote more than once.

Can you say more about forging the reported IP? I've always been under
the impression that forging the source IP in a TCP session is a pretty
sophisticated operation, but maybe I'm mistaken about that.

Of course source IP isn't a reliable unique-ID, for the opposite
reason also: forward proxies, NAT, etc., make it pretty likely that
several users will come to the site from the same IP. So you'd end up
incorrectly refusing legitimate votes.

Ben

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] user permissions

2009-08-27 Thread Ben Dunlap
 Sort of. Create two tables a login table with user details and a specific
 field for a ROLE.

 Then create a roles table that lists the various permissions. I store this
[8]
 This process is significantly simpler when managing users, it's easier to
 adjust permissions on one role than to edit a bunch of users when something
 changes.

In this mechanism, does a role differ significantly from a group?
I have to admin a CRM system that has both roles /and/ groups, and it
always seems a bit excessive. But maybe there's some benefit to roles,
as such, that I'm not seeing.

Thanks, Ben

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] user permissions

2009-08-27 Thread Ben Dunlap
 Yes, they offer an additional layer of granularity on permissions. The apps
 I write use groups and role to limit acces to certain functionality. The
 roles determine functional access to records, ie what the user can do with
 them. The groups membership determines what records the user can see. E.g.

But is this substantially different from just allowing groups to
determine access to functionality, /and/ access to records, and
letting the admin create different groups for different reasons? I
guess I'm thinking of the way Active Directory works, which I've
found, in my second life as a system administrator, to be both easy to
grasp and extremely flexible/powerful.

Ben

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] What if this code is right ? It worked perfectly for years!!

2009-08-26 Thread Ben Dunlap
 ?
  $fName = $_REQUEST['fName'] ;
  $emailid = $_REQUEST['emailid'] ;
    $number = $_REQUEST['number'] ;
  $message = $_REQUEST['message'] ;

  mail( ch...@gmail.com, $number, $message, From: $emailid );
  header( Location: http://www.thankyou.com/thankYouContact.php; );
 ?

This is a bit of a hang-up of mine so forgive me if it's mildly OT,
but if you do figure out what the problem is, and fix it, you may want
to revisit this code in a more extensive way, if what you've pasted
above is exactly the code you use in your live application. Please
ignore if you've simplified the code above for simplicity's sake.

At any rate the code above is most likely vulnerable to SMTP
injection, because it passes the unfiltered value of '$emailid' as
part of the 'additional_headers' argument to mail().

So the form could be used to send spam to arbitrary email addresses.
I'd recommend using filter_input(), with the FILTER_VALIDATE_EMAIL
filter, to get at the 'emailid' parameter:
http://us3.php.net/manual/en/function.filter-input.php

Ben

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Re: PHP and CGI

2009-08-19 Thread Ben Dunlap
        That's exactly the case.  I have been running my business on a Perl
 cart for the last 5+ years, and I can't switch to a PHP cart just yet.  I
 was just hoping to add some functionality with PHP.  Perl was much harder

It would probably bomb your performance but you could always call a
separate PHP script from your Perl code:

#!/usr/bin/perl

# do some stuff in perl

my $php_output = `/usr/bin/php whatever.php`

# do something with $php_output

1;

If you're just looking to add some features quickly to your existing
Perl code: Have you searched CPAN for what you need?

Ben

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] SESSIONS lost sometimes

2009-08-19 Thread Ben Dunlap
 We have a server with a site that does some XML calls. After lots of testing
 I have found that the server is losing session variables.
[8]
 Also the site goes from HTTP to HTTPS at some point but this isn't the issue
 as it loses the sessions as soon as they are set sometimes.

 Therefore I would like to know what I could check. I have read in other

Can you clarify what you mean by losing sessions? Have you taken a
network trace to see whether the client is consistently sending the
session ID with every request?

When the problem happens, is $_SESSION completely empty or is it only
missing some variables? Does it seem to happen on any page, or only
certain ones?

Thanks,

Ben

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Sanitizing mysql inserts of user data

2009-08-17 Thread Ben Dunlap
 Note: If this function is not used to escape data, the query is
 vulnerable to SQL Injection Attacks.

 Does that necessarily imply this:
 If this function is used to escape data, the query is not vulnerable
 to SQL Injection Attacks.?

 Logically, it does _not_ mean the same thing.

Definitely not -- it would be a bit presumptuous to claim If you do
X, the query is not vulnerable to SQL injection attacks for just
about any value of X.

That said, I would recommend binding parameters if you can. It's a
cleaner way of separating the logic of a query from its data, and
theoretically more reliable than mysql_real_escape_string():

http://en.wikipedia.org/wiki/SQL_injection#Parameterized_statements

Ben

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] is there a better way to know from which php file the request comes from ??

2009-08-17 Thread Ben Dunlap
 This is a newbie question...
 Let's say there are 3 php files, page1.php, page2.php and page3.php. Form
 submission from page1.php or page2.php will take user to page3.php.
 I know that we can use parameter that is appended in the action attribute of
 the form (e.g FORM METHOD=POST ACTION=tes.php?var1=val1)
 But I think, appending this parameter is transparent to the user, since it's
 visible in the url.

Why does it matter?

I don't meant to suggest that it doesn't, but I'm just wondering if
you could explain the design of your app a bit.

You've sketched out an attack scenario in which a user maliciously
alters a variable in the request so that page3.php thinks the request
is coming from page2.php, when in fact it's coming from page1.php --
or vice versa.

But suppose an attacker does trick page3.php into mistaking the origin
of the POST. Does it make a difference? Presumably page3.php will be
filtering all of its input, and will discard the request if, for
example, it claims to be from page2.php but doesn't contain the sort
of data that a request from page2 would contain.

But if it does contain the right data, and the data is valid, then
does it matter if the data was not actually collected on page2.php?
The statelessness of HTTP can be one of its beauties -- and I would be
inclined against introducing statefulness unless the app really needs
it.

At any rate your problem is reminiscent of CSRF:

http://en.wikipedia.org/wiki/Cross-site_request_forgery

And I'm wondering if you could borrow from anti-CSRF techniques to
solve it (assuming, again, that it really needs to be solved).

Ben

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Sanitizing mysql inserts of user data

2009-08-17 Thread Ben Dunlap
 $stmt = $db-prepare(SELECT priv FROM testUsers WHERE
 username=:username AND password=:password);
 $stmt-bindParam(':username', $user);
 $stmt-bindParam(':password', $pass);
 $stmt-execute();
[8]
 I haven't followed this thread, so I don't know what you mean by, I
 do not see how there could possibly be a prepared statement for a user
 comment. Maybe someone else can answer that part of your query.

Thanks Paul, that was a much better explanation than the one I was
attempting. I'm guessing the OP was being thrown off by the colons in
the SELECT statement above. I can see how those could look like
comments to someone not familiar with PDO and named parameters.

Ben

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] session variables - help

2009-08-14 Thread Ben Dunlap
 Thanks all for your patience! I will work on this today and write back with
 any further questions I can't figure out on my own. And if anyone has any
 advice I will be checking my email regularly.

If you've already tried this with no luck, please ignore -- but you
might speed up the whole process by stepping aside from the real
code briefly, starting fresh in an empty directory, and just putting
together a handful of extremely simple scripts with the single goal of
entering one value, updating it, and then doing some final
pseudo-processing on the updated value.

Then, you could step it up a bit by by adding a second value that gets
entered at the beginning, and cannot be updated in the middle but must
be preserved through to the end.

Doing all this might help clarify the basic flow of the system and
enable you to simplify its structure before going back and tackling
the real code.

Ben

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Re: ini files as config - hidden

2009-08-14 Thread Ben Dunlap
2009/8/14 João Cândido de Souza Neto j...@consultorweb.cnt.br:
 I think a good solution is to put the ini file out of your html folder so
 only your scripts can read it.

I agree, and I try to do the same, but I've noticed that most
open-source CMSes I've looked at (Drupal, Joomla, Textpattern, CMS
Made Simple) have always stored database credentials inside of
DocumentRoot, by default.

Not sure if this is a compromise to allow ease-of-use by
less-technical users, or if my insistence on putting this sort of file
outside of DocumentRoot is just paranoia (and not the good kind).

I'd definitely be interested to hear how others on the list approach
this problem.

And that's only one part of the equation, if you're on a
shared-hosting platform. Are you, or do you have your own server?

Ben

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Re: ini files as config - hidden

2009-08-14 Thread Ben Dunlap
 1) Name your ini files .php so, database.ini will be database.php

Actually I was assuming the configuration file to be a PHP script --
as is typical in big open-source CMSes. I took ini file earlier in
the thread to be a generic description of any file, whatever the
extension, that contains sensitive configuration data.

 Our data will be safe as long as the first line will remains there.

And as long as the file is actually handed off to PHP for processing.
Seems like there are plenty of situations, none of them too
far-fetched, that could cause the web server to mistakenly serve a
file with .php in its name as a generic text file rather than
handling it correctly. I'd rather just have the file outside of
DocumentRoot and avoid that risk entirely. But again, maybe that's
just unproductive paranoia?

Ben

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] session variables - help

2009-08-13 Thread Ben Dunlap

 I have the following code for order_update.php:

 [code]

 session_start();
 extract($_POST);
 foreach ($_POST as $var = $val) {
  if ($val  0) {
  $_SESSION[$var] = $val;
  } else {
  unset($var);

  }
  header(Location: order_process.php);
 }

 [/code]

 This is not working, however, and it just loads order_process.php with no
 values for the varaibles, as if I just refreshed the page with no sessions.


Maybe you left it out but I didn't see any place where you used $_SESSION in
order_process.php. Also, your redirect in order_update.php appears to be
inside your foreach loop, which would definitely mess things right up -- but
maybe that was just a typo in your email?

Otherwise the logic in order_update.php looks OK, but there are a few side
notes that jumped out:

1. I'm not seeing why you used extract($_POST) in order_update.php. Right
after the extract() call, you iterate through $_POST with a foreach loop, so
what's the purpose of calling extract()? Is there more code that you left
out?

2. Calling extract($_POST) is dangerous. The PHP manual warns against it,
although without giving much of an explanation:

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

Apart from making it difficult to filter the input you're expecting to see,
extract($_POST) also allows a malicious end-user to define any variable of
his choosing and to overwrite any variables that you may have defined in the
script before the extract() call.

I like to use filter_input() to read the values of POST variables.

By much the same token, you'll want to escape $a, etc., in your
writeResultRow() function, with something like htmlentities().

3. Why the unset($var) in order_update.php? $var already gets reset each
time foreach iterates. So, calling unset() on it at the end of the loop
doesn't really do much. I'm wondering what you were aiming at there.

Thanks,

Ben


Re: [PHP] how to say inverse your value (to a boolean)?

2009-08-11 Thread Ben Dunlap
 # before was $styles = array( 'even', 'odd' );
 # after new requirements it is...
 $styles = array( 'white', 'white', 'gray' );
 foreach($items as $item)
 {
 printf( 'li class=%s%s/li', current( $styles ), $item );

 next( $styles ) or  reset( $styles );
 }


+5000. I think is by far the most readable and flexible solution suggested.
I also like it because it's PHPish -- it uses the features of the language
that were made-to-order for this problem.

Ben


Re: [PHP] Embedding foreach loops

2009-08-11 Thread Ben Dunlap
 statements, it becomes unmaintainable very quickly, use a templating
 language, ether with a framework(recomended) or standalone.


But he /is/ using a templating language... PHP. ;-)

Ben


Re: [PHP] Single quoted strings (was: ereg_replace to preg_replace translation)

2009-08-11 Thread Ben Dunlap

 Personally I try to not use double quoted.
 PHP parses single quoted very much faster.

 # for this
 echo Hi, $name, wellcome $home;

 # I use
 echo 'Hi, ', $name, ', wellcome ', $home;


I'm not sure if this was true in older versions of PHP, but it's not so much
any more, and I wonder if it was ever worth the loss of readability.

Interesting discussion about this on the Google Group Make the Web Faster.
The focal points of the discussion are an article by a lead Google engineer,
and then a point-by-point refutation by a PHP core developer. Here's the
refutation:

http://groups.google.com/group/make-the-web-faster/browse_thread/thread/ddfbe82dd80408cc

Ben


Re: [PHP] Image Headers break when image is out of bounds

2009-08-11 Thread Ben Dunlap
 @Adam
 The headers_sent() wasa  test to ensure that no other data was creeping
 into the headers before I wanted it to. Keeping it in does no harm, as
 it is basically saying, if there are no headers that have been sent,
 send the correct ones for the image.


But if there are headers that have been sent, it sounds like they would not
have been the correct ones. Which I think would cause exactly the problem
you're describing.

Ben


Re: [PHP] Image Headers break when image is out of bounds

2009-08-11 Thread Ben Dunlap
On Tue, Aug 11, 2009 at 11:52 AM, Ben Dunlap bdun...@agentintellect.comwrote:


 @Adam
 The headers_sent() wasa  test to ensure that no other data was creeping
 into the headers before I wanted it to. Keeping it in does no harm, as
 it is basically saying, if there are no headers that have been sent,
 send the correct ones for the image.


 But if there are headers that have been sent, it sounds like they would not
 have been the correct ones. Which I think would cause exactly the problem
 you're describing.

 Ben

 Oops, looked back at your earlier post and it sounds like you only send the
image inside the if(!headers_sent()) block. Never mind, pls disregard my
earlier noise.

Ben


Re: [PHP] how to say inverse your value (to a boolean)?

2009-08-11 Thread Ben Dunlap
 # before was $styles = array( 'even', 'odd' );
 # after new requirements it is...
 $styles = array( 'white', 'white', 'gray' );
 foreach($items as $item)
 {
 printf( 'li class=%s%s/li', current( $styles ), $item );

 next( $styles ) or  reset( $styles );
 }


  +5000. I think is by far the most readable and flexible solution
 suggested.
 I also like it because it's PHPish -- it uses the features of the language
 that were made-to-order for this problem.


 Actually it's the wrong way to do it.

 Change the class names to alternate1 and alternate2 (or something else
 meaningful without being tied to a definition). That way when you set the
 colour for style white to green it doesn't result in confusion.
 Seriously though... this is nomenclature 101.


Good point, and thanks for the presentation-vs-content reality check. I'll
downgrade my vote to a more sober +4990, in consideration of the class names
in $styles.

Ben


Re: [PHP] Embedding foreach loops

2009-08-11 Thread Ben Dunlap
 statements, it becomes unmaintainable very quickly, use a templating
 language, ether with a framework(recomended) or standalone.



 But he /is/ using a templating language... PHP. ;-)


 Keep telling yourself that... and be sure to pat your own back.


I'm sure there are plenty of situations that call for a more focused
templating system than the one that PHP already is. And there are plenty
that don't.

From the earlier content of this thread, I suspect the problem the OP is
currently working on falls into the latter camp. Didn't mean to bash
templating systems.

This is probably flame-war tinder, so I'll try to tread more delicately in
the future. Next you know we'll be on the ternary operator and which is
better, Mac or Windows. ;-)

Ben


Re: [PHP] Embedding foreach loops

2009-08-10 Thread Ben Dunlap
 $shows = array();
  $show_01 = array();
  $show_01['title'] = 'Van Cliburn Gold Medal Winner';
  $show_01['date'] = 'Tues. 10/13/2009';
  $show_01['time'] = '11am';
  $show_01['price'] = 4.00;
  $show_01['soldout'] = 0; //IF THE SHOW SELLS OUT, CHANGE 0 to 1
 (without quotations).
  $shows['show_01'] = $show_01;
[etc.]

If I'm setting up a lot of static data ahead of time like this, I
prefer a slightly simpler syntax (or at least it seems simpler to me):

$shows = array(
'show_01' = array(
'title' = 'Van Cliburn Gold Medal Winner',
'date' = [etc.]
),
'show_02' = array(
'title' = [etc.]
),
[etc.]
);

And sure, you could do all this in a database, or some other sort of
external storage, but unless you're looking at creating a separate UI
for someone other than yourself to input the data, it's probably
simpler all around just to define the data directly in PHP. No reason
you couldn't upgrade to something more sophisticated down the road, if
the customer requires it.

Ben

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Embedding foreach loops

2009-08-10 Thread Ben Dunlap
 I am using the print function to display my html. I cannot get the line
 return ( \n ) character to actually push the html onto the next line, it
 just gets displayed instead. Should I be using echo?

In the PHP code snippet you pasted above, you're using single-quotes
to delimit your literal strings. In-between single-quotes, '\n' is not
converted to a newline character. It's interpeted completely
literally:

http://us.php.net/manual/en/language.types.string.php#language.types.string.syntax.single

Also, are you looking to insert a line break into the HTML itself --
just to keep your HTML code clean -- or into the visible page that's
rendered from the HTML? Because newlines don't have any significance
in HTML. You'd need to insert a br / or close a block-level element
to get the effect of a line-break in the visible page.

Ben

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] use preg_replace to nix and line with display: none

2009-08-09 Thread Ben Dunlap
  $pattern = '|^.+?display:none.+?$|mi';
[8]
 I found your use of ? rather... creative...  Anyway, just add the

You mean the non-greedy flag? I think that's necessary the way the
regex was originally formulated -- without it, .+display would
gobble up all of the list-items until the last one.

Ben

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] reason for a Notice:.. on one site but not another? (Same code.)

2009-08-09 Thread Ben Dunlap
 But on another site it still works, but gives this error:
 Notice: Undefined index: UserWishesDateRange in
 /home/vs/site/phvs/bl/7solarsecrets/admin/trackingcode.html on line 79

 I assume that is because the error display settings are set to a more
 rigorous level in this latter site.
 Is this correct?

It's either the 'error_reporting' configuration directive that's
different between the two servers, or 'display_errors', or both.

On one server the E_NOTICE bit-field is set in 'error_reporting', and
it sounds like 'display_errors' is also set (unless you're seeing that
notice in a log file).

On the other server, one or the other of those things is not set (or
both of them aren't).

You can use call ini_get('error_reporting') and
ini_get('display_errors'), to see what they're set to on each server.
Or just create a small page that only calls phpinfo(), to see all
configuration directives.

Here's the write-up of the directives (one is right below the other):

http://us3.php.net/manual/en/errorfunc.configuration.php#ini.error-reporting

As others have pointed out, it's a good idea to call isset() on a
POST-variable before trying to get at its value. This will avoid a
notice being thrown.

Lately I've stopped touching $_POST directly and started using
filter_input() instead; this also avoids the problem and provides
several other benefits:

http://us2.php.net/manual/en/function.filter-input.php

The filter_* functions are only available in core since 5.2.0, though.

Ben

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



[PHP] Re: Server change affecting ability to send downloaded files???

2009-08-07 Thread Ben Dunlap
 changes to the code or to the files, just one day all of a sudden any
 time someone purchases a DMG, EXE, PDF, etc. they get zero bytes. I've
[8]
 Has anyone ever heard of something (besides my code and my files) that
 could cause this behavior? You'll be my best friend if you can help.
 Thanks.

That list of failing file types makes me suspect some sort of anti-malware
software at the perimeter of Rackspace's network. Could also be anti-malware on
the users' machines, but if this is happening to a wide cross-section of users,
I'd doubt the latter.

Plus, in the latter case, I would expect the users' machines to end up with no
file on disk at all, but it sounds like they're getting empty files instead.

You'd think Rackspace would know about potentially destructive changes to their
perimeter, but my experience with their first-level support is that they are
wonderfully friendly and well-intentioned but could sometimes be
better-informed.* Have you been able to push through to second-level support or
beyond?

You might have to tweak your code a bit to support your case to Rackspace (and
make double-darn-sure it's actually not your problem): for example, you could
grab the return value of readfile() and write it to a log file (or just call
error_log() to write it to the PHP error log).

This will prove that your code is actually sending bytes across the wire. Even
if your headers are wrong -- which they obviously aren't, if the code works for
some file types -- your users shouldn't be getting 0 bytes if readfile() is
reporting otherwise.

Ben

*I don't intend to bash on Rackspace here -- I'm a very happy customer of
theirs for email and Cloud Servers. I always give them an 8 or a 9 on
customer-satisfaction surveys, and then explain my frustration with their
first-level support in the comments section.

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Server change affecting ability to send downloaded files???

2009-08-07 Thread Ben Dunlap
 Very interesting. Excellent debugging advice. It's giving me a 500
 error, probably why the Rackspace techs told me to check my code:
 
 HTTP/1.0 500 Internal Server Error

Did you get that 500 while running curl from a machine outside of Rackspace's
network?

If so, I'd be interested to see what you get if you run it from the server's
command line (using 'localhost' in the URL you pass to curl).

Have you checked your Apache error log as well, and PHP's? There will usually
be more detail in those locations when the server sends a 500.

Ben

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Displaying user data and picture

2009-08-06 Thread Ben Dunlap
 I don't have any data blobs in my database - which makes incremental
 backups easier - I use rsync for files and do a nightly mysql dump.
 Except for the first of the month, the diff of that nights backup
 compared to first of month is saved to flat file for rsync. Binary blobs
 in the database would likely mean I have to change my backup protocol,
 but if it really is advantageous, I'd do it.

This is just an aside but are you aware of the '--hex-blob' argument to
mysqldump? It causes binary data to be dumped as a hexadecimal string:

http://dev.mysql.com/doc/refman/5.1/en/mysqldump.html#option_mysqldump_hex-blob

It's space-greedy (every byte in your original data requires two bytes in the
dump file) but it seems like it would be compatible with your mysqldump/diff
approach.

Ben

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



[PHP] Re: Time keeping in DB

2009-08-05 Thread Ben Dunlap
 sorry man, but a good data design keeps only data in a table u can not
 calculate. in ur case that would be only date start and end time.
 refernces to user and project/tasks in other tables.
 
 ur time sheet is definately a job for a report. that type of design limits u
 to nothing. a user can start ans stop as many times he wants a day or time
 range. u can report any number of time bits to any number of project a day
 or time range

I agree (unless the app just doesn't have access to the start/stop data).

Ben

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



[PHP] Re: Time keeping in DB

2009-08-05 Thread Ben Dunlap
 OK, I think I understand most points except the start and stop time.
 Every time sheet I have used, SAP and several other smaller ones, I
 enter a weeks worth of time data like:
 
 Project   Sun Mon TuesWed ThurFri Sat
 ---
 Grill steaks  8   8   8   8   0   
 Vacation  0   0   0   0   8
 
 So why wouldn't I store the dates and the hours instead of start and
 stop times?
 

Maybe it comes down to what the users of the app prefer (or what you prefer, if
you're building this app for yourself).

From a user's perspective, I like start/stop data-entry better. I love that I
can do this in Freshbooks, for example -- just click 'start' and then later
click 'stop', 'log hours' -- and I never have to think about things like how
many hours are there between 11:26am and 2:12pm?

I think Ralph's point was that start/stop data is about as granular as any sort
of time-keeping data gets, so if you store only start/stop data, you have
ultimate flexibility in the way you can manipulate that data in your app.

And it's probably a reasonable generalization that the most forward-looking
database designs will store data in as simple and raw a form as possible. Or as
Ralph put it, a good data design keeps only data in a table u can not
calculate.

With start/stop data, you could create weekly timesheets like the one above, in
PHP -- and you could also figure out how many hours you log before noon, on
average, etc.

On the other hand, if the simplest data you enter is already the implicit
result of a calculation (stop_time - start_time), you've limited the
flexibility of your app from the get-go. But maybe that limitation isn't
significant for the app you're building.

Ben

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Multiple MySQL Queries

2009-08-04 Thread Ben Dunlap
 Sorry... I'm using GET.  I have used the code you supplied below,
 but as I mentioned, it gets sent for every itemid in the table.  I needs
 to be sent only once, and right after the action.  That's where I'm
 stumped.

Hidden form inputs should work with GET or POST -- they're only hidden from
being displayed on the page where the form is displayed.

I don't follow what you mean by it gets sent for every itemid -- can you post
an example of the query string that's being generated?

Ben

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



[PHP] Re: What makes _SERVER stop working

2009-08-03 Thread Ben Dunlap
Miller, Terion wrote:
  if ($_SERVER['SCRIPT_FILENAME'] = browse.php ) {

You're using the assignment operator above ('=') instead of the comparison
('=='). If that's not simply a typo that entered the code when you composed
your email, then that's the source of your problem.

You might consider putting the literal side of your comparisons on the left of
the operator. Using the example above you could write:

if (browse.php == $_SERVER['SCRIPT_FILENAME']) {

This way if you accidentally use the assignment operator, PHP will give you a
parse error before it even tries to execute the script.

Ben

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] preg_match too greedy

2009-07-30 Thread Ben Dunlap
 echo (preg_match($pattern, $test) != false)

 The  != false  here is redundant.
 
 Understood. But what you think is redundancy is, to me, clarity in
 programming. I happen to think that boolean tests shouldn't ride on
 whether or not an array returned from a function is empty or not (or a
 freaking boolean). If what I'm looking for is a false then that's what
 I'll test for.

Fair enough, but in that case I think you want !== false. The expression you
have -- ($x != false) -- will be true whether $x is 0, NULL, an empty string,
an empty array, or actually FALSE.

But $x !== false will only be true in the last case.

Ben

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] preg_match too greedy

2009-07-30 Thread Ben Dunlap
Ben Dunlap wrote:
 have -- ($x != false) -- will be true whether $x is 0, NULL, an empty 
 string,
[8]
 But $x !== false will only be true in the last case.

Sorry, replace be true with be false above.

-Ben

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Re: Page or URL function? (RESOLVED)

2009-07-30 Thread Ben Dunlap
Jim Lucas wrote:
 Miller, Terion wrote:
 I Figured it out using this:

 if ($_SERVER['SCRIPT_FILENAME'] = browse.php ) {
 $default = A;
 } else {
 $default = ;
 }

 $letter = isset($_GET['letter'])? $_GET['letter'] :$default ;
 
 unless you are doing more then what you are showing above.
 
 I would do it like this:
 
 if ( $_SERVER['SCRIPT_FILENAME'] = 'browse.php' ) {
   if ( isset($_GET['letter']) ) {
   $letter = $_GET['letter'];
   } else {
   $letter = 'A';
   }
 } else {
   $letter = '';
 }
 
 Basically, it is the same thing.  But it doesn't execute the additional
 IF statement when it doesn't need to.

They end up slightly different. In your version, Jim, only the page
'browse.php' will examine the GET-parameter called 'letter'.

In Terion's version, any page with this code in it will examine the 'letter'
parameter.

Either one might be appropriate, depending on the context, but they don't have
quite the same effect.

Ben

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



[PHP] Re: This isn't infinitely recursive is it?

2009-07-30 Thread Ben Dunlap
 I don't THINK I need to worry about circular mappings... but I'm not
 sure how to check for it if I did...
 
 Any suggestions? Thanks!

Would the following work? It avoids recursion entirely and also checks for
circular mappings. You can plug in your own code where the comments are to do
whatever is appropriate when a circular mapping is detected.

function GetMappedField($Field)
{
$OriginalField = $Field;

while (isset($FieldMap[$Field]) {
$Field = $FieldMap[$Field];

if ($Field === $OriginalField) {
/*
 * circular mapping has been detected;
 * report an error or explode or whatever
 */
 break;
}
}

return $Field;
}


Ben

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



[PHP] Re: This isn't infinitely recursive is it?

2009-07-30 Thread Ben Dunlap
 while (isset($FieldMap[$Field]) {

Oops, left out the final close-parenthesis. I always do that with isset() for
some reason.

Ben

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] preg_match too greedy

2009-07-29 Thread Ben Dunlap
Jim Lucas wrote:
 I expected 'no match' but get 'match'.
[8]
 cut/paste your code and it works for me.

Works for me as well. I get 'no match' from PHP 5.1.2, 5.2.6, and 5.2.8. What
version do you have?

If I might suggest a couple of simplifications that would make it easier to
follow/troubleshoot:

 $url = '/foo(/)?';

I don't think you need parentheses around your second forward-slash. If you had
multiple characters that were optional you'd want to group them in parentheses,
but here I think it just makes the regex harder to read.

 echo (preg_match($pattern, $test) != false)

The  != false  here is redundant. Combined with the ternary operator, the
logical switchbacks make me a little dizzy (especially this close to lunchtime).

Ben

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



[PHP] Re: Page or URL function?

2009-07-29 Thread Ben Dunlap
 I've been searching php.net for a function to do this:
 
if page_url('browse.php') {

The $_SERVER global array has this sort of information. The 'PHP_SELF' key
might be what you want:

http://us.php.net/manual/en/reserved.variables.server.php

But where is the code that needs to know? I'm guessing it's in a common library
file that's going to be included in browse.php as well as other scripts, but am
I guessing rightly?

BTW, you could simplify your code slightly by defining $default as an empty
string before the IF block. Then you only have to read from $_GET once.

?php
$default = ;
if (url condition) {
   $default = A;
}
/*
 * No need for an else any more, now you can just
 * set the value of $letter
 */
?

I'd also suggest using filter_input() rather than reading directly from $_GET:

?php
$letter = filter_input(INPUT_GET, 'letter', filter, [options]);
if (empty($letter)) {
$letter = $default;
}
?

Presumably you'd want to use FILTER_VALIDATE_REGEXP in place of filter and,
for options, pass a regex that ensures that 'letter' is a single
alphabetical character.

You can read about the filter functions here (sort of, the documentation is a
little sparse):

http://us.php.net/manual/en/ref.filter.php

A VALIDATE_REGEXP example is available here:

http://www.w3schools.com/php/filter_validate_regexp.asp

Ben

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



[PHP] Re: Page or URL function?

2009-07-29 Thread Ben Dunlap
Ben Dunlap wrote [TWICE]:
 The $_SERVER global array has this sort of information. The 'PHP_SELF' key
[8]
 Ben

Very sorry for the double-post. Reply-all in Thunderbird News seems a little
overzealous by default.

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Single Quotes in Form Inputs

2009-07-27 Thread Ben Dunlap

 You can use http://us.php.net/mysql_real_escape_string to escape the
input.

[8]

You should prep your data for insertion into the data by using a tool
that formats it strictly for the database.  In the ops case
mysql_real_escape_string() is the correct tool for the job.


What about using prepared statements? This is my preferred method of 
escaping output when I'm using variables in a database query. Of 
course the ease and convenience of this method will depend to a great 
extent on what version of PHP is available on the server.


For the OP, have you read up much on SQL injection? If not, here's a 
decent place to start: http://www.owasp.org/index.php/SQL_injection


Ben

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] This is the kind of [expletives deleted] answer that is certain to prevent bugs being reported.

2009-07-24 Thread Ben Dunlap
Per Jessen wrote:

 Which is exactly the bug I reported.  An application that deliberately
 ignores the locale setting passed from the environment is buggy unless
 it is clearly documented.  Why should a developer be forced to be aware
 of the locale when it has already been done for him?  That is just dim. 

In what sense is this a bug in PHP, though? If anything it is a bug in the
documentation, but for Kyle at least, the existing documentation makes it clear
that the pre-existing environment variable be ignored unless you call setlocale
with a NULL or empty second argument.

I had the same experience as Kyle, when I read the documentation at
http://us.php.net/manual/en/function.setlocale.php -- and I thought to read
that documentation because I first searched the bug database for LC_ALL (as
requested at http://bugs.php.net/how-to-report.php ). Here's what I found:

http://bugs.php.net/bug.php?id=48876

Which shed some light on the whole issue for me. After reading that bug report
and the setlocale() manual page, it was clear to me that the PHP developers
intended for PHP to initially ignore the environment variable LC_ALL.

Your sense is that the developers made a bad design decision here, and perhaps
you're right, but a bug is a mistake in the code that causes the software to
do something other than what the developers intended. There's no bug here.

  As for being aggressive - well, being fobbed off with an RTFM when
 
 1) I've spent some time and effort in testing, documenting and reporting
 the bug, and
 2) the behaviour is at best undocumented,
 
 well, yes, it p.. me off.  It's just not professional and not at all
 conducive to getting any more bugs reported. 

I thought the response on the bug was awfully polite under the circumstances.
Again, from bugs.php.net's How to Report a Bug:

'Take special note of that word in bold above. The people who are going to help
you with a bug you report are *volunteers*. Not only are you not paying them to
help you, but nobody else is either. So, to paraphrase the immortal words of
Bill and Ted, be excellent to them.'

Have you read the classic How to Ask Questions the Smart Way?

http://catb.org/~esr/faqs/smart-questions.html

Ben
--
Twitter: @bdunlap

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Compare PHP settings of two different servers

2009-07-23 Thread Ben Dunlap
 Thank you for replying.
 Just diff the HTML. 
 Unfortunately it is not that easy. Even if the same PHP modules are 
 present, if they are written into the page in a different place, they 
 show up as differences. The same goes for all the HTML tags and 
 everything else, so what I end up with is a ton of text, no more 
 streamlined or easy to analyze than the original output from
 phpinfo().

Do you have shell access on these servers, and are they running Linux or the
like? If so, this seems like what you'd want:

  php -i | sort -u

Ben
--
Twitter: @bdunlap

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Question on code profiling

2009-07-23 Thread Ben Dunlap
 Nope. Basically it connects to a database to load an ACL (which at
 [...]
 I thought xdebug was supposed to be a pretty good profiler. If it
 calculating the time correctly, where are the other ~3.6 seconds
 going?

One night I saw a script wait indefinitely for a response from a tanked
database, and PHP's max_execution_time trigger never fired to end the script,
even though it was set to a pretty low value. Some poking around led me to
http://us.php.net/manual/en/function.set-time-limit.php where I found this odd
note:

Any time spent on activity that happens outside the execution of the script
such as system calls using system(), stream operations, database queries, etc.
is not included when determining the maximum time that the script has been
running. This is not true on Windows where the measured time is real.

The last sentence was particularly confusing because I was running on Windows.

At any rate, if xdebug is using the same mechanism used by set_time_limit() and
max_execution_time, perhaps that could explain your discrepancy?

I second Jonathan's suggestion; I would try calling microtime() before and
after your database query, and before and after anything else that isn't
strictly execution of the script.

Ben
--
Twitter: @bdunlap

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php