[PHP] Sessions can be dangerous
Dear All, There doesn't seem to be much discussion of the disadvantages and long term dangers of using php sessions. So let's redress the balance: 1. Heterogeneous Code Environments php session data is not easily accessible from non-php code e.g. Perl/C/ASP etc. In contrast, either client-stored data e.g. cookies, hidden posts, get variables, or data stored in a structured database table, (i.e. one column per variable), is easily accessible from other code. The implication is that sessions may suit you fine as long as only php is used on your site. However, if your site matures and you ever want or need to use another language for some pages, it will be hard for those pages to access data stored in sessions. On the other hand, if the data had been stored in an well-established industry standard format, you should have no problems. 2. Provably Secure Authentication Data Hopefully we all know by now that the best way to safely authenticate for access control is to make sure the username/password is checked every time either by your script, your webserver or a trusted third-party. However, I have the feeling some session users are tempted to simply authenticate in one script and store a logged in or username flag in the session without the username/password having been re-validated. It's not a complete disaster if you do this, which probably means lots of people do it! But this is only as secure as the session_id key. I don't doubt that session_ids are generated with a high-quality random number generator and should be suitably uncrackable. However, the crackability/vulnerability of a username/password schema is very well understood. Can we really say that the vulnerability/crackability of a session_id is as well understood? What happens if, and I'm sure it's a remote chance, there is ever a bug in the session-key generation that stops them being so random so a session_id crack becomes not just possible but real easy! Usernames/passwords just don't have that kind of vulnerability, and the vulnerabilities they do have are well known. 3. Independent Audit of Server Stored Data Procedures for independently verifying the data stored on a server in a SQL RDBMs are well established. It is easy to query the database schema to see what columns are defined. It is easy to verify that the data actually held in a column is as expected. In general it is easy to prove and verify what data is held e.g. to prove Data Protection compliance or Bank/Credit Card requirements, (no storage of cvv2 for example). It is intrinsically much harder to prove that the contents of php session data are compliant. You need to write a php script to unpack the session data. That means proving that that script itself is safe. Even after you've unpacked the session data, you still have to make sense of it. Different sessions may hold different numbers of differently named variables. But that's not all, the same variable may hold data in different formats in different sessions! Practically you have some pretty complex processes to prove what data you have stored and to verify that you have stored what you thought you'd stored! All in all, php sessions are NOT going to be popular with data auditors. Once again, that may not matter to you now, but down the line it could become a BIG issue. 4. State-ful Designs My personal concern about sessions, is more about the design issues. What worries me is that sessions may be used to try and re-create client/server style state when the most distinctive advantage of the internet, (and the key to its astounding success), is that it is fundamentally state-less. What this means, is that the internet is based on the principle that every request is entirely self-contained and independent of any other request. There is for example, absolutely and explicitly, no guarantee that http requests will be received in chronological order. It is all strictly about best effort, and no guarantees. This is why the internet works: each component does its own job as well as it can without worrying about what else is happening. The implication from a design point of view is that you should not be making any assumptions about what has gone before or what will come after your php script runs. The functionality offered, should, as far as possible, be completely self-contained, with each php script acting as a component in its own right. That means no direct interaction between the scripts. Interaction should be gated through third-party standard interfaces such as http or SQL. The problem with sessions is that they encourage you to break this model by creating a new set of super-global data holding state information. This data is not exchanged through established standards, but rather, floats around in the background, changing the behaviour of the script but without being clearly externally defined. If the session data is only
[PHP] Re: Variables don't pass... *sniff*
Daniel, Switch register_globals back on, and everything works as it always did. So do it! All this fuss about register_globals being insecure is a complete load of rubbish. This issue really bores me, but it seems programmers are wasting a lot of time on it, so I guess I'd better run through the arguments one more time... 1. You can never know whether the input to your script came from a real GET, a COOKIE, or a POST. It's very easy to create a simulated GET, COOKIE or POST. You don't even need a programming language if you've got the right tools. Even with php, (hardly a typical hacking tool), it's only a few lines of code. 2. That means that checking to make sure a variable was specifically a GET, COOKIE or POST variable has no security value whatsoever. 3. On the other hand, not worrying about how your script got its request variables (i.e. register globals is on) is intrinsically sound programming practice. Your code should work and your logic should be sound regardless of what happened before your script got executed. It's one of the great advantages of the internet. For example, on searches, you can have exactly the same search code and results page driven from a search form, or a link on another page, or a remote http request. You code once, but your code can be used in many different ways. 4. In any case, register globals off only protects the sloppy programmer from the sloppy hacker. It doesn't stop the good programmer from being as cautious as they like. You can already control the order in which variables are registered e.g. to make POST variables always override COOKIES or vice versa. And, you can, if you really need to, double-check with the global variables, HTTP_POST_VARS etc. 5. When it comes to access control, (which seems to be where the bogus security argument starts), there is only one safe approach. That is to require that a valid username and password are supplied with every request and then check them in every script. It's not hard, it doesn't take long and it's the proper way to do it. There's a whole section of the http protocol, http authentication, which is designed precisely to make this easy. But hey, don't worry about all this guff. Just switch register globals back on. If your system administrator/ISP won't let you, just refer them to this mail and tell them I'd be happy to explain anything they don't get. Keep it simple! George [EMAIL PROTECTED] wrote: Hi all! I'm using Apache 2.0.45, PHP 4.3.2RC4, and MySQL 3.23.49 on Windows 2003 Server Standard. I have a problem passing variables between pages. They simply get lost. Neither GET nor POST pass values, and even hardcoding them into the URL, like htpp://localhost/comeon.php?aVariable=dinganotherVariable=dong and putting this in comeon.php: echo(Values: $aVariable, $anotherVariable); only outputs Values: , ...I've tried with RC3 of PHP, even 4.3.1, but it doesn't work. I've used PHP on my machine with Apache 2 before, and it worked fine. Actually I used the same scripts fine on my old config. This was on XP however, so I'm not sure if it's got something to do with the OS. I'm hoping it's a configuration issue. Any ideas are VERY much appreciated =). Thanks, Daniel » There are 10 kinds of people - those who know binary and those who don't. « -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] Re: sessions and domains
Bk wrote: Hi I've to set up a shared shopping cart to buy items from four different sites and pay them at once passing trough a single checkout. Provided that these sites are hosted on the same server (actually in the same directory), but have different names, is it possible to share php sessions across multiple domains? How? Bk, I notice your question has basically been answered i.e. you have to pass something e.g. session_id, between the sites via a GET/POST. So just a couple of related points: 1. I seem to remember that you can set sessions to use IP addresses or URL'ed session_ids as well as cookie'd session ids. Either of these techniques would solve your problem as well, (although cookies strike me as a better route if you must use sessions ;)). 2. If you are doing this kind of multi-site stuff and have Apache, it's worth checking out the php virtual() and header() commands. With these you can leave your shops to just handle their own stuff and use a master domain to do all the basket/order processing. The basic technique is to direct your order forms/buttons to a script on the master domain which does the procesing, (and can set cookies if it wants). Once it's finished, instead of generating its own page it uses a Location header to redirect the user back to an appropriate page on the shop domain. The user never knows you've done this. Similarily, the checkout button can go to the master domain to do the actual procesing, where it automatically picks up any cookies (e.g. session_ids), that you set from a master domain page. The virtual command might come into the picture if you want to show the user the status of their shopping basket while in one of the shops. Virtual allows you to run a http request behind the scenes and include the output in your page. So your page can mix output from different php scripts running on different domains. They don't even have to be scripts in domains on the same server if you set up an Apache proxy to point to the remote script. You can use this to include a basket status section on your shop pages without having to run the code to create it in your script. You can have one set of basket status code across as many shops/domains as you like i.e. code once, use often. Unfortunately, what you can't do with a virtual() is to get the foreign script to pick up any cookies set for its domain. (That's because the user's browser never sees the http request, so it doesn't know that it should send the cookies for the domain). That means you would still have to swap the session_id, (or basket key), around between sites. You can see these techniques in action at any Ishop e.g. www.levitron.co.uk. All the main procesing is done by www.ishop.co.uk, but the shop has entirely its own identity. Order buttons, searches and checkouts go to the master ishop domain and product pages include a checkout status line generated on the master domain. You'll notice that there is no use of php sessions. Basket information is stored in the database and then the database key is cookied, posted and urled. Partly that's because there's still a mix of php, C and perl coded pages. Sessions are not really appropriate for heterogeneous environments. C or Perl or any other language can easily pick up a cookied database key and query a database but how do they get hold of data in a php session? Even if it was all php, I still wouldn't use sessions. My view is that if data is to be stored on a server it should be stored properly in a structured format in a database, not in a unstructured and pretty much inaccessible session object. For example, it's hard to prove to a third party what data you have stored about users, if some of it might be in stored sessions. Ummm, I wonder if I should explicitly raise my concerns about sessions in a separate thread? I don't use sessions so it doesn't bother me, but I wonder if some people are just storing up trouble for themselves by basing their code on the use of sessions... Anyway, hope this helps, George -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] Re: MySQL Date
Why not get MySQL to compare your date with today? e.g. select if(Booking_Date = curdate(),'booked','free') as Todays_Status ... $Todays_Status = mysql_result($result,$i, Todays_Status); echo you are $Todays_Status today; I find it is much, much safer to only use the database for finding out the date/time. Why? My applications typically run where the database and the web-server are on different machines and where there often multiple machines running the web-servers. That means different clocks. This can cause some really horrid bugs to start appearing e.g. records you just inserted today appearing on the next select as yesterday's or tomorrow's, records appearing to be inserted out of order, etc. etc. What makes them so nasty is that you may notice until the data is completely screwed up. You won't get these problems as long as you only ever use the database server to supply the date/time. You will always get consistent results even if they are consistently a few seconds fast or slow. Records will always appear to have been inserted in the expected order, a row with today's date will show up on every query for today etc. You have to be careful as and when the time is changed on the database server, (which is why they so often do have the wrong time!). To pick up today from the database server, remember you don't have to have any tables in your query e.g. your query can be as simple (and fast) as :- select curdate() as today; Regards, George Shaun wrote: Hi, I have a date stored in a table in my MySQL Database using a DATE type for the column. How can i compare the date in the table to today e.g. $today = mysql_result($result, $i, Booking_Date); if($today = *HELP*){ echo you are booked today; }else{ echo you are free today; } thanks for your help -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] Re: New window, new session
Riaan Stander wrote: Hi there I know this is not a php specific question, but I don't know where else to ask. I've got the following situation. The website I'm currently working on has got a administration page where the administration user must be able to login as all the users available. It is fine getting all the data, but I want to open the login in a new browser window, otherwise the administrator has go to re-login with his account. Thus, I need to somehow open a new browser window, with a new session id. When somebody logs in I check to see if there is already a session variable registered. If there is, I unset this variable, and register a new one for the login account. You can see where my problem is. At this stage I'm using some java script window.open() to open the new window, but it is still with the save session id. If any of you can tell me how to open a new browser window with a new session id, I would greatly appreciate it. Thanx Riaan Riaan, Would it help if you opened the window at another domain? I don't use sessions, as I much prefer http authentication/stateless pages etc. But I get the same problem i.e. admin user has to keep logging in between accounts. The solution is just to change the realm/domain for the admin user e.g. admin.mysite.com. Then the browser keeps separate login/passwords. This should also be possible with cookie based sessions since the browsers will hold separate cookies for different domains and also for different paths if you specify a path on the cookie setting. I don't know if all this session stuff lets you specify the path on the session cookie, but certainly the separate domain technique should work. Hope that helps, George -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] Re: Problem with regular expressions
Drew wrote: When I run the following script it returns String Okay! when it should say Invalid Characters Found. I've tried the script substituting $ for other characters, such as j, and it works just fine. What do I need to do? ?php $input = johnon@company.$com; if (ereg([$], $input)) { die(Invalid Characters Found.); } elseif (ereg([[:space:]], $input)) { die(Whitespace found.); } else { echo String okay!; } ? Thanks, Drew Try changing the double quotes to single quotes i.e. $input = 'johnon@company.$com'; php automatically attempts variable substitution on double-quoted strings, but not single-quoted strings. Unless you know that you want variable substitution, it's always safer and faster to use single-quotes. George -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] rounding a number
Jason Wong wrote: On Monday 24 June 2002 11:34, Phil Schwarzmann wrote: I want to round a number to the nearest decimal place... if the number is 4.623, I want it to display 4.6 if the number is 2.36, I want it to display 2.7 You don't really mean 2.36 -- 2.7 ?? Is there a function that does this? round(), ceil(), floor() don't do this and I've checked through all the math functions in my handy-dandy PHP Functions reference book. round() seems to work. What's the problem you're having? It's worth noting that round doesn't always work e.g. try round(0.35,1) -- Jason Wong - Gremlins Associates - www.gremlins.com.hk Open Source Software Systems Integrators * Web Design Hosting * Internet Intranet Applications Development * /* That's no moon... -- Obi-wan Kenobi */ -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] Re: rounding a number
Phil Schwarzmann wrote: I want to round a number to the nearest decimal place... if the number is 4.623, I want it to display 4.6 if the number is 2.36, I want it to display 2.7 Is there a function that does this? round(), ceil(), floor() don't do this and I've checked through all the math functions in my handy-dandy PHP Functions reference book. Thanks for your help!!! Or..if it's too hard to do that, I could just use a function that chops off the end of some decimals, like... if the number is 2.343234, I want just 2.3 or if the number is 2.545434534534534534, I want just 2.5 Thanks!! As I understand it, you just want to truncate the number, without rounding. I think you are right, there isn't a function to do it for you but the following code should do it: intval(4.623 * 10)/10 or more generally: function truncate_number($mynumber,$places) { return intval($mynumber * pow(10,$places))/pow(10,$places); } -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] Re: getting the value of a javascript variable
Otteneder Hermann wrote: hi everybody, i have a short problem: i have two drop down menues in a form. the content of the second dropdown is dependent from the selection in the first dropdown menue. now i want write a short javascript which runs on the onSelect - event of the first dropdown. this script gives me the selected entry of the first dropdown menue. now i have to give this value somehow into the PHP-environment for a DB-Query. The feched data i want dynamically fill into the second dropdown. But how do I get the value from the javascript variable into the php environment without an submit of the form?? has enybody a solution for this? thanx so far - hermann... Ottneder, You can't easily do what you want i.e. to have an html page in the user's browser with Javascript which goes back to a php script on the server after a user select in order to pick up the data for a new select list. Normally when creating dynamic select lists, I actually get the php to drop ALL the data in the top of the page as Javascript variables. You can see an example in the source of http://tandridge.cpfc.co.uk/tables. I guess it is at least theoretically possible to do what you want by getting your Javascript to open up a hidden background frame targetted at a php script which then puts the data back into that frame so you can then access it in the original frame. It would be a bit complicated and clumsy... The third option is to have your select as a separate frame and do a submit of just that part of the page. This is the easiest to code but probably the most clumsy from a graphics point of view. How much data is involved? How many different versions of the select list and how many options in each version? If it's not too much, then I'd put it all in the page as I do, as compactly as you can e.g. short variable names etc. Hope this helps, George -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Limiting text inputs by character count?
John Holmes wrote: The best way to do this is server side with strlen(). You can use javascript or maxlength, but if a user wants to get around it, they can. ---John Holmes... John, The best way to do this is with both. maxlength/Javascript as a courtesy, strlen for security. As you say, you can NEVER rely on any kind of client-side check, all checks must be done on the server side. So, it's tempting to skip client-side checks, but making the user wait for server side execution before any checks are done is actually very rude. Every time I see server-only checks for required fields etc., I switch off and lose confidence in the site. George -Original Message- From: Martin Towell [mailto:[EMAIL PROTECTED]] Sent: Sunday, June 23, 2002 9:47 PM To: '[EMAIL PROTECTED]'; [EMAIL PROTECTED] Subject: RE: [PHP] Limiting text inputs by character count? a) maxlength=xx b) use javascript (document.forms[frm_name].elements[textarea].value.length) (I think you need the .value bit) -Original Message- From: Andre Dubuc [mailto:[EMAIL PROTECTED]] Sent: Monday, June 24, 2002 11:53 AM To: [EMAIL PROTECTED] Subject: [PHP] Limiting text inputs by character count? Is there a way to limit the number of characters that may be inputed into: a) a input type=text . . . input b) a textarea . . . input I would like to control the maximum number of characters for each of these inputs. Any suggestions of where to look, or how to do it, if it's possible, would be greatly appreciated. Tia, Andre -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] Re: Using $PHP_SELF in a form
Frank Miller wrote: I'm working on a project here at our university and need a little. We installed a wireless network and bought 5 ipaq's to use and experiment with. I wrote a work order system that we are still using. Basically the tech guys want to be able to check WO from the ipaq's and if they finish them fill in a check box and have it be updated in the WO database and not be displayed on the open or uncompleted work order page. I can do everything except when the completed box is filled I can't get it to fill in the database. Below is the code I'm using. Keep in mind it is being displayed on a ipaq so the headings are brief. Also I'm working on my local computer before it is put in production. Any help would be appreciated. Frank, I can't see anything obviously wrong with your code, but it's a bit hard to follow. In general I tend to do all processing in a script first before writing any output so you get something like: if (isset($submit)) { ... sql updates } ... sql selects e.g. $cursor=mysql_query(); HTML BODY header ...form start while ($row = mysql_fetch_array($cursor)) { print ' per row html '.$row[value1] etc. } ...form end... ... footer stuff /HTML A big advantage of this is that if you do hit an error during your SQL stuff, then you can redirect straight to an error page without having to worry about headers already sent messages. A secondary advantage is that if you do your updates first, you can just let the normal select code run so after every update the form just returns with the new values of data without another stage of selection. Anyway, back to the problem, it looks as if you'll need some traces to find out what is actually happening. First of all I'd suggest you just print your query string before executing it, then you can have a look and see what it's actually trying to do. Most likely it either is never getting to the query or no value set in $checkbox[0]. I guess (!$HTTP_POST_VARS['submit']) works, but I always go for a named submit e.g. type=submit name=update, and an explicit isset check if isset($update) etc. I also wonder why you look for submit in HTTP_POST_VARS but pick up $checkbox[0] directly. As your code stands I guess they can only check one box at once. Have you considered a foreach($checkbox as $orderno) loop for the updates? Personally, after very unpleasant experiences with early Internet Explorers I still name each form field individually instead of trusing arrays e.g. checkbox0, checkbox1 etc. Of course if you do that you need to have a hidden field with the number of records displayed to know how many checkboxes to check which is a bit of a pain. Sorry I couldn't help more. Good Luck, George -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] Re: Rounding....
Matthew Clark wrote: Seeing as the mathematically correct way to round numbers is to round down to n for n-1=m=n.5 and up to n+1 for n.5mn+1, I wonder why the PHP round() function couldn't include a little 'fuzz' to handle the rounding problems we encounter due to floating point representation in the hardware? It could even be a configurable option - but it would save writing a wrapper... Matthew, I can't agree with you more. I really don't understand the point of php having a round function which gives the wrong answer on even very simple decimals e.g. round(0.35,1) returns 0.3. The fuzz you suggest works fine and need only be very small. pow(10.0,places-DBL_DIG) seems to do the job. e.g. a change to the source of math.c:PHP_FUNCTION(round) as follows, (changes underlined): f = pow(10.0, (double) places); return_val *= f; if (return_val = 0.0) return_val = floor(pow(10.0,places - DBL_DIG)) + 0.5 + return_val); - else return_val = ceil(return_val - (0.5 + pow(10.0,places - DBL_DIG))); return_val /= f; You'll note that this implies a bias to high absolute values, but then we already have that bias since we're rounding up anyway. The only numbers which would be incorrectly rounded because of the bias in the fix, already have more than 14 significant figures e.g 0.349 rounds to 0.4 but 0.34 still rounds to 0.3. I can't see any possible reason for this not being fixed, but then I also think we should fix the rest of the binary representation problems i.e. 1. Comparison of Floating Points 0.8 == 0.7 + 0.1; evaluates as false not true. In general, all the comparison operators, ==, !=, =, , , =, === may give incorrect results if either of the operands is a floating point. 2. Conversion of Floating Point to Integer floor(10 * (0.7 + 0.1)); evaluates to 7 not 8. In general, floor(), ceil() and (int) may give incorrect results. 3. Spurious Differences print (0.8 - (0.7 + 0.1)); outputs 1.1102230246252E-16 not 0 4. Cumulative Conversion Errors for($i=1,$i=10,++$i){$total = $total + 0.1;}; calculates $total as 1. not 1 They all have the same cause as the round problem i.e. the use of binary floating points for decimal arithmetic without any compensation for conversion errors. As it happens, there's a simple fix for all of these as well The fix is to automatically round the results of php's arithmetic operators to 15 significant figures when floating point numbers are involved. It comes to about 20 lines of code change to zend_operators.c i.e.8 calls to the following new function: double decimalise(double dval) { double f; if (dval == 0) { return dval; } f = pow(10.0, DBL_DIG - (1 + floor(log10(fabs(dval); return (double) (rint(dval*f))/f; } There is a performance downside, although much less than doing your own workarounds. To put it in perspective, the impact is a twentieth of that of using a string cast/sprintf. Indeed, the slowdown is less than using objects or arrays in your arithmetic i.e. with the fix $a = $b + $c takes the same or less time than unfixed $a = $b + $c-d Or, to put it another way, if you are not worried about the performance impact of using objects and arrays in arithmetic operations, you should not be worried by the impact of this fix for decimal arithmetic. (The decimalise function could also be speeded up with a more clever calculation of f, e.g. by skipping the log10 and pow functions but I'd rather leave that to a real C programmer ;)) I haven't had a very enthusiastic response from the php developers in the past on these issues, but I'm keen to have another go if you or anyone else thinks it's worth sorting this out properly. Personally, I just don't see the point of having operators/functions in php that can go wrong at even a single decimal digit! Regards, George -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] Re: Rounding....Message repeated
Repeat of previous message in thread without the extra ugly wrapping, (sorry!!!) Matthew Clark wrote: Seeing as the mathematically correct way to round numbers is to round down to n for n-1=m=n.5 and up to n+1 for n.5mn+1, I wonder why the PHP round() function couldn't include a little 'fuzz' to handle the rounding problems we encounter due to floating point representation in the hardware? It could even be a configurable option - but it would save writing a wrapper... Matthew, I can't agree with you more. I really don't understand the point of php having a round function which gives the wrong answer on even very simple decimals e.g. round(0.35,1) returns 0.3. The fuzz you suggest works fine and need only be very small. pow(10.0,places-DBL_DIG) seems to do the job. e.g. a change to the source of math.c:PHP_FUNCTION(round) as follows, (changes underlined): f = pow(10.0, (double) places); return_val *= f; if (return_val = 0.0) return_val = floor(pow(10.0,places - DBL_DIG)) + 0.5 + return_val); - else return_val = ceil(return_val - (0.5 + pow(10.0,places - DBL_DIG))); return_val /= f; You'll note that this implies a bias to high absolute values, but then we already have that bias since we're rounding up anyway. The only numbers which would be incorrectly rounded because of the bias in the fix, already have more than 14 significant figures e.g 0.349 rounds to 0.4 but 0.34 still rounds to 0.3. I can't see any possible reason for this not being fixed, but then I also think we should fix the rest of the binary representation problems i.e. 1. Comparison of Floating Points 0.8 == 0.7 + 0.1; evaluates as false not true. In general, all the comparison operators, ==, !=, =, , , =, === may give incorrect results if either of the operands is a floating point. 2. Conversion of Floating Point to Integer floor(10 * (0.7 + 0.1)); evaluates to 7 not 8. In general, floor(), ceil() and (int) may give incorrect results. 3. Spurious Differences print (0.8 - (0.7 + 0.1)); outputs 1.1102230246252E-16 not 0 4. Cumulative Conversion Errors for($i=1,$i=10,++$i){$total = $total + 0.1;}; calculates $total as 1. not 1 They all have the same cause as the round problem i.e. the use of binary floating points for decimal arithmetic without any compensation for conversion errors. As it happens, there's a simple fix for all of these as well The fix is to automatically round the results of php's arithmetic operators to 15 significant figures when floating point numbers are involved. It comes to about 20 lines of code change to zend_operators.c i.e.8 calls to the following new function: double decimalise(double dval) { double f; if (dval == 0) { return dval; } f = pow(10.0, DBL_DIG - (1 + floor(log10(fabs(dval); return (double) (rint(dval*f))/f; } There is a performance downside, although much less than doing your own workarounds. To put it in perspective, the impact is a twentieth of that of using a string cast/sprintf. Indeed, the slowdown is less than using objects or arrays in your arithmetic i.e. with the fix $a = $b + $c takes the same or less time than unfixed $a = $b + $c-d Or, to put it another way, if you are not worried about the performance impact of using objects and arrays in arithmetic operations, you should not be worried by the impact of this fix for decimal arithmetic. (The decimalise function could also be speeded up with a more clever calculation of f, e.g. by skipping the log10 and pow functions but I'd rather leave that to a real C programmer ;)) I haven't had a very enthusiastic response from the php developers in the past on these issues, but I'm keen to have another go if anyone else shares my view that it's time to sort out decimal arithmetic properly. I just don't see the point of these operators/functions that can go wrong at even a single decimal digit! Regards, George -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Which costs more: connecting to a DB or accessing the file system?
Mike wrote: Erik, thaks for the reply. I conducted a simple/rough benchmark to which is more expensive. I tested on a Intel PIII (450MHz 384MB ram) box running Win Xp, Apache 1.3.26 and PHP 4.2.1, and mysql 3.23.49 and freeBSD of similar stats (1000MHz, 1G ram). I used the adodb database abstraction layer to make my connections (which adds extra weigt to the db initialization and queries, but this is the default method I use to access databases) to a db, and then queried a smallish db with a select * from table. I then benchmarked a file read of a similarily sized file. Win DB results average (not including the include of the adodb class): time indexex time % Start1024676092.32095600-0.00% init db 1024676092.342583000.021627 75.19% query 1024676092.349426000.006843 23.79% close1024676092.349631000.000205 0.71% Stop1024676092.349719000.880.31% total - 0.028763 100.00% Win Filesystem results average: time indexex time % Start 1024676092.35610400-0.00% file open1024676092.35685300 0.000749 28.59% read 1024676092.35846200 0.001609 61.41% close 1024676092.35863700 0.000175 6.68% Stop 1024676092.35872400 0.87 3.32% total- 0.002620 100.00% freeBSD DB results average (not including the include of the adodb class): time indexex time % Start 1024677559.22131200 -0.00% init adodb 1024677559.22266700 0.001355 75.66% query 1024677559.22303400 0.000367 20.49% close 1024677559.22307900 0.45 2.51% Stop 1024677559.22310300 0.241.34% total - 0.001791 100.00% freeBSD Filesystem results average: time index ex time % Start 1024677559.22374400- 0.00% file open1024677559.22380700 0.63 11.23% read 1024677559.22423200 0.000425 75.76% close 1024677559.22428200 0.508.91% Stop 1024677559.22430500 0.234.10% total-0.000561 100.00% On the win box, file system access was 11 times faster, while on the freeBSD box, file system access was 3 times faster. The include of the adodb class is not benchmarked, as part of this test, that that adds extra overhead as well. I suppose that filesystem access is faster. Michael Erik Price [EMAIL PROTECTED] wrote in message [EMAIL PROTECTED]">news:[EMAIL PROTECTED]... On Friday, June 21, 2002, at 11:19 AM, mike wrote: I was reading somewhere (can't remember where) that connecting to a db is a pretty costly transaction. DB queries aside, does anyone know of any benchmarks that demonstrate file access vs. db connections? Similarily, while DB queries offer alot of power, would it be cheaper (faster) to drop simple information that does not require heavy queries into a file and access it through the file system? I don't have any stats, but I think it really depends. If you're executing a really complex query that uses like six JOINs and eight WHERE clauses, then the bottleneck is the DB and not the DB access itself, so it would probably be quicker to have this information ready in a file (or even better, cached in memory somehow, though I have no experience doing this). But I believe that with a simpler DB query, a DB access is faster than a file read. Here's something that turned up in Google... http://phplens.com/lens/php-book/optimizing-debugging-php.php Erik Erik Price Web Developer Temp Media Lab, H.H. Brown [EMAIL PROTECTED] Mike, I'm not quite sure what you are trying to achieve, but if holding the data in a file is realistically an option i.e. your data is static, then why not consider holding your final output e.g. your web page/partpage in the file system? If you need your php script to generate it in the first place or regenerate it on request there are simple techniques to allow you to do this without reassembling it on every request. Basically you get your script to see if the output has been already created (if (file_exist), and simply redirect or include the output if it does. If it isn't you can get the script to run on and
Re: [PHP] Advanced User Authentication
César aracena wrote: I like very much the idea of using a short way. Actually, I did and here's how: // After I queried the DB for a username password match: if (mysql_num_rows($result) 0) { $row = mysql_fetch_array($result); if ($row[authlevel] == '1') { $valid_user = $username; session_register(valid_admin); } else if ($row[authlevel] == '0') { $valid_user = $username; session_register(valid_user); } } but still doesn't work. I'm still getting the posted values back (when pointed to phpinfo.php) including the sessionID variable, but the Session doesn't show like registered. That is, when I called the following Script, nothing happens: Cesar, For the admin users, you set $valid_user but then register valid_admin. It's a typo. $valid_user = $username; session_register(valid_admin); should be $valid_admin = $username; session_register(valid_admin); Another time, I would have made auth_level in the database a character field set to 'user', 'admin', 'readonly' or whatever and then just pass it straight through i.e. if (mysql_num_rows($result) 0) { $row = mysql_fetch_array($result); $user_type = $row[auth_level]; session_register('auth_level'); } or even, just let auth_level default to '' if no match found i.e. $row = mysql_fetch_array($result); $user_type = $row[auth_level]; session_register('auth_level'); For the record, I don't like using sessions to pass around access control information, I would force http authentication on every page i.e. .. check user/password as per above but using $PHP_AUTH_USER and $PHP_AUTH_PW ... and then add the following to force an authentication if they haven't authenticated themselves: if ($auth_level == '') { $REALM = 'My Application'; header(WWW-Authenticate: Basic Realm=\$REALM\); header(HTTP/1.0 401 Unauthorised); include(authenticate_failure_message.html); exit; } Of course, you can wrap this all up in a function and do extra useful things like having a central user database and passing through application/section/page information to a single get_access function etc.,etc... But it sounds like you're too far done your current track to be interested in that sort of approach. And, in any case, it might not match your style if you like sessions. Personally, I don't like using sessions for anything on the grounds that they're trying to retrofit state onto intrinsically state-less protocols and therefore bound to be clumsy/buggy/limiting. Good Luck, George [snip] if (session_is_registered(valid_admin)) { // do admin stuff } else if (session_is_registered(valid_user)) { // do users stuff } else { // prompt for login // this is still what's showing!!!??? } [snip] César Aracena IS / MCSE+I Neuquén, NQN (0299) 156-356688 (0299) 446-6621 -Mensaje original- De: Miguel Cruz [mailto:[EMAIL PROTECTED]] Enviado el: Viernes, 14 de Junio de 2002 03:11 a.m. Para: César Aracena CC: PHP General List Asunto: Re: [PHP] Advanced User Authentication I think you're making it needlessly complicated. Why don't you just select * from * FROM auth WHERE authname = '$username' AND authpass = password('$password') and not worry about WHERE authlevel = 1? Then, if that query is successful, you can just fetch the result row and see what 'authlevel' is for that user, and act accordingly. miguel On Fri, 14 Jun 2002, César Aracena wrote: I?m trying to make a somehow ?advanced? user authentication system fro my own web site. What I?m using as a model example, is the authentication system explained by Luke Welling Laura Thomson in their book ?PHP and MySQL Web Development?. In the book, they explain how to make apparently a perfect user authentication system, but only for one level users. I would like to change that somehow in order to make my scripts recognize whether the user is an Administrator or a Common User, identified by a ?authlevel? field in my DB (1 for Admin - 2 for Users). I?m making all my web sites, by using an ?include? schema, so the user is authenticated only in the Header (included in all the pages). What I have so far is: ? // this is where the original script begin session_start(); if ($userid $password) { $db_conn = mysql_connect(localhost, user, password); mysql_select_db(dbname, $db_conn); $query = SELECT * FROM auth WHERE authname = '$username' AND authpass = password('$password') AND authlevel = 1;
[PHP] HTTPS spoofing and $_SERVER
Hi, I want to know if the user is connected on a secure socket and have two problems: 1. My Apache (Stronghold), variables are not turning up in $_SERVER or $HTTP_SERVER_VARS although they are in $GLOBALS e.g. I have $GLOBALS[SERVER_PORT] but not $_SERVER[SERVER_PORT]. This is with track vars and register globals both on. It seems I have to rely on the $GLOBALS value and be careful with variables_order. 2. As well as $SERVER_PORT, I also get $HTTPS, but only if there it is an HTTPS connect i.e. on a secure connect, $HTTPS == 'on', but on an insecure connect it is not set. This makes it easy to spoof even with variables_order set to ECGPS. I could just use $SERVER_PORT, which is always set and thus not so easily spoofed but then I have to worry if the secure port changes. Any suggestions? George -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Cool PHP Tricks/Features ?
Ummm, This output compression sounded cool to me when I came across it, but I wasn't sure it really helped or was appropriate for us to use: 1. My biggest concern is the slowest user i.e. at the end of a modem on the other side of the planet. I thought they would almost certainly have modem compression so doing our own compression doesn't really help them at all i.e. actual download speeds stay the same, it's just we/they do the work rather than the modems. 2. I was surprised when I got ISDN dial-up that it didn't seem to have automatic compression on the line, but assumed that was going to change. Am I too hopeful? 3. But surely, ASDL, cable, the backbone and decent intranets must all do hardware compression, don't they? Or are they secretly not very keen on decreasing network traffic? 4. Finally, if the network hardware isn't handling compression for us, I would have thought it was a good job for a web server. I guess I'd have to ask the Apache guys, but I would guess this can be really neatly done with some fancy mod_rewrite, custom extension or whatever. In summary, I can't agree more that all pages should be compressed, but don't feel it should be our job. Maybe I'm wrong and this is another case of the poor old application developer having to do all the * work, just because the rest of the computing industry is too busy counting its profits to do its own job properly ;). What's everyone else think? George Sqlcoders.Com Programming Dept wrote: I've seen real-life examples of 100k pages going down to around 30k, considering that decrease in size, when you remember that CPU time is relatively cheap compared to bandwidth, it's worth the processing overhead in my opinion. Small (20k) pages probably aren't worth it, for anything larger then as it's been mentioned, even if visitors have no idea the pages are smaller, if they load in 1/3 of the time it's useful, wanted, and definitely cool. Just remember that not every browser understands gzip compression, but also remember that a probably larger percentage of visitors have ECMAScript (JavaScript) switched off. You takes your chances, you makes your choice... William. - Original Message - From: SP [EMAIL PROTECTED] To: [EMAIL PROTECTED]; 'Girish Nath' [EMAIL PROTECTED]; [EMAIL PROTECTED] Sent: May 14 2002 06:29 PM Subject: RE: [PHP] Cool PHP Tricks/Features ? Well if his normal page is 100k and he can cut the size down to 50k with gzip then instead of having a monthly transfer of 100 GB for example, he would only be paying for 50 GB. Seems like it's useful for extremely large sites. -Original Message- From: John Holmes [mailto:[EMAIL PROTECTED]] Sent: May 14, 2002 6:43 PM To: 'Girish Nath'; [EMAIL PROTECTED] Subject: RE: [PHP] Cool PHP Tricks/Features ? Why do you think this is useful to you? I remember reading an article on this and its conclusion was that zipping the output was only beneficial for large data between fast computers over a slow pipe. You have to look at who your clients are and if it's beneficial to have their machine use up extra time (processing power) unzipping things or not. Also, you're using more processing time on your computer having to do the zipping for every request, too. ---John Holmes... -Original Message- From: Girish Nath [mailto:[EMAIL PROTECTED]] Sent: Tuesday, May 14, 2002 9:28 AM To: [EMAIL PROTECTED] Subject: [PHP] Cool PHP Tricks/Features ? Hi I've been using PHP for about 2 years now but only just discovered ob_gzhandler and gzip/compressing http output. It's something i wish i'd found out about earlier because even though it's a simple concept the result blew me away :) Anyway, i just wanted to know of any other cool tricks/features that you guys are using that others could have overlooked. Thanks Girish -- www.girishnath.co.uk -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php --- Incoming mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.361 / Virus Database: 199 - Release Date: 07/05/02 --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.361 / Virus Database: 199 - Release Date: 07/05/02 -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] HTTPS spoofing and $_SERVER
1LT John W. Holmes wrote: Well, if you fix #1, that will fix #2 because you can use $_SERVER[HTTPS], which can't be spoofed by the user. What versions of PHP and Apache are you using, on what OS? ---John Holmes... Oops, Just run up phpinfo and this appears to be php 4.0.1pl2, Stronghold 3.0/Apache 1.13.9 and Debian 2.2.20. I guess the 4.0.1pl2 explains the absence of $_SERVER, but I would still have expected it in $HTTP_SERVER_VARS, wouldn't I? Anyway, it sounds like you've answered my key concern that HTTPS, and all the other Apache variables SHOULD be in $_SERVER, even if with this stupid *** build they aren't. I suppose I'll just have to rely on $SERVER_PORT not changing for the SSL port until I can manage to persuade the System Administrators to upgrade the php again. (My main problem with getting them to keep up to date is that Debian's php package lags so far behind, and they really don't like upgrading unless Debian have rubber stamped it). Kind regards, George - Original Message - From: George Whiffen [EMAIL PROTECTED] To: [EMAIL PROTECTED] Sent: Wednesday, May 15, 2002 7:35 AM Subject: [PHP] HTTPS spoofing and $_SERVER Hi, I want to know if the user is connected on a secure socket and have two problems: 1. My Apache (Stronghold), variables are not turning up in $_SERVER or $HTTP_SERVER_VARS although they are in $GLOBALS e.g. I have $GLOBALS[SERVER_PORT] but not $_SERVER[SERVER_PORT]. This is with track vars and register globals both on. It seems I have to rely on the $GLOBALS value and be careful with variables_order. 2. As well as $SERVER_PORT, I also get $HTTPS, but only if there it is an HTTPS connect i.e. on a secure connect, $HTTPS == 'on', but on an insecure connect it is not set. This makes it easy to spoof even with variables_order set to ECGPS. I could just use $SERVER_PORT, which is always set and thus not so easily spoofed but then I have to worry if the secure port changes. Any suggestions? George -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] Re: Right way to do the MySQL thing
The simplest way to do the connection thing is, as is often the case in php, to do nothing i.e. forget it. If you don't specify a connect id MySQL happily uses the last one opened, so the only thing you need do with the return from mysql_connect is check it for errors i.e. if (!mysql_connect(localhost,root)) { // panic There's certainly no point in putting it in a session variable, the connection is closed for you as your script terminates. The only time you might want to actually do something is if you were doing a LOT of switching between different database servers during one page request. Switching between databases doesn't matter, but different servers = different connects. George connection if you don't specify one, so the only thing I've ever done wih David Johansen wrote: I was just wondering what the right way to do the MySQL connection thing is. Am I supposed to do it everytime through in the php code, should I make it a session variable, or is a global variable the way to go? Right now this is the code that I have if (empty($_SESSION['db'])) { $_SESSION['db'] = mysql_connect(localhost, root); mysql_select_db(clients,$_SESSION['db']); } Is that a good way to do it or is there a better way or anything like that. Thanks, Dave -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] A good PHP Shop
Here's a mini-checklist on tricky bits, some of which are as much about payment as much as cart: 1. Delivery Packing especially pricing on composite loads, destination, different speeds. 2. Sales taxes. 3. Quantity discounts, discount vouchers, reusable vouchers, loyalty cards. 4. Affiliate and referral tracking and their accounts. 5. Order processing, separate auth and debit, refunds, partial refunds 6. Stock control. and, of course, currencies, languages etc., if you want to do the proper job. Depending on your target base, I'd be particularly careful about the shopping process. It's really easy to put off customers, especially the general public. For example, insisting on user registration before you get to the cart or order will lose you business, unless you're the likes of zend store and are guaranteed confident customers. If you want to look at a mall for ideas, try http://www.ishop.co.uk which only has php at the backend but does show you can get rich functionality, without having to have Amazon's budget. George Jaxon wrote: www.fishcart.org :) i've been trying to decide which one to use to tackle a big mall project, but don't know enough about 'carts to make an intelligent assessment yet. cheers, jaxon -Original Message- From: Bradley Goldsmith [mailto:[EMAIL PROTECTED]] Sent: Thursday, March 07, 2002 5:06 PM To: '[EMAIL PROTECTED]'; Bradley Goldsmith; 'Peter Haywood'; [EMAIL PROTECTED] Subject: RE: [PHP] A good PHP Shop Dunno, Havn't looked at it. What's the Url? -bcg -Original Message- From: Jaxon [mailto:[EMAIL PROTECTED]] Sent: Friday, 8 March 2002 8:49 AM To: Bradley Goldsmith; 'Peter Haywood'; [EMAIL PROTECTED]; [EMAIL PROTECTED] Subject: RE: [PHP] A good PHP Shop hi how does it compare to fishcart? cheers, jaxon -Original Message- From: Bradley Goldsmith [mailto:[EMAIL PROTECTED]] Sent: Thursday, March 07, 2002 4:40 PM To: 'Peter Haywood'; [EMAIL PROTECTED]; [EMAIL PROTECTED] Subject: RE: [PHP] A good PHP Shop Check out phpshop.org. It's base implimentation is a little dry (but extremely functional). You can view a heavily modified version in the wild at my shop: www.artsupplies.com.au All the best, Brad -Original Message- From: Peter Haywood [mailto:[EMAIL PROTECTED]] Sent: Thursday, 7 March 2002 2:31 PM To: [EMAIL PROTECTED]; [EMAIL PROTECTED] Subject: [PHP] A good PHP Shop Hello,, I am looking at setting up PHP driven shop. Can anyone recommend one? Or which ones to stay away from? And why? I am reviewing phpShop at the moment, and it looks pretty nicely featured. Thanks, Pete -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] Re: uploading images
Filippo Veneri wrote: When uploading image files to my powerpc linux box (derived from redhat 7.1) running apache + php4.0.4pl1 something wierd happen. Images get corrupted by (IMHO) php itself. It adds the following 2 lines at the top of the file: Content-Type: image/jpeg^M ^M ...(rergular image file data) (as displayed by my text editor, vim). It seems a bug, as uploading images to another machine (a i386 debian 2.2 box) works as expected. Is this a known issue/bug? thanks, fbv Wierd, sounds like it could be a bug. What's the actual code you use for the upload? I presume you are running vim from the command line of the box to which the image is uploaded. Content-Type: image/jpeg is, of course, what Apache would add if you requested a .jpg file over the web. Good Luck, George -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] Re: User accounts
David Johansen wrote: I'm new to this php thing and I would like to set up a web page were the users can login and edit their preferences and all that stuff. I have the basic login stuff worked out and I was passing the username and password as a hidden input in the form, but then the password can be seen with view source. I know that there's a better way to do this, so could someone point me to a good tutorial or example on how I could make it so that the user could login and logout and then I wouldn't need to be passing the password all around like this. Thanks, Dave For me, the all round best approach to usernames and passwords is to use http authentication. Then the browser, or whatever's at the other end of the web, takes care of storing usernames and passwords for you, with the full knowledge that it is storing a username and password. The big downside is that you have so little control over how the login looks, all you get to set is the domain name. The plus sides are that your users will certainly be familiar with the prompts, it looks professional and you get all the benefits of automatic standards compatibility. For example, I was amazed to find when I was doing a wml version of a script that my existing http authentication worked fine on a mobile phone, with no changes to the code at all. I'd go into more detail, but if you've already done your login page, I guess you've already made your mind up. ;( Good luck anyway, George -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] Re: Help needed with speading up a function.
William, You need a mathematician not a computer programmer. This is classic number theory which must have been very well explored. I have a very vague recollection that there may be partial proofs that there are no primes between x and y or no more than n primes between w and z for low ranges of numbers. My instinct would be that you cannot, in general, know you are near a prime. But that's based on a wishy-washy assumption that primes are the only significant rational numbers and that all other rationals are just short hand for prime relationships. Or rather, only the primes and irrationals are necessary. Or, if you want a database metaphor, only primes are 5th normal form. Hope you are/are not trying to crack ciphers! George William Bailey wrote: Hello again. I have the following function that generates a prime number of x bits. It seems to work but i am just trying to see if i can make it any faster as generateing 1024 bit prime can take a while. so i thoought i would ask here to see if anybody has any ideas or suggestions. The function is as follows: mt_srand((double)microtime()*1); function generate_prime ($bits) { $number=gmp_init('0'); for($i=$bits; $i=0; $i--){ $rand=mt_rand()%2; gmp_setbit($number, $i, $rand); } while(gmp_prob_prime($number)1){ $number=gmp_add($number, 1); } if(strlen(gmp_strval($number, 2))!=$bits){ $number=generate_prime($bits); }else{ return (string)gmp_strval($number); } } At the moment im generating a random number of the required length and then +1ing it untill it is a prime. I suppose i really want to know if their is some way of knowing how close you are to a possiable prime so that if the random number is too far away then it could call itself again and try a different random start location. I look forward to any ideas that you might have. Regards, William. -- William Bailey. http://wb.pro-net.co.uk -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] Re: time limit ?
ÁC¬P wrote: How can I set a time limit for a form made by PHP (i.e.the value will auto transfer after a certain time) -- Ác¬P¤u§@«Ç http://fansing.hk.st/ ACG¤¬°Ê°Ï°ì(¤j®a¦h¨Ç¨Ó¶K¹Ï§a!) http://acgzone.hk.st/ HTML forms execute in the client's browser, which does not care at all whether the form came from static html file, php, Perl, whatever. The simplest way to get a browser to time out is with a META refresh html tag in the HEADER part of your page e.g. META HTTP-EQUIV=Refresh CONTENT=15; URL=http://www.mysite.com/too_long.html;. This would automatically redirect to the too_long.html page after 15 seconds. George -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] Re: Multiple browser instances - is it possible to determine which browser?
Neil Kimber wrote: We have an application framework that tidies up application session variables as you traverse from page to page It works really nicely - until a user opens up 2 instances of a browser Our code cannot distinguish between different browser instances, so browser instance 2 causes our application session vars for browser instance 1 to be cleared out We've toyed with many ideas and short of forcing a unique hidden value to be 'POST'ed to every page from every page we don't have an elegant solution Is there any other way that we could do this? Neil Good question! I'm not sure there is an elegant solution Other alternatives are: a) Pass the value as a a GET value or PATH_INFO on the urls That at least works with links as well b) Route your urls through a master script that picks up the value and then includes the real pages c) Get your web-server to do an url rewrite from a url with the embedded id to your scripts eg a rewrite from http://wwwmysitecom/id=123456/rest_of_the_url to http://wwwmysitecom/rest_of_the_url, with id set as an environment variable I guess my favourite of these would be c), which is fairly easy with Apache and mod_rewrite and saves you having to make any changes to your scripts It also means you don't have to change any urls which are relative to the current page, but absolute urls are another matter You would need to have set the id in the first place somewhere, either by trapping when it's missing on a page, picking it up and sending a location header with it included, or by getting the rewrite to go off to a special script if it's missing My very favourite solution is not to use sessions They've always struck me as swimming against the tide ie trying to impose state on fundamentally state-less protocols But then I never believed in client-server, which is what sessions seem to be about fudging Cheers, George -- PHP General Mailing List (http://wwwphpnet/) To unsubscribe, visit: http://wwwphpnet/unsubphp
Re: [PHP] MySQL Query
Erik Price wrote: I haven't seen yet a tutorial that teaches coding from the perspective of using register_globals off, which I think is pretty important (personal opinion) It's not that hard to pick up, though, once you've gotten started Still, I think it makes alot more sense to do so since it helps the new user remember that variable $x is actually in the $_GET array for example You surprise me One of my most favourite features of php is that I don't have to know that $x is actually in the $_GET array, or post array or cookie array or session array or environment array It's not just that it seems like Perl geekery I quite specifically do not want my code to be specific to a particular request/calling method To my eyes, it is much more powerful if it can be used from a form, or a link, or the command line, possibly with overrides from cookies or sessions, without changing a line of code! So, why do you want to know where $x came from? George -- PHP General Mailing List (http://wwwphpnet/) To unsubscribe, visit: http://wwwphpnet/unsubphp
Re: [PHP] how to: variable = php parsed file include
Terry Kearns wrote: I'm not sure I understand you 100% but it sounds like you want to get the static HTML results of your dynamic PHP script and and do something with it. Happily, PHP is one of the few languages that can do this with ease :-) The feature you want is output buffering. Output buffering _traps_ the output, that would normally be sent to the browser, into memory. Once you have trapped it, you can retrieve it into a variable and opptionally release it again so that it does get sent. I highly recommend reading the manual on it. http://www.php.net/manual/en/ref.outcontrol.php Gotta luv PHP ;) OK, now that you've read the manual on it, read the following example code. Maybe you want ?php ob_start(); // start trapping include_once(menu_file.php); // let PHP process the dynamic stuff $output = ob_get_contents(); // get the output into a variable ob_end_clean(); // stop trapping and release the memory used printf($output,$blah1,$blah2,$blah3); // make replacements and send output ? As you can see, an elegant way to perform the replacements would be to use printf() if possible. This means the the static output must have the right % codes in the output that would normally be sent to the browser were it not for the ob functions. http://www.php.net/manual/en/function.sprintf.php [TK] This is a very neat way of doing it now we've got output buffering. The old way would have been to read the file and then eval it. That approach is still useful if you need to do some substitutions BEFORE the php parse e.g. your own templating etc. George -Original Message- From: Brian Petro [mailto:[EMAIL PROTECTED]] Sent: Friday, 1 March 2002 6:37 AM To: [EMAIL PROTECTED] Subject: [PHP] how to: variable = php parsed file include I've got a site that I've used php to include the navigation bar as a separate file. Within that nav-bar is a small php application. I have no problem including the php nav-bar file and it gets parsed by php and the application works. The problem is that I also want to use the same file include for the navigation in a dynamic thank you page that is generated by a php-based form processor. I'm using phorm.com's php form processor which I really like. The dynamic thank you page that it generates is actually a hard coded html page which phorm.php parses to replace form variables. I think my best way to do what I want is to have the script grab the nav-bar file, parse it through php, then take the string results and set a variable equal to that string. That way I can still use the script's built in parsing that replaces form variables in the hard coded thank you page. Does anyone know the syntax to do this? I understand the concept, but I'm way over my head. Thanks! -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] pages will not refresh publically
I had this kind of old/new page problem because of proxy cacheing. The failsafe is to send out the full set of don't cache headers e.g. header(Expires: Mon, 26 Jul 1997 05:00:00 GMT); header(Last-Modified: . gmdate(D, d M Y H:i:s) . GMT); header(Cache-Control: no-cache,must-revalidate); header(Pragma: no-cache); George Miles Thompson wrote: Sounds like the old page is cached somewhere along the line. I am assuming that the same server is serving both the Internet and the private network, and there's no Oops, forgot up upload it. smack on the side of the head Miles At 08:32 PM 12/2/2001 -0500, Keith Kwasigroch wrote: I have a W2k box setup with IIS and PHP. It works fine, well almost. I can create a .php page and it works great. But, when I edit that page, the old page still shows up pubically. The page is updated if I open it from within the private network. For instance: www.domain.com displays old page, but 192.168.x.x displays updated page. Thanks in advance for any help. -- PHP General Mailing List (http://www.php.net/) To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] To contact the list administrators, e-mail: [EMAIL PROTECTED] -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] Re: PATH INFO urls - replacing GET syntax
think about putting a proper article somewhere or other. George mailto::[EMAIL PROTECTED] Navid Yar wrote: George, Good point. I actually like your idea a lot. I have never thought about using $SCRIPT_NAME. You also mentioned using $PATH_INFO to implement elegant (and search-engine safe) urls... below. Can you give me a couple of examples of how I might do this? I always hated the GET strings at the end of the url. Sometimes I redirect a user to the same page two times just to get rid of the trailing GET string. I know that's a bad way of doing it, but it was a temporary thing until I could find a way around it. I would really appreciate your help on this one. Thanks... Navid -Original Message- From: George Whiffen [mailto:[EMAIL PROTECTED]] Sent: Monday, February 18, 2002 7:09 AM To: Navid Yar Subject: Re: [PHP] form submission error trapping Navid, $SCRIPT_NAME is sometimes a safer alternative than $PHP_SELF. The difference is that $PHP_SELF includes $PATH_INFO while $SCRIPT_NAME is just the name of the actual script running. http://www.php.net/manual/en/language.variables.predefined.php This becomes particularly important if you use $PATH_INFO to implement elegant (and search-engine safe) urls e.g. /search/products/myproduct rather than /search.php?category=productskey=myproduct. George Navid Yar wrote: Simply, to send a form to itself, you can use a special variable called $PHP_SELF. Here's an example of how to use it: if ($somevalue) { header(Location: $PHP_SELF); } else { execute some other code... } Here, if $somevalue holds true, it will call itself and reload the same script/file. This code is not very useful at all, but it gets the point across. If you wanted to pass GET variables to this, then you could easily say: header(Location: $PHP_SELF?var=valuevar2=value2var3=value3); ...and so on. You can also use this approach with Sessions if you wanted to turn the values back over to the form page, assuming you had two pages: one for the form, and one for form checking and entry into a database. There are several ways to check forms, whether you want it on one page or span it out to several pages. You just need to be creative in what tools are avaiable to you. Here is an example of how you can pass session values: header(Location: some_file.php??=SID?); Here, whatever variables you've registered in session_register() will be passed to the php page you specify, in this case some_file.php. Hope this helps. Have fun, and happy coding. :) -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] zend studio 2.0
Zeev, If you find that GUI tools are not overwhelmingly better for C++, Java product development, that does weaken the case for php studios even more. Why so? 1. Conciseness of php php is a high level application development tool so the code is, or at least, should mostly consist of highly specific encapsulated business logic. This is relatively more suited to a general (possibly application progammable) text editor rather than a php-specific studio. 2. The other code php is mostly about integrating other code i.e. html/sql/Javascript/xml/pdf whatever. In the overall application these are just as important as php. The php studios seem to do a good job of bundling in sql and html tools but it's always going to be hard for one studio, however well designed, to cover the needs of several languages. 3. Maintenance vs Development Personally, I've never understood that there are distinct development and maintenance activities. Isn't maintainability the key quality issue for all code? And isn't the best way to ensure maintainability to make sure the developer maintains? In any case, php progamming is particularly likely to be mostly about maintenance. For all the right reasons: good match to business needs = more sensitivity to business needs = more changes; more robust applications = longer life = more changes; easy coding = easy changes = more changes; shorter development cycles = more prototyping = more changes. So there's lots of maintenance style work (i.e. small, short edits) relative to development. Once again this probably favours less structured development tools. 4. Unix Development Platform If my own development platform was Microsoft, I'm sure I'd need a development studio, if only to do all that opening and closing of windows. But if you can have X hundred windows open on K different desktops with G different tools, it isn't such an issue. 5. Testing on Live Servers Even with all these disincentives I'd still be very tempted to use a php development studio, especially for debugging, but the killer problem is how I test code. Typically, even unit testing is done on test domains/databases of live public servers. The advantage is that it greatly reduces the need for deployment/performance testing (and nasty last-minute deployment issues such as discovering you haven't got a live gd library with png). It also means it's very easy to get the end users/customers involved in testing early on and you don't have to worry about setting up access to lots of different platforms for third-parties e.g. html developers. The disadvantage is that there's always a firewall in the way, so it's not so easy, or desirable, to run back-door client connects to sql, debug or even ftp! (Before anyone jumps down my throat on security issues, why else do we have execution timeouts, user aborts, includes from outside document root etc., etc., unless it's to make this sort of thing possible? And isn't it better to have to focus on security right from the start of development?) I guess the bottom line is... Darned if I can see how anyone can make money out of php add-on tools, even top-notch development studios :( php is just too good! George P.S. On the other hand, if someone was asking for sponsorship to make 0.7 + 0.1 == 0.8, I'd get the cheque book out right away... Zeev Suraski wrote: At 05:02 18/02/2002, Peter J. Schoenster wrote: Well, as you said, no point in arguing. Just that I think if someone really wants to develop they should learn some better tools than a GUI but it's a question of balance. That's quite an arguable point. I don't code PHP but C++ and Java, and I can say that I'm much more productive using an advanced GUI (Visual C++, IntelliJ IDEA) than I am using a text editor and aid tools. There are still things I do in a shell (diffing, grepping, patching, even tiny text edits), but to actually write big code portions, and/or refactor existing code portions, IDE's give you tools that simple text editors just don't. Of course, it's a matter of habits and taste, but saying that 'someone who really wants to develop should learn some better tools than a GUI' is simply bogus in my opinion. GUIs are better than text-mode tools in many ways, and text-mode tools sometimes get the job done quicker than GUIs. A good GUI would address 80% of your needs, and you can fill in the gap with the tools you were used to. Zeev -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] Re: uploading files | how to avoid submitting twice?
Jim Winstead wrote: Andy [EMAIL PROTECTED] wrote: Is there a way to redirect imediatelly to a waiting page? I tryed to redirect, but somehow the server is first uploading the file before something else happens. unfortunately, no. one thing you can do is use javascript to pop up a small window in your form's onsubmit method that tells the user to hang on, and then close that window in the next page's onload method. it isn't easy to do a real progress meter, but even this little bit should help tremendously. you may also want to check the md5 sum of the file contents against previous uploads to detect duplicates. jim I've never tried it, but it may also be possible to disable the submit button once it has been pressed once to stop the second upload e.g. HTML HEAD SCRIPT LANGUAGE=javascript function submitonce() { if (document.form.submitted.value == No) { document.form.submitted.value == Yes; return true; } else { alert(Please wait...); return false; } } /SCRIPT /HEAD BODY FORM OnSubmit=return submitonce(); INPUT TYPE=HIDDEN NAME=submitted VALUE=No INPUT TYPE=FILE NAME=uploadfile INPUT TYPE=SUBMIT OnClick=return submitonce(); /FORM /BODY /HTML N.B. I've set the form's OnSubmit and the submit button's onClick, only because I'm not sure which will work best. I'd expect this to work with a normal form submit but maybe file upload is funny... George -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] form submission error trapping
Navid, $SCRIPT_NAME is sometimes a safer alternative than $PHP_SELF. The difference is that $PHP_SELF includes $PATH_INFO while $SCRIPT_NAME is just the name of the actual script running. http://www.php.net/manual/en/language.variables.predefined.php This becomes particularly important if you use $PATH_INFO to implement elegant (and search-engine safe) urls e.g. /search/products/myproduct rather than /search.php?category=productskey=myproduct. George Navid Yar wrote: Simply, to send a form to itself, you can use a special variable called $PHP_SELF. Here's an example of how to use it: if ($somevalue) { header(Location: $PHP_SELF); } else { execute some other code... } Here, if $somevalue holds true, it will call itself and reload the same script/file. This code is not very useful at all, but it gets the point across. If you wanted to pass GET variables to this, then you could easily say: header(Location: $PHP_SELF?var=valuevar2=value2var3=value3); ...and so on. You can also use this approach with Sessions if you wanted to turn the values back over to the form page, assuming you had two pages: one for the form, and one for form checking and entry into a database. There are several ways to check forms, whether you want it on one page or span it out to several pages. You just need to be creative in what tools are avaiable to you. Here is an example of how you can pass session values: header(Location: some_file.php??=SID?); Here, whatever variables you've registered in session_register() will be passed to the php page you specify, in this case some_file.php. Hope this helps. Have fun, and happy coding. :) -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] Re: PHP-JavaScript
Mëòv îçîÎ òsyïn wrote: Is it posible to get values from javascript to PHP? Without having to post the variables.. Thanks //Mårten _ Chatta med vänner online, prova MSN Messenger: http://messenger.msn.se I'm not quite sure what you are trying to do. Javascript is executing on the browser, php executes on the server, therefore to get anything from the Javascript to php your browser will have to communicate with the server via a request. This could be a form submission, which might be a POST or a GET. Alternatively, it is also possible to send data to a php script via a url e.g. myscript.php?myfield=myvalue. That means that wherever you can get Javascript to cause the browser to issue a request for a url, if the target at the other end is a php script then you can send data to that script. I don't know what you are trying to do, and this is all pretty obscure stuff, but you could for example put a hidden 1x1 image in the page and then get your Javascript to change the location of this image to be a php script with a variable passed on e.g. something like dummyimage.location = /myscript.php?myfield=+myjsvalue; As long as you get the php to send back another empty 1x1 pixel, e.g. via a header(Location: 1x1pixel.gif), then your browser page will stay the same as ever. As it happens I do sometimes do just this in Javascript but it's to get a new dynamic image back without reloading a page. Go to http://tandridge.cpfc.co.uk/tables/0222/graph/2/d7 and then select something different in the Team 1 or Team 2 selection box, and watch the graph at the bottom of the page to see this happen. In the source look for the Javascript function chteam_id() to see how it's done here. Good luck, George -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] Re: form submission error trapping
Jason, You didn't mention Javascript checks. Personally I really dislike having to wati for a page to reload before finding out that I've just failed to fill in a field. The Javascript to do basic on-page checks is all pretty simple stuff. Of course this doesn't mean we can skip checking the data again in the php! Javascript might be switched off, we might have a bug in the Javascript (easy to do), or we (or someone else) might want to simulate form entry via a url link. It's also quite likely that there may be checks e.g. checks for duplicate entries, which cannot be done on a form. Here's some skeleton code that handles a basic form with both php and javascript checks, (I've deliberately tried to keep the php/Javascript as similar as possible). You can try it at http://www.whiffen.net/simple.php if you want. *** simple.php*** SCRIPT LANGUAGE=php if (isset($surname)) { $errormessage = ; if ($surname == ) { $errormessage = $errormessage . brYou must enter a value for surname; } if ($age = 0 or $age != floor($age)) { $errormessage = $errormessage . brAge must be a whole number; } if ($errormessage == ) { // do whatever you have to with the data and maybe finish with // a redirect to a success page } } print ' HTML HEAD SCRIPT LANGUAGE=javascript function check() { var message = ; if (document.myform.surname.value == ) { message = message+\nYou must enter a value for surname; } if (document.myform.age.value != parseInt(document.myform.age.value)) { message = message+\nAge must be a whole number; } if (message != ) { alert(You have the following errors to correct:+message); return false; } else { return true; } } /SCRIPT /HEAD BODY H1MY FORM/H1 FORM name=myform method=post onSubmit=return check(); '; if ($errormessage != ) { print 'You have the following errors to correct'.$errormessage.'BR'; } print ' Surname: INPUT TYPE=TEXT NAME=surname VALUE='.$surname.' BR Age: INPUT TYPE=TEXT NAME=age VALUE='.$age.' BR INPUT TYPE=SUBMIT BR A HREF='.$SCRIPT_NAME.'sSource/A /FORM /BODY /HTML '; /SCRIPT You'll see that http://www.whiffen.net/simple.php?surname=whiffenage=23.2 works perfectly well too. Personally, I'm not a huge fan of Javascript. It always seems to be much more trouble than php for some reason, but it has its place, (as long as you never rely on it!). George Jason Dulberg wrote: I am working on some error trapping for several forms on my site. After visiting a bunch of websites, I've noticed 2 common methods of displaying error messages. 1. display an error box on a new page and force the user to hit the back button 2. display the form again with appropriate error text and pre-filled fields. I have part of the error on the new page working but I'm running into the infamous no contents in the form after going back. There are some useability issues with forcing the user to hit the back button -- some just don't want to bother. Is there a way to display the form w/original contents and error messages 'without' having to code the entire form twice? I have about 5 forms with 50 fields or so each. What would be the best way to go about redrawing the form with the errors shown beside each field? Any suggestions are greatly appreciated. __ Jason Dulberg Extreme MTB http://extreme.nas.net -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] Re: Has anyone created or called a Web Service from PHP? (SOAP)
Yeah, From php, I've called paybox (http://www.paybox.de), which is a mobile phone based payment service. You exchange transactions with them via xml. They have their own cartridge for php, but it's just a perl rewrite and not very wonderful, so I rewrote most of it. The basic approach is simply to open a socket to the service, send out your xml, and/or listen for xml from them. To parse the xml, you could try one of the php xml parsers, or if they are simple, known, messages, you could just parse them yourself with a few regular expressions see ereg. If you want to write an xml server, php may not be your best bet although I guess it could be done. The problem with the server is all about multi-threading so you don't force everyone to queue on the port while you're processing each request. I've done something similar with tcl using a simple looping stub that listened on the port and passed off requests to sub-processes asynchronously But if you only need to call, then the functions you need are: fsockopen(), fputs(), fgets(), fclose() You might also want to tweak with socket_set_blocking, socket_set_timeout and socket_get_status The manual is quite good on all these nowadays, start with http://www.php.net/manual/en/function.fsockopen.php If this is communication with an xml server to execute a payment, (as with Paybox), you have to design your transactions carefully if you want to avoid all the problems of duplicate payments, interrupted payments, user cancels, web server goes down in the middle of a transaction, php bombs out, their xml server goes down in the middle of a transaction etc. If you get this wrong, you WILL end up with discrepancies between your record of transactions and your payment providers sooner or later. The good news is that you can make it very robust with php, and with a lot less work than if you had to use Java, C or some similar language. The main tricks are:- a) Make your communication with the xml server a 2-phase commit, so if either of you goes down mid-way, the other one knows and can rewind. b) Record your own version of the transaction in a database and use that to check for duplicates, user cancel requests, timeouts etc. c) Put up a holding page with an auto-submit to tell the user you've started and give them an option to cancel explicitly in case they see problems. In Paybox's case the user was involved in the payment authorisation loop via their mobile phone, so this was essential. If you do this you can safely wrap your code in an ignore_user_abort to give extra protection, while still giving the user a sensible message and their own option to cancel if they feel they are waiting too long. d) Make your sql transaction updates atomic i.e. when marking your transaction as valid include a where clause on the update to make sure it has the expected status and hasn't for example, already been processed from another browser window. That way even if your database doesn't support transactions, provided the database server at least locks a row during update, you'll be safe from transactions switching back to cancelled after they've actually been completed (and vice-versa). The key point is that you can do just as secure and safe a job of commercial-grade transaction processing with the likes of php/mysql etc., as with the hard-core geek tools, provided you get the design right. You have a very good channce of doing a much better job, since you don't have to waste so much time on all their geekery. George Eric wrote: I have a PHP webstore that I want to call my web service that is running on an IIS machine. The web service returns XML. Has anyone called or written a web service with PHP? TIA Eric -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] Apache keeping php waiting on output flush
Hi, Apologies if this is more of an Apache question than a php one, but as it's about the relationship between them, I thought it was safe to bring it up here ;) While investigating a possible performance issue, I discovered that (according to microtime()), my script runs 5 times faster for a local client i.e. telnet GET from the web host itself. I had expected that although the local GET would obviously be much faster than anything else overall, the php execution as reported by microtime() would be similar for any kind of client. I had mistakenly thought that Apache would handle buffering to the client, leaving php to get on with the rest of its script. It seems that when php flushes its output buffer it has to wait for Apache to actually send it to the browser client before the flush returns. Any thoughts/observations? George For the record the environment is : php/4.0.1pl2 Linux/2.0.36 Stronghold/2.4.2 Apache/1.3.6 -- PHP General Mailing List (http://www.php.net/) To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] To contact the list administrators, e-mail: [EMAIL PROTECTED]
[PHP] Is php safe for e-commerce applications?
What a scary day, and it just gets worse 1. A user finds their account balance is displayed incorrectly on one of my live e-commerce sites. 2. I discover that floor() intermittently gives the wrong answer i.e. print floor(10*(8.20 - 0.20)); Answer : 79 print floor(10*(8.10 - 0.10)); Answer : 80 (php 4.0.6 and 4.0.4.pl1 under Linux 2.2.19.) 3. I find this is a known feature with no intention of ever being fixed. See http://bugs.php.net/bug.php?id=6220 print floor( (0.7 + 0.1) * 10); Answer : 7 4. I check the php documentation that was added because of that bug (http://www.php.net/manual/en/language.types.float.php) and discover :- never trust floating number results to the last digit and never compare floating point numbers for equality. 5. I realise that the last digit might also be the first so that means never trust anything except integers! 6. The truth really sinks in... It seems I simply cannot use php for e-commerce applications unless I convert all money to integers e.g. $4.32 must be handled as 432 cents, or all arithmetic operations and comparisons have to be converted to use bc functions. Instead of : if ($cost == 10.00) you must write if (bcomp($cost,10.00,2)) == 0) etc.,etc. 7. The horror unfolds... php is just as full of geeko-trash as C/Perl/Java and the rest of them! I will have to spend the rest of my life worrying about types/casts/floating point precision and all that garbage even when I'm just adding up dollars and cents! I can't even escape to Italy and work in Lira, they're switching to euros with decimal places too! I should have stayed with Java, it may be rubbish but at least it's obviously rubbish! Please someone, tell me I'm wrong! Tell me that 0.1 + 0.7 can be 0.8 and not almost 0.8! Tell me I don't have to check the last three years of work! Tell me php isn't just for kids waiting to graduate/degradate to Java! Tell me the techno-geeks haven't won! Hell.. George -- PHP General Mailing List (http://www.php.net/) To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] To contact the list administrators, e-mail: [EMAIL PROTECTED]
[PHP] Re: Need advide on partnership agreement for a php application...
Py wrote: Hello, I have an application wich I maintained on my servers (PHP, Apache, MySQL). I have a client that is already using the application trought a secure link directly from his web site. But he would like to have my application update a database directly on his server (Oracle) in order to protect the statistical data collected trought the application, wich is a lot... I see no problem to open a connection to update his Oracle database on his server. I use phplib so it would not be a major modification. But some questions remains: - Opening a connection directly to his oracle database is not really more secure in any way. (If I get hacked, he get's hacked...) - It seems to me a false security since the data are manipulated by the PHP engine on my server anyway... - Creating a database (in order to replicate mine) would tell him a lot about how I do my stuff... (but I do not really care tho) My solution was to provide all statistical data to him with a secure (SSL) link and give him everything in XML so he could update his database just the way he want's it. What do you think? What sould I tell him? I really need advice since this is a field unknown to me... py p.s. I do not really know where to post a question like this one wich is not really related to PHP directly... Sorry... Hi Py, I guess it all depends on why your user really wants the data. Does he want to keep it as a backup in case something happens to the copy on your server or does he really want to manipulate it via Oracle? If he wants a backup I guess that's fair enough but why should he bother putting it in Oracle until he needs it? If he wants to manipulate, I guess your question is what is that he wants that do you not provide? Some observations: 1. If I were you I would not want to get involved with his Oracle database at all. It's all too easy for you to get blamed unjustifiably for all kinds of problems e.g. the comms link doesn't work, they don't like the data structures, their Oracle crashed etc. etc. 2. Your idea of providing the data in xml sounds good. But are they up to handling xml? Everyone talks about it and claims they want it, but when it comes down to it, they're not ready! What about giving him a boring old csv or tab-delimited text file? He can easily enough get it into Oracle when he wants, and it's very hard for anyone to blame you for Oracle problems. It's also nice for managerial customers, because you can show them the data in Excel/whatever and they can see for themselves that you're supplying the data. Then, if they are not getting what they want, it's absolutely clear that it's because of problems at their end, not your end. 3. The one time I met a proper cracker, Oracle databases were among his favourite targets, so, as you say, opening an Oracle connection doesn't sound like an improvement to security! Practically, my approach to your customer would be to agree with whatever he asks for in principle, but make sure that you end up sending him csv/tab-delimited versions of all the data via a https download first. You can say it's as a test, or so they can explore the issues, get a feel for the data structure/volumes or whatever. My guess is that is all you will ever have to do. Once they see how much work they have to do at THEIR end, they'll go all quiet. You might also suggest that while they are exploring the issue you could fill in any immediate gaps in what you're offering them e.g. more summaries, different analyses, whatever... Hope that helps, George -- PHP General Mailing List (http://www.php.net/) To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] To contact the list administrators, e-mail: [EMAIL PROTECTED]
Re: [PHP] How do I convert from perl to php? - Reality Check Taxation
Ok, Let's concentrate on acceptable syntaxes for your html programmers to specify the required fields first. Here are some options grouped by technique and roughly put into order of increasing difficulty for an html author: HTML 1. INPUT TYPE=HIDDEN NAME=required VALUE=name address phone PHP FUNCTION 2. required(name,phone,address); 3. required($name,$phone,$address); PHP ASSIGNMENT -- 4. $required = 'name address phone'; 5. $required = 'name,address,phone'; 6. $required = array($name,$address,$phone); COMPLETE INLINE PHP CODE 7. Rasmums solution (slightly modified): if (!(1==1 isset($name) isset($address) isset($phone) )){print 'You left one empty.';} It's really up to you to say which of these is most acceptable to your html guys. The order also roughly corresponds to decreasing amounts of php code and support required. Here's the supporting code for each: 1. INPUT TYPE=HIDDEN NAME=required VALUE=name address phone --- foreach(explode(' ',$required)) as $field) { if (${$field) == '') { print 'You left one empty.'; break; } } 2. required(name,phone,address); function required() { foreach(func_get_args() as $field) { global ${$field}; if (${$field} == '') { print 'You left one empty.'; return; } } } 3. required($name,$phone,$address); --- function required() { foreach(func_get_args() as $field) { if ($field == '') { print 'You left one empty.'; return; } } } 4. $required = 'name address phone'; foreach(explode(' ',$required) as $field) { if (${$field} == '') { print 'You left one empty.'; break; } } 5. $required = 'name,address,phone'; foreach(explode(',',$required) as $field) { if (${$field} == '') { print 'You left one empty.'; break; } } 6. $required = array($name $address $phone); foreach(explode(' ',$required) as $field) { if (${$field} == '') { print 'You left one empty.'; return; } } 7. Rasmus Solution -- Already complete! The closest to your original is 4., and it is pretty close. However, if your html guys are really so allergic to code I would have thought that 1. would suit them best. The great benefit of 7., is that your html guys would learn something useful that they could apply elsewhere rather than a special rule on where to put required fields when they're working with you on a particular kind of job. For the record I typically have a completely different approach to the whole problem i.e. A. I would have field-specific (onChange) and form-wide (onSubmit) Javascript validation on the form page itself as a courtesy to the browser users and to save them unnecessary page loads. B. In the php, the checks would be repeated explicitly for users without Javascript or non-browser users and would include an unique identifier so that the form could be intelligently driven remotely by another application e.g. if ($name == '') { $errormessage .= error:myform:0100 name is a required field.br; } if ($address == '') if ($errormessage != '') { print 'Please correct the following errors -br'.$errormessage; etc. C. The data would almost certainly have ended up in a database even if it is being mailed on or whatever. So the question of non-programming html designers adding required fields would not arise. I can't think of much data that I might trouble a user to enter that isn't worth explicitly storing. But then I guess we work on different kinds of applications. It sounds like you can't afford more than a couple of minutes per form while I have the luxury of half an hour or so. Good luck, George Brandon Lamb wrote: The point of keeping it easier is what if i want to give my script to a friend, do you REALLY want to explain to a non-programmer how to add another if statement or condition when they could simply add the field to the array? And actually you only have to change the name in 2 places. 1. you define the variable as an input from a form 2. in the required fields array - Original Message - From: George Whiffen [EMAIL PROTECTED] To: [EMAIL PROTECTED] Sent: Wednesday, November 21, 2001 7:28 AM Subject: Re: [PHP] How do I convert from perl to php? - Reality Check Taxation So I would have to write a seperate if condition for each form input field i wanted to require? that doesn't make for a very dynamic script... if(!(isset($name) isset($address) isset($phone)) { echo You left one empty.; } Reality Check
[PHP] Re: possible problems working with sessions
Sorry if I'm off-topic, but I've always wondered what people use sessions for. I seem to be either dealing with logged-in users who I pick up via http-authentication and maintain any details I need in a user data structure, or casual users, for whom the odd hidden input field or occasional cookie seems quite enough. I guess I'm also nervous of anything state-full, especially if it makes you dependent on cookies/funny urls/IP addresses etc.. So why do people use sessions? Alberto Mucignat wrote: well, if you're using default session handling provided with php, users sessions are stored in /tmp directory (also used by default for temporary caching of uploaded files). assume to have the php.ini file with default settings: session.gc_probability = 1 session.gc_maxlifetime = 1440 this means garbage collector lauched 1 times every 100 started sessions. furthermore, deletable sessions are those ones opened 1440 seconds ago (24 minutes). well, i've doing some tries asking web server the following by wget command, (but i suppose you can use also a sockopen or CURL (!) functions...): HEAD /test_session.php HTTP/1.0 where /test_session.php simply starts a session with session_start() function. every single request create a session file in the /tmp server directory. if someone find out how to do many simultanious requests could create so many files in the /tmp dir (while the garbage clean them only after 24 minutes). we know that linux filesystem is limited to 64K files per directory. this could create problems... obviously there are some kind of solutions... - play with session.gc_* php settings in order to prevent problems (but i can't be sure that's a good idea...) - provide a different session storage than the default one. in this case, you have only two other solutions: mm and database storage. i prefer to store sessions in a database, because with mm this could generate worse problems with memory usage... but i mean... there are so many php developers that uses php with default settings (for example: newbies that uses phpnuke or other php content manager session based)... about sessions i've found: http://www.phpwizard.net/resources/tutorials/session_intro.html seen Tobias around? :-) bye, alberto. ps: well, i work with session since not long time, so can be i made a mistake... -- PHP General Mailing List (http://www.php.net/) To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] To contact the list administrators, e-mail: [EMAIL PROTECTED]
[PHP] Different syntax = different performance (concatenating assignment)
Dear All, I had always thought of concatenating assignment and concatenation + assignment to the same variable as really just syntatical variations i.e. I thought that $data = $data . some strings; and $data .= some strings; were just alternate syntaxes for the same operation. I've always tended to use the long format on the grounds that it was more readable and maintainable. How wrong I was! It seems the performance on big strings can be hugely different. I think I know why but I'd appreciate confirmation. I came across this when investigating a performance issue with writing out a gz-encoded csv file from an SQL table. The code is something like: $data = ''; while ($row_product = mysql_fetch_array($cur_product)) { $data = $data . ''.str_pad(strip_tags(strtr($row_product[product_code],'\',',' ')),40) .','.str_pad(strip_tags(strtr($row_product[product_name],'\',',' ')),60) .','.str_pad(strip_tags(strtr($row_product[product_desc],'\',',' ')),120) .''.\r\n; } $Size = strlen($data); $Crc = crc32($data); $data = gzcompress($data); $data = \x1f\x8b\x08\x00\x00\x00\x00\x00 . substr($data,0,strlen($data) -4) . pack(V,$Crc). pack(V,$Size); fwrite($handle,$data); fclose($handle); There seemed to be plenty of reasons why this ran slow (5 seconds plus on only a couple of thousand product rows). I suspected each of the strtr, strip_tags, str_pad and gzcompress in turn but it turned out that a simple change:- $data = $data . into $data .= ran an order of magnitude faster (i.e. less than 0.5s). I guess that in the first case a working copy of $data has to be made, whereas in the second, the concatenation is done directly on the existing copy of data i.e. the performance difference is just the price of creating and throwing away two thousand copies of $data. Does that make sense? Anyone know of other cases where alternate syntaxes can make such a difference to performance? If I get some confirmation of this analysis I'll bung a note on the manual at http://www.php.net/manual/en/language.operators.string.php Humbled, George -- PHP General Mailing List (http://www.php.net/) To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] To contact the list administrators, e-mail: [EMAIL PROTECTED]
Re: [PHP] How do I convert from perl to php? - Reality Check Taxation
So I would have to write a seperate if condition for each form input field i wanted to require? that doesn't make for a very dynamic script... if(!(isset($name) isset($address) isset($phone)) { echo You left one empty.; } Reality Check: We write code to solve real world problems! The parts of our code which are essential to the describe the real world problem we want solved are essential. All the rest of our code is an unfortunate tax on the rest of the world. The code can be as complex, dynamic, interesting or clever as it likes, it's still tax! Very dynamic scripts have to be JUSTIFIED, they are not, repeat not, intrinsically good! In this case, the essential elements are the names of the fields required and the message to be sent if they are not present i.e. the following 38 characters name address phone You left one empty. Rasmus code consists of 92 characters i.e. 44 extra characters or around 110% tax. Does that sound a lot? Your original perl had 192 characters i.e. over 400% tax. What about maintainability/reusability? Lets look at the tax element of some likely changes: 1. Change in the name of one of the required fields e.g. name should now be lastname Rasmus : 0% TAX: (You change name to lastname once) Perl : 200% TAX: (You change name to lastname in 3 places) 2. Remove one of the fields from the required list Rasmus : 12 characters TAX (You have to remove isset($) as well as the field name itself) Perl : 13 characters + 200% TAX (You must remove $ = param($);\n and the field name 3 times) 3. Add a new field As per 2. above. 4. Modify the conditions for the error message e.g. change to name and either address or phone required Rasmus : 4 characters TAX (change to or and add two brackets) i.e. if(!(isset($name) (isset($address) or isset($phone)) { Perl : Rewrite requiredunknown cost! Well, I hope that resolves the question of which is the more world-friendly code (i.e. more tax efficient). Personally, and all views on simplicity, elegance and beauty of code are subjective, I also find Rasums php version much simpler and easier to understand. It involves far fewer commands and is therefore much more accessible to the novice programmer. It has much less extraneous structure and is clearly focussed on the task in hand. It can very easily be extended and modified to provide richer functionality. What more do we want? (Well personally, I'd rather he used and instead of and not instead of ! and put the separate conditions on separate lines and generally had more white space ;). George P.S. Is this a characteristic example of the difference beteeen Perl and PHP or an extreme example? Is Perl really so geeky in style and application? Or am I just too stupid, stubborn, ignorant to see that Perl is better than php? [EMAIL PROTECTED] wrote: So I would have to write a seperate if condition for each form input field i wanted to require? that doesn't make for a very dynamic script... if(!(isset($name) isset($address) isset($phone)) { echo You left one empty.; } On Tue, 20 Nov 2001 [EMAIL PROTECTED] wrote: I am a perl user trying to convert to php how would i turn this perl into php? use CGI; $name = param(name); $address = param(address); $phone = param(phone); @required = qw( name address phone ); foreach $key($required) { if (!$$key) { out(You left one empty.); } } ?? -- PHP General Mailing List (http://www.php.net/) To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] To contact the list administrators, e-mail: [EMAIL PROTECTED]
Re: [PHP] Process bar
Arvydas V. wrote: Hello, I have to solve one problem - my script searches simply text document, so - if this document is big enought - i have to replace timeout of my script, besides - i have to make, that then this proceeds some kind of process bar must scroll until script finishes his job... so - any ideas ? Thnx anyway :) See flush(). You can send output as you go along as long as you flush it as you go. George -- PHP General Mailing List (http://www.php.net/) To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] To contact the list administrators, e-mail: [EMAIL PROTECTED]
[PHP] Re: Authenticating Users with their Windows Login
Feroze Md. Arif wrote: Hi, First of all, my apologies if this question has been asked earlier. I am in a hurry and I haven't checked the archives (Actually, I am in the process of doing it but am trying to cover all the bases). I know that PHP has functions which will allow Users to be authenticated off a NIS Server or a LDAP server. Will it be possible to do something similar in PHP with the User IDs and Passwords stored in a NT or Windows 2000 server? I would appreciate it very much if anyone could point me to resources that could help me or share some sample scripts :) :) Thanks in Advance, Feroze === Jar Jar Binks will be Jedi! I'm no expert but I think this depends on your web server. I know for sure that IIS can do http authenticates against NT/Windows 2000 accounts and although I know Microsoft used to make it difficult for third-party web servers in the old days, I would have thought it was possible nowadays. As far as Php is considered, the user/password show up in $PHP_AUTH_USER, $PHP_AUTH_PW or something similar. To force an authentication you send an http Authentication header e.g. Bottom line: Check with your web server news group/user list. -- PHP General Mailing List (http://www.php.net/) To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] To contact the list administrators, e-mail: [EMAIL PROTECTED]
[PHP] Re: Date Problem
Mindhunter wrote: Hi, I am reading a date from an input in format 'DD-MM-' ex. 10-11-2001. Now I want to add 3 months to the date. I have tested mktime and strftime etc and no matter what I do I get the year as 1970. (Systemdate works fine). How would I go about adding 3 months to a date in that format? Thanks MH The following works for me: $mydate = '10-11-2001'; list($myday,$mymonth,$myyear) = explode('-',$mydate); $mymktime = mktime(0,0,0,3 + $mymonth,$myday,$myyear); $newdate = date('d-m-Y',$mymktime); newdate is then 10-02-2002 You might check : 1. You always use a 4 digit year 2. mktime order of arguments i.e. hours,minutes,seconds,months,days,years 3. Output date format on date() function 4. There are problems with dates pre 1970 AND pre 1901, (pre 1970 is pre unixtime, pre 1901 is pre phptime). I had problems with pre 1901 dates which the calendar module solved ( see jdtojulian, juliantojd) -- PHP General Mailing List (http://www.php.net/) To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] To contact the list administrators, e-mail: [EMAIL PROTECTED]
[PHP] Re: Problem with Header!
Yeah, It seems to be a black art to get the browsers to behave properly. I don't know if it's relevant but I use Content-disposition and Content-type rather than Content-Disposition and Content-Type and it seems to work for me for inline;. I haven't tried inside;. If you really can't get it working, I guess there is a pretty kludgy workaround available (at least with Apache) by doing a redirect to the filename first and then getting your script to pretend to be that file and just return the result anyway. If you can guarantee that your file will NOT exist, you could for instance get Apache to go to your php script on a 404 not found. So the sequence goes: 1. Request comes to your script 2. Your script immediately redirects to the filename you want to be. 3. Apache fails to find the file and calls your script as the error handler. 4. Your script then correctly executes and returns the appropriate results. Or maybe there is some very clever trick that could be done with the Apache rewrite module, but that's another black art! You might want to try a post to Apache or another http mailing list. Regards George and then making sure there is something there to supply your result For downloads of tab data: header(Content-type: text/tab-separated-values); header(Content-disposition: inline; filename=missing.txt); seems to work. Andre Lacour wrote: I want to sent a script-result as a renamed html-document to the client. I tried: - header(Content-Disposition: inside; filename=name.html); - header(Content-Disposition: inside; filename=\name.html\); - header(Content-Disposition: inside;); header(Content-filename=name.html); even with a content-type: text/html... but it doesn't work. inside replaced by something other like attachement or inline does not work, either! someone an idea? thx -- PHP General Mailing List (http://www.php.net/) To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] To contact the list administrators, e-mail: [EMAIL PROTECTED]
[PHP] Re: How to save a dynamic search result for later use as a static page?
Look at the output buffer handling functions: ob_handler etc. These let you take the final (or intermediate) output of the script and do whatever you want with it e.g. save it, or in your case save it and empty it. In that case your user could have a simple SAVE button which ran the entire script and then at the last minute saved the output, (possibly with extra stuff added in), as a static page (or in a database) but didn't pass it back to the user at all. Tom Smith wrote: Hi All, Here is the problem: I have a quey building form that returns results from a database as a form to generate a new query. On open, it shows a form, then on submit it shows resutls that are in a form (checkboxes that let you omit that record from the next query by $id). What I want to do is let the user save the page to show others in his group. First I though of saving the query, but then it seemed simpler to just save the resutling html to a file that could be referenced in email. How do you get the current page to slurp into a file along with all the current variables? On an unrelated note, it seems like I'm generating the restults twice. Any input on how to stream-line it? full script: ?php if ($save) { //save is a hidden field, will always be true so that I can test fwriting to saved.html $fp = fopen(/home/www/html/locations/site/saved.html, w); //$fp = fopen(saved.html, w); //fflush($fp); //fpassthru($fp); fwrite($fp, ??); } # ln -s index.php omit.php # This file is a search form/query builder with the ability to # pare down a result set. function Refine($query, $to_omit) { $query = str_replace(order by locations.id, AND , $query); /* //debug: foreach ($HTTP_POST_VARS as $k = $v){ echo k: $k, v: pre$v/pre; } */ if ($to_omit) { trim($to_omit); $arr_to_omit = explode( , $to_omit); array_pop($arr_to_omit); foreach($arr_to_omit as $v) { $query .= locations.id != '$v' AND \n; } } $query = chop($query); $query = substr_replace($query, '', -3, 3); $query .= order by locations.id; $query = str_replace(~, ', $query); return $query; } ? html headtitleLocations search/title link rel=stylesheet href=images/klamath.css type=text/css script language=JavaScript !-- hide from old browser// function checkOmit() { var form = document.refine form.to_omit.value = '' for (var i = 0; i (form.omit.length); i++) { if (form.omit[i].checked) { form.to_omit.value += (form.omit[i].value) + ' ' } } return true } //quit hiding -- /script /head body bgcolor=#6E89AB ?php $db = mysql_connect(localhost, user, password) or die (No connection); mysql_select_db(locations,$db) or die (No select db); if ($submit == 'refine') { Refine($query, $to_omit); //debug: // echo h2After function calll we get:/h2\$query\; /* //debug: $headers = getallheaders(); while (list ($header, $value) = each ($headers)) { echo $header: $valuebr\n; } */ $res = mysql_query ($query, $db) or die (brBad query, comrade. line 77, number: .mysql_errno()., . mysql_error()); $query = str_replace(', ~, $query); //gotta hack 2wice $numrows = mysql_numrows($res); if($numrows 1) { echo Nope, nothing like that.; } echo h2Refined Results:/h2\n; echo form name=refine onSubmit='return checkOmit();' method=post\n; echo input type=hidden name=query value=\$query\br; echo input type=hidden name=refine value=true\n; echo input type=hidden name=to_omit value='$to_omit'\n; echo input type=hidden name=save value='save'\n; echo tabletrtd background='images/bg-menu.gif'valign=top\n; include menu.php; echo /tdtd\n; echo table align=center width=95%\n; echo tr bgcolor=silvertdThumbnail/tdtdAddress/tdtdContact/td/tr\n; $c = 0; while (($row = mysql_fetch_array ($res)) $numrows 0) { $c++; $id = $row[id]; $loc_name = $row[loc_name]; $folder = $row[folder]; $thumb = $row[thumb]; $address = $row[address]; $city = $row[city]; $state = $row[state]; $zip = $row[zip]; $contact_id = $row[contact_id]; $name = $row[name]; if(strlen($description) 150) { $description = substr($row[description], 0, 150).'...'; }
[PHP] Re: strpos
I always get strpos wrong. So typically in this case I would do something like: list($file,$ext) = explode('.',$yourimage); if ($ext != 'jpg' or $ext != 'jpeg') { error... } (More properly we should make sure jpg or jpeg are at the very end of the filename i.e. you probably don't like myfile.jpegold.gif so you would need: list($ext,$file) = explode('.',strrev($yourimage)); $ext = strrev($ext); $file = strrev($file); if ($ext != 'jpg .etc. ) If $yourimage really is a reference to an image e.g. an uploaded image, you might like to run getimagesize() on it to see if it really, really is a jpeg and not just called .jpg or .jpeg see (http://www.php.net/manual/en/function.getimagesize.php). George Jtjohnston wrote: I suppose I'm doing this right? I want to know if the user entered \.jpeg or \.jpg. If he didn't, it should error. It errors anyways? What do I have to do add slashes in my input??? :o) // if((!strpos($yourimage, \.jpg)) || (!strpos($yourimage, \.jpeg))) \\ --- tried both! if((!strpos($yourimage, .jpg)) || (!strpos($yourimage, .jpeg))) { error_found(error found); $errorfound++; } -- PHP General Mailing List (http://www.php.net/) To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] To contact the list administrators, e-mail: [EMAIL PROTECTED]
[PHP] Re: JPG Images from database to filename.jpg
I'm confused. Is your problem serving up the images in your database to the web or writing them out to files on the server? If it's serving images, I would expect you to have: select myimage from db Header(Content-type: image/jpeg); echo $myrow[myimage]; exit(); etc. If it's writing from the db to a real file on your server, I would expect: select myimage from db open myfile write $myrow[myimage]; close myfile etc. The Header is just for the web, to tell the browser or other client what kind of file it is getting from your php script since it is not the expected type automatically supplied by the web-server (text/html). Real physical files don't need a header. The web servers automatically generate appropriate headers for real image files based on the file extension before they send them out over the web. Does that make sense, or have I completely missed the point? George Mike Gifford wrote: Hello, I've got a number of images in a database.. Ultimately what I would like to do is be able to resize the image that is already in the database and then insert that image into another field. Uploading the files generally inserts these both at the same time, however I need to create a number of new thumbprints based on a different scale. What I thought would be easiest would be to take the image, save it to filename.jpg and then run the thumbnailing script on it. I think that this would look like the following: ?php // There's other DB stuff here, but this isn't important $Images = stripslashes($row[0]); $File = ReThumbnail.jpg; // Create JPG image ImageJPEG(imagecreatefromstring($Images), $File); // Scale image system(djpeg -pnm $File | pnmscale -xscale .1 -yscale .1 | cjpeg $File.tmb); // Write thumbprint $fd = fopen( $File.tmb, r+); $tmb = addslashes(fread($fd, filesize($File.tmb))); fclose($fd); // Insert Thumbprint image into database $sql = UPDATE Images SET Thumbnail='$tmb' WHERE ID=$ID; // There's other DB Stuff here too... ? I'm really quite stuch here.. How do you take a db image of a database and create a physical jpg file? I think I'm getting messed up by the header in: Header(Content-type: image/jpeg); echo $Images; I can't figure out how to create the header. There's lots of examples of how to do the above, but I have yet to stumble across an example which allows you to write the header into a file Suggestions would be appreciated.. Mike -- PHP General Mailing List (http://www.php.net/) To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] To contact the list administrators, e-mail: [EMAIL PROTECTED]
[PHP] Re: HTTP_POST_VARS and eval?
Henrik, I think your problem is jsimply that you are not getting variable substitution of $HTTP_GET_VARS[whatever] inside double quotes. print whatever is $HTTP_GET_VARS[whatever]; is not safe. You need print whatever is {$HTTP_GET_VARS[whatever]}; or, (IMHO better), print 'whatever is '.$HTTP_GET_VARS[whatever]; The fact that you are actually evaluating an assignment is I think irrelevant, it's just the variable substitution that's failing. See the variable parsing section of http://www.php.net/manual/en/language.types.string.php George Henrik Hudson wrote: Hey List- Working on a program and I seem to have run into a problem with HTTP_POST_VARS. Are the HTTP_VARS considered special? Here is what I am doing, reading in from a file into an array and then grabbing each line and looking for ]string[ and replacing that with $HTTP_POST_VARS[string] The first echo prints out the lines correctly, but the echo after the eval prints out the same lines. My error log shows this: PHP Parse error: parse error, expecting `T_STRING' or `T_VARIABLE' or `T_NUM_STRING' in /data/www/webpages/test.rhavenn.net/public_html/formmail/formmail.php(164) : eval()'d code on line 1 So, its having problems doing an eval on the HTTP_POST? If I replace the HTTP_POST stuff with just$\\1 and then define $string = $HTTP_POST_VARS[string] it works just fine, but I can't do this since I don't know what string is going to be, just that it is between ] [ chars and there can be multiple ] [ on one line. Any thoughts? Code is below. //Read the array $form_data = ; for($i=0; $i count($filearr); $i++){ $line = $filearr[$i]; //Strip the ] [ from around the variables so they will be interpreted $line = eregi_replace(\]([^\[]+)\[, \$HTTP_POST_VARS['\\1'], $line); echo Line: $lineBR; //eval the variables from $line into themselves and they become literal eval (\$line = \$line\;); echo Lineafterwards: $lineBR\n; //Write the line back into a single variable $form_data = $form_data . $line; } exit; Thanks! Henrik -- Henrik Hudson [EMAIL PROTECTED] -- PHP General Mailing List (http://www.php.net/) To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] To contact the list administrators, e-mail: [EMAIL PROTECTED]
[PHP] Re: Image Upload, renaming question
Joe, One approach that works for me is to have a separate IMAGE table with an automatically generated primary key image_id (auto_increment with MySQL). I don't use this store the image, but just to give me the unique name for the image file. I also use the IMAGE table to store away the original image name, and the image type and dimensions from GetImageSize. Type and dimensions can be useful to have stored in case you need to set IMG WIDTH and HEIGHT dynamically to maintain proportions if the image is over-sized for the page it's on and/or manipulate and image with gd functions. The IMAGE table is shared across the whole site to guarantee unique image names and any updates of images are always handled as inserts to stop problems with browsers caching old images. image_id is then held on the table where the use of the image is recorded e.g. the table holding a page's content. The actual directory where the images reside is not actually held in the database but set as a global in a standard include. This makes it easier to move between machines/sites etc. without changing data. This seems to work well, you can use standard code for image upload/update/deletion and functions for image_insert, image_delete etc. Cheers, George Joe Van Meer wrote: Thx Richard, I would like the files to all be dumped into one directory, each with a unique name. Then I will create a path and store that in the db. Thx for the ideas, I will check them out and get back to youvia this thread. Cheers Joe:) Richard Lynch [EMAIL PROTECTED] wrote in message [EMAIL PROTECTED]">news:[EMAIL PROTECTED]... Joe Van Meer wrote: Hi there, I have an upload form on my website that works great, however I have come to a roadblock...how the heck do I rename the copied file? Everytime I upload an image it overwrites the old one with the new. The code below uploads the file and displays the following: Your photo has been uploaded successfully. Size of Image in Bytes: 36315 Image Type: image/pjpeg File exists on server. /rotatingimages/C:\PHP\uploadtemp\php12D.tmp -- I notice that this is a temporary name If two files were being uploaded at once, you'd get two different names... But it's entirely up to *YOU* to decide where to copy the file to. Maybe you'd *WANT* to replace files as they were uploaded. I tend to use the user's filename and preg_replace() to get rid of everything except a-zA-Z._- and then checking where I'm copying to tack on 1, 2, 3, ... until I find a new filename that's not in use. You should also start using http://php.net/move_uploaded_file instead of copy or whatever you are doing. -- Like music? http://l-i-e.com/artists.htm -- PHP General Mailing List (http://www.php.net/) To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] To contact the list administrators, e-mail: [EMAIL PROTECTED]
[PHP] Re: Example code for multiple uploads? (Using PHP 4.0.6)
Nate Carlson wrote: I'm trying to create a form that supports multiple uploads (of up to 4 files), but does not require each of them. I've tried all the code examples in the PHP documentation, and they don't appear to work with PHP 4.0.6. Basically, I get the file names returned in the arrays, but the array that should contain the name of the temporary file just says 'none'. Things work fine for a single upload. Does anyone have example code for this? Thanks! :) -- Nate Carlson [EMAIL PROTECTED] | Phone : (952)943-8700 http://www.real-time.com| Fax : (952)943-8500 Multi loads are fine for me in 4.0.3 at least, but I don't use arrays, each upload has a different name (I gave up on form arrays at IE 3!). Have you tried giving them unique names? George -- PHP General Mailing List (http://www.php.net/) To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] To contact the list administrators, e-mail: [EMAIL PROTECTED]
[PHP] Re: apache+php overloading when user clicks many times on the same link
Peter Frlicka wrote: Hello. What does apache + php do if the user refreshes a page 10 times in a while before the scripts finishes? do all 10 .php scripts finish or do the first 9 get aborted? how can i solve the problem that when someone clicks a lot on a link (always the same link) the server gets overloaded (because the action taken in the script is somehow memory consuming). i need to ensure a user (www) can run only one instance of a .php script. Peter Frlicka See http://www.php.net/manual/en/features.connection-handling.php I'm worried about why the user is clicking so much. If your connection/processing really is going to take a long time you could consider sending them the first bit of your page as quickly as possible using flush(). That will take away any buttons/links they've clicked on (but not Refresh), and at least make them feel something is happening! However multiple clicking is a general problem with no great solutions. It's a particularly important issue for on-line E-commerce applications when it is not only vital that the php script complete but also that it should not be repeated. For that you almost have to use a database to record transactions (or at least the session variables which identify a transaction). I typically do the following : 1. set ignore_user_abort 2. check to see if we have a record of this transaction, if we do check to see if it is complete. If it's complete take them to a results/end page, if it's not complete take them to a holding page with an automatic META-REFRESH to the same url. 3. if we have no record of the transaction, create one, do the work, mark the transaction as complete and show them the results/end page. If the user only clicks once, everything proceeds smoothly and they get their results page as normal. If the user clicks two or more times they go to a holding page with an automatic refresh which keeps showing the same holding page until the first script completes and the next refresh takes them to the results. This is basically a safe approach but it's significant work unless you really need it! George -- PHP General Mailing List (http://www.php.net/) To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] To contact the list administrators, e-mail: [EMAIL PROTECTED]
[PHP] Re: PHP versus all other languages
Pat Hanna wrote: I'm doing my senior exit project on database languages online. I'm asking for help from anyone who can provide any information on the comparison between the different languages. I'm comparing languages such as PHP, ASP, ColdFussion, perl and any others that I might not know about that you guys might know. Thank you to anyone who helps me out in the least. Patrick -- Database integration--E-commerce solutions The Wentworth Company Get paid cash every time you receive email! Sign up FREE at: http://www.MintMail.com/?m=1080349 What criteria are you thinking of using to compare them? You might, for example, consider : - useability - supportability - productivity - functionality - performance - scalability - stability/robustness - product support - ease of integration with other technologies and I guess you'll mention cost, but don't forget to include : - licensing costs - hardware costs - development personnel costs e.g. development programmers - administrative personnel costs e.g. system administrators, DBAs - support personnel costs e.g. support programmers For the record, I'd pick php over the others on the following grounds: 1. ColdFusion worries me when it comes to performance, functionality and its ease of integration with other technologies. Good integration with the other Macromedia technologies, e.g. Dreamweaver, Flash rather than good integration with databases and third-party web technologies smtp/xml etc. 2. ASP has product support,stability,robustness and in particular long-term backward compatibility issues. I would feel very nervous about signing a five year support contract for an ASP application without plenty of escape clauses! 3. Perl has issues over useability/supportability primarily because it was never designed for web database applications, not because it can't do them well. I would rather have to maintain an application someone else wrote in php than the same application written using Perl, simply because the php is likely to be much easier to follow and understand than the Perl. 4. It's not easy to find fault with php, except when it comes to marketing. It's grossly undersold, but then some of us find that very refreshing ;). George George. -- PHP General Mailing List (http://www.php.net/) To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] To contact the list administrators, e-mail: [EMAIL PROTECTED]
Re: [PHP] Session
For the record: You can control the order of precedence of variable reading through a php.ini setting, variable_order, (replaces gpc_order). I believe the default is EGPCS i.e. environment, get, post, cookie, session. The last in the list takes precedence, i.e. session variables normally have precedence over get/post variables George Rudolf Visagie wrote: The problem lies with the fact that you have a variable 'name' that gets posted in the form as well as a session variable 'name' that is passed to the script when it is executed again. As far as I remember the session variable supercedes the posted variable, so the session variable would overwrite the value of the posted variable every time. You need to register the session variable with another name and then toggle between the two variables in you script. Also, a session variable need only be registered once: if (!session_is_registered(name)) { session_register(name); } Rudolf Visagie Principal Software Developer Digital Healthcare Solutions Tel. +27(0)11 266 6946 Fax. +27(0)11 266 5080 Cell: +27(0)82 895 1598 E-mail: [EMAIL PROTECTED] -Original Message- From: jtjohnston [mailto:[EMAIL PROTECTED]] Sent: 15 November 2001 09:08 To: [EMAIL PROTECTED] Subject: [PHP] Session Hi, I have read: http://www.php.net/manual/en/function.session-register.php Could I ask you a question about how to set a session $vars in a FORM? It seems to be quite a mystery/controversy!! This is my problem: http://www.collegesherbrooke.qc.ca/languesmodernes/postcard/test_session.php Type something. Press submit. Change your text and re-submit. $name doesn't re-save itself. This is my code: http://www.collegesherbrooke.qc.ca/languesmodernes/postcard/test_session.php s Would you have any suggestions? It can't be that complicated can it? J.T-Johnston -- PHP General Mailing List (http://www.php.net/) To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] To contact the list administrators, e-mail: [EMAIL PROTECTED] -- PHP General Mailing List (http://www.php.net/) To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] To contact the list administrators, e-mail: [EMAIL PROTECTED]
[PHP] Re: FTP Clients
I kind of like Leech FTP, http://stud.fh-heilbronn.de/~jdebis/leechftp/downloads.html George Rudi Ahlers wrote: Sorry for the totally OT question, but can anyone recommend a good, FREE, FTP client for windows? I now have to pay for AceFTP aswell, which used to be free. Thank you Rudi Ahlers -- PHP General Mailing List (http://www.php.net/) To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] To contact the list administrators, e-mail: [EMAIL PROTECTED]
[PHP] Re: Including declare statements that contain variables
Well you have an interestingly different approach! Personally I kind of like either having the SQL statements in-line with the rest of the code or functions that retrieve data for that particular query e.g. function get_students($class) { Anyway based on your approach: 1. You could still solve your problem of having to worry when the constant definitions are included by setting global variables instead of constants and then doing an explicit eval-uation at their time of use e.g. In include : global $SelectByClass; $SelectByClass = 'Select * from students where class = \'.$class.\''; In code : GetData('SelectByClass'); In GetData: function GetData($query_mask) { extract($GLOBALS); eval ('$query_string = '.${$query_mask}.''); mysql_query($query_string . This would guarantee that you always use the values of the global variables current when you issue the query. So you can move your includes back up the top! Of course it doesn't help if you ever want to use a local value of a variable in a query but it seems that doesn't interest you. 2. I notice you return a pointer to the results set rather than the results themselves. This means you still have to have mysql_fetch_... outside of GetData. Why not return an array of the result rows instead? i.e. add to GetData while ($rows[] = mysql_fetch_array($result)); mysql_free_result($result); return ($rows); This has the advantage of letting the rest of your code remain database independent. 3. You may not need to pass the connection id ($db_conn) to mysql_query. Mysql will default to using the last connect if none is specified. 4. You should be aware that you approach may have performance implications since you are carting ALL global variables into the symbol space of each call to GetData. Running under Apache with register_global_vars that meant 158 variables even without any GET or POST variables. However the new reference count implementation of variables in php4 may minimise the impact of this. With any luck, it won't actually make a copy of any of your global variables in memory! I was pleasantly surprised at how fast an extract($GLOBALS) ran, (7ms for me). I guess the choice between your approach and the more conventional approaches of in-line selects, per-select function call, or encapsulation as a data object is simply about maintainability. Personally I always prefer more lines of boring but simple code to clever structures which may be obtuse to the poor guy who ends up maintaining my code. Anyway, it's always interesting to see different approaches. I'd never properly checked out define, extract and $GLOBALS until now. Good Luck, George Fred wrote: I would like to offer my recent experience in the hope that it will help others avoid the wasted effort and frustration I managed to burden myself with yesterday. I will start by stating that the conclusions I have drawn may seem obvious at first blush, however in a troubleshooting environment it is sometimes difficult to see the forest for the trees. This is particularly true when several principles of PHP syntax are working in concert to produce a problem. My problems started when I found myself in the rare position of needing to write a function that accessed global variables rather than passed values or references. This need arose because I was writing a data access abstraction function and would have no way of knowing in advance what variables would need to be accessed or in what order. The total number of possible variables was large when compared with the total number of lines of code in the function. If I had chosen to write the function to accept an associative array that could be extracted within the function to produce the needed variables the total number of lines of code needed outside of the function to produce the array would have been greater than the total number of lines of code within the function. Because the purpose of choosing to use a function rather than writing the code several times was to reduce the number of lines of code and provide clarity to the script I decided that passing an array to the function was not an option. I decided to simply write the function so that it had access to all variables in the GLOBALS array to overcome this problem. The function was as follows: // Function to send query and retrieve result pointer function GetData($Query) { extract ($GLOBALS); $Result = mysql_query($Query, $db_conn) or die (mysql_error()); Return $Result; } The function accepts an SQL statement as an argument and returns a pointer to a result set. The SQL statement that is passed to the function is one of many defined constants, many of which contain variables. For example: define (ClassesByTeacher,SELECT Classes.SectionNo, Period, CourseNo, Title, Teacher FROM Classes, Attendance WHERE Classes.SectionNo = Attendance.SectionNo AND Teacher LIKE \$Teach\ AND
Re: [PHP] keeping my code! Why?
Zend encoder is probably your best option. But why do you want to hide your php code from your Server Admin? 1. If you can't trust your Server Administrator you've got big problems. Change your hosting! 2. Are you sure your code is so valuable? Developers always seem to greatly overestimate the value of their code to anyone else. There's loads of really great php freely available out there to handle almost any general task. A lot of effort goes into publicising it yet it's still hard to get anyone interested in looking at it, let alone using it. 3. Is the php code really what you need to protect? My experience is that most of the difficult parts of an application are embedded in the data structures, the functionality and the presentation, not the php code. Any idiot can develop php code if they know exactly what it has to do (and that it can be done...) 4. If you're worried about your customer simply keeping the code and not paying you, my advice is to give up. If someone wants to rip you off they probably will. You'll do yourself just as much good by taking the simple step of asserting your copyright and being ready to go to court if they don't pay and still use the software. You'll be lucky to win, but at least it'll be clear who is ripping off who. 5. I hope your real interest is not just to lock your users/ customers into using you for all maintenance work. If so my advice is to stop using Open Source products such as php and switch to proprietary products. The proprietary world has been living for years off customer lock-in and has all the techniques to help you get your share of the rip-off as long as you're on their side. If you stick with Open source, you get none of that business support/price umbrella and your customers are much more likely to come up with embarrassing questions like: Why are you fleecing us? In general, if you think your old code is an asset and you're just protecting it, think again. All code is obsolete before it's finished. It's only your skills/experience that really matter and the best way to protect them is to share your work and learn from others. Good Luck, George Michael A. Peters wrote: On Wed, 14 Nov 2001 18:38:48 +0700 Ye Tun [EMAIL PROTECTED] wrote: Hi all, I am not sure if this is the right list to ask. But I am wondering if I can keep my php code from Server Administrator of the web server I am putting my code on? Is there anyway I can encrypt or do something so that the server admin can't look at my code. REgards, Ye ZendEncoder works really really well. It's not free- but hey, those guys have given us a lot already. The server _must_ be running the ZendOptimizer or it won't work. I recommend getting the ZendEncoder (assuming it has been ported to your devel platform- last time I checked, it hadn't yet been ported to OS X or PPC Linux- but it has been ported to the major x86 distro's) ZendEncoder solves a lot of problem. When you code, that's your value :) -- -=-=-=-=-=-=-=-=-=-=-=-=- Michael A. Peters http://24.5.29.77:10080/ -- PHP General Mailing List (http://www.php.net/) To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] To contact the list administrators, e-mail: [EMAIL PROTECTED]
[PHP] Re: Time out for file()? - Use fsockopen
Jean-Arthur, Your set_time_limit/shutdown function solution looks like a clever trick. If you can come up with that you might just as well do the proper job with an fsockopen and socket_set_timeout. The manual pages on fsockopen, socket_set_timeout plus the user comments have plenty of useful examples: http://www.php.net/manual/en/function.fsockopen.php http://www.php.net/manual/en/function.socket-set-timeout.php You might also want to look at socket_set_blocking as an alternative. (Switch to non-blocking so that your gets always returns immediately and then you can put in your own wait/action before trying another gets). Check out: http://www.php.net/manual/en/function.socket-set-blocking.php Either way, to write your own jasfile() to emulate file() shouldn't be more than 10-20 lines. An extra advantage of using fsockopen is that you can send a HEAD request before your GET/POST to check the server/page are there. If that works you can then give the target server longer to serve the GET in case the problem is just slow communications rather than a missing/slow server. Good Luck George Jean-Arthur Silve wrote: Hi ! I use the file function for accessing to pages on another server. It works perfectly. But if the server does not respond or is too long to send datas, the file function wait too long.. Is there a way to tune the time out ?? I would like that id the server does not respond, the function return in few seconds only. I thought to a solution using : set_time_limit(2); register_shutdown_function(func); file(myurl); set_time_limit(30); func(); In this example if the file function takes more than 2 seconds, then func() would be called. If the file function does not time out, then then func is called too... But may be there is a cleanest way to do this (I checked the manual, somethink like socket_set_timeout), in the way that if the time function timed out then the script continues normally, returning an error: tuning the time out(2); $f=file(myurl); if ($f==false) // Timed out else // ok Thank you ! jean-arthur --- EuroVox 4, place Félix Eboue 75583 Paris Cedex 12 Tel : 01 44 67 05 05 Fax : 01 44 67 05 19 Web : http://www.eurovox.fr -- PHP General Mailing List (http://www.php.net/) To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] To contact the list administrators, e-mail: [EMAIL PROTECTED]
Re: [PHP] Help! How do i mail a value from a mysql databse?
There's also a potential problem with: Her har du ditt passord: $myrow[id] \n God appetitt! Hilsen Subway You are using double quotes for the array index,(id) within a double quoted string. I'm amazed php accepts this, you might expect it to parse that as Her har du ditt passord: $myrow[ and then id and then ] \n God appetitt! Hilsen Subway which should generate a syntax error at id. Until recently it certainly didn't substitute array variables in double quoted strings at all. There's a whole bunch of stuff in the manual now about ensuring correct parsing of variables inside double quotes with the use of braces etc. See: http://www.php.net/manual/en/language.types.string.php (N.B. I think the English version is more comprehensive than the German) However the simple safe thing to do is just to break the string i.e. Her har du ditt passord: . $myrow[id] . \n God appetitt! Hilsen Subway Or even better IMHO: 'Her har du ditt passord: ' . $myrow['id'] . ' \n God appetitt! Hilsen Subway' Personally I don't think the automatic substitution of variables in double quotes really helps. I prefer to use single quotes since they don't get in the way of double quotes in HTML e.g. print 'TD COLSPAN=3'; My simple rules are : single quotes for php strings double quotes in HTML/Javascript explicit concatenation of any php variables e.g. print 'TD COLSPAN='.$myrow['colspan'].''; NOT print TD COLSPAN=\{$myrow[colspan]}\; Of course ,the important thing is to be consistent. Once you start inserting php array variables into Javascript strings inside HTML attributes of HTML embedded into php strings, you want to be sure you can work out what on earth is going on! Regards, George David Robley wrote: On Wed, 14 Nov 2001 04:26, Raymond wrote: Hi! I'm trying to send a mail with password to the new user of my website, but . Does anyone know how to put the variable inside my mail? I have tried this: -- else { // sende kundeopplysninger til databasen $db = mysql_connect(localhost, root); mysql_select_db(subway,$db); $sql = INSERT INTO nettkunder (fornavn,etternavn,firma,adresse,postnr,sted,telefon,epost) VALUES ('$fornavn','$etternavn','$firma','$adresse','$postnr','$sted','$telefo n','$ epost'); $result = mysql_query($sql); echo Velkommen som kunde hos Subway.\n; } $db = mysql_connect(localhost, root); mysql_select_db(subway,$db); $id = mysql_query(GET id FROM nettkunder WHERE epost = '$epost',$db); mail($epost, Velkommen som kunde hos Subway, Her har du ditt passord: $myrow[id] \n God appetitt! Hilsen Subway); The value you are passing in $myrow[id] doesn't exist in your code. You need to do $myrow = mysql_fetch_row($id); after your mysql_query to populate the row data. And your query should probably read SELECT id FROM... -- David Robley Techno-JoaT, Web Maintainer, Mail List Admin, etc CENTRE FOR INJURY STUDIES Flinders University, SOUTH AUSTRALIA Washed the cat - took HOURS to get the hair off my tongue! -- PHP General Mailing List (http://www.php.net/) To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] To contact the list administrators, e-mail: [EMAIL PROTECTED]
[PHP] Re: silly question
Rodrigo, I don't quite understand your problem, it might help to see some of the php or form html. It might also help if I explain how I usually handle updates. I have a single php page with the form on it which is also the target of the form. Typically users get to the form via a link which includes the id on the url (i.e. passed as a GET variable). The php picks up this id and uses it to query the database to get the current data. Then the form is presented with the form values set to the current values and the id included as a hidden field. The user makes a change and presses a submit button with the name update (INPUT TYPE=SUBMIT NAME=update) The php checks to see if update is set (isset($update)). If it is it uses the form values to update the database before it goes to search for the current values. Then it just continues as normal retrieving the database (new) values and printing out the form. i.e. the logic is : if (isset($update)) { update database for id record e.g. update mytable set myfield = '.$myfield.' where id = '.$id.' } select data for id record into myrow e.g. select * from mytable where id = '.$id.' print form including data e.g. print ' HTMLHEAD/HEADBODY FORM ACTION='.$SCRIPT_NAME.' METHOD=POST MY FIELD : INPUT TYPE=TEXT NAME=myfield VALUE='.$myrow['myfield'].' INPUT TYPE=SUBMIT NAME=update /FORM /BODY/HTML For the user this means they always have visual confirmation that their changes have gone to the database after pressing SUBMIT. If they're happy they have a link to go wherever they want to next. If they're not happy they can correct the data and submit again. Could you be getting problems because there is confusion between your hidden id and the id on the url? The ACTION='.$SCRIPT_NAME.' should sort that out since it will remove anything passed on the url when the form is submitted. Or perhaps you have set the values in the form to php variables with the same name as the form variables e.g. print 'INPUT TYPE=TEXT NAME=myfield VALUE='.$myfield.' If this is the case, then the form will always come back with the last entered details and not blank details since $myfield is continually being set to the value of the HTML input variable myfield. Sorry I can't help more without getting a better idea of what you are trying to achieve! George Rodrigo Peres wrote: Hi list, I have PHP code to insert the result of a form into mysql. When I nedd to made an update, I pass an id in the url and use it to make the update query. The problem is after I click in the update button (input submit) my page refresh and came back in the same state, to see the changes I need to type in the url again with the parameter?? why?? There's a way to avoid this and get a new blank form page after the update? ps: I've stored the id in a input type hidden, so I could click the button and still have the id Thank's in advance Rodrigo Peres -- -- PHP General Mailing List (http://www.php.net/) To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] To contact the list administrators, e-mail: [EMAIL PROTECTED]
[PHP] Basic handling of pre 1901 dates
I'm feeling dumb! The Basic Problem = Basically all I want to do is to output each day in turn from 1900 i.e. 01-Jan-1900 02-Jan-1900 03-Jan-1900 etc. But date() won't accept dates pre 13-Dec-1901 and mktime doesn't like anything pre 01-Jan-1970. I know I can get mysql to do this without trouble but not efficiently. So how do you work with pre-1901 dates in php? The Full Problem In actual fact what I'm trying to do is list all dates within a given range which are NOT in a mysql table. The dates and date ranges can span anywhere from 1850 to the present. I can very easily use mysql to generate an array of the days which are present in the table. What I can't seem to do is get php to run through each day in turn and let me output it. The only possible solution I can think of is to just generate a dummy mysql table with all dates I might ever use and then join that to my actual date table and select the non-matches. Not a very elegant solution! What have I missed? George -- PHP General Mailing List (http://www.php.net/) To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] To contact the list administrators, e-mail: [EMAIL PROTECTED]
[PHP] Re: Validate CSV file With Table in Database!!
Coenraad, Here are some links to relevant sections of the php manual. What you want to do is not too hard at all. I'm assuming that you want to upload the csv file via a web page. This is much less trouble for the user than fooling around with ftp. They get to browse their computer for the file and then upload with a single click. 1. Uploading a file http://www.php.net/manual/en/features.file-upload.php#features.file-upload.post-method 2. Opening the uploaded file http://www.php.net/manual/en/function.fopen.php 3. Reading fields from the uploaded file http://www.php.net/manual/en/function.fgetcsv.php 4. Updating the table It depends what database you are using as to how you do this. The obvious approach is to SELECT for each row in your csv file, and then either UPDATE it or INSERT a new one, depending on whether you found it. So putting it altogether you want something like this. You'll have to check the syntax, add error checks etc., and this is based on mysql as the database:- // refreshdata.php ?php if ($mycsvfile != '') { $fp = fopen($mycsvfile); mysql_connect(); while (list($keyfield,$datafield) = fgetcsv($fp)) { $cur_table = mysql_query(select datafield from mytable where keyfield ='.$keyfield.'); if (mysql_num_rows($cur_table) == 0) { $ins_table = mysql_query(insert into mytable (keyfield,datafield) values ('.$keyfield.','.$datafield.'); } else { $upd_table = mysql_query(update mytable set datafield = '.$datafield.' where keyfield = '.$keyfield.'); } } mysql_close(); fclose($fp); } ? HTML BODY FORM enctype=multipart/form-data method=post CSV file : INPUT TYPE=FILE NAME=mycsvfile INPUT TYPE=SUBMIT /FORM /BODY /HTML Coenraad Steenkamp wrote: I need to compare a csv file to a table in the database but only one field in the database with one field in the CSV file! Comparing only one field will make it much easier! When there is any change in the Database compared to the CSV file , the database must then be updated or if there are no such a field it must be added to the table! I am new in php Please help! -- PHP General Mailing List (http://www.php.net/) To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] To contact the list administrators, e-mail: [EMAIL PROTECTED]
[PHP] Re: newbie looking to sync access with MySQL
Tom, Every man and his dog seems to have an Access database they want to view on the web. What I usually do for them is : a) Tell them to save the data from Access as a text file, comma separated. (It's a standard Access option). b) Give them a web page where they can upload it, (INPUT TYPE=FILE etc., it's discussed in the php manual). c) Parse the file using parsecsv and store away the bits you want in MySQL. If you get them to leave the field names on the first line of the file (another standard Access option), you can do a quick check that all the fields are there and in the expected place, before you put the data into MySQL. d) Serve the web pages from MySQL. e) You may still need your Web Data Administration. There's often missing data that you need for sensible web pages e.g. categories, more user friendly descriptions of codes etc. From the customer's point of view the uploads are a manual exercise which doesn't sound very sexy, and it would probably take them 3-4 minutes every time. The good thing is that it's all pretty easy, and they should be able to get their most junior member of staff to do it. They also get the comfort of knowing if anything went wrong. If that's not acceptable, it's more tricky. In principle you could use an ODBC interface to their Access database to establish a live connection to it and suck up the data that way, but it's fiddly and much less reliable than a boring old upload. Another option would be to execute the extract and transfer of the data via a batch job running on their platform. But, personally, I would hate to have to support that kind of activity. The bottom line as far as I'm concerned is that if they insist on holding important information on a MS platform, they can expect a) not to have a seamless operation, b) to have to watch out for problems themselves! Once they see how easy an extract/upload is they probably won't mind anyway. Tom Beidler wrote: I have a potential customer that just called and would like to create a web site that would display secure info for their clients. Currently his employees are using a flat Access database to add, edit and delete records and he would like to keep it that way. Normally I would create a web manager for them to add, edit and delete the MySQL database. Is there an easy, reliable way to sync up Access with MySQL. Maybe a nightly script that could upload the contents of Access to MySQL. Would it be easier to start with ASP and SQL Server? Thanks, Tom -- PHP General Mailing List (http://www.php.net/) To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] To contact the list administrators, e-mail: [EMAIL PROTECTED]
Re: [PHP] php includes === Dreamweaver library items
Robert, Well, I bet you're getting tired of this thread! So just a few closing remarks: a) Nested Loops - Yup, they're not so common that we can't just fudge about with a bit of embedded html. b) Luggage - I may yet agree with you about the advantages of two neatly packed bags! c) An awkward DreamWeaver/php solution - It seems I'm close to achieving what I set out, it may be functional, but it's not particularly elegant,thats for sure. Here's how it goes : For the Dreamweaver user: - the files on the site targetted by urls are .php templates which remain fully Dreamweaver editable/previewable and link-testable. All the html is in those files. The designer can include any number of Dreamweaver library items and change their names at any time as they like. - the Dreamweaver library files must be synced with the server along with the .php templates, style sheets etc. Provided the designers do that, all pages are guaranteed to have the library code in the current master (server) copy, which can be edited by any means. Designers have to watch out for master copies changing either because of the activity of other designers or programmers of course. For the php programmer: - the main body of php code (queries etc.) is in a per page include, i.e. the template reads the code instead of the code reading the template! (That's so the designers can check the links are ok). - the include of the code is added to the top of the designer's template in a php tag. - in the html of the template the progammer adds/checks tags for the php data and control structures i.e. for data ?= $myvar;? or ?php //?Example of myvar?php;print $myvar;?. for repeating or conditional blocks you need start and end tags ?php if ? or ?php while ...? at the start and ?php };? at the end of the block. There are no restrictions on the php you can embed, you can have includes of any depth, functions, whatever. - you can also, if you want, add php to library items without restriction. Noone of that seems to be too bad, but the one special and really horrid extra on each page is to force the substitution of includes for library items. It seems (but I haven't tested it fully), that the code to top and tail the actual template html is this : IMMEDIATELY PRIOR TO ACTUAL TEMPLATE HTML/PHP eval(dream_sub(strrev(substr(strrev(substr(PHPENDFILE ? TEMPLATE HTML/PHP HTML HEAD etc. /HTML IMMEDIATELY AFTER ACTUAL TEMPLATE HTML/PHP !-- PHPENDFILE ,3)),5; //--?php ? where dream_sub is something like this: - function dream_sub($string) { return(preg_replace('/!-- #BeginLibraryItem ([[:alpha:].\/]+) --.*?!-- #EndLibraryItem --/' ,'?php eval(dream_sub(implode(,file(\\1;\?\',$string); } (Beware, the regular expression is wrong, I'm still trying to get it to work, ereg_replace was fine but too greedy so I had to switch to preg) That's it. It's not too much code and it is the same every single time, but ugly or what! It could be a bit prettier, but as it's always going to be horrible, I'm tempted to leave it looking horrible, so noone's under any illusions! What we're actually doing is turning the whole of the template html/php into a string via the heredoc but while fooling Dreamweaver that we closed the php tags. We strip out the php/comment tags which fool Dreamweaver with a strrev and substr's to save having to store the text and then fooling about, (that could be changed). Then having picked up the template contents we substitute any Dreamweaver library item tags by an include of whatever the library name was. Just in case we have nested library items (I don't know if that's possible with Dreamweaver), we make sure we recursively substitute any library items in the library item files themselves as we bring them in. (That's why we have the dream_sub/implode/file stuff instead of a plain include). I reckon this should work (when I get the b regular expression working!). It should also work reasonably well with any other html editors that respect php tags, and if they have library functionality it shouldn't be too hard to adapt dream_sub for an appropriate effect. At the end of the day, this all seems to be spoiling the Dreamweavers far too much. I've even gone back to calling the pages .php rather than leaving them extensionless, just so that their stupid desktops don't get too confused! So my urls are going to be uglier but I guess it at least means that php gets some credit on the sites! Anyway, it's been very interesting to hear your ideas, and don't be surprised if I give up and switch to FastTemplate! George Robert V. Zwink wrote: George Whiffen, a) Nested Loops One problem that I see is that if I have nested loops: !-- BEGIN DYNAMIC BLOCK: loop1 -- {LOOP1_VARIABLE} !-- BEGIN DYNAMIC BLOCK: loop2 -- {LOOP2_VARIABLE} !-- END DYNAMIC BLOCK
[PHP] ereg_replace - How do I stop it being greedy?
Hi, I've got a problem with regular expression syntax with ereg_replace: ereg_replace(':start:(.*):end:','this is \\1',':start: first :end: middle :start: last :end:'); returns - this is first :end: middle :start: last but I want - this is first middle this is last The problem seems to be that ereg_replace is being greedy on the match and matching as much as it can instead of just finding the first match, handling that and then going on to the next match. I can get it to work with preg_replace i.e. preg_replace(':start:(.*?):end:','this \\1',':start first :end: middle :start: last :end:') returns - this is first middle this is last But my actual string is on multiple lines, and preg_replace doesn't seem to continue trying to match on the next line, whereas ereg_replace happily treats newlines just like any other character. So how do I stop ereg_replace being greedy or alternatively get preg_replace to treat multiple lines as a single source string? George -- PHP General Mailing List (http://www.php.net/) To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] To contact the list administrators, e-mail: [EMAIL PROTECTED]
Re: [PHP] ereg_replace - How do I stop it being greedy?
Thanks Jack, preg_replace with an s modifier works a treat. I'm still curious as to how to get ereg_replace to work as well. Everything I read about regex/Posix Regular Expressions, seems to suggest that a ? should also work with ereg_replace! George Jack Dempsey wrote: look into the s modifier...it makes a dot match a newline as well, where normally it wouldn't jack -Original Message- From: George Whiffen [mailto:[EMAIL PROTECTED]] Sent: Friday, September 07, 2001 1:09 PM To: [EMAIL PROTECTED] Subject: [PHP] ereg_replace - How do I stop it being greedy? Hi, I've got a problem with regular expression syntax with ereg_replace: ereg_replace(':start:(.*):end:','this is \\1',':start: first :end: middle :start: last :end:'); returns - this is first :end: middle :start: last but I want - this is first middle this is last The problem seems to be that ereg_replace is being greedy on the match and matching as much as it can instead of just finding the first match, handling that and then going on to the next match. I can get it to work with preg_replace i.e. preg_replace(':start:(.*?):end:','this \\1',':start first :end: middle :start: last :end:') returns - this is first middle this is last But my actual string is on multiple lines, and preg_replace doesn't seem to continue trying to match on the next line, whereas ereg_replace happily treats newlines just like any other character. So how do I stop ereg_replace being greedy or alternatively get preg_replace to treat multiple lines as a single source string? George -- PHP General Mailing List (http://www.php.net/) To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] To contact the list administrators, e-mail: [EMAIL PROTECTED] -- PHP General Mailing List (http://www.php.net/) To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] To contact the list administrators, e-mail: [EMAIL PROTECTED]
[PHP] Re: clear contents?
Jeremy, I don't think it's possible to do what you want, and I have tried finding a way. With your header you are requestion an http authentication which means the browser has to store the username and password and send them with EVERY page. Those are the rules. The only way to tell the browser to lose the username/password that I've found is to tell it that they're incorrect, (even though they are correct). But if you do that it will go and ask the user to type them in again another three times before it gives up and drops them. You'll find that most of your users will probably keep the username/password even after closing the browser and switching their computer off, which I guess is even worse as far as you're concerned. I hope I'm wrong but if you really must get them to enter username/password every time, I think you'll have to create your own login box and forget about http authentication. It might be worth posting your question to an apache newsgroup as well. Even if you're not using Apache, you should find those guys know just about everything there is to know about http authentication. Good Luck and I hope I'm wrong! George Jeremy Morano wrote: Hi everone... I'm having a little problem. The code below pops up a password dialog box where the user types in a username and a password to be able to proceed. However, if the user does not close the browser and goes back to the link, which they pops up the diolog box again and they don't have to type in there username and password again. They are remembered. I would like it so that the user has to type in there username and password any and every time that the diolog box is called on. Doe anyone know how to do this? I tried to clear the contents of PHP_AUTH_USER and PHP_AUTH_PW at the top of the page but that just messed things up. Can someone please help me? ? session_start(); session_register(PHP_AUTH_USER); if (isset( $PHP_AUTH_USER ) isset($PHP_AUTH_PW)) // Connect to MySQL mysql_connect( 'l', 'c', 'c' ) or die ( 'Unable to connect to server.' ); // Select database on MySQL server mysql_select_db( 'contact' ) or die ( 'Unable to select database.' ); // Formulate the query $sql = SELECT * FROM users WHERE username = '$PHP_AUTH_USER' AND password = '$PHP_AUTH_PW'; // Execute the query and put results in $result $result = mysql_query( $sql ) or die ( 'Unable to execute query.' ); // Get number of rows in $result. $num = mysql_numrows( $result ); if ( $num != 0 ) // A matching row was found - the user is authenticated. $auth = true; } } if ( ! $auth ) header( 'WWW-Authenticate: Basic realm=Private' ); header( 'HTTP/1.0 401 Unauthorized' ); echo 'Authorization Required.'; exit; } else session_start(); } if ($valid != yes) { header(Location: contact_menu.php); exit; } ? -- PHP General Mailing List (http://www.php.net/) To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] To contact the list administrators, e-mail: [EMAIL PROTECTED]
[PHP] Re: clear contents? - Ignore previous response
Oops!!! I didn't read your question fully. I think you CAN do what you want, if you can get some kind of cookie or and/or session variable to work to record when the user got to your page. You leave your logic as is, except that when you get a valid user you check to see if they have been on the page before via a cookie and/or session variable. If they haven't, you just go on as normal. If they have been to your page you FIRST reset the cookie/session variable to say they haven't been to the page and THEN issue your header AS IF THEY HAD THE INCORRECT USERNAME/ PASSWORD. This will force the browser to reprompt for username/password and when they come back to your page, you'll treat them as if they've never been there and let them through. e.g. using cookies (I don't use sessions so I might get the syntax wrong), if ( (! $auth) or $reprompt == 'Yes') { // Cancel the reprompt cookie(reprompt); header( 'WWW-Authenticate: Basic realm=Private' ); header( 'HTTP/1.0 401 Unauthorized' ); echo 'Authorization Required.'; exit; } else // Mark them ready to be reprompted next time cookie(reprompt,Yes); session_start(); } Sorry, George George Whiffen wrote: Jeremy, I don't think it's possible to do what you want, and I have tried finding a way. With your header you are requestion an http authentication which means the browser has to store the username and password and send them with EVERY page. Those are the rules. The only way to tell the browser to lose the username/password that I've found is to tell it that they're incorrect, (even though they are correct). But if you do that it will go and ask the user to type them in again another three times before it gives up and drops them. You'll find that most of your users will probably keep the username/password even after closing the browser and switching their computer off, which I guess is even worse as far as you're concerned. I hope I'm wrong but if you really must get them to enter username/password every time, I think you'll have to create your own login box and forget about http authentication. It might be worth posting your question to an apache newsgroup as well. Even if you're not using Apache, you should find those guys know just about everything there is to know about http authentication. Good Luck and I hope I'm wrong! George Jeremy Morano wrote: Hi everone... I'm having a little problem. The code below pops up a password dialog box where the user types in a username and a password to be able to proceed. However, if the user does not close the browser and goes back to the link, which they pops up the diolog box again and they don't have to type in there username and password again. They are remembered. I would like it so that the user has to type in there username and password any and every time that the diolog box is called on. Doe anyone know how to do this? I tried to clear the contents of PHP_AUTH_USER and PHP_AUTH_PW at the top of the page but that just messed things up. Can someone please help me? ? session_start(); session_register(PHP_AUTH_USER); if (isset( $PHP_AUTH_USER ) isset($PHP_AUTH_PW)) // Connect to MySQL mysql_connect( 'l', 'c', 'c' ) or die ( 'Unable to connect to server.' ); // Select database on MySQL server mysql_select_db( 'contact' ) or die ( 'Unable to select database.' ); // Formulate the query $sql = SELECT * FROM users WHERE username = '$PHP_AUTH_USER' AND password = '$PHP_AUTH_PW'; // Execute the query and put results in $result $result = mysql_query( $sql ) or die ( 'Unable to execute query.' ); // Get number of rows in $result. $num = mysql_numrows( $result ); if ( $num != 0 ) // A matching row was found - the user is authenticated. $auth = true; } } if ( ! $auth ) header( 'WWW-Authenticate: Basic realm=Private' ); header( 'HTTP/1.0 401 Unauthorized' ); echo 'Authorization Required.'; exit; } else session_start(); } -- PHP General Mailing List (http://www.php.net/) To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] To contact the list administrators, e-mail: [EMAIL PROTECTED]
Re: [PHP] php includes === Dreamweaver library items
://www.powerspec.com/support/support_archive.html?selection=4611 Here is an example of the parsed output, notice the file names? http://www.powerspec.com/support/support_archive.phtml?selection=4611 View the source and you will see where Dreamweaver keeps notes of where library items should go. The problem seems to be to make sure they don't show up in the saved Dreamweaver html file as well as it's saved library item. The problem you describe is really a feature, if used properly this feature can pretty handy. I don't believe that Dreamweaver's Library items are meant to be directly included into php pages. You are supposed to allow Dreamweaver to update all the pages affected by the library item after you make a change to the library item. Its one of the reasons to use Dreamweaver. Its seems possible to write a regex to remove the library item and replace with a php include(), but this is really what FastTemplate was made to do in the first place, so you've reinvented the wheel. Also another reason to consider Template (IMHO) are the programmers who support them, Sascha Schumann wrote the article I referred you to, Andrei Zmievski wrote Smarty (another templating system for php). phplib contains a templating system, and I'm sure there are countless others. Templates seem to be adopted by experieced programmers more often than not. I haven't even mentioned the advantages of CachedFastTemplate which is reason alone to use templates. If you decide to try it out, I'm happy to relay my experiences. Robert V. Zwink http://www.zwink.net/daid.php -Original Message- From: George Whiffen [mailto:[EMAIL PROTECTED]] Sent: Wednesday, September 05, 2001 2:34 PM To: [EMAIL PROTECTED]; Robert V. Zwink Subject: Re: [PHP] php includes === Dreamweaver library items Robert, Thanks for the suggestions, but... a) I do want to do this and I do think I can. The big problem is not the templating, php is pretty damn good at that already. It's handling the header/footer html which appears on every page. On the one hand we only want one master copy so there's only one thing to fix if it's wrong, on the other hand we want the designer's tools (Dreamweaver in this case), to show the page they're designing with those headers/footers included while they work locally on their server. I still think this can be done with Dreamweaver's library items. They seem to be held as separate files with little snippets of html, just as we'd hold them on the server, so with a little discipline or fancy ftp synchronisation we can make sure they are up to date. The problem seems to be to make sure they don't show up in the saved Dreamweaver html file as well as it's saved library item. b) I looked at FastTemplate and I'm pretty sure I don't want to use it. The main difference from a pure php approache seems to be that instead of embedding real live php in the template (and then hiding it from the designers), instead you embed your own invented tags that you then separately translate into the results of some php via tpl methods. The disadvantage is that you seem to have to create lots of itty bitty little .tpl files for every part of the page which is either repeated or conditional and bunches of other structure which doesn't do anything to help productivity or maintainability. I would much rather include the looping/conditional php in the template itself, safely tucked away in a php tag e.g. (using the FastTemplate example) mytemplate.html HTML BODY TABLE TITLEHALLO/TITLE ?php // Start looping through files while($filename = readdir($handle)) { $filesize = filesize($filename); ? TR TD?= $filename?/TD TD?= $filesize?/TD /TR ?php // End of loop through files } ? /TABLE /BODY /HEAD etc. myphpprogram Then the master php just has : //standard stuff $handle = opendir(...); //error checking include(mytemplate.html) close($handle); The template can then include any number of loops and conditionals all in the same full previewable/editable html page. It's not going to be a perfect copy of the final page i.e. each repeating section only appears once and conditionals always appear, but that's impossible anyway until you actually execute the page on the server. But compared to the FastTemplate approach this is less code, less files, less things to go wrong, same amount of coordination with the designers, more educative for the designers (some might even get curious and look at the php!), and it does mean the designers get a whole page to work on/preview. I guess FastTemplate may improve reusability of the html formats by splitting the html into separate chunks. That might matter for system admin/software engineering type applications where you might list the same kind of data in the same format more than once. But in my
Re: [PHP] password sanity checker
A cheap and cheerful rule is to insist on at least one numeric. Then you don't have to bother with a dictionary check! The php to force only alphas and numerics (upper or lower case) and at least one numeric is something like : - if (!ereg(^[a-zA-Z0-9]*[0-9][a-zA-Z0-9]*$,$password)) { $message = no good; } and the Javascript : - var passwordPat=new RegExp(^[a-zA-Z0-9]*[0-9][a-zA-Z0-9]*$); if ( password.match(passwordPat)==null) { alert(no good); } Good Luck, George Chris Anderson wrote: Getting the size is easy, and if you had a small dictionary you could see if the password existed in that by looping through it. Not sure about checking if it is LIKE the username - Original Message - From: Charles Sprickman [EMAIL PROTECTED] To: [EMAIL PROTECTED] Sent: Tuesday, July 03, 2001 12:18 PM Subject: [PHP] password sanity checker Hi, I've been digging around for a function to do a sanity check on user-supplied passwords when creating a new account. Haven't found anything yet... Any pointers appreciated. Ideally it should: -check for a min number of numerals -check for similarity against username (?) -check at least a small dictionary Although anything that could provide a starting point would be great. Thanks, Charles | Charles Sprickman | Internet Channel | INCH System Administration Team| (212)243-5200 | [EMAIL PROTECTED] | [EMAIL PROTECTED] -- PHP General Mailing List (http://www.php.net/) To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] To contact the list administrators, e-mail: [EMAIL PROTECTED] -- PHP General Mailing List (http://www.php.net/) To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] To contact the list administrators, e-mail: [EMAIL PROTECTED]
[PHP] php includes === Dreamweaver library items
Hi, Has anyone experience of using Dreamweaver library item files (.lbi)s as php includes? We've got a standard header and footer to go across all pages on a site with the navigation etc. We want both the designers, (using Dreamweaver), and the php programmers to have access to these includes, so that the Dreamweavers can view the pages automatically with the headers/footers shown, and the programmers can still maintain the pages and includes without Dreamweaver. I don't fully understand how Dreamweaver library files work, so I guess my questions are : a) Can you use a url for a Dreamweaver libary file rather than using a local file so we can all share a single master copy? b) Can we tell Dreamweaver to include the libary file's html when previewing but exclude it when saving, so we don't end up with the library code twice, once embedded by Dreamweaver on the save and once included by php at execution? (I insist on the live page using the master version as I'm not prepared to trust the Dreamweavers to rebuild the pages when the library files change!) I guess I've got workarounds if the answers to these prove negative. For a) I can bully the Dreamweavers into keeping the master/local copies in step, and for b) I guess I can get the php to strip out the Dreamweaver copy of the library code at execution with a little bit of spoofing of Dreamweaver about where php starts and ends i.e. something like ?php turn_into_an_include(ENDLIBRARY ? dreamweaver library item tags and text !-- ENDLIBRARY ); //--?php ? where turn_into_an_include is a function which just finds the library file name in the passed string of library code and includes it from the appropriate server directory. Of course, this is a bit clumsy, any better suggestions? Many thanks, George ? c) In the worst case I guess, we can live with local and master copies of library files and remind the Dreamweavers to always update the master when they make changes get the php code to strip out the embedded library file html at execution time and replace it with an appropriate include statement of the server copy. I've got an idea how to do this by as anyone else tried this? -- PHP General Mailing List (http://www.php.net/) To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] To contact the list administrators, e-mail: [EMAIL PROTECTED]
[PHP] Re: Download function for php
Mark Lo wrote: Hi, Is there any php download function for php. I am asking is the one like downloading the file from the server when people click the link. Like downloading php sources tar file. Thank you Mark No download function that I know of, but it isn't hard to download. The trick is to send out a Content-Type header with the Mime type, an optional Content-disposition to suggest a name and then whatever it is you want to download. e.g. to download some data in tab-delimited format - header(Content-type: text/tab-separated-values); header(Content-disposition: inline; filename=.$myfilename); while(... { print \t$field1\t$field2\t$field3\t$field4\n; } exit; You can download any mime type, so it could just as well be downloading a text file, a word-processor document, an image, a Shockwave file or whatever. You can easily use readfile to pick up the contents of an existing file. If you find the browser is trying to get too clever when it spots the Mime type, you can always make up your own, which should force it to just offer a save. Hope that helps. George -- PHP General Mailing List (http://www.php.net/) To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] To contact the list administrators, e-mail: [EMAIL PROTECTED]
[PHP] Re: Help with a variable
James Bartlett wrote: Hi, Is there some way that I can check to see if a variable is present? e.g. if (variable is not present) { set variable to 0; } else { some code that uses variable; } Thanks for any advice. James isset function variable is already 0 if !isset -- PHP General Mailing List (http://www.php.net/) To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] To contact the list administrators, e-mail: [EMAIL PROTECTED]
[PHP] Re: checking if checkbox is checked
To check if a type checkbox variable has been set use isset() i.e. if ( isset($interest) or isset($interest2) or isset($interest3) or isset($interest4) or isset($interest1) ) { // Everthing is ok } else { $error = . ) This should do exactly what you want, and although it may not use the least characters it should be the quickest to write/debug/maintain and run. Regards, George Richard Kurth wrote: I have 5 checkbox's in a form that I what to make sure at least one of the checkbox is checked. input type='checkbox' name='interest' value='basic' input type='checkbox' name='interest3' value='Internet access ' input type='checkbox' name='interest1' value='pro' input type='checkbox' name='interest4' value='domain name' input type='checkbox' name='interest2' value='platinum' I am checking for blank field buy doing this below How can I check for at least one of the above check boxes is checked if ($name == ) { $name_err = font color=redPlease enter your name!/fontbr ; $send = no; } Best regards, Richard mailto:[EMAIL PROTECTED] -- PHP General Mailing List (http://www.php.net/) To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] To contact the list administrators, e-mail: [EMAIL PROTECTED]
[PHP] Re: javascript var on a php var...
Romeo Manzur wrote: hi, I want to know how could I save a javascript variable on a php variable??? Thanks... It depends how the user will get to the php page: 1. Form If the user is about to submit a form and you want some Javascript variable from your page to end up as a php variable after the form is submitted then: Create a hidden form variable e.g. INPUT TYPE=HIDDEN NAME=myvariable Set this formvariable to your Javascript variable in the Javascript e.g. document.form.myvariable.value = myjavascriptvariable; After submission $myvariable will be a php variable in the target page with the value you gave it. 2. Link If you want to set a php variable in a page which the user will get to by a link, then you need to add a GET query to the link e.g. your Javascript will have something like this: document.myhref.location = document.myhref.location+?myvariable=+myjavascriptvariable; i.e. the link becomes myoriginallink?myvariable=... php will automatically become up the value you specify and set $myvariable to that value. George -- PHP General Mailing List (http://www.php.net/) To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] To contact the list administrators, e-mail: [EMAIL PROTECTED]
[PHP] Re: Batch job in UNIX.
mysql client will read from standard input, so you can just pipe in the sql e.g. echo insert into . ; | mysql -p -u root test or from a shell script you can use here is syntax e.g. mysql -p -u root test endmysql insert into endmysql Johan Vikerskog (ECS) wrote: If i want to add something into a table with just the mysql command. Is this possible. Like /mysql -p -u root test insert into... Something like this.Is that possible and how in that case. Johan Vikerskog Technician - CAE Tools Support Research Technology Development ''' Ericsson Mobile Communications AB Mobile Phones Terminals Telephone: +46 46 19 33 38 Nya VattentornetTelefax:+46 46 19 32 36 SE-221 83 Lund, Sweden -- PHP General Mailing List (http://www.php.net/) To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] To contact the list administrators, e-mail: [EMAIL PROTECTED]
Re: [PHP] General Coding Question
And what about the third option using single quotes on the outside i.e. print 'INPUT TYPE=TEXT VALUE='. $hash[var2] .'.. or even better print ' INPUT TYPE=TEXT VALUE='.$hash[var2].' SIZE= .. This should be better than an outer double quote since it stops any php parsing, so it's a bit faster and you don't have to worry if you have any dollar signs in the HTML. It does mean that you can't just embed the variables but then that doesn't work for array variables anyway yet, so it's no great loss. I must say I'm tempted by being able to write ? INPUT TYPE=TEXT SIZE=? if ($length20){print '40';} else {print '20';}? VALUE= etc.. rather than my normal style which would be : print ' INPUT TYPE=TEXT SIZE='; if ($length20) { print '40'; } else { print '20'; } print ' VALUE= etc.. I'd be very interested to hear other's views on what they find easiest. After all, style is mostly about making it easy for other people (especially the inexperienced) to maintain our code, not to suit our ideas of elegance. My own gut feeling is that consistency is probably the most important thing, i.e. pick any of the styles and then stick to it. What do you think? George Whiffen Chris Lee wrote: im here to start a flamewar. dont use then. why not use ' ? echo input type=\text\ name=\name\ value=\$name\ echo input type='text' name='name' value='$name' I like the second. it is proper html check it with w3.org. -- Chris Lee [EMAIL PROTECTED] scott [gts] [EMAIL PROTECTED] wrote in message [EMAIL PROTECTED]">news:[EMAIL PROTECTED]... on pages with mostly HTML code, the second style is much prefereable, but on pages with mostly PHP code, the first style is usually OK. overall, i tend towards the second, becuase it's a pain in the ass to esape all the double-quotes in my HTML, my echo statements usulaly end up looking like thi (which, to me, is terrible form) echo INPUT TYPE=\TEXT\ VALUE=\. $hash['var'] .\.. so i usually use this format, which to my eyes is much prettier :) ? INPUT TYPE=TEXT VALUE=?= $hash['var'] ? ? -Original Message- From: James Stevens [mailto:[EMAIL PROTECTED]] Sent: Wednesday, June 20, 2001 12:23 PM To: [EMAIL PROTECTED] Subject: [PHP] General Coding Question Does it have any effect on performance in either case if a file is completely done in PHP(1) or interspersed with PHP(2). (1) ?php echo html; ... ? (2) html ... ?php echo $forminput; ? ... Also, and this is personal preference, which is easier to read/debug? James -- PHP General Mailing List (http://www.php.net/) To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] To contact the list administrators, e-mail: [EMAIL PROTECTED] -- PHP General Mailing List (http://www.php.net/) To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] To contact the list administrators, e-mail: [EMAIL PROTECTED] -- PHP General Mailing List (http://www.php.net/) To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] To contact the list administrators, e-mail: [EMAIL PROTECTED] -- PHP General Mailing List (http://www.php.net/) To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] To contact the list administrators, e-mail: [EMAIL PROTECTED]
Re: [PHP] How to connect to remote database server through PHP?
Manisha, For the Sybase network connections, you are probably best off contacting Sybase specialists. php via the sybase_connect function is likely to look like any other Sybase client on a remote box, so the question is mostly about how do you get any Sybase client on your web server to communicate with the main database server. What about the administrator of the main database server? They should be able to help you on the Sybase networking side. In any case they are likely to have lots of opinions about the security implications of what you are trying to do. What you can tell your client is that you should have no problem with sending updates to the main database server from your side, but you really need their central database people to brief you on what is acceptable/sensible from their side. Sorry I couldn't help more. Manisha wrote: Hi, We are developing web application. The client wants it to get connected to their central database server in USA. Web server is in Singapore. Web server configuration - Situated in Singapore, unix / php / mysql - this database is only for some special cases where application does not require central database. Main central database server - Situated in USA, HP UX / sybase On web site we will be providing product listing and order form. After the order is confirmed and payment is made, client wants to update some fields on central database. Can anybody give me the details, how to do it? If I am using php, how to connect to remote server's database? What are the components require on both servers? How will be the network configuration? Any information source? Any mailing list for network connections ? Thanks in advance manisha -- PHP General Mailing List (http://www.php.net/) To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] To contact the list administrators, e-mail: [EMAIL PROTECTED] -- PHP General Mailing List (http://www.php.net/) To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] To contact the list administrators, e-mail: [EMAIL PROTECTED]
Re: [PHP] session question
Derick, If you're seriously looking at thousands of concurent users (let alone millions) and the kind of budget on hardware and comms that implies, then I'd suggest you seriously look at your own session solution with MySQL or whatever. You can perfectly easily just use your own authentication against your MysQL user base and pick up all their session data from the same table or related tables if there is a lot of it. The basic logic for each page runs : Is $PHP_AUTH_USER set? If not send out an authenticate header. If $PHP_AUTH_USER is set pick out the user entry and password from your MySQL database and check the password, if it fails send back the authenticate header. Pick up all your session data while you're checking the password, so from one database query you've got everything sorted out. Do whatever processing you need and just before sending back the next bunch of html, update the user's record storing back all the session information. That's session management for you. The only advantage of standard session management tools like php's session management is that you can change what you store without making any database changes. But your volume of traffic you shouldn't expect to make any quick and easy changes to the logic of whatever you're doing. It's not really a lot of work to do this and you do get extra benefits in terms of flexibility over what session data is stored for how long and in what format. Basically you don't have a problem as long as the user's don't have a lot of session data. If they do have a lot of session data, you've got a major storage/retrieval problem regardless of your session tool and you probably need to chuck a highly-tuned customised database structure at it anyway!! Hope that helps, George Moax Tech List wrote: I am setting up a website with a need to use some sort of session management for a large amount of users. I cannot use typical file based session managment because at any given time there could be up to a million users logged in at once. (It is a LAMP linux/apache/php4/mysql system). I am a bit confused though as how to go about this. The user will be authenticated by verifying a username/password combo in a database, and then a session created. My question is this: After authentication, which type of session managment should I use? I mean, just do the standard php stuff with the session_ functions? (wo'nt this be bad with the # of simoltaneous users i need to support, because of the # of files on the server?) Or, shall I use something more complex like PHPLIB or create my own scheme using mysql? Is there any exisiting code/functions that can make creating my own scheme easier in order to support mysql or am i way off with this question? I just need a bit of direction here and any help is appreciated. Thanks! -Derick -- PHP General Mailing List (http://www.php.net/) To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] To contact the list administrators, e-mail: [EMAIL PROTECTED]