sprintf bug with php & apache in windows? - php

I've run into a strange problem on a WAMP server setup (PHP version 5.3.0, Apache 2.2.11). When using sprintf to output a number, I occasionally get erroneous characters in the output string.
Example: (not trimmed from anything, this is the only code in the script)
$dt1 = new DateTime('now');
$dt2 = new DateTime('now - 10 min');
$interval = $dt1->diff($dt2);
$number = 10.0;
$string = sprintf("%.1f", $number);
echo "number: $number, string: $string\n";
If I run this at the command prompt with PHP CLI, I get the expected output:
number: 10, string: 10.0
However, if I serve it using Apache, in the browser I get
number: 10, string: :.0
with a colon where '10' should be. (Note that ':' is the next ascii character in sequence after '9', if $number is 0-9, everything works. Numbers greater than 10 appear to use ascii equivalents - so 11 is ';', 12 is '<', etc.)
The strangest part is that the first four lines in the above code sample seem to affect the results. Logically, those statements should have no impact, but if I comment them out or remove them the problem goes away.
Any ideas? Anyone else able to replicate this?
Notes:
I've tried php 5.3.1 and 5.3.2, both behave the same way
The above script works fine, even in the browser, for 5-6 page refreshes after restarting Apache. Then the error, as described, returns

Try adding this above the code setlocale(LC_ALL, 'en_US');

Try this:
Change echo "number: $number, string: $string\n"; to:
for ($i = 0, $n = strlen($string); $i < $n; $i++) {
echo ord($string[$i]).' ';
}
It will basically give you the numeric character code for each byte in the string. Note that I said byte. If it's a character set problem, or a problem with Apache mangling bytes, you should see that here. Expected output is: 49 48 46 48. If you instead see 58 46 48, then you indeed may have found a bug with php and should submit a bug report. You also should try upgrading your php version (5.3.2 is out)...

Related

Getting different output for same PHP code

(Can't paste the exact question as the contest is over and I am unable to access the question. Sorry.)
Hello, recently I took part in a programming contest (PHP). I tested the code on my PC and got the desired output but when I checked my code on the contest website and ideone, I got wrong output. This is the 2nd time the same thing has happened. Same PHP code but different output.
It is taking input from command line. The purpose is to bring substrings that contact the characters 'A','B','C','a','b','c'.
For example: Consider the string 'AaBbCc' as CLI input.
Substrings: A,a,B,b,C,c,Aa,AaB,AaBb,AaBbC,AaBbCc,aB,aBb,aBbC,aBbCc,Bb,BbC,BbCc,bC,bCc,Cc.
Total substrings: 21 which is the correct output.
My machine:
Windows 7 64 Bit
PHP 5.3.13 (Wamp Server)
Following is the code:
<?php
$stdin = fopen('php://stdin', 'r');
while(true) {
$t = fread($stdin,3);
$t = trim($t);
$t = (int)$t;
while($t--) {
$sLen=0;
$subStringsNum=0;
$searchString="";
$searchString = fread($stdin,20);
$sLen=strlen($searchString);
$sLen=strlen(trim($searchString));
for($i=0;$i<$sLen;$i++) {
for($j=$i;$j<$sLen;$j++) {
if(preg_match("/^[A-C]+$/i",substr($searchString,$i,$sLen-$j))) {$subStringsNum++;}
}
}
echo $subStringsNum."\n";
}
die;
}
?>
Input:
2
AaBbCc
XxYyZz
Correct Output (My PC):
21
0
Ideone/Contest Website Output:
20
0
You have to keep in mind that your code is also processing the newline symbols.
On Windows systems, newline is composed by two characters, which escaped representation is \r\n.
On UNIX systems including Linux, only \n is used, and on MAC they use \r instead.
Since you are relying on the standard output, it will be susceptible to those architecture differences, and even if it was a file you are enforcing the architecture standard by using the flag "r" when creating the file handle instead of "rb", explicitly declaring you don't want to read the file in binary safe mode.
You can see in in this Ideone.com version of your code how the PHP script there will give the expected output when you enforce the newline symbols used by your home system, while in this other version using UNIX newlines it gives the "wrong" output.
I suppose you should be using fgets() to read each string separetely instead of fread() and then trim() them to remove those characters before processing.
I tried to analyse this code and that's what I know:
It seems there are no problems with input strings. If there were any it would be impossible to return result 20
I don't see any problem with loops, I usually use pre-incrementation but it shouldn't affect result at all
There are only 2 possibilities for me that cause unexpected result:
One of the loops iteration isn't executed - it could be only the last one inner loop (when $i == 5 and then $j == 5 because this loop is run just once) so it will match difference between 21 and 20.
preg_match won't match this string in one of occurrences (there are 21 checks of preg_match and one of them - possible the last one doesn't match).
If I had to choose I would go for the 1st possible cause. If I were you I would contact concepts author and ask them about version and possibility to test other codes. In this case the most important is how many times preg_match() is launched at all - 20 or 21 (using simple echo or extra counter would tell us that) and what are the strings that preg_match() checks. Only this way you can find out why this code doesn't work in my opinion.
It would be nice if you could put here any info when you find out something more.
PS. Of course I also get result 21 so it's hard to say what could be wrong

PHP / mysqli does not echo single zero

This is a strange bug I've come across when switching my code over from 000webhost to ipage. It's the same code and a consistently different result.
The following example does nothing.
echo 0;
This example gives us '00'
echo 0;
echo 0;
Seems to be a problem with ipage's host. This is my current workaround. This workaround echoes 00 instead of 0, and the correct integer with no leading 0 otherwise.
if(empty($count[0])) echo 0; // Don't get why we need this--not needed on 000webhost, e.g.
echo $count[0];
Update: confirmed bug on ipage's end

Does this PHP code crash Apache for anyone else?

preg_match_all('/(a)*/', str_repeat('a', 1000), $matches);
(edit: change the regexp a bit to make it simpler while still crashing)
I ran it on PHP 5.3.5 with Apache 2.0 and it crashes the server. If I change 339 to 338 it doesn't crash anymore, so it seems like a bug to me. I tried reporting it to http://bugs.php.net/ but it's down. Is this a PHP bug? Does it crash for anyone else?
Edit: Changing the code to
preg_match_all('/(?:a)*/', str_repeat('a', 339), $matches);
allows for a longer string before crashing.
If it doesn't crash, try increasing the string length by a factor of 10 or 100 as it may be a memory issue and you may have more memory.
Edit 2: the crash is a complete process crash, on Windows 7 I get the "End task" message instantaneously after execution.
Edit 3: if the crash is due to too much backtracing, and the above example clearly can cause it, the following should not:
preg_match('/[^"\']*(;|$)/',
str_repeat('x', 1000), $matches);
This is my actual code that's crashing. It's simply meant to split multiple SQL queries by ;, while allowing ; inside single or double quotes. Why is this causing so much backtracing, and how can I fix it?
The problem isn't memory or execution time...
ini_set('pcre.backtrack_limit', 10000);
Feel free to decrease the 10000 to a different value if necessary. For more information, see http://php.net/manual/en/pcre.configuration.php.
If you feel like testing where it crashes:
<?php
ini_set('pcre.backtrack_limit', 10000);
for ( $i = 1; $i < 65535; $i++ )
{
echo $i . PHP_EOL;
preg_match_all('/(a)*/', str_repeat('a', $i), $matches);
}
?>

Which PHP version is required for str_split?

I relogin to my server in dreamhost and test some scripts.And I found I couldn't use str_split. Message of Undefined function was given.I checked the version in the server and its PHP Version is 5.2.12.And I just wonder which version is required?Thanks.
Testcode:
<?php
$arr = str_split("lsdjflsdjflsdjflsdjfl");
print_r($arr);
?>
Message:
Fatal error: Call to undefined function: str_split() in /test.php on line 3
Edit #Justin Johnson
I checked the server's system directory,and I found there are two versions of PHP in Dreamhost.In user's webroot,file will be parsed by PHP5 and that's why I got php 5.2.12 by putting a phpinfo.php in the webroot.And if php files are ran in command line directly using php test.php,another php version which is 4.x worked.That's the reason I got an error.When I use
/usr/local/php5/bin/php test.php
Everything is fine.
Rather than use str_split, it's usually much easier to iterate through the characters of the string directly:
$s="abc";
$i=0;
while(isset($s[$i])) {
echo $s[$i++]." ";
}
see?
First off: The PHP documentation will always say what version is required for every function on that function's documentation page directly under the function name.
It is possible that an .htaccess file is somewhere in your path and is causing a previous version (<5) of PHP to be used. To double (or triple) check to make sure that you are running in the proper PHP version, place this code above the line where you call str_split
echo "version:", phpversion(),
"<br/>\nstr_split exists? ",
function_exists("str_split") ? "true" : "false";
However, as shown by Col. Shrapnel, it is not necessary to convert a string to an array of individual characters in order to iterate over the characters of that string. Strings can also be iterated over using traditional iteration methods, thus making the call to str_split unnecessary and wasteful (unless you need to segment the string into fixed length chunks, e.g.: str_split($s, 3))
foreach ( str_split($s) as $c ) {
// do something with character $c
}
can be replaced by
$s = "lsdjflsdjflsdjflsdjfl";
for ( $i=0; isset($s[$i]); ++$i ) {
// do something with character $s[$i]." ";
}
which is equally, if not more clear.
According to dreamhost wiki, you need to switch to php5 manually from control panel, if you created your domain before 2008 sept.
http://wiki.dreamhost.com/Installing_PHP5#Using_DreamHost.27s_PHP_5
PHP 5 was added to all plans by
DreamHost as of June 2005. As of
September 2008, support for PHP4 was
discontinued, so you can no longer
switch back to PHP 4 from PHP 5 from
the panel.
If you haven't switched to PHP 5 yet,
you can do this in the Control Panel.
But, again, you will not be able to
switch back to PHP 4 after switching
to PHP 5.
Here's how to switch from PHP 4 to PHP
5:
Log into the DreamHost Control Panel.
Click Domains, then Manage Domains.
Click the wrench icon next to the domain you want to activate PHP 5
on (under the Web Hosting column).
Select PHP 5.x.x from the dropdown menu.
Click Change fully hosted settings now! at the bottom of the
section.
Repeat steps 3-5 for each additional domain you want to
activate.
you could also check your php version with
<?php
phpinfo();
?>
The version required is PHP 5 or later. So theoretically your program should work.
If you can't get str_split to work, just use a string as an array:
$stuff = "abcdefghijkl";
echo $stuff[3];
will produce
d
This method is fastest, anyway. I don't know if it suits your needs, but if it does, I hope it helps!
Could be anything in your code. How do we know its not a 10 line script or 2000 line script?
You can use preg_split() to split an array into single characters, but it will return an extra empty string at the begining and the end.
$a = preg_split("//","abcdefg");
echo json_encode($a);
prints:
["","a","b","c","d","e","f","g",""]

Seeking STDOUT in PHP

I have a php script that is running in CLI and I want to display the current percent progress so I was wondering if it is possible to update the STDOUT to display the new percent.
When I use rewind() or fseek() it just throws an error message.
See this code:
<?php
echo "1";
echo chr(8);
echo "2";
The output is only 2 since "chr(8)" is the char for "backspace".
So just print the amount of chars you need to go back and print the new percentage.
Printing "\r" works too on Linux and Windows but isn't going to cut it on a mac
Working example:
echo "Done: ";
$string = "";
for($i = 0; $i < 100; ++$i) {
echo str_repeat(chr(8), strlen($string));
$string = $i."%";
echo $string;
sleep(1);
}
Output \r and then flush to get back to the first column of the current line.
Writing to a console/terminal is surprisingly complex if you want to move backwards in the output raster or do things like add colours - and the behaviour will vary depending on the type of console/terminal you are using. A long time ago some people came up with the idea of building an abstract representation of a terminal and writing to that.
See this article for details of how to do that in PHP.

Categories