php-general Digest 10 Dec 2007 10:53:26 -0000 Issue 5173
php-general Digest 10 Dec 2007 10:53:26 - Issue 5173 Topics (messages 265593 through 265599): Re: build a multi chat server with php 265593 by: Børge Holen Re: proc_open fclose streams.. 265594 by: Chris Shipping Address on Paypal 265595 by: Javed Chauhan 265596 by: Chris Mysqli support - test or complain? 265597 by: Dave M G 265599 by: Per Jessen LoadXML trouble 265598 by: Dani Castaños Administrivia: To subscribe to the digest, e-mail: [EMAIL PROTECTED] To unsubscribe from the digest, e-mail: [EMAIL PROTECTED] To post to the list, e-mail: [EMAIL PROTECTED] -- ---BeginMessage--- On Sunday 09 December 2007 23:46:44 Jochem Maas wrote: Nathan Rixham wrote: Anybody up for (or indeed see a need for) a multi threaded php daemonised jabber client? Looks like an interesting challenge! u know the old saying, if you build it they will come ;-) lol, for true... -- --- Børge Holen http://www.arivene.net ---End Message--- ---BeginMessage--- Nathan Rixham wrote: Hi Guys, Hoping somebody out there may have come across this one, possible functionality request depending on responses. $descriptor = array( 0 = array(pipe, r), 1 = array(pipe, w), 2 = array(pipe, w) ); $process = proc_open('mysql', $descriptor, $pipes); fwrite($pipes[0], 'show databases;'); echo stream_get_contents($pipes[1]); //won't work, crash, time out.. nothing returns as we need to.. fwrite($pipes[0], 'show databases;'); fclose($pipes[0]); // note the fclose echo stream_get_contents($pipes[1]); I don't want to fclose pipes[0] though, as i want to keep it open and keep writing to it, alternating with reading from pipes[1] and [2].. so a replacement for fclose, or an fflush on stdout that works? The problem appears to be that nothing is returned to php until the stdin pipe is closed, even if I write hundreds of commands to it. I think that's controlled by the process you're calling rather than a php thing. For example, smtp connections do this until you enter a '.' on a single line. ie the process you're calling doesn't know when to stop reading from stdin until you close the conn. -- Postgresql php tutorials http://www.designmagick.com/ ---End Message--- ---BeginMessage--- Hello Friends, As i am integrating Paypal pro (For CC) in my site. Our client has a merchant account. We have a kit for paypal integration with client 'credential certificate'. We are getting success and payment is completed. We have a problem that shipping address is not displayed on paypal site in merchant account in order detail page. Ship to: tab is blank. We tried a lot to send the shipping address from our site but could not succeed. So please help us to send the shipping address to the paypal so our merchant can see the shipping address in order detail page with other details. If any code please post it will be help to us and also to the others. Thansk, Javed -- View this message in context: http://www.nabble.com/Shipping-Address-on-Paypal-tp14247826p14247826.html Sent from the PHP - General mailing list archive at Nabble.com. ---End Message--- ---BeginMessage--- Javed Chauhan wrote: Hello Friends, As i am integrating Paypal pro (For CC) in my site. Our client has a merchant account. We have a kit for paypal integration with client 'credential certificate'. We are getting success and payment is completed. We have a problem that shipping address is not displayed on paypal site in merchant account in order detail page. Ship to: tab is blank. We tried a lot to send the shipping address from our site but could not succeed. So please help us to send the shipping address to the paypal so our merchant can see the shipping address in order detail page with other details. If any code please post it will be help to us and also to the others. https://www.paypal.com/IntegrationCenter/ic_home.html Ask paypal how to do it. They have api's and even an area for support tickets. -- Postgresql php tutorials http://www.designmagick.com/ ---End Message--- ---BeginMessage--- PHP List, Based on what seemed to be good advice to switch to using mysqli for interacting with a MySQL database, I built a content management system that uses mysqli for all it's calls. It works great on a lot of my servers. However, I just discovered that one web hosting service I use does not have mysqli enabled. I ran the phpinfo() command and they are running 5.2.5, but the configure command does not contain --with-mysqli. I would like the scripts I've written to be somewhat portable, but I'm unsure of whether or not I should assume that mysqli is in use. I see it as being a situation of essentially two options. One is based on the assumption that mysqli is as likely not to be available as it is to be installed. In this case I should write my scripts to test whether it
[PHP] Mysqli support - test or complain?
PHP List, Based on what seemed to be good advice to switch to using mysqli for interacting with a MySQL database, I built a content management system that uses mysqli for all it's calls. It works great on a lot of my servers. However, I just discovered that one web hosting service I use does not have mysqli enabled. I ran the phpinfo() command and they are running 5.2.5, but the configure command does not contain --with-mysqli. I would like the scripts I've written to be somewhat portable, but I'm unsure of whether or not I should assume that mysqli is in use. I see it as being a situation of essentially two options. One is based on the assumption that mysqli is as likely not to be available as it is to be installed. In this case I should write my scripts to test whether it exists and then use either mysqli or straight mysql commands as appropriate. If this is the way to go, what do I do to test for the existence of mysqli from within a PHP script? The other is to assume that recent installs and upgrades of PHP 5 should have mysqli because that's the currently preferred way of doing things, and therefore I should contact the web host and ask that they install it, or I find a different host. Which assumption should I be proceeding with? Thank you for any advice or assistance. -- Dave M G -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] LoadXML trouble
Hi list! I have a problem with DOMDocument loadXML method. I used Windows to develop my applications, and nothing happens on it when i do something like $xml = new DOMDocument(); $xml-loadXML( $request ); Obviously, request is not empty... But when I have upload this code to production machine ( which runs under Debian ) it doesn't works properly, The DOMDocument Object is empty... Any ideas? Thank you in advance -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Mysqli support - test or complain?
Dave M G wrote: One is based on the assumption that mysqli is as likely not to be available as it is to be installed. In this case I should write my scripts to test whether it exists and then use either mysqli or straight mysql commands as appropriate. If this is the way to go, what do I do to test for the existence of mysqli from within a PHP script? In my opinion, that is overkill. If you need mysqli and a provider does not provide it, simply chose another provider. A lot less effort. The other is to assume that recent installs and upgrades of PHP 5 should have mysqli because that's the currently preferred way of doing things, and therefore I should contact the web host and ask that they install it, or I find a different host. Which assumption should I be proceeding with? Find a provider/hoster that meets your requirements. You're the customer. /Per Jessen, Zürich -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Mysqli support - test or complain?
One is based on the assumption that mysqli is as likely not to be available as it is to be installed. In this case I should write my scripts to test whether it exists and then use either mysqli or straight mysql commands as appropriate. If this is the way to go, what do I do to test for the existence of mysqli from within a PHP script? The other is to assume that recent installs and upgrades of PHP 5 should have mysqli because that's the currently preferred way of doing things, and therefore I should contact the web host and ask that they install it, or I find a different host. Which assumption should I be proceeding with? You can: 1. Change your program to use the much more common mysql extension and forget about mnysqli for the time being (this is what I would do). You can switch to mysqli when its use becomes prevalent. 2. State that mysqli is required and not change anything (not advisable) 3. Alter your program to support both - use mysqi if it's avilable, mysql if it's not. If you use an API and not the mysqli functions directly this won't be too much hassle. Your last option to to assume that it's installed is very bad indeed. You shouldn't ever make assumptions, particularly when your dealing with software distributions. -- Richard Heyes http://www.websupportsolutions.co.uk Knowledge Base and HelpDesk software that can cut the cost of online support ** NOW OFFERING FREE ACCOUNTS TO CHARITIES AND NON-PROFITS ** -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
RE: [PHP] Mysqli support - test or complain?
-Original Message- From: Per Jessen [mailto:[EMAIL PROTECTED] Dave M G wrote: One is based on the assumption that mysqli is as likely not to be available as it is to be installed. In this case I should write my scripts to test whether it exists and then use either mysqli or straight mysql commands as appropriate. If this is the way to go, what do I do to test for the existence of mysqli from within a PHP script? In my opinion, that is overkill. If you need mysqli and a provider does not provide it, simply chose another provider. A lot less effort. The other is to assume that recent installs and upgrades of PHP 5 should have mysqli because that's the currently preferred way of doing things, and therefore I should contact the web host and ask that they install it, or I find a different host. Which assumption should I be proceeding with? Find a provider/hoster that meets your requirements. You're the customer. /Per Jessen, Zürich -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php Yes but what about development clients that have their hosting accounts elsewhere?... you cannot push them to change from hosting provider. I would rephrase Dave's questions like this: 1 - What is the chance your clients have PHP 5 nowadays? 2 - What is the change that a PHP 5 hosting provider has mysqli installed? Multiply both and you get the chance of getting mysqli installed when a new development client arrives asking for a development quote... If you are a company, you can provide the PHP 5 hosting yourself, and have a PHP 5 Required rule in the TOS for development projects. But if you are a freelancer... you risk loosing the client with such a requirement. Despite the EOL for PHP 4 has been announced, I still see webhosts bundled with PHP 4.1 and MySQL 3.23. Anyway... it depends on your target, and the real need for mysqli. Rob Andrés Robinet | Lead Developer | BESTPLACE CORPORATION 5100 Bayview Drive 206, Royal Lauderdale Landings, Fort Lauderdale, FL 33308 | TEL 954-607-4207 | FAX 954-337-2695 Email: [EMAIL PROTECTED] | MSN Chat: [EMAIL PROTECTED] | SKYPE: bestplace | Web: http://www.bestplace.biz | Web: http://www.seo-diy.com -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Mysqli support - test or complain?
Richard, Per, Andres, Thank you for responding. If it were entirely my web site to dictate what to do with, I would just switch for a server that has mysqli available to me. However, in this one case, the web site is owned by a small, not very profitable group that has reasons to stay with their current webhosting service. I want to support them if possible. Richard said: Alter your program to support both - use mysqi if it's avilable, mysql if it's not. How exactly do I test for the presence of mysqli from within a script? Or are you saying I have two different versions of my script? -- Dave M G -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Mysqli support - test or complain?
2007. 12. 10, hétfő keltezéssel 21.58-kor Dave M G ezt írta: Richard, Per, Andres, Thank you for responding. If it were entirely my web site to dictate what to do with, I would just switch for a server that has mysqli available to me. However, in this one case, the web site is owned by a small, not very profitable group that has reasons to stay with their current webhosting service. I want to support them if possible. Richard said: Alter your program to support both - use mysqi if it's avilable, mysql if it's not. How exactly do I test for the presence of mysqli from within a script? for example if (function_exists('mysqli_connect')) greets Zoltán Németh Or are you saying I have two different versions of my script? -- Dave M G -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Mysqli support - test or complain?
Dave M G wrote: Richard said: Alter your program to support both - use mysqi if it's avilable, mysql if it's not. How exactly do I test for the presence of mysqli from within a script? Or are you saying I have two different versions of my script? I think you can test for the availability of an extension, but I don't know how. I'm sure someone will be able to tell us. To enable your script to use one or the other, you could wrap each database call in your own mysqldave(), which would check the mysqli availability and call the appropriate API. You'd obviously check the mysqli availability at startup, then store the status somewhere for your wrapper to query. /Per Jessen, Zürich -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Mysqli support - test or complain?
How exactly do I test for the presence of mysqli from within a script? IIRC there's a function called extension_loaded(). Or something similar. Or are you saying I have two different versions of my script? Not at all. Taking PEAR::DB for example, you could test for the existence of mysqli, and use one DSN if it's there. If not, use another. This is one of the reasons abstraction layers exist. -- Richard Heyes http://www.websupportsolutions.co.uk Knowledge Base and HelpDesk software that can cut the cost of online support ** NOW OFFERING FREE ACCOUNTS TO CHARITIES AND NON-PROFITS ** -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Mysqli support - test or complain?
Richard Heyes wrote: another. This is one of the reasons abstraction layers exist. Which brings us to alternative #3 - odbc. /Per Jessen, Zürich -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] LoadXML trouble
On Dec 10, 2007 4:48 AM, Dani Castaños [EMAIL PROTECTED] wrote: Hi list! I have a problem with DOMDocument loadXML method. I used Windows to develop my applications, and nothing happens on it when i do something like $xml = new DOMDocument(); $xml-loadXML( $request ); Obviously, request is not empty... have you checked the contents of $request on the production machine prior to the invocation of loadXML() ? But when I have upload this code to production machine ( which runs under Debian ) it doesn't works properly, The DOMDocument Object is empty... are the systems running the same major version of php; and have you verified the linux system has DOM support? -nathan
Re: [PHP] Mysqli support - test or complain?
On Dec 10, 2007 3:16 AM, Dave M G [EMAIL PROTECTED] wrote: Which assumption should I be proceeding with? Rather than assume (because we all know what happens then), why not build for both scenarios? Here's an example of one way ? // inc/include_files.php # # Includes all files necessary in one file. # include_once('inc/config.php'); include_once('inc/db.php'); include_once('func/db.php'); ? ? // inc/db.php # # Database connection information. # // Establish the connection with the primary database if(function_exists('mysqli_connect')) { $db_conn = mysqli_connect($_DB[host],$_DB[user],$_DB[pass]) or die ('I couldn\'t connect to the database. Know why? Because MySQL is complaining about something. Does this make sense to you...? :BR /'.mysql_error().\n); } else { $db_conn = mysql_connect($_DB[host],$_DB[user],$_DB[pass]) or die ('I couldn\'t connect to the database. Know why? Because MySQL is complaining about something. Does this make sense to you...? :BR /'.mysql_error().\n); } ? ? // func/db.php # # Customized database functions. # function db_error($function) { // This is what we'll use to process and output (or otherwise handle) errors. $err = MySQL error reached when calling function .$function.(). MySQL said:BR /\n; $err .= FONT COLOR=#FF; if(function_exists('mysqli_error')) { $err .= mysqli_error(); } else { $err .= mysql_error(); } $err .= /FONTBR /\n; $err .= BR /\n; return $err; } function db_query($sql) { // Simply return the connection resource ID require('inc/config.php'); require('inc/db.php'); // Select the site database if(function_exists('mysqli_query')) { $db_select = mysqli_select_db($_DB[name],$db_conn); } else { $db_select = mysql_select_db($_DB[name],$db_conn); } return $r; } ? ? // index.php # # The primary file. # $sql = SELECT * FROM table_name; // Note that you use the custom function `db_query()`, // not `mysql_query()` or `mysqli_query()`. $result = db_query($sql); while($row = mysql_fetch_array($result)) { // Do the rest of your stuff here. } ? -- Daniel P. Brown [Phone Numbers Go Here!] [They're Hidden From View!] If at first you don't succeed, stick to what you know best so that you can make enough money to pay someone else to do it for you. -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Shipping Address on Paypal
On Dec 10, 2007 1:56 AM, Chris [EMAIL PROTECTED] wrote: Javed Chauhan wrote: [snip!] So please help us to send the shipping address to the paypal so our merchant can see the shipping address in order detail page with other details. If any code please post it will be help to us and also to the others. https://www.paypal.com/IntegrationCenter/ic_home.html Ask paypal how to do it. They have api's and even an area for support tickets. You can also go directly to the PayPal development forum, where you'll get support from the developer community and on-staff PayPal engineers. http://paypaldev.com/ -- Daniel P. Brown [Phone Numbers Go Here!] [They're Hidden From View!] If at first you don't succeed, stick to what you know best so that you can make enough money to pay someone else to do it for you. -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] build a multi chat server with php
On Dec 9, 2007 6:11 PM, Børge Holen [EMAIL PROTECTED] wrote: On Sunday 09 December 2007 23:46:44 Jochem Maas wrote: Nathan Rixham wrote: Anybody up for (or indeed see a need for) a multi threaded php daemonised jabber client? Looks like an interesting challenge! u know the old saying, if you build it they will come ;-) lol, for true... This sounds like a job for SourceForge! [Heroic music plays and a cape suddenly appears out of nowhere, attached to nothing, blowing in the wind.] -- Daniel P. Brown [Phone Numbers Go Here!] [They're Hidden From View!] If at first you don't succeed, stick to what you know best so that you can make enough money to pay someone else to do it for you. -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] LoadXML trouble
I've checked $request previously and is not empty... it has something like: ?xml version=1.0? response ticketID1197026188_ec76/ticketID statusKO/status errCode500/errCode errMsgInternal Server Error/errMsg /response The curious thing is that I've built this xml string with DOMDocument in my request... Then I suppose my Linux system has DOM support, Nathan Nobbe escribió: On Dec 10, 2007 4:48 AM, Dani Castaños [EMAIL PROTECTED] mailto:[EMAIL PROTECTED] wrote: Hi list! I have a problem with DOMDocument loadXML method. I used Windows to develop my applications, and nothing happens on it when i do something like $xml = new DOMDocument(); $xml-loadXML( $request ); Obviously, request is not empty... have you checked the contents of $request on the production machine prior to the invocation of loadXML() ? But when I have upload this code to production machine ( which runs under Debian ) it doesn't works properly, The DOMDocument Object is empty... are the systems running the same major version of php; and have you verified the linux system has DOM support? -nathan -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] LoadXML trouble
On Dec 10, 2007 11:40 AM, Dani Castaños [EMAIL PROTECTED] wrote: I've checked $request previously and is not empty... it has something like: ?xml version=1.0? response ticketID1197026188_ec76/ticketID statusKO/status errCode500/errCode errMsgInternal Server Error/errMsg /response have you been testing this in the context of your application, or have you also tried a focused test script? i would try something trivial, like: ?php $xml = XML ?xml version=1.0? response ticketID1197026188_ec76/ticketID statusKO/status errCode500/errCode errMsgInternal Server Error/errMsg /response XML; $domDoc = new DOMDocument(); $domDoc-loadXML($xml); echo $domDoc-saveXML() . PHP_EOL; ? just to ensure the DOM extension is available and working as expected. -nathan
Re: [PHP] LoadXML trouble
Yep, it works when i do saveXML, but not on loadXML step... The thing is... i'm trying to do something like this: $request = $_POST['xml']; $logger-debug( 'New ticket request' ); /** * Parse XML request to obtain values */ $xml = new DOMDocument(); //$xml-validateOnParse = true; $xml-loadXML( $request ); $customer_id = $xml-getElementsByTagName( 'customerID' )-item( 0 )-nodeValue; $app_name = $xml-getElementsByTagName( 'appName' )-item( 0 )-nodeValue; $ticket_type = $xml-getElementsByTagName( 'ticketType' )-item( 0 )-nodeValue; $ticket_action = $xml-getElementsByTagName( 'ticketAction' )-item( 0 )-nodeValue; $ticket_params = $xml-getElementsByTagName( 'parameters' )-item( 0 )-childNodes; ... Nathan Nobbe escribió: On Dec 10, 2007 11:40 AM, Dani Castaños [EMAIL PROTECTED] mailto:[EMAIL PROTECTED] wrote: I've checked $request previously and is not empty... it has something like: ?xml version=1.0? response ticketID1197026188_ec76/ticketID statusKO/status errCode500/errCode errMsgInternal Server Error/errMsg /response have you been testing this in the context of your application, or have you also tried a focused test script? i would try something trivial, like: ?php $xml = XML ?xml version=1.0? response ticketID1197026188_ec76/ticketID statusKO/status errCode500/errCode errMsgInternal Server Error/errMsg /response XML; $domDoc = new DOMDocument(); $domDoc-loadXML($xml); echo $domDoc-saveXML() . PHP_EOL; ? just to ensure the DOM extension is available and working as expected. -nathan -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] LoadXML trouble
On Dec 10, 2007 12:08 PM, Dani Castaños [EMAIL PROTECTED] wrote: Yep, it works when i do saveXML, but not on loadXML step... did the loadXML() method work in the test script i sent over in my last post? if it does then something else is going on when loadXML() is called in the context of your application. The thing is... i'm trying to do something like this: $request = $_POST['xml']; $logger-debug( 'New ticket request' ); /** * Parse XML request to obtain values */ $xml = new DOMDocument(); //$xml-validateOnParse = true; $xml-loadXML( $request ); you should always sanitize input. at the very least you should be running $_POST['xml'] through a call to trim() before handing it to the DOMDocument instance. $request = trim($_POST['xml']); $xml = new DOMDocument(); $xml-loadXML($request); i suspect there is some garbage in or around the string contained in $_POST['xml'] that the DomDocument instance doesnt like, therefore its not behaving the way youd anticipate. for example if you modify the script i sent over last time by putting some spaces in between the xml declaration and the opening tag of the envelope (response) you should see the following error (or something similar [depending on the value of error_reporting]) Warning: DOMDocument::loadXML(): XML declaration allowed only at the start of the document in Entity, line: 3 in /home/nathan/testDom.php on line 19 which consequently leads to ?xml version=1.0? when invoking echo $domDoc-saveXML() . PHP_EOL; rather than ?xml version=1.0? response ticketID1197026188_ec76/ticketID statusKO/status errCode500/errCode errMsgInternal Server Error/errMsg /response which is what you would expect. -nathan
[PHP] Generating Random Numbers with Normal Distribution
Dear list, For some computer-based simulation, i need to generate random numbers that have a normal distribution. It seems that PHP's rand() and mt_rand() functions return uniformly distributed numbers which is not suitable for simulation purposes. Is there any way to generate random numbers with normal distribution in PHP? Thanks in advance -abe -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Generating Random Numbers with Normal Distribution
True randomization is only really possible in nature, so I am not sure you ever be completely happy with programming random numbers... But it may help you get better results if you include srand() in your randomization code. -- Stephen Johnson c | eh The Lone Coder http://www.thelonecoder.com continuing the struggle against bad code http://www.thumbnailresume.com -- From: AmirBehzad Eslami [EMAIL PROTECTED] Date: Mon, 10 Dec 2007 22:58:36 +0330 To: PHP General list php-general@lists.php.net Subject: [PHP] Generating Random Numbers with Normal Distribution Dear list, For some computer-based simulation, i need to generate random numbers that have a normal distribution. It seems that PHP's rand() and mt_rand() functions return uniformly distributed numbers which is not suitable for simulation purposes. Is there any way to generate random numbers with normal distribution in PHP? Thanks in advance -abe -- 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] Generating Random Numbers with Normal Distribution
On Dec 10, 2007 2:37 PM, Stephen Johnson [EMAIL PROTECTED] wrote: True randomization is only really possible in nature, so I am not sure you ever be completely happy with programming random numbers... But it may help you get better results if you include srand() in your randomization code. the seeding methods have been deprecated; this from the manual: *Note*: As of PHP 4.2.0, there is no need to seed the random number generator with srand() http://us3.php.net/manual/en/function.srand.php or mt_srand() http://us3.php.net/manual/en/function.mt-srand.php as this is now done automatically. -nathan
Re: [PHP] Generating Random Numbers with Normal Distribution
LOL.. Guess I need to keep up with the change log a little better... -- Stephen Johnson c | eh The Lone Coder http://www.thelonecoder.com continuing the struggle against bad code http://www.thumbnailresume.com -- From: Nathan Nobbe [EMAIL PROTECTED] Date: Mon, 10 Dec 2007 14:40:36 -0500 To: Stephen Johnson [EMAIL PROTECTED] Cc: AmirBehzad Eslami [EMAIL PROTECTED], PHP General list php-general@lists.php.net Subject: Re: [PHP] Generating Random Numbers with Normal Distribution On Dec 10, 2007 2:37 PM, Stephen Johnson [EMAIL PROTECTED] wrote: True randomization is only really possible in nature, so I am not sure you ever be completely happy with programming random numbers... But it may help you get better results if you include srand() in your randomization code. the seeding methods have been deprecated; this from the manual: *Note*: As of PHP 4.2.0, there is no need to seed the random number generator with srand() http://us3.php.net/manual/en/function.srand.php or mt_srand() http://us3.php.net/manual/en/function.mt-srand.php as this is now done automatically. -nathan -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
RE: [PHP] Generating Random Numbers with Normal Distribution
if you really want to.. you can hook various devices up to your serial/parallel port and take specific readings, and from there compute some really great random numbers.. i think white noise from frequency generators/scopes have been used by research functions... google is your friend in this regard!! however, for what you're trying to accomplish, php (or any other language) is probably more than quite suitable!! have fun -Original Message- From: Nathan Nobbe [mailto:[EMAIL PROTECTED] Sent: Monday, December 10, 2007 11:41 AM To: Stephen Johnson Cc: AmirBehzad Eslami; PHP General list Subject: Re: [PHP] Generating Random Numbers with Normal Distribution On Dec 10, 2007 2:37 PM, Stephen Johnson [EMAIL PROTECTED] wrote: True randomization is only really possible in nature, so I am not sure you ever be completely happy with programming random numbers... But it may help you get better results if you include srand() in your randomization code. the seeding methods have been deprecated; this from the manual: *Note*: As of PHP 4.2.0, there is no need to seed the random number generator with srand() http://us3.php.net/manual/en/function.srand.php or mt_srand() http://us3.php.net/manual/en/function.mt-srand.php as this is now done automatically. -nathan -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Generating Random Numbers with Normal Distribution
On Mon, 2007-12-10 at 11:37 -0800, Stephen Johnson wrote: True randomization is only really possible in nature. Can you say for certain nature is truly random? Just because the seed may have occurred 13.7 billion years ago and we don't know what that initial state was and we couldn't possibly calculate all the interactions since, doesn't mean that everything since hasn't been happening in accordance with some universal formula and in absence of randomness. We know that there appear to be certain laws in physics, would they not have applied to that initial state in a non random manner? It may just be that due to the hugantic sample space from which to draw arbitrary values that we think things are random. Food for thought :) Cheers, Rob. -- ... SwarmBuy.com - http://www.swarmbuy.com Leveraging the buying power of the masses! ... -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Generating Random Numbers with Normal Distribution
On Dec 10, 2007 2:28 PM, AmirBehzad Eslami [EMAIL PROTECTED] wrote: Dear list, For some computer-based simulation, i need to generate random numbers that have a normal distribution. It seems that PHP's rand() and mt_rand() functions return uniformly distributed numbers which is not suitable for simulation purposes. Is there any way to generate random numbers with normal distribution in PHP? this is straight from a comment on the rand() documentation: http://us3.php.net/rand -nathan Random numbers with Gauss distribution (normal distribution). A correct alghoritm. Without aproximations, like Smaaps' It is specially usefull for simulations in physics. Check yourself, and have a fun. ?php function gauss() { // N(0,1) // returns random number with normal distribution: // mean=0 // std dev=1 // auxilary vars $x=random_0_1(); $y=random_0_1(); // two independent variables with normal distribution N(0,1) $u=sqrt(-2*log($x))*cos(2*pi()*$y); $v=sqrt(-2*log($x))*sin(2*pi()*$y); // i will return only one, couse only one needed return $u; } function gauss_ms($m=0.0,$s=1.0) { // N(m,s) // returns random number with normal distribution: // mean=m // std dev=s return gauss()*$s+$m; } function random_0_1() { // auxiliary function // returns random number with flat distribution from 0 to 1 return (float)rand()/(float)getrandmax(); } ? JanS student of astronomy on Warsaw University
RE: [PHP] Generating Random Numbers with Normal Distribution
stop... trying to make people think bad... bad!!! -Original Message- From: Robert Cummings [mailto:[EMAIL PROTECTED] Sent: Monday, December 10, 2007 11:47 AM To: Stephen Johnson Cc: AmirBehzad Eslami; PHP General list Subject: Re: [PHP] Generating Random Numbers with Normal Distribution On Mon, 2007-12-10 at 11:37 -0800, Stephen Johnson wrote: True randomization is only really possible in nature. Can you say for certain nature is truly random? Just because the seed may have occurred 13.7 billion years ago and we don't know what that initial state was and we couldn't possibly calculate all the interactions since, doesn't mean that everything since hasn't been happening in accordance with some universal formula and in absence of randomness. We know that there appear to be certain laws in physics, would they not have applied to that initial state in a non random manner? It may just be that due to the hugantic sample space from which to draw arbitrary values that we think things are random. Food for thought :) Cheers, Rob. -- ... SwarmBuy.com - http://www.swarmbuy.com Leveraging the buying power of the masses! ... -- 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] Generating Random Numbers with Normal Distribution
Wow... You clearly put a lot of thought into randomization... I am impressed..LOL Personally, most of my web applications do not have to factor 13.7 billion years of space drift in to the calculations, so php's rand function has been great for me... ;) -- Stephen Johnson c | eh The Lone Coder http://www.thelonecoder.com continuing the struggle against bad code http://www.thumbnailresume.com -- From: Robert Cummings [EMAIL PROTECTED] Organization: InterJinn Date: Mon, 10 Dec 2007 14:46:47 -0500 To: Stephen Johnson [EMAIL PROTECTED] Cc: AmirBehzad Eslami [EMAIL PROTECTED], PHP General list php-general@lists.php.net Subject: Re: [PHP] Generating Random Numbers with Normal Distribution Can you say for certain nature is truly random? Just because the seed may have occurred 13.7 billion years ago and we don't know what that initial state was and we couldn't possibly calculate all the interactions since, doesn't mean that everything since hasn't been happening in accordance with some universal formula and in absence of randomness. We know that there appear to be certain laws in physics, would they not have applied to that initial state in a non random manner? It may just be that due to the hugantic sample space from which to draw arbitrary values that we think things are random. Food for thought :) -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Generating Random Numbers with Normal Distribution
On Dec 10, 2007 2:28 PM, AmirBehzad Eslami [EMAIL PROTECTED] wrote: For some computer-based simulation, i need to generate random numbers that have a normal distribution. [snip!] Unfortunately, because computers are logical, there's no such thing (at least as of yet) as a truly random number being generated by a machine. -- Daniel P. Brown [Phone Numbers Go Here!] [They're Hidden From View!] If at first you don't succeed, stick to what you know best so that you can make enough money to pay someone else to do it for you. -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Generating Random Numbers with Normal Distribution
On Dec 10, 2007 3:04 PM, Daniel Brown [EMAIL PROTECTED] wrote: On Dec 10, 2007 2:28 PM, AmirBehzad Eslami [EMAIL PROTECTED] wrote: For some computer-based simulation, i need to generate random numbers that have a normal distribution. [snip!] Unfortunately, because computers are logical, there's no such thing (at least as of yet) as a truly random number being generated by a machine. Hmph. I only sent that message about 35 minutes ago -- Daniel P. Brown [Phone Numbers Go Here!] [They're Hidden From View!] If at first you don't succeed, stick to what you know best so that you can make enough money to pay someone else to do it for you. -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
RE: [PHP] Generating Random Numbers with Normal Distribution
[snip] Can you say for certain nature is truly random? Just because the seed may have occurred 13.7 billion years ago and we don't know what that initial state was and we couldn't possibly calculate all the interactions since, doesn't mean that everything since hasn't been happening in accordance with some universal formula and in absence of randomness. We know that there appear to be certain laws in physics, would they not have applied to that initial state in a non random manner? It may just be that due to the hugantic sample space from which to draw arbitrary values that we think things are random. Food for thought :) [/snip] Without order there cannot be randomness. -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] Command-line PHP script CPU usage goes sky-high, stays there--why?
Hello, I have a command-line PHP script--called Listener--that is designed to run indefinitely with a predictable CPU usage and memory footprint. In a nutshell, it's a multi-client socket server that waits for incoming connections, processes incoming data, stores results in a MySQL database, and basically gets on with its life. And it works. No errors or serious problems to speak of. And I've been running it for a couple years on an Xserve dual-G5 2GHz w/ OS X Server 10.4.11). Six months ago, the program would run for days, even a couple weeks, without a hitch. The only reason I would stop the script is for some other purpose, like a software update. However, the number of socket clients connecting in the past 3-4 months has steadily increased, and this seems to have exposed (if not created) a strange performance issue with PHP 5.2.4, MySQL 5.0.45 and/or Mac OS X Server 10.4.11. (I say and/or because I am unsure where the problem's cause really lies.) Basically, after the script has been running for a day or so (processing essentially the amount data that used to take two weeks), the CPU usage of the machine goes from 30% (normal) to 80-90%. This appears to be irrespective of the number of clients connected to the server at the time, but rather the amount of time the script has been running (and therefore cumulative cycles it's operated, data processed, MySQL queries executed, etc.). And the CPU usage stays high, even when the actual load (number of clients) decreases. At this time, if I run top, I get the following info: 22512 mysqld 91.6% 8:22:12 31 106 125 305M+ 3.20M 260M 475M 17104 php 7.2% 81:14.01 115 145 5.08M 7.80M 10.9M- 87.5M 22537 Terminal 6.6% 2:59:59 22 176 240 12.3M 21.2M 18.3M- 236M [...] At first I thought, okay, it's MySQL's fault. Maybe a lot of slow- running queries. But the slow query log is pretty clean. So maybe it's a combination of Mac OS X and MySQL and PHP? I Googled for a similar problem, and finally ran across this article: http://www.shawnhogan.com/2005/10/mysql-problems-on-mac-os-x-server.html ...where the author describes a very similar CPU usage pattern. I tried his suggested fixes and they seemed to have helped a little (or maybe it's my wishful thinking--hard to tell), since the high CPU load issue doesn't appear to happen as soon... But it still happens. Anyway, I'm really stumped as to what to do next, where to look, etc. If I stop the script, and restart it (but not the MySQL itself), CPU usage goes back to normal--for about a day or two. The only thing I thought might be connected is how many short-lived PHP child processes Listener creates--around 20-30,000 per day. Sounds higher, but on average it's just one every 2-3 seconds. Anyway, although the number of child processes isn't concurrent, would there be a problem with the number of historical child processes in view of ulimits or kern.maxfilesperproc? Anyway suggestions, tips, or links are much appreciated. Thanks. ...Rene -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Command-line PHP script CPU usage goes sky-high, stays there--why?
René Fournier wrote: Hello, I have a command-line PHP script--called Listener--that is designed to run indefinitely with a predictable CPU usage and memory footprint. In a nutshell, it's a multi-client socket server that waits for incoming connections, processes incoming data, stores results in a MySQL database, and basically gets on with its life. And it works. No errors or serious problems to speak of. And I've been running it for a couple years on an Xserve dual-G5 2GHz w/ OS X Server 10.4.11). Six months ago, the program would run for days, even a couple weeks, without a hitch. The only reason I would stop the script is for some other purpose, like a software update. However, the number of socket clients connecting in the past 3-4 months has steadily increased, and this seems to have exposed (if not created) a strange performance issue with PHP 5.2.4, MySQL 5.0.45 and/or Mac OS X Server 10.4.11. (I say and/or because I am unsure where the problem's cause really lies.) Basically, after the script has been running for a day or so (processing essentially the amount data that used to take two weeks), the CPU usage of the machine goes from 30% (normal) to 80-90%. This appears to be irrespective of the number of clients connected to the server at the time, but rather the amount of time the script has been running (and therefore cumulative cycles it's operated, data processed, MySQL queries executed, etc.). And the CPU usage stays high, even when the actual load (number of clients) decreases. At this time, if I run top, I get the following info: 22512 mysqld 91.6% 8:22:12 31 106 125 305M+ 3.20M 260M 475M 17104 php 7.2% 81:14.01 115 145 5.08M 7.80M 10.9M- 87.5M 22537 Terminal 6.6% 2:59:59 22 176 240 12.3M 21.2M 18.3M- 236M [...] At first I thought, okay, it's MySQL's fault. Maybe a lot of slow-running queries. But the slow query log is pretty clean. So maybe it's a combination of Mac OS X and MySQL and PHP? I Googled for a similar problem, and finally ran across this article: http://www.shawnhogan.com/2005/10/mysql-problems-on-mac-os-x-server.html ...where the author describes a very similar CPU usage pattern. I tried his suggested fixes and they seemed to have helped a little (or maybe it's my wishful thinking--hard to tell), since the high CPU load issue doesn't appear to happen as soon... But it still happens. Anyway, I'm really stumped as to what to do next, where to look, etc. If I stop the script, and restart it (but not the MySQL itself), CPU usage goes back to normal--for about a day or two. The only thing I thought might be connected is how many short-lived PHP child processes Listener creates--around 20-30,000 per day. Sounds higher, but on average it's just one every 2-3 seconds. Anyway, although the number of child processes isn't concurrent, would there be a problem with the number of historical child processes in view of ulimits or kern.maxfilesperproc? Anyway suggestions, tips, or links are much appreciated. Thanks. ...Rene I have a server that listens like yours does. I get 80k - 85k connections a day to it. When I first started it, I was only getting about 3k of connections aday. Then I upped the listening pattern and it tanked. I noticed that all my mail/web/db connections just sat there. When I investigated, I found that the number of connections to the server was being overloaded. So I increased the kern.maxfilesperproc setting to 32000. All the problems went away. I have about have the horse power you do, running OpenBSD 4.1, and it runs great now as my listener / web / ftp / mail / named / database / spam filter / etc... One question about the listener program, does it maintain a connection to the DB or does it open/close a connection upon each socket connection? If it does the latter, you might look into using a constant connection rather then opening/closing on a per connection basis. -- Jim Lucas Some men are born to greatness, some achieve greatness, and some have greatness thrust upon them. Twelfth Night, Act II, Scene V by William Shakespeare -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Generating Random Numbers with Normal Distribution
On Dec 10, 2007 2:28 PM, AmirBehzad Eslami [EMAIL PROTECTED] wrote: Dear list, For some computer-based simulation, i need to generate random numbers that have a normal distribution. It seems that PHP's rand() and mt_rand() functions return uniformly distributed numbers which is not suitable for simulation purposes. Just for fun, I decided to write out an algorithm to randomize with a never-known seed that would update constantly, with no human or external script intervention required to initiate or maintain it. What I came up with to count all CPU processing percentages of all PIDs on the system, concatenate them into a single, long string, and then add each number, in turn, to a running total; each number, in succession, is added the sum of all numbers before it, until the end of the number string has been reached. Then the function runs through some other routines to see if certain conditions are matched, and eventually returns the randomized number. Keep in mind that this is just something I put together in about 20 minutes, so it's far from perfect, but feel free to check it out. http://www.pilotpig.net/code-library/source.php?f=rand.php -- Daniel P. Brown [Phone Numbers Go Here!] [They're Hidden From View!] If at first you don't succeed, stick to what you know best so that you can make enough money to pay someone else to do it for you. -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
RE: [PHP] Generating Random Numbers with Normal Distribution
bruce wrote: if you really want to.. you can hook various devices up to your serial/parallel port and take specific readings, and from there compute some really great random numbers.. That's pretty much what /dev/random does for you. /Per Jessen, Zürich -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
RE: [PHP] Generating Random Numbers with Normal Distribution
On Mon, 2007-12-10 at 14:22 -0600, Jay Blanchard wrote: [snip] Can you say for certain nature is truly random? Just because the seed may have occurred 13.7 billion years ago and we don't know what that initial state was and we couldn't possibly calculate all the interactions since, doesn't mean that everything since hasn't been happening in accordance with some universal formula and in absence of randomness. We know that there appear to be certain laws in physics, would they not have applied to that initial state in a non random manner? It may just be that due to the hugantic sample space from which to draw arbitrary values that we think things are random. Food for thought :) [/snip] Without order there cannot be randomness. But is the reverse true? Cheers, Rob. -- ... SwarmBuy.com - http://www.swarmbuy.com Leveraging the buying power of the masses! ... -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
RE: [PHP] Generating Random Numbers with Normal Distribution
[snip] Without order there cannot be randomness. But is the reverse true? [/snip] Yes -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Command-line PHP script CPU usage goes sky-high, stays there--why?
Hi Jim, I have a server that listens like yours does. I get 80k - 85k connections a day to it. When I first started it, I was only getting about 3k of connections aday. Then I upped the listening pattern and it tanked. I noticed that all my mail/web/db connections just sat there. When I investigated, I found that the number of connections to the server was being overloaded. So I increased the kern.maxfilesperproc setting to 32000. All the problems went away. I have about have the horse power you do, running OpenBSD 4.1, and it runs great now as my listener / web / ftp / mail / named / database / spam filter / etc... One question about the listener program, does it maintain a connection to the DB or does it open/close a connection upon each socket connection? If it does the latter, you might look into using a constant connection rather then opening/closing on a per connection basis. Thanks for the reply. (Not many people seem to be doing what I'm doing in the way I'm doing it... so I really appreciate the feedback.) I don't think the kern.maxfilesperproc setting is a problem. I'm currently set to 102400 per Shawn Hogan's advice. And my Listener program only receives ~1000 connections per day. However, each connection involves multiple MySQL queries, often as many as 50 or so per connection each day. So perhaps your second observation applies. MySQL is showing ~ 1,500 connections per hour. And I'm using mysql_connect() in Listener. I will see if using mysql_pconnect(), and reducing the number of connections helps. My.cnf's max connections, presently at 100, may have been too low in view using mysql_connect(). If mysql_pconnect() doesn't improve things, maybe I should bump up max_connections to 500? ..Rene -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Generating Random Numbers with Normal Distribution
On Dec 10, 2007 5:29 PM, Robert Cummings [EMAIL PROTECTED] wrote: On Mon, 2007-12-10 at 14:22 -0600, Jay Blanchard wrote: [snip] Can you say for certain nature is truly random? Just because the seed may have occurred 13.7 billion years ago and we don't know what that initial state was and we couldn't possibly calculate all the interactions since, doesn't mean that everything since hasn't been happening in accordance with some universal formula and in absence of randomness. We know that there appear to be certain laws in physics, would they not have applied to that initial state in a non random manner? It may just be that due to the hugantic sample space from which to draw arbitrary values that we think things are random. Food for thought :) [/snip] Without order there cannot be randomness. But is the reverse true? i would have to say randomness came before order. but i suppose thats a chicken and egg problem.. btw, i found this later today; http://us.php.net/manual/en/ref.stats.php there is a function in there for getting a random value from a normal distribution: stats_rand_gen_normal but it looks to be in pecl and i didnt see it in portage so i gave up on trying it out pretty quickly =/ -nathan
RE: [PHP] Generating Random Numbers with Normal Distribution
On Mon, 2007-12-10 at 16:32 -0600, Jay Blanchard wrote: [snip] Without order there cannot be randomness. But is the reverse true? [/snip] But disorder isn't necessarily random. Cheers, Rob. -- ... SwarmBuy.com - http://www.swarmbuy.com Leveraging the buying power of the masses! ... -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Generating Random Numbers with Normal Distribution
On Dec 10, 2007 5:39 PM, Robert Cummings [EMAIL PROTECTED] wrote: On Mon, 2007-12-10 at 16:32 -0600, Jay Blanchard wrote: [snip] Without order there cannot be randomness. But is the reverse true? [/snip] But disorder isn't necessarily random. Unless you get into Shannon entropy, but that still doesn't disprove your statement. -- Daniel P. Brown [Phone Numbers Go Here!] [They're Hidden From View!] If at first you don't succeed, stick to what you know best so that you can make enough money to pay someone else to do it for you. -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Generating Random Numbers with Normal Distribution
On Mon, 2007-12-10 at 17:45 -0500, Daniel Brown wrote: On Dec 10, 2007 5:39 PM, Robert Cummings [EMAIL PROTECTED] wrote: On Mon, 2007-12-10 at 16:32 -0600, Jay Blanchard wrote: [snip] Without order there cannot be randomness. But is the reverse true? [/snip] But disorder isn't necessarily random. Unless you get into Shannon entropy, but that still doesn't disprove your statement. Shannon entropy (from what I briefly scanned) is based upon the presumption of random. As such you can't use it to argue a case for the existence of true random. Entropy is merely the tendency of an ordered state to move toward disorder. It also doesn't in any way make an argument for random. For instance, let's say I order 10 peas into a line in a straw. I then shoot them all at a target which they more or less hit and scatter. The peas are now in disorder, but their places of rest (presuming we're not in outer space ;) would be the logical outcome of the application of the laws of physics with respect to mass, force, angle, gravity, etc. They aren't randomly lying on the ground. Although, one might casually choose their resting locations to derive a pseudo-random number since it is unlikely one could easily guess the precise landing location of each pea. Anyways... this was just a fun sidetrack like we used to get our teachers on when we were kids :) Cheers, Rob. -- ... SwarmBuy.com - http://www.swarmbuy.com Leveraging the buying power of the masses! ... -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] Advice with some code
Hi all, I'm having a brain freeze with some simple code that I wrote and now trying to refactor. I have a block of code that looks like this: public function backup() { $fname = $this-dbName.sql.$this-zip; $this-cmd = mysqldump -Q -u $this-dbUser -p$this-dbPass $this-dbName 21 {$this-dest}/{$this-dbName}.{$this-lastId}.sql; $res = shell_exec($this-cmd); error_log(First res: .$res); if(!$res) { $this-cmd = ($this-zip===bz2) ? bzip2 {$this-dest}/{$this-dbName}.{$this-lastId}.sql 21 : gzip {$this-dest}/{$this-dbName}.{$this-lastId}.sql 21; $res = shell_exec($this-cmd); error_log(second error: .$res); return !$res; } return FALSE; } Now instead of that FALSE, is there a way I can pass FALSE with a particular error message? This is because on the other end I have code that looks like this: if($mysqlDump-backup()) { $success = array('success' = '1'); $sqlres = mysql_query($sql, $link) or die(json_message('error',mysql_error())); shell_exec('/usr/bin/touch /tmp/build_transfer'); mysql_close($link); return '(' . json_encode($success) . ')'; } else { $fail = array('fail' = $res); return '(' . json_encode($fail) . ')'; } I'd ultimately like to be able to deliver a failure message from the return value...and properly catch that message so I can send it back in JSON format to the client browser to report what the error is. Think I should approach this with some try{..} catch code? Am I overlooking something really simple? :-) Thanks for your advice.
Re: [PHP] Advice with some code
On Mon, 2007-12-10 at 18:25 -0500, Steve Finkelstein wrote: Hi all, I'm having a brain freeze with some simple code that I wrote and now trying to refactor. I have a block of code that looks like this: public function backup() { $fname = $this-dbName.sql.$this-zip; $this-cmd = mysqldump -Q -u $this-dbUser -p$this-dbPass $this-dbName 21 {$this-dest}/{$this-dbName}.{$this-lastId}.sql; $res = shell_exec($this-cmd); error_log(First res: .$res); if(!$res) { $this-cmd = ($this-zip===bz2) ? bzip2 {$this-dest}/{$this-dbName}.{$this-lastId}.sql 21 : gzip {$this-dest}/{$this-dbName}.{$this-lastId}.sql 21; $res = shell_exec($this-cmd); error_log(second error: .$res); return !$res; } return FALSE; } Now instead of that FALSE, is there a way I can pass FALSE with a particular error message? This is because on the other end I have code that looks like this: if($mysqlDump-backup()) { $success = array('success' = '1'); $sqlres = mysql_query($sql, $link) or die(json_message('error',mysql_error())); shell_exec('/usr/bin/touch /tmp/build_transfer'); mysql_close($link); return '(' . json_encode($success) . ')'; } else { $fail = array('fail' = $res); return '(' . json_encode($fail) . ')'; } I'd ultimately like to be able to deliver a failure message from the return value...and properly catch that message so I can send it back in JSON format to the client browser to report what the error is. Think I should approach this with some try{..} catch code? Am I overlooking something really simple? :-) You can use try/catch, or since your current semantics are to return boolean only, you could check do the following: ?php if( ($status = backup()) !== true ) { if( is_string( $status ) ) { echo 'Failure: '.$status.\n; } } ? Cheers, Rob. -- ... SwarmBuy.com - http://www.swarmbuy.com Leveraging the buying power of the masses! ... -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Command-line PHP script CPU usage goes sky-high, stays there--why?
Hi, Tuesday, December 11, 2007, 6:42:18 AM, you wrote: RF Hello, RF I have a command-line PHP script--called Listener--that is designed RF to run indefinitely with a predictable CPU usage and memory RF footprint. In a nutshell, it's a multi-client socket server that RF waits for incoming connections, processes incoming data, stores RF results in a MySQL database, and basically gets on with its life. And RF it works. No errors or serious problems to speak of. And I've been RF running it for a couple years on an Xserve dual-G5 2GHz w/ OS X RF Server 10.4.11). Six months ago, the program would run for days, even RF a couple weeks, without a hitch. The only reason I would stop the RF script is for some other purpose, like a software update. RF However, the number of socket clients connecting in the past 3-4 RF months has steadily increased, and this seems to have exposed (if not RF created) a strange performance issue with PHP 5.2.4, MySQL 5.0.45 RF and/or Mac OS X Server 10.4.11. (I say and/or because I am unsure RF where the problem's cause really lies.) Basically, after the script RF has been running for a day or so (processing essentially the amount RF data that used to take two weeks), the CPU usage of the machine goes RF from 30% (normal) to 80-90%. This appears to be irrespective of the RF number of clients connected to the server at the time, but rather the RF amount of time the script has been running (and therefore cumulative RF cycles it's operated, data processed, MySQL queries executed, etc.). RF And the CPU usage stays high, even when the actual load (number of RF clients) decreases. At this time, if I run top, I get the following RF info: RF 22512 mysqld 91.6% 8:22:12 31 106 125 305M+ 3.20M RF 260M 475M RF 17104 php 7.2% 81:14.01 115 145 5.08M 7.80M RF 10.9M- 87.5M RF 22537 Terminal 6.6% 2:59:59 22 176 240 12.3M 21.2M RF 18.3M- 236M RF [...] RF At first I thought, okay, it's MySQL's fault. Maybe a lot of slow- RF running queries. But the slow query log is pretty clean. So maybe RF it's a combination of Mac OS X and MySQL and PHP? I Googled for a RF similar problem, and finally ran across this article: RF http://www.shawnhogan.com/2005/10/mysql-problems-on-mac-os-x-server.html RF ...where the author describes a very similar CPU usage pattern. I RF tried his suggested fixes and they seemed to have helped a little (or RF maybe it's my wishful thinking--hard to tell), since the high CPU RF load issue doesn't appear to happen as soon... But it still happens. RF Anyway, I'm really stumped as to what to do next, where to look, etc. RF If I stop the script, and restart it (but not the MySQL itself), CPU RF usage goes back to normal--for about a day or two. RF The only thing I thought might be connected is how many short-lived RF PHP child processes Listener creates--around 20-30,000 per day. RF Sounds higher, but on average it's just one every 2-3 seconds. RF Anyway, although the number of child processes isn't concurrent, RF would there be a problem with the number of historical child RF processes in view of ulimits or kern.maxfilesperproc? RF Anyway suggestions, tips, or links are much appreciated. Thanks. RF ...Rene Put a usleep(1000) in the listen while() loop and give the cpu a break. -- regards, Tom -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Advice with some code
Steve Finkelstein wrote: Hi all, I'm having a brain freeze with some simple code that I wrote and now trying to refactor. I have a block of code that looks like this: public function backup() public function backup($errors) { $fname = $this-dbName.sql.$this-zip; $this-cmd = mysqldump -Q -u $this-dbUser -p$this-dbPass $this-dbName 21 {$this-dest}/{$this-dbName}.{$this-lastId}.sql; $res = shell_exec($this-cmd); error_log(First res: .$res); if(!$res) { $this-cmd = ($this-zip===bz2) ? bzip2 {$this-dest}/{$this-dbName}.{$this-lastId}.sql 21 : gzip {$this-dest}/{$this-dbName}.{$this-lastId}.sql 21; $res = shell_exec($this-cmd); error_log(second error: .$res); $errors[] = second error: .$res; return !$res; } return FALSE; } Now instead of that FALSE, is there a way I can pass FALSE with a particular error message? This is because on the other end I have code that looks like this: $errMsgs = array(); if($mysqlDump-backup($errMsgs)) { if($mysqlDump-backup()) { $success = array('success' = '1'); $sqlres = mysql_query($sql, $link) or die(json_message('error',mysql_error())); shell_exec('/usr/bin/touch /tmp/build_transfer'); mysql_close($link); return '(' . json_encode($success) . ')'; } else { $fail = array('fail' = $res); $fail = array('fail' = $res, 'errors' = $errMsgs); return '(' . json_encode($fail) . ')'; } I'd ultimately like to be able to deliver a failure message from the return value...and properly catch that message so I can send it back in JSON format to the client browser to report what the error is. Think I should approach this with some try{..} catch code? Am I overlooking something really simple? :-) simple enough? the basic idea is the same as passing a variable by reference to exec() as the second argument in order to capture output. so your func has a return value to determine status and you can pass in an array to capture detailed process related messages. Thanks for your advice. -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Command-line PHP script CPU usage goes sky-high, stays there--why?
On 10-Dec-07, at 4:42 PM, Tom Rogers wrote: Put a usleep(1000) in the listen while() loop and give the cpu a break. Good advice, but I've already been doing that. The thing is, when the script first starts up, the CPU rarely exceeds 30%, even when many clients (200+) are simultaneously connected and sending data. When a few clients are connected, CPU is typically below 10%. Again, it's only after 24-48 hours that, all of a sudden, CPU usage increases by 40-50%. And it stays high until I stop the script and restart it. One question I have though is, is there actually any benefit to using mysql_pconnect(), since the script simply loops? My understanding is that pconnect only benefits if a script would otherwise be using mysql_connect repeatedly--and this script doesn't, since it calls mysql_[p]connect() just once, in the start tof execution. ...Rene -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Mysqli support - test or complain?
Per Jessen wrote: Richard Heyes wrote: another. This is one of the reasons abstraction layers exist. Which brings us to alternative #3 - odbc. That's probably less likely to be available than mysqli. If you're targetting php5 then you could use pdo::mysql as well (and there's even the less available dbx functions). Good thing about php = so many options Bad thing about php = too many options :) -- Postgresql php tutorials http://www.designmagick.com/ -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Command-line PHP script CPU usage goes sky-high, stays there--why?
Tom Rogers wrote: Hi, Tuesday, December 11, 2007, 6:42:18 AM, you wrote: RF Hello, Put a usleep(1000) in the listen while() loop and give the cpu a break. This makes me think about asking if you have to short of a timeout on your receiving connection? What are you using to setup your connection? fsockopen() or stream_socket_server() ? here is a snippet of what I have ?php $conn = mysql_connect(...); if ( $socket = @stream_socket_server('udp://'.LISTEN_IP.':'.LISTEN_PORT, $errno, $errstr, STREAM_SERVER_BIND) ) { while ( true ) { /* Get the exact same packet again, but remove it from the buffer this time. */ $buff = stream_socket_recvfrom($socket, 1024, 0, $remote_ip); # do stuff with your incoming data and mysql connection } fclose($socket); } mysql_close($conn); ? I don't have a timeout set on the *_recvfrom() call. I just wait until the next connection comes in. You don't need to use mysql_pconnect(), especially if you are using, what in essence is, a daemon. Just don't open and close the connection constantly, leave it open. Also, make sure you are not using an array that you are not re-initializing through each iteration of the loop. If the array keeps getting bigger, PHP might $*% on itself. Always re-initialize arrays to clean them up. Hope some of this helps! -- Jim Lucas Some men are born to greatness, some achieve greatness, and some have greatness thrust upon them. Twelfth Night, Act II, Scene V by William Shakespeare -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Command-line PHP script CPU usage goes sky-high, stays there--why?
Jim Lucas wrote: Tom Rogers wrote: Hi, ... Also, make sure you are not using an array that you are not re-initializing through each iteration of the loop. If the array keeps getting bigger, PHP might $*% on itself. Always re-initialize arrays to clean them up. even then he may still have creeping memory ... in which it might be possible to have a mother process that spawns and watchs a child process .. the child process is the actual deamon, the child could then keep a track of it's own memory usage and then kill itself when it gets too big ... the mother in turn would automatically spawn a new child deamon process upon seeing it's child has committed suicide. does that make sense? -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Command-line PHP script CPU usage goes sky-high, stays there--why?
On 10-Dec-07, at 5:20 PM, Jim Lucas wrote: Tom Rogers wrote: Hi, Tuesday, December 11, 2007, 6:42:18 AM, you wrote: RF Hello, Put a usleep(1000) in the listen while() loop and give the cpu a break. This makes me think about asking if you have to short of a timeout on your receiving connection? One second on stream_socket_server(), with a 900 second timeout stream_socket_accept(). What are you using to setup your connection? fsockopen() or stream_socket_server() ? here is a snippet of what I have [...] Thanks for sharing your code. Seems pretty similar to mine at first glance. I don't have a timeout set on the *_recvfrom() call. I just wait until the next connection comes in. You don't need to use mysql_pconnect(), especially if you are using, what in essence is, a daemon. Yeah, after thinking about it, that's what I figured. Thanks for confirming though. Just don't open and close the connection constantly, leave it open. Yes, I just open it once at the top of the script. And that's it. Also, make sure you are not using an array that you are not re- initializing through each iteration of the loop. If the array keeps getting bigger, PHP might $*% on itself. Always re-initialize arrays to clean them up. Hope some of this helps! All good advice. I will check my arrays, although I don't think this is a problem since I monitor the scripts memory usage with memory_get_usage() and memory_get_peak_usage(), and it never tops 3MB (max allocated is 16MB). There are a few little parts to the daemon. One thing I'm doing that could be problematic is running an include (); on a couple files each time a socket has new data (this allows me to adjust the processing logic on the fly without having to start the script and wait for clients to reconnect)--but I can see this being expensive in terms of performance and resources. Actually, I wonder if THAT is not what's starving the script of resources over time-- each fread() involves several includes(); I'll have to look into that... FWIW, here's the stripped-down skeleton of the server: As always, constructive criticism is very welcome. ?php $socket = stream_socket_server(tcp://127.0.0.1:9876, $errno, $errstr); if ($socket) { $master[] = $socket; $read = $master; $write = $master; while (1) { $read = $master; $write = $master; $mod_fd = stream_select($read, $_w = NULL, $_e = NULL, 1); if ($mod_fd === FALSE) { break; } for ($i = 0; $i $mod_fd; ++$i) { if ($read[$i] === $socket) {// NEW SOCKET $conn = stream_socket_accept($socket, 900); $master[] = $conn; $key_num = array_search($conn, $master, TRUE); } else { $sock_data = fread($read[$i], 32768); if (strlen($sock_data) === 0) { // CONNECTION GONE $key_to_del = array_search($read[$i], $master, TRUE); fclose($read[$i]); unset($master[$key_to_del]); } elseif ($sock_data === FALSE) { // CONNECTION BROKEN $key_to_del = array_search($read[$i], $master, TRUE); fclose($read[$i]); unset($master[$key_to_del]); } else { // READ INCOMING DATA // include (somefiles); // include (somefiles); // include (somefiles); // [ ... ] } } } } } ? -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Generating Random Numbers with Normal Distribution
Rob your sick ;-) this thread made me think about the Observer Effect - probably the randomness is just in your/my/his/her head :-P or we're all green men or something. Robert Cummings wrote: On Mon, 2007-12-10 at 17:45 -0500, Daniel Brown wrote: On Dec 10, 2007 5:39 PM, Robert Cummings [EMAIL PROTECTED] wrote: On Mon, 2007-12-10 at 16:32 -0600, Jay Blanchard wrote: [snip] Without order there cannot be randomness. But is the reverse true? [/snip] But disorder isn't necessarily random. Unless you get into Shannon entropy, but that still doesn't disprove your statement. Shannon entropy (from what I briefly scanned) is based upon the presumption of random. As such you can't use it to argue a case for the existence of true random. Entropy is merely the tendency of an ordered state to move toward disorder. It also doesn't in any way make an argument for random. For instance, let's say I order 10 peas into a line in a straw. I then shoot them all at a target which they more or less hit and scatter. The peas are now in disorder, but their places of rest (presuming we're not in outer space ;) would be the logical outcome of the application of the laws of physics with respect to mass, force, angle, gravity, etc. They aren't randomly lying on the ground. Although, one might casually choose their resting locations to derive a pseudo-random number since it is unlikely one could easily guess the precise landing location of each pea. Anyways... this was just a fun sidetrack like we used to get our teachers on when we were kids :) Cheers, Rob. -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Command-line PHP script CPU usage goes sky-high, stays there--why?
Jochem Maas wrote: Jim Lucas wrote: Tom Rogers wrote: Hi, ... Also, make sure you are not using an array that you are not re-initializing through each iteration of the loop. If the array keeps getting bigger, PHP might $*% on itself. Always re-initialize arrays to clean them up. even then he may still have creeping memory ... in which it might be possible to have a mother process that spawns and watchs a child process .. the child process is the actual deamon, the child could then keep a track of it's own memory usage and then kill itself when it gets too big ... the mother in turn would automatically spawn a new child deamon process upon seeing it's child has committed suicide. does that make sense? it may ... but it's besides the point ... apparently I'm having difficulty even reading the subject of [EMAIL PROTECTED] :-P -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] Heritage web solutions
Hi everyone, I was curious if anyone has had the opportunity to work with or for heritage web solutions? If so, would you be able to share your two cents with any experience with them? Thanks! - sf -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Mysqli support - test or complain?
On Monday 10 December 2007, Dave M G wrote: One is based on the assumption that mysqli is as likely not to be available as it is to be installed. In this case I should write my scripts to test whether it exists and then use either mysqli or straight mysql commands as appropriate. If this is the way to go, what do I do to test for the existence of mysqli from within a PHP script? The other is to assume that recent installs and upgrades of PHP 5 should have mysqli because that's the currently preferred way of doing things, and therefore I should contact the web host and ask that they install it, or I find a different host. Which assumption should I be proceeding with? Thank you for any advice or assistance. -- Dave M G ext/mysqli is not part of the stock install of any version of PHP. Some shared hosts install it, some do not. PDO, as of PHP 5.1, is part of the stock install. Nearly any shared host that has MySQL will install the PDO-MySQL backend driver. I'd say this is the most likely MySQL connection method you'll find on a modern host. (A host that doesn't offer PHP 5.2 or later by default is not one you want to do business with. http://gophp5.org/ ) ext/mysql used to be part of the stock install of PHP, but has not been since PHP 5.0 for assorted legal reasons. Most shared hosts install it anyway for legacy support, but you shouldn't use it because it hasn't had any worthwhile updates since MySQL 3 or so. Securing queries in PDO or mysqli is far far far easier. My recommendation is to use PDO rather than mysqli if you don't control the server configuration. If you can be choosy about the host, then write what you want and only pick hosts that will support you. Even better, if you are able to do so, write your own thin abstraction layer that uses PDO or mysqli internally. Then you can switch from one to the other more easily if you find you need to, and you can also add whatever syntactic convenience sugar you want. -- Larry Garfield AIM: LOLG42 [EMAIL PROTECTED] ICQ: 6817012 If nature has made any one thing less susceptible than all others of exclusive property, it is the action of the thinking power called an idea, which an individual may exclusively possess as long as he keeps it to himself; but the moment it is divulged, it forces itself into the possession of every one, and the receiver cannot dispossess himself of it. -- Thomas Jefferson -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Generating Random Numbers with Normal Distribution
On Mon, December 10, 2007 1:37 pm, Stephen Johnson wrote: ever be completely happy with programming random numbers... But it may help you get better results if you include srand() in your randomization code. srand and mt_srand have been no-ops (done internally once at startup) since version (mumble mumble). Adding them in current versions will make zero difference. -- Some people have a gift link here. Know what I want? I want you to buy a CD from some indie artist. http://cdbaby.com/from/lynch Yeah, I get a buck. So? -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Incorporating a PHP/MySQL based search
On Sat, December 8, 2007 4:36 pm, Steve Finkelstein wrote: One area I lack experience in is writting a solution to index/search on a site. Would anyone be kind enough and point me in the right direction as far as any books which discuss some simple solutions or articles/blogs on the web? Clearly I'm not looking for anything as complex as Google's engine, ;-) but would love just to be able to understand/incorporate a decent level of search capabilities. If it's a publicly-available site, you would probably be best served by integrating with Google's search engine and their custom search forms for your site. Another pre-packaged option is ht://dig (a.k.a. htdig) If you want to roll your own for fun it kind of depends on your schema and what is on your site in terms of DB versus static versus... As suggested, MySQL's fulltext index and match operator can be very useful for large text field[s]. You can also provide search in very specific fields with an advanced search form. A crude/simple way to do this is to just assign point values to everything and to add up points for various fields. An example for a library site might go like this: $query = select 0 ; if (isset($_REQUEST['author'])){ $query .= + 10 * author like '%$_REQUEST[author]%' ; } if (isset($_REQUEST['title'])){ $query .= + 10 * author like '%$_REQUEST[title]%' ; } if (isset($_REQUEST['synopsis'])){ $query .= + 5 * synopsis like '%$_REQUEST[synopsi]%' ; } $query .= as score ; $query .= from books ; $query .= having score 0 ; $query .= order by score desc ; $query .= limit 10 ; $query .= offset $_REQUEST[offset] ; Of course, you'd have to validate/cleanse the $_REQUEST data instead of just slamming it directly into a query! But the idea is to give points to various things that match whatever the user inputs, and add them up as a sort of score for each book. -- Some people have a gift link here. Know what I want? I want you to buy a CD from some indie artist. http://cdbaby.com/from/lynch Yeah, I get a buck. So? -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] build a multi chat server with php
On Sat, December 8, 2007 2:59 am, abderrazzak nejeoui wrote: i want build a multi chat server based in php. Okay. 1- is that possible Yes. 2- if yes can you instruct me how to bigin Step 1: http://php.net/sockets BIG PICTURE: You MIGHT want to consider taking a well-supported MUD or whatever, and using its API to make an extension to PHP. This would probably give you MUCH more bang for the buck than writing the whole dang thing from scratch in PHP. There even may be such a beast in PECL already, for all I know. http://pecl.php.net/ -- Some people have a gift link here. Know what I want? I want you to buy a CD from some indie artist. http://cdbaby.com/from/lynch Yeah, I get a buck. So? -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
RE: [PHP] LoadXML trouble
first, create dealxml.php with ansi charset : ?php $r = XML ?xml version=1.0? response customerIDked/customerID appNametickcenter/appName ticketTypetrain/ticketType ticketActionback/ticketAction ticketID1197026188_ec76/ticketID statusKO/status errCode500/errCode errMsgInternal Server Error/errMsg /response XML; $xml = new DOMDocument(); //$xml-validateOnParse = true; $xml-loadXML( $r ); $customer_id = $xml-getElementsByTagName( 'customerID' )-item( 0 )-nodeValue; $app_name = $xml-getElementsByTagName( 'appName' )-item( 0 )-nodeValue; $ticket_type = $xml-getElementsByTagName( 'ticketType' )-item( 0 )-nodeValue; $ticket_action = $xml-getElementsByTagName( 'ticketAction' )-item( 0 )-nodeValue; $ticket_params = $xml-getElementsByTagName( 'parameters' )-item( 0 )-childNodes; echo $customer_id br; echo $app_name br; echo $ticket_typed br; echo $ticket_action br; echo $ticket_params br; ? IE output : Warning: DOMDocument::loadXML() [function.loadXML]: Input is not proper UTF-8, indicate encoding ! in Entity, line: 4 in W:\www\test\dealxml.php on line 26 next , saved the dealxml.php as UTF-8 charset, then it works well. I think that the xml resource should be encoded by utf-8 charset, right or wrong ? My OS : win2000 , simplified chinese. Dose the OS blight DOMDocument ? -Original Message- From: Nathan Nobbe [mailto:[EMAIL PROTECTED] Sent: Tuesday, December 11, 2007 1:25 AM To: Dani Castaños Cc: php-general@lists.php.net Subject: Re: [PHP] LoadXML trouble On Dec 10, 2007 12:08 PM, Dani Castaños [EMAIL PROTECTED] wrote: Yep, it works when i do saveXML, but not on loadXML step... did the loadXML() method work in the test script i sent over in my last post? if it does then something else is going on when loadXML() is called in the context of your application. The thing is... i'm trying to do something like this: $request = $_POST['xml']; $logger-debug( 'New ticket request' ); /** * Parse XML request to obtain values */ $xml = new DOMDocument(); //$xml-validateOnParse = true; $xml-loadXML( $request ); you should always sanitize input. at the very least you should be running $_POST['xml'] through a call to trim() before handing it to the DOMDocument instance. $request = trim($_POST['xml']); $xml = new DOMDocument(); $xml-loadXML($request); i suspect there is some garbage in or around the string contained in $_POST['xml'] that the DomDocument instance doesnt like, therefore its not behaving the way youd anticipate. for example if you modify the script i sent over last time by putting some spaces in between the xml declaration and the opening tag of the envelope (response) you should see the following error (or something similar [depending on the value of error_reporting]) Warning: DOMDocument::loadXML(): XML declaration allowed only at the start of the document in Entity, line: 3 in /home/nathan/testDom.php on line 19 which consequently leads to ?xml version=1.0? when invoking echo $domDoc-saveXML() . PHP_EOL; rather than ?xml version=1.0? response ticketID1197026188_ec76/ticketID statusKO/status errCode500/errCode errMsgInternal Server Error/errMsg /response which is what you would expect. -nathan -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Generating Random Numbers with Normal Distribution
On Dec 10, 2007 5:56 PM, Robert Cummings [EMAIL PROTECTED] wrote: On Mon, 2007-12-10 at 17:45 -0500, Daniel Brown wrote: On Dec 10, 2007 5:39 PM, Robert Cummings [EMAIL PROTECTED] wrote: On Mon, 2007-12-10 at 16:32 -0600, Jay Blanchard wrote: [snip] Without order there cannot be randomness. But is the reverse true? [/snip] But disorder isn't necessarily random. Unless you get into Shannon entropy, but that still doesn't disprove your statement. Shannon entropy (from what I briefly scanned) is based upon the presumption of random. As such you can't use it to argue a case for the existence of true random. Entropy is merely the tendency of an ordered state to move toward disorder. It also doesn't in any way make an argument for random. For instance, let's say I order 10 peas into a line in a straw. I then shoot them all at a target which they more or less hit and scatter. The peas are now in disorder, but their places of rest (presuming we're not in outer space ;) would be the logical outcome of the application of the laws of physics with respect to mass, force, angle, gravity, etc. They aren't randomly lying on the ground. Although, one might casually choose their resting locations to derive a pseudo-random number since it is unlikely one could easily guess the precise landing location of each pea. actually a couple of guys spent some time to figure that out many years back and applied it to the roulette wheel. they made a small computer you could put in your shoe and trained a bunch of people how to use it. they then sent the people out to various casinos and became millionares. -nathan
Re: [PHP] Mysqli support - test or complain? [SOLVED]
Zoltan, Per, Richard, Chris, Daniel, Larry, Thank you for responding. I have created a method in the class that handles my database connections that will first test on extension_loaded(mysqli) before connecting to the database. Then I store the result in a session variable for reference, so future calls will use the correct mysqli or regular syntax. Thank you for helping me to find this solution. My scripts are that much more portable now. -- Dave M G -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Mysqli support - test or complain? [SOLVED]
On Tue, 2007-12-11 at 13:02 +0900, Dave M G wrote: Zoltan, Per, Richard, Chris, Daniel, Larry, Thank you for responding. I have created a method in the class that handles my database connections that will first test on extension_loaded(mysqli) before connecting to the database. Then I store the result in a session variable for reference, so future calls will use the correct mysqli or regular syntax. Thank you for helping me to find this solution. My scripts are that much more portable now. You use a session variable for that? That's entirely the wrong place to store something like which database API is installed. It should a class variable or global configuration variable. Heck, I'd say it's more appropriate to do extension_loaded( 'mysqli' ) on every call than to use a session variable. Cheers, Rob. -- ... SwarmBuy.com - http://www.swarmbuy.com Leveraging the buying power of the masses! ... -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] Help Sending Mail
Dear All, i wrote this class below to send Mail. but when i use it. i get the sender No Body. and from the address of the server, not the From address that i specify. and the MIME Headers as text in the message itself. and the attachment is pasted as binary text also. can anyone help please ?? here is the code : ?php $Mail = new MainClass(); $Mail-Construct(Ahmed, [EMAIL PROTECTED], Test Mail, Hello, this is my first message); $Mail-AddTo([EMAIL PROTECTED], Ahmed); $Mail-AddCc([EMAIL PROTECTED], Me2resh); $Mail-AddBcc([EMAIL PROTECTED], hola); $Mail-AddAttach(favicon.ico); $Mail-SendMail(); echo pre; print_r($Mail); /** * */ class MainClass{ /** * */ var $To = ; var $Cc = ; var $Bcc = ; var $From = ; var $Name = ; var $Subject = ; var $Message = ; var $Headers = ; function Construct($name, $from, $subject, $message){ //construct message if ($name == ){ $name = $from; } $this-Name = $name; $this-From = $from; $this-Subject = $subject; $this-Message = $message; }//end of Construct function AddTo($email, $name){ // add reciepnt to To array if ($name == ){ $name = $email; } if ($this-To == ){ $this-To .= $name.' '.$email.''; }else{ $this-To .= ,.$name.' '.$email.''; } }// end of AddTo function AddCc($email, $name){ // add reciepnt to Cc array if ($name == ){ $name = $email; } if ($this-Cc == ){ $this-Cc .= $name.' '.$email.''; }else{ $this-Cc .= ,.$name.' '.$email.''; } } function AddBcc($email, $name){ // add reciepnt to Bcc array if ($name == ){ $name = $email; } if ($this-Bcc == ){ $this-Bcc .= $name.' '.$email.''; }else{ $this-Bcc .= ,.$name.' '.$email.''; } } function AddAttach($attach){ //add attach to array //if (is_uploaded_file($attach)) { // Read the file to be attached ('rb' = read binary) $file = fopen($attach,'rb'); $data = fread($file,filesize($attach)); fclose($file); // Generate a boundary string $semi_rand = md5(time()); $mime_boundary = ==Multipart_Boundary_x{$semi_rand}x; // Add the headers for a file attachment $this-Headers .= \nMIME-Version: 1.0\n . Content-Type: multipart/mixed;\n . boundary=\{$mime_boundary}\; // Add a multipart boundary above the plain message $this-Message = This is a multi-part message in MIME format.\n\n . --{$mime_boundary}\n . Content-Type: text/plain; charset=\iso-8859-1\\n . Content-Transfer-Encoding: 7bit\n\n . $this-Message . \n\n; // Base64 encode the file data $data = chunk_split(base64_encode($data)); // Add file attachment to the message $this-Message .= --{$mime_boundary}\n . Content-Type: {filetype($attach)};\n . name=\{$attach}\\n . Content-Disposition: attachment;\n . filename=\{$attach}\\n . Content-Transfer-Encoding: base64\n\n . $data . \n\n . --{$mime_boundary}--\n; // }// end of if }// end of add attach function SendMail(){ $this-Headers .= \r\n; $this-Headers .= 'To: '.$this-To.\r\n; $this-Headers .= 'From: '.$this-Name.''.$this-From.''.\r\n; $this-Headers .= 'Cc: '.$this-Cc.\r\n; $this-Headers .= 'Bcc: '.$this-Bcc.\r\n; mail($this-From, $this-Subject, $this-Message, $this-Headers); } }// end of class ? Here is the text in the email : MIME-Version: 1.0 Content-Type: multipart/mixed; boundary===Multipart_Boundary_xd609c629ba34ecb645a7572abb61eb27x To: Ahmed [EMAIL PROTECTED] From: Ahmed[EMAIL PROTECTED] Cc: Me2resh [EMAIL PROTECTED] Bcc: hola [EMAIL PROTECTED] This is a multi-part message in MIME format. --==Multipart_Boundary_xd609c629ba34ecb645a7572abb61eb27x Content-Type: text/plain; charset=iso-8859-1 Content-Transfer-Encoding: 7bit Hello, this is my first message --==Multipart_Boundary_xd609c629ba34ecb645a7572abb61eb27x Content-Type: {filetype(favicon.ico)}; name=favicon.ico Content-Disposition: attachment; filename=favicon.ico Content-Transfer-Encoding: base64 AAABAAEAEBEAGABoAwAAFgAAACgQIAEAGAMA AAASEhIHBwcHBwcJCQkoKChLS0tZWVlOTk4MDAwHBwcHBwcHBwcHBwcHBwcHBwcmJiYKCgok
Re: [PHP] Command-line PHP script CPU usage goes sky-high, stays there--why?
René Fournier wrote: FWIW, here's the stripped-down skeleton of the server: As always, constructive criticism is very welcome. ?php $socket = stream_socket_server(tcp://127.0.0.1:9876, $errno, $errstr); if ($socket) { $master[] = $socket; $read = $master; $write = $master; while (1) { $read = $master; $write = $master; The follow part, I think, is where your problem is. This line tells the system to wait 1 second and then continue, whether you have an inbound connection or not. $mod_fd = stream_select($read, $_w = NULL, $_e = NULL, 1); Then here you are testing for success or failure of the last call. if ($mod_fd === FALSE) { break; } Problem, if you don't have a connection, then the will fail constantly. once every second X (times) the number of connections you have... for ($i = 0; $i $mod_fd; ++$i) { if ($read[$i] === $socket) {// NEW SOCKET $conn = stream_socket_accept($socket, 900); $master[] = $conn; $key_num = array_search($conn, $master, TRUE); } else { $sock_data = fread($read[$i], 32768); if (strlen($sock_data) === 0) { // CONNECTION GONE $key_to_del = array_search($read[$i], $master, TRUE); fclose($read[$i]); unset($master[$key_to_del]); } elseif ($sock_data === FALSE) {// CONNECTION BROKEN $key_to_del = array_search($read[$i], $master, TRUE); fclose($read[$i]); unset($master[$key_to_del]); } else {// READ INCOMING DATA Here, you are not removing the successful connections from $master, so it keeps growing on and on... As for the includes, well, I would turn them into function calls and then have a different function for the different ways you want the program to react. // include (somefiles); // include (somefiles); // include (somefiles); // [ ... ] } } } } } ? I didn't see anything about your DB connections. Are those located in the includes? How long, on average, does your processing of the incoming data take? Because, to me, it looks like you might have a blocking problem with the in-coming connections. If the initial connection takes too long, then the following connections might be getting blocked. You might want to look into pcntl_* functions to do forking if you need it. -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Help Sending Mail
On Tue, 2007-12-11 at 06:33 +0200, Me2resh Lists wrote: Dear All, i wrote this class below to send Mail. but when i use it. i get the sender No Body. and from the address of the server, not the From address that i specify. and the MIME Headers as text in the message itself. and the attachment is pasted as binary text also. can anyone help please ?? here is the code : ?php $Mail = new MainClass(); $Mail-Construct(Ahmed, [EMAIL PROTECTED], Test Mail, Hello, this is my first message); $Mail-AddTo([EMAIL PROTECTED], Ahmed); $Mail-AddCc([EMAIL PROTECTED], Me2resh); $Mail-AddBcc([EMAIL PROTECTED], hola); $Mail-AddAttach(favicon.ico); $Mail-SendMail(); echo pre; print_r($Mail); /** * */ class MainClass{ /** * */ var $To = ; var $Cc = ; var $Bcc = ; var $From = ; var $Name = ; var $Subject = ; var $Message = ; var $Headers = ; function Construct($name, $from, $subject, $message){ //construct message if ($name == ){ $name = $from; } $this-Name = $name; $this-From = $from; $this-Subject = $subject; $this-Message = $message; }//end of Construct function AddTo($email, $name){ // add reciepnt to To array if ($name == ){ $name = $email; } if ($this-To == ){ $this-To .= $name.' '.$email.''; }else{ $this-To .= ,.$name.' '.$email.''; } }// end of AddTo function AddCc($email, $name){ // add reciepnt to Cc array if ($name == ){ $name = $email; } if ($this-Cc == ){ $this-Cc .= $name.' '.$email.''; }else{ $this-Cc .= ,.$name.' '.$email.''; } } function AddBcc($email, $name){ // add reciepnt to Bcc array if ($name == ){ $name = $email; } if ($this-Bcc == ){ $this-Bcc .= $name.' '.$email.''; }else{ $this-Bcc .= ,.$name.' '.$email.''; } } function AddAttach($attach){ //add attach to array //if (is_uploaded_file($attach)) { // Read the file to be attached ('rb' = read binary) $file = fopen($attach,'rb'); $data = fread($file,filesize($attach)); fclose($file); // Generate a boundary string $semi_rand = md5(time()); $mime_boundary = ==Multipart_Boundary_x{$semi_rand}x; // Add the headers for a file attachment $this-Headers .= \nMIME-Version: 1.0\n . Content-Type: multipart/mixed;\n . boundary=\{$mime_boundary}\; // Add a multipart boundary above the plain message $this-Message = This is a multi-part message in MIME format.\n\n . --{$mime_boundary}\n . Content-Type: text/plain; charset=\iso-8859-1\\n . Content-Transfer-Encoding: 7bit\n\n . $this-Message . \n\n; // Base64 encode the file data $data = chunk_split(base64_encode($data)); // Add file attachment to the message $this-Message .= --{$mime_boundary}\n . Content-Type: {filetype($attach)};\n . name=\{$attach}\\n . Content-Disposition: attachment;\n . filename=\{$attach}\\n . Content-Transfer-Encoding: base64\n\n . $data . \n\n . --{$mime_boundary}--\n; // }// end of if }// end of add attach function SendMail(){ $this-Headers .= \r\n; The last line above is your problem. Remove it. Cheers, Rob. -- ... SwarmBuy.com - http://www.swarmbuy.com Leveraging the buying power of the masses! ... -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Help Sending Mail
Me2resh Lists wrote: Dear All, i wrote this class below to send Mail. but when i use it. i get the sender No Body. and from the address of the server, not the From address that i specify. and the MIME Headers as text in the message itself. and the attachment is pasted as binary text also. can anyone help please ?? here is the code : ?php $Mail = new MainClass(); $Mail-Construct(Ahmed, [EMAIL PROTECTED], Test Mail, Hello, this is my first message); $Mail-AddTo([EMAIL PROTECTED], Ahmed); $Mail-AddCc([EMAIL PROTECTED], Me2resh); $Mail-AddBcc([EMAIL PROTECTED], hola); Your calling this $Mail-AddAttach(favicon.ico); Before this... ( see below ) $Mail-SendMail(); echo pre; print_r($Mail); /** * */ class MainClass{ /** * */ var $To = ; var $Cc = ; var $Bcc = ; var $From = ; var $Name = ; var $Subject = ; var $Message = ; var $Headers = ; function Construct($name, $from, $subject, $message){ //construct message if ($name == ){ $name = $from; } $this-Name = $name; $this-From = $from; $this-Subject = $subject; $this-Message = $message; }//end of Construct function AddTo($email, $name){ // add reciepnt to To array if ($name == ){ $name = $email; } if ($this-To == ){ $this-To .= $name.' '.$email.''; }else{ $this-To .= ,.$name.' '.$email.''; } }// end of AddTo function AddCc($email, $name){ // add reciepnt to Cc array if ($name == ){ $name = $email; } if ($this-Cc == ){ $this-Cc .= $name.' '.$email.''; }else{ $this-Cc .= ,.$name.' '.$email.''; } } function AddBcc($email, $name){ // add reciepnt to Bcc array if ($name == ){ $name = $email; } if ($this-Bcc == ){ $this-Bcc .= $name.' '.$email.''; }else{ $this-Bcc .= ,.$name.' '.$email.''; } } function AddAttach($attach){ //add attach to array //if (is_uploaded_file($attach)) { // Read the file to be attached ('rb' = read binary) $file = fopen($attach,'rb'); $data = fread($file,filesize($attach)); fclose($file); // Generate a boundary string $semi_rand = md5(time()); $mime_boundary = ==Multipart_Boundary_x{$semi_rand}x; Because, right here, you are adding a blank line to the email body. This tells the system that the rest is the message. Take off the leading \n and move it to the end of the statement and it might work for you. // Add the headers for a file attachment $this-Headers .= \nMIME-Version: 1.0\n . Content-Type: multipart/mixed;\n . boundary=\{$mime_boundary}\; // Add a multipart boundary above the plain message $this-Message = This is a multi-part message in MIME format.\n\n . --{$mime_boundary}\n . Content-Type: text/plain; charset=\iso-8859-1\\n . Content-Transfer-Encoding: 7bit\n\n . $this-Message . \n\n; // Base64 encode the file data $data = chunk_split(base64_encode($data)); // Add file attachment to the message $this-Message .= --{$mime_boundary}\n . Content-Type: {filetype($attach)};\n . name=\{$attach}\\n . Content-Disposition: attachment;\n . filename=\{$attach}\\n . Content-Transfer-Encoding: base64\n\n . $data . \n\n . --{$mime_boundary}--\n; // }// end of if }// end of add attach function SendMail(){ Are these really suppose to be \r\n??? Or should you use the PHP_EOL constant? $this-Headers .= \r\n; $this-Headers .= 'To: '.$this-To.\r\n; $this-Headers .= 'From: '.$this-Name.''.$this-From.''.\r\n; $this-Headers .= 'Cc: '.$this-Cc.\r\n; $this-Headers .= 'Bcc: '.$this-Bcc.\r\n; mail($this-From, $this-Subject, $this-Message, $this-Headers); } }// end of class ? Here is the text in the email : MIME-Version: 1.0 Content-Type: multipart/mixed; boundary===Multipart_Boundary_xd609c629ba34ecb645a7572abb61eb27x To: Ahmed [EMAIL PROTECTED] From: Ahmed[EMAIL PROTECTED] Cc: Me2resh [EMAIL PROTECTED] Bcc: hola [EMAIL PROTECTED] This is a multi-part message in MIME format. --==Multipart_Boundary_xd609c629ba34ecb645a7572abb61eb27x Content-Type: text/plain; charset=iso-8859-1 Content-Transfer-Encoding: 7bit Hello, this
Re: [PHP] Help Sending Mail
Robert Cummings wrote: On Tue, 2007-12-11 at 06:33 +0200, Me2resh Lists wrote: Dear All, i wrote this class below to send Mail. but when i use it. i get the sender No Body. and from the address of the server, not the From address that i specify. and the MIME Headers as text in the message itself. and the attachment is pasted as binary text also. can anyone help please ?? here is the code : ?php $Mail = new MainClass(); $Mail-Construct(Ahmed, [EMAIL PROTECTED], Test Mail, Hello, this is my first message); $Mail-AddTo([EMAIL PROTECTED], Ahmed); $Mail-AddCc([EMAIL PROTECTED], Me2resh); $Mail-AddBcc([EMAIL PROTECTED], hola); $Mail-AddAttach(favicon.ico); $Mail-SendMail(); echo pre; print_r($Mail); /** * */ class MainClass{ /** * */ var $To = ; var $Cc = ; var $Bcc = ; var $From = ; var $Name = ; var $Subject = ; var $Message = ; var $Headers = ; function Construct($name, $from, $subject, $message){ //construct message if ($name == ){ $name = $from; } $this-Name = $name; $this-From = $from; $this-Subject = $subject; $this-Message = $message; }//end of Construct function AddTo($email, $name){ // add reciepnt to To array if ($name == ){ $name = $email; } if ($this-To == ){ $this-To .= $name.' '.$email.''; }else{ $this-To .= ,.$name.' '.$email.''; } }// end of AddTo function AddCc($email, $name){ // add reciepnt to Cc array if ($name == ){ $name = $email; } if ($this-Cc == ){ $this-Cc .= $name.' '.$email.''; }else{ $this-Cc .= ,.$name.' '.$email.''; } } function AddBcc($email, $name){ // add reciepnt to Bcc array if ($name == ){ $name = $email; } if ($this-Bcc == ){ $this-Bcc .= $name.' '.$email.''; }else{ $this-Bcc .= ,.$name.' '.$email.''; } } function AddAttach($attach){ //add attach to array //if (is_uploaded_file($attach)) { // Read the file to be attached ('rb' = read binary) $file = fopen($attach,'rb'); $data = fread($file,filesize($attach)); fclose($file); // Generate a boundary string $semi_rand = md5(time()); $mime_boundary = ==Multipart_Boundary_x{$semi_rand}x; // Add the headers for a file attachment $this-Headers .= \nMIME-Version: 1.0\n . Content-Type: multipart/mixed;\n . boundary=\{$mime_boundary}\; // Add a multipart boundary above the plain message $this-Message = This is a multi-part message in MIME format.\n\n . --{$mime_boundary}\n . Content-Type: text/plain; charset=\iso-8859-1\\n . Content-Transfer-Encoding: 7bit\n\n . $this-Message . \n\n; // Base64 encode the file data $data = chunk_split(base64_encode($data)); // Add file attachment to the message $this-Message .= --{$mime_boundary}\n . Content-Type: {filetype($attach)};\n . name=\{$attach}\\n . Content-Disposition: attachment;\n . filename=\{$attach}\\n . Content-Transfer-Encoding: base64\n\n . $data . \n\n . --{$mime_boundary}--\n; // }// end of if }// end of add attach function SendMail(){ $this-Headers .= \r\n; The last line above is your problem. Remove it. Partly, check the $this-Headers .= ... part in the AddAttach method Cheers, Rob. -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re[2]: [PHP] Command-line PHP script CPU usage goes sky-high, stays there--why?
Hi, Tuesday, December 11, 2007, 10:01:38 AM, you wrote: RF On 10-Dec-07, at 4:42 PM, Tom Rogers wrote: Put a usleep(1000) in the listen while() loop and give the cpu a break. RF Good advice, but I've already been doing that. The thing is, when the RF script first starts up, the CPU rarely exceeds 30%, even when many RF clients (200+) are simultaneously connected and sending data. When a RF few clients are connected, CPU is typically below 10%. Again, it's RF only after 24-48 hours that, all of a sudden, CPU usage increases by RF 40-50%. And it stays high until I stop the script and restart it. RF One question I have though is, is there actually any benefit to using RF mysql_pconnect(), since the script simply loops? My understanding is RF that pconnect only benefits if a script would otherwise be using RF mysql_connect repeatedly--and this script doesn't, since it calls RF mysql_[p]connect() just once, in the start tof execution. RF ...Rene I have found pconnect to be a problem (several years ago) and have never tried it since, it may well be ok now. The most likely cause is memory consumption on long running php scripts, what does top say? I have a script which runs from cron and was hammering the system when it ran and i have had to put the usleep() in the while($result = ..) loop as there are a few thousand rows. Probably bad design but it works and I'm loath to touch it :) One way to solve the memory issue is to have the script started by inetd, slower but more memory friendly. Also have a look at memcached to reduce the load a bit. -- regards, Tom -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Help Sending Mail
On Mon, 2007-12-10 at 21:05 -0800, Jim Lucas wrote: Robert Cummings wrote: On Tue, 2007-12-11 at 06:33 +0200, Me2resh Lists wrote: Dear All, i wrote this class below to send Mail. but when i use it. i get the sender No Body. and from the address of the server, not the From address that i specify. and the MIME Headers as text in the message itself. and the attachment is pasted as binary text also. can anyone help please ?? here is the code : ?php $Mail = new MainClass(); $Mail-Construct(Ahmed, [EMAIL PROTECTED], Test Mail, Hello, this is my first message); $Mail-AddTo([EMAIL PROTECTED], Ahmed); $Mail-AddCc([EMAIL PROTECTED], Me2resh); $Mail-AddBcc([EMAIL PROTECTED], hola); $Mail-AddAttach(favicon.ico); $Mail-SendMail(); echo pre; print_r($Mail); /** * */ class MainClass{ /** * */ var $To = ; var $Cc = ; var $Bcc = ; var $From = ; var $Name = ; var $Subject = ; var $Message = ; var $Headers = ; function Construct($name, $from, $subject, $message){ //construct message if ($name == ){ $name = $from; } $this-Name = $name; $this-From = $from; $this-Subject = $subject; $this-Message = $message; }//end of Construct function AddTo($email, $name){ // add reciepnt to To array if ($name == ){ $name = $email; } if ($this-To == ){ $this-To .= $name.' '.$email.''; }else{ $this-To .= ,.$name.' '.$email.''; } }// end of AddTo function AddCc($email, $name){ // add reciepnt to Cc array if ($name == ){ $name = $email; } if ($this-Cc == ){ $this-Cc .= $name.' '.$email.''; }else{ $this-Cc .= ,.$name.' '.$email.''; } } function AddBcc($email, $name){ // add reciepnt to Bcc array if ($name == ){ $name = $email; } if ($this-Bcc == ){ $this-Bcc .= $name.' '.$email.''; }else{ $this-Bcc .= ,.$name.' '.$email.''; } } function AddAttach($attach){ //add attach to array //if (is_uploaded_file($attach)) { // Read the file to be attached ('rb' = read binary) $file = fopen($attach,'rb'); $data = fread($file,filesize($attach)); fclose($file); // Generate a boundary string $semi_rand = md5(time()); $mime_boundary = ==Multipart_Boundary_x{$semi_rand}x; // Add the headers for a file attachment $this-Headers .= \nMIME-Version: 1.0\n . Content-Type: multipart/mixed;\n . boundary=\{$mime_boundary}\; // Add a multipart boundary above the plain message $this-Message = This is a multi-part message in MIME format.\n\n . --{$mime_boundary}\n . Content-Type: text/plain; charset=\iso-8859-1\\n . Content-Transfer-Encoding: 7bit\n\n . $this-Message . \n\n; // Base64 encode the file data $data = chunk_split(base64_encode($data)); // Add file attachment to the message $this-Message .= --{$mime_boundary}\n . Content-Type: {filetype($attach)};\n . name=\{$attach}\\n . Content-Disposition: attachment;\n . filename=\{$attach}\\n . Content-Transfer-Encoding: base64\n\n . $data . \n\n . --{$mime_boundary}--\n; // }// end of if }// end of add attach function SendMail(){ $this-Headers .= \r\n; The last line above is your problem. Remove it. Partly, check the $this-Headers .= ... part in the AddAttach method Yeah, he's all over the place with his line endings. Personally, I use an array to track the headers and use implode in one shot before sending. Cheers, Rob. -- ... SwarmBuy.com - http://www.swarmbuy.com Leveraging the buying power of the masses! ... -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Command-line PHP script CPU usage goes sky-high, stays there--why?
Thanks Jim. Several good points here that I will look into. I've already moved the include() bits into function calls. (That's simple thing I should have corrected long ago.) The socket areas though I'm less sure about how to adjust, since networking programming isn't something I grok naturally. On 10-Dec-07, at 9:57 PM, Jim Lucas wrote: René Fournier wrote: FWIW, here's the stripped-down skeleton of the server: As always, constructive criticism is very welcome. ?php $socket = stream_socket_server(tcp://127.0.0.1:9876, $errno, $errstr); if ($socket) { $master[] = $socket; $read = $master; $write = $master; while (1) { $read = $master; $write = $master; The follow part, I think, is where your problem is. This line tells the system to wait 1 second and then continue, whether you have an inbound connection or not. $mod_fd = stream_select($read, $_w = NULL, $_e = NULL, 1); Then here you are testing for success or failure of the last call. if ($mod_fd === FALSE) { break; } Problem, if you don't have a connection, then the will fail constantly. once every second X (times) the number of connections you have... But my understanding from the docs (where I used one of the examples as a template for the script) socket is that it could/would only fail on startup, that is if it can't perform stream_select() because it's unable to bind to with stream_socket_server(), or am I wrong?: If the call fails, it will return FALSE and if the optional errno and errstr arguments are present they will be set to indicate the actual system level error that occurred in the system-level socket(), bind(), and listen() calls. If the value returned in errno is 0 and the function returned FALSE, it is an indication that the error occurred before the bind() call. This is most likely due to a problem initializing the socket. Note that the errno and errstr arguments will always be passed by reference. (http://www.php.net/manual/en/ function.stream-socket-server.php) In other wrongs, mod_fd can't return FALSE once the socket_server has been created and bound to the specified IP... right? for ($i = 0; $i $mod_fd; ++$i) { if ($read[$i] === $socket) {// NEW SOCKET $conn = stream_socket_accept($socket, 900); $master[] = $conn; $key_num = array_search($conn, $master, TRUE); } else { $sock_data = fread($read[$i], 32768); if (strlen($sock_data) === 0) { // CONNECTION GONE $key_to_del = array_search($read [$i], $master, TRUE); fclose($read[$i]); unset ($master[$key_to_del]); } elseif ($sock_data === FALSE) {// CONNECTION BROKEN $key_to_del = array_search ($read[$i], $master, TRUE); fclose($read[$i]); unset($master[$key_to_del]); } else {// READ INCOMING DATA Here, you are not removing the successful connections from $master, so it keeps growing on and on... But only until the connection closes, or no longer blocks (goes away), in which case the program fcloses that socket and removes it from master[]. As for the includes, well, I would turn them into function calls and then have a different function for the different ways you want the program to react. Yes, I did that. It helps a bit with CPU. // include (somefiles); // include (somefiles); // include (somefiles); // [ ... ] } } } } } ? I didn't see anything about your DB connections. Are those located in the includes? Just at header.inc, once. How long, on average, does your processing of the incoming data take? Because, to me, it looks like you might have a blocking problem with the in-coming connections. If the initial connection takes too long, then the following connections might be getting blocked. You might want to look into pcntl_* functions to do forking if you need it. The processing is pretty quick. I don't think that's a bottleneck. It basically just inserts the data into MySQL, not much processing actually. -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: Re[2]: [PHP] Command-line PHP script CPU usage goes sky-high, stays there--why?
Curiously, would you agree with this guy's comments concerning low- level PHP socket functions vs stream_socket_server() ? If you want a high speed socket server, use the low-level sockets instead (socket_create/bind/listen). The stream_socket_server version appears to have internal fixed 8k buffers that will overflow if you don't keep up by reading. This is a serious problem if you an application that reads the socket for messages and then, say, saves the result in a database. The delay while it is busy processing means you can't read the data in time unless you get involved in muti-threading. With the the low-level functions, the OS quietly buffers TCP/IP packets so there is no problem (tested on Windows XP Professional). (http://www.php.net/manual/en/function.stream-socket- server.php#67837) On 10-Dec-07, at 9:46 PM, Tom Rogers wrote: Hi, Tuesday, December 11, 2007, 10:01:38 AM, you wrote: RF On 10-Dec-07, at 4:42 PM, Tom Rogers wrote: Put a usleep(1000) in the listen while() loop and give the cpu a break. RF Good advice, but I've already been doing that. The thing is, when the RF script first starts up, the CPU rarely exceeds 30%, even when many RF clients (200+) are simultaneously connected and sending data. When a RF few clients are connected, CPU is typically below 10%. Again, it's RF only after 24-48 hours that, all of a sudden, CPU usage increases by RF 40-50%. And it stays high until I stop the script and restart it. RF One question I have though is, is there actually any benefit to using RF mysql_pconnect(), since the script simply loops? My understanding is RF that pconnect only benefits if a script would otherwise be using RF mysql_connect repeatedly--and this script doesn't, since it calls RF mysql_[p]connect() just once, in the start tof execution. RF ...Rene I have found pconnect to be a problem (several years ago) and have never tried it since, it may well be ok now. The most likely cause is memory consumption on long running php scripts, what does top say? I have a script which runs from cron and was hammering the system when it ran and i have had to put the usleep() in the while($result = ..) loop as there are a few thousand rows. Probably bad design but it works and I'm loath to touch it :) One way to solve the memory issue is to have the script started by inetd, slower but more memory friendly. Also have a look at memcached to reduce the load a bit. -- regards, Tom -- 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