» PHP.JS Licensing

399 PHP equivalents

PHP to Javascript Project: php.js

php.jsThis article is part of the 'Porting PHP to Javascript' Project, which aims to decrease the gap between developing for PHP & Javascript.

A lot of people are familiar with PHP's functions, and though Javascript functions are often quite similar, some functions may be missing or addressed differently. The Javascript implementations should be as compliant with the PHP versions as possible, a good indication is that the PHP function manual could also apply to the Javascript version.

Porting crucial PHP functions to Javascript can be fun & useful. Currently some PHP functions have been added, but readers are encouraged to contribute and improve functions by adding comments. Eventually the goal is to save all the functions in one php.js file and make it publicly available for your coding pleasure.

If you choose to contribute, let me know how you want to be credited in the function's comments. You may also want to subscribe to RSS so you receive updates whenever new functions are posted.

Licensing

Since the project is really kicking off and we're almost at 100 ported functions, I thought it was probably time to think about licensing. So I did a little bit of research, and I think the MIT license might be what we're looking for.

In short, it permits reuse within proprietary software on the condition that the license is distributed with that software. It's also GPL-compatible, meaning that the GPL permits combination and redistribution with software that uses the MIT License.

The license

This is what I've come up with so far:

/* 
 * More info at: http://kevin.vanzonneveld.net/techblog/category/php2js
 * 
 * php.js is copyright 2008 Kevin van Zonneveld.
 * 
 * Portions copyright Ates Goral (http://magnetiq.com), Legaev Andrey,
 * _argos, Jonas Raoni Soares Silva (http://www.jsfromhell.com),
 * Webtoolkit.info (http://www.webtoolkit.info/), Carlos R. L. Rodrigues, Ash
 * Searle (http://hexmen.com/blog/), Tyler Akins (http://rumkin.com), mdsjack
 * (http://www.mdsjack.bo.it), Alexander Ermolaev
 * (http://snippets.dzone.com/user/AlexanderErmolaev), Andrea Giammarchi
 * (http://webreflection.blogspot.com), Bayron Guevara, Cord, David, Karol
 * Kowalski, Leslie Hoare, Lincoln Ramsay, Mick@el, Nick Callen, Peter-Paul
 * Koch (http://www.quirksmode.org/js/beat.html), Philippe Baumann, Steve
 * Clay, booeyOH
 * 
 * Licensed under the MIT (MIT-LICENSE.txt) license.
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL KEVIN VAN ZONNEVELD BE LIABLE FOR ANY CLAIM, DAMAGES 
 * OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 
 * OTHER DEALINGS IN THE SOFTWARE.
 */

The "Portions copyright" section is updated autmatically as we update the source files.

Got ideas?

If any of  you have different ideas about this license, please let me know, because this is  an initial draft.

New to php.js ?

If you're new to php.js, checkout an example. We are not trying to port or emulate the entire language or control structures of PHP. We don't see the need because Javascript seems to have more elegant features in that category anyway.

However in our eyes, PHP does provide a large set of standard functions that make developing very easy, and some of them don't have good standard Javascript implementations, though they often would be great to have client-side.

So in this project by also providing the functions separately, we hope to keep people from inventing the wheel and give them a head start.

Stay up to date

You can track my blog rss articles and rss comments. You may also find my rss bookmarks interesting. Or twitter Follow me on Twitter


Like this article?

   Then Dzone it!
Or use another bookmark button below to show your support &
help me spread the word.


tags: programming, javascript, php, phpjs
category: Programming - Javascript - PHP equivalents
read: 44,707 times

Add Comment

PHP.JS is outgroing this blog and moving to it's own space. Please leave your comment here: http://phpjs.org

Comments

#82. Kevin on 16 March 2009

Member avatar: Kevin@ bhu vidya & bit: I will review your comment soon over at http://phpjs.org . Please bear with me, and use that new site for comments on PHP.JS from now on.

Thanks a lot!!

#81. Kevin on 16 March 2009

Member avatar: Kevin@ Erik Pohler: I will review your comment soon over at http://phpjs.org . Please bear with me, and use that new site for comments on PHP.JS from now on.

Thanks a lot!!

#80. bit on 08 March 2009

Gravatar.com: bitHey, nice project. I like how each function can be used on its own (unlike those nasty big cpu and memory consuming "libraries") and that everyone can update the script to make it better!

But I don't get why you even need a license. if you goal is to be truely free, you can release the code into public domain. You should look into it.

#79. bhu vidya on 08 March 2009

Gravatar.com: bhu vidyagreat project! i am going to start using it....quick issue - i downloaded the namespaced versions but there is a syntax error throughout the file - the PHP_JS.prototype object is meant to list each function as a named object member, but each function entry after the first one (init) is missing a trailing comma, and so the javascript interpreter falls over - i might do the edit by hand and upload????? would that be of value? surely someone else has seen this issue?

#78. Erik Pöhler on 05 March 2009

Gravatar.com: Erik PöhlerMuch appreciated! Thanks a lot for your efforts. I'm using a handful of string functions. regularly. For my own site but also when working on client projects

#77. Brett Zamir on 03 March 2009

Gravatar.com: Brett ZamirOle, can you make clear what the problem with str_word_count() was exactly. I didn't see any problems when I did testing on it, using the PHP examples, except for:

1) the debugging alert() for reg was still there
2) var assArr = []; should probably be var assArr = {}; since we're trying objects as associative arrays
3) the reg.test() check should be preceded by "reg &&" in case that condition is reached but there was no charlist parameter
... [more]
I was also unclear on whether the PHP example, when translated to JavaScript should have an \n and/or \r added. If both are added the associative array is numbered correctly.

#76. Kevin on 02 March 2009

Member avatar: Kevin@ Ole Vrijenhoek: Thanks for your contributions! I've added them to expirimental:
http://trac.plutonia.nl/projects/phpjs/browser/trunk/_experimental/strings

So others can improve upon them until they work perfectly!

#75. Ole Vrijenhoek on 25 February 2009

Gravatar.com: Ole VrijenhoekI also have made the function str_word_count() But the problem is that the charlist parameter works correct but the last word in the given string will not be counted.

function str_word_count(str, format, charlist) {
// A word is valid when it contains a-z A-Z ' -
// Ole Vrijenhoek
var l = str.length; var tmpStr = "";
var wArr = []; var wC = 0;
var assArr = []; var aC = 0; var reg = "";
if(charlist) {
for(var i=0;i<=charlist.length-1;i++) {
if(i!=charlist.length-1) {
reg = reg + charlist.charCodeAt(i) + "|";
} else {
reg = reg + charlist.charCodeAt(i);
}
}
reg = new RegExp(reg);
alert(reg);
}
for(var i=0;i<=l-1;i++) {
var c = str.charCodeAt(i);
if((c<91&&c>64)||(c<123&&c>96)||c==45||c==39||reg.test(c)) {
if(tmpStr==""&&format==2) {
aC = i;
}
tmpStr = tmpStr + String.fromCharCode(c);
} else {
if(tmpStr=="") {
} else {
if(format!=2) {
wArr[wArr.length] = tmpStr;
} else {
assArr[aC] = tmpStr;
}
tmpStr = "";
wC++;
}
}
}
if(!format) {
return wC;
} else if(format==1) {
return wArr;
} else if(format==2) {
return assArr;
}
}

#74. Ole on 25 February 2009

Gravatar.com: OleOk second try

// Author: Ole Vrijenhoek
 
function convert_uuencode(data) {
var c = "";
var a = 0;
var newStr = "";
for(var i=0;i<=data.length-1;i++) {
c += "0" + data.charCodeAt(i).toString(2);
}
for(var i=0;i<=(c.length/6)-1;i++) {
newStr += String.fromCharCode(parseInt(c.substr(a, 6), "2")+32);
a += 6;
}
return newStr;
}

#73. Kevin on 25 February 2009

Member avatar: Kevin@ Dave: Please take a look at
http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_strtotime/

..again

#72. Kevin on 25 February 2009

Member avatar: Kevin@ Ole Vrijenhoek: I'm afraid your function didn't fully come through. If you want you can try again and we can see if it can be fixed

#71. Ole Vrijenhoek on 22 February 2009

Gravatar.com: Ole VrijenhoekHi

The uuencode function I sent doesn't work good.
Looks like I tested it too little.
The word "Cat" gives the expected "0V%T" but "Hello world!" returns a wrong string.
... [more] I am sorry for this but I hope you can do something with my old function ;)

#70. Ole Vrijenhoek on 22 February 2009

Gravatar.com: Ole VrijenhoekI made the function convert_uuencode

[CODE="Javascript"]
// Author: Ole Vrijenhoek

function convert_uuencode(data) {
var c = "";
var a = 0;
var newStr = "";
for(var i=0;i

#69. ChaosNo1 on 15 February 2009

Gravatar.com: ChaosNo1OK, sorry ;) Thank you!

#68. Kevin on 15 February 2009

Member avatar: Kevin@ ChaosNo1: I meant the separate function in SVN:
http://trac.phpjs.org/projects/phpjs/browser/trunk/functions/datetime/timezone_abbreviations_list.js

The php.min.js package as a whole, is build from these separate functions. I haven't done that yet because I'm in the middle of rewriting compiler parts for www.phpjs.org and I could destroy things now ;)

#67. ChaosNo1 on 15 February 2009

Gravatar.com: ChaosNo1Thank you for your quick answer.

I tried it with the svn version, but there are still the same problems.

#66. Kevin on 15 February 2009

Member avatar: Kevin@ Dave: The problem seems to be caused early on by:

} else if (!isNaN(parse = Date.parse(strTmp))) {
return parse/1000;


Basically, Date.parse (an internal JS function) is called. If that can't handle it properly, the function goes on with our specific code.

So right now it looks like it isn't even an PHP.JS problem. But I've contacted the original author Caio Ariede. Maybe he's willing to look into it a bit deeper than I can right now.

#65. Kevin on 15 February 2009

Member avatar: Kevin@ ChaosNo1: There was an issue with the timezone_abbreviations_list function. It's fixed in SVN now, and will be relaunched shortly. Thanks for letting us know!

#64. ChaosNo1 on 13 February 2009

Gravatar.com: ChaosNo1problem in internet explorer 7 when using php.min.js (not checked with other version).

When i open a page where the js is included in ie7 an error occours: (translatet from german)
Runtime Error
Line 426
Error:
variable, string or number expected

I try to use serialize in context with sajax like this:

x_updateContent((serialize(content)), contentReturnHandler);


in FF still works fine, but IE has also problems here: Object expected

i have removed the serialize and ie did not longer show this error message (but still the first one when reloading the page)

#63. David on 12 February 2009

Gravatar.com: DavidThe strtotime function is broken. In my example it returns a timestamp that is 1 month behind.

var timestr = '2009-05-04 08:30:00';
var timestamp = strtotime(timestr);
alert('Old Value: ' + timestr); // Result: "Old Value: 2009-05-04 08:30:00"
alert('New Value: ' + date('Y-m-d H:i:s', timestamp)); // Result: "New Value: 2009-04-04 08:30:00"



#62. Kevin on 11 February 2009

Member avatar: Kevin@ Jonathan Sampson: Unfortunately the php.min.js has been overwritten by newer versions. Is it possible for you to determine in which function the bug occured?

@ raul montejano rodriguez: Would it be possible for you to give us more detail on the error?

#61. raul montejano rodriguez on 09 February 2009

Gravatar.com: raul montejano rodriguezyou base64_decode dont work in ie7 xp/vista. you can fix with this other in http://www.webtoolkit.info/javascript-base64.html

#60. Jonathan Sampson on 06 February 2009

Gravatar.com: Jonathan SampsonUsing php.min.js in Firefox was working properly, but my client informed me forms were ignoring validation in Internet Explorer.

After checking my application in IE7, I received the following error:

Line: 821
... [more] Char: 330
Error: Expected ']' in regular expression

This was tracked down to be originating from php.min.js. I have since removed reference to the full source-file, and instead replaced it with exclusive definitions of the needed functions.

Again, no errors in other browsers I tested, but IE7 certainly doesn't handle a particular bug in the .js file too well.

Thank you for the excellent work on this project.

Jonathan Sampson

#59. Kevin on 01 February 2009

Member avatar: Kevin@ Brett Zamir: Yes Brett you guessed right I don't want to have those global vars by default in the package. But the alternatives you propose are good. If people choose to include import_request_variables in their package & then call it: it's OK. So I've added the function, and..

@ Jalal Berrami: Thanks for your code, we can put it to good use!

#58. Brett Zamir on 31 January 2009

Gravatar.com: Brett ZamirHi,

Some useful code, Jalal.

Although I don't know if you're keen to include global non-function code like Jalal submitted, Kevin, I think it could be pretty cool to have it in the namespaced version at least (attaching them at the end of the closure to the window object, so they wouldn't introduce globals besides the natural ones).

But even if you are only sticking with functions, Jalal's code came in handy with this PHP (var-related) function (and which is more secure anyways, potentially even in JavaScript)--a PHP function which lets you choose whether to import GET and COOKIE (or POST if we could support that) and then give an optional prefix to all such variables when they are imported: http://php.net/import_request_variables

document.cookie = 'snack=yummy';
import_request_variables('gc', 'pr_');
alert(pr_a); // when URL of this file is XXX?a=5, this line will alert '5'
alert(pr_snack); // 'yummy'
 
 
function import_request_variables (types, prefix) {
prefix = prefix || '';
if (/g/i.test(types)) { // GET
for(var i = 0, url = window.location.href, vars = url.substring(url.lastIndexOf("?") + 1, url.length).split("&"); i < vars.length;i++){
current = vars[i].split("=");
window[prefix+current[0]] = current[1] || null;
}
}
if (/c/i.test(types)) { // COOKIE
for(var i = 0, vars = document.cookie.split("&"); i < vars.length;i++){
current = vars[i].split("=");
window[prefix+current[0]] = current[1].split(";")[0] || null;
}
}
}

#57. Jalal Berrami on 31 January 2009

Gravatar.com: Jalal BerramiThis code below allows the user to get the famous php SUPERGLOBALS $_GET and $_COOKIE. and right now I'm working on the $_POST (impossible though)

var $_GET = [], $_COOKIE = [];
// It generates both of $_GET and $_COOKIE variables
for(var i = 0, url = window.location.href, vars = url.substring(url.lastIndexOf("?") + 1, url.length).split("&"); i < vars.length;i++){ current = vars[i].split("=");
$_GET[current[0]] = current[1] || null;
}
for(var i = 0, vars = document.cookie.split("&"); i < vars.length;i++){
current = vars[i].split("="); $_COOKIE[current[0]] = current[1].split(";")[0] || null;
}

#56. Kevin on 25 January 2009

Member avatar: Kevin@ Mike: Yeah it's all a bit confusing still. In the end, everything will be over at phpjs.org, but quite a ride till we get there.

Anyway: everything is updated automatically but it could be that phpjs is one version behind, so either keep using the blog a little while longer, or pull your sources straight from svn.

#55. Mike on 23 January 2009

Gravatar.com: MikeThere are three places where you can download php.js

* phpjs.org
* kevin.vanzonneveld.net
* trac.phpjs.org/projects/phpjs/
... [more]
Where can I download the latest code and where can I see the versioning?

If I download from the first and last the version is 2.09 and when I download from the second the version is 2.10 but the thing is that phpjs.org looks like the base of the code, isn't it?

I'll download from this site because it looks like the newest version.

This is very good work, if there is any way of merging or extending jQuery for example would be great too...

#54. Kevin on 15 January 2009

Member avatar: Kevin@ Ben: Couple of things:

- You are stretching the limits of what browsers were designed to do.

- Binary safe sha1: The current implementation is by webtoolkit.info, I haven't tested it with binary files.
... [more] All of the JavaScript sha1 algorithms I've found so far mention that they are aimed at hashing text messages. Maybe I haven't look good enough.
Unfortunately writing this myself would take me forever (I'd have to study mathematics again first).

- Different values for PHP vs JavaScript: I take it you mean even with normal string input? That surprises me a bit. What if your run the example we provide? If that works, please provide the test string that doesn't work (if it's not too long that is)

#53. Ben on 15 January 2009

Gravatar.com: BenThis project shows a lot of promise!

I'm trying to get the sha1_file function to work properly for binary files though. I'm getting different SHA1 values for PHP versus Javascript. Also, large files containing a few MBs seem to crash the browser.

I'm hoping to leverage this functionality in an Adobe AIR application. Any ideas on how I can get this to work?

#52. Kevin on 14 January 2009

Member avatar: Kevin@ Nile: well, I have looked into it, and created:

http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_json_encode/

and
... [more]
http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_json_decode/

They're still a bit rough, but the basics are there and I'm sure they will evolve to become nice additions to our project.

#51. Kevin on 12 January 2009

Member avatar: Kevin@ Nile: Ah, I see you fixed the:
- depends on an outside function: applyEncode
issue already! Still leaves the other ones open unfortunately. For completeness I will paste:
- does not support associative arrays (in terms of traversing)
- does not support index arrays, numbers, etc (in terms of encoding)
... [more]
Please have a look here:
http://www.json.org/json2.js

The code is public domain, so maybe it's possible to modify it and use it in PHP.JS. We could look into that!

#50. Nile on 09 January 2009

Gravatar.com: NileJson_encode(kinda buggy..)

var arr = new Array('Hello');
var json_encode = function(value){
var data = '';
for(i=0,endCount='';i<value.length;++i){
var endCount = (i!=value.length-1) ? ", " : "";
data += '"'+key(value[i])+'" : "'+value[key(value)]+'"'+endCount;
}
var json_encode_apply_encode = function(varIn){
return '{'+varIn+'}';
}
return json_encode_apply_encode(data);
}
document.write(json_encode(arr));

#49. Kevin on 30 December 2008

Member avatar: Kevin@ Caio Ariede: Wow. Every once in a while a true gem comes to pass. I'd be happy to include this in our little project. You can be very proud of yourself Caio! Thanks a lot.

#48. Caio Ariede on 26 December 2008

Gravatar.com: Caio AriedeHello man, congratulations and thanks for your project.

I made a strtotime function in Javascript.

Don't know if it is of interest to your project, because it don't works exactly as the PHP function, but with some improvements can come close.
... [more]
Can found it in my blog, here:

http://caioariede.com/2008/javascript-equivalent-function-to-phps-strtotime

cya! :)

#47. Kevin on 17 December 2008

Member avatar: Kevin@ Pedro Sland: Sounds good.
Maybe if you could work on a jQuery user interface that works with JSON. I can write the CakePHP part that supplies the JSON and the compiler part that glues the functions together and stores them as packages.

I imagine the jQuery part as a big form, with some presets in a select box in the top.
And checkboxes for every function, grouped by category.

When a function is selected (either automatically by a default, preset, or user), it's dependencies should be selected as well. This should recursively fire an onSelect function so that their dependencies in turn are also selected (e.g. md5_file requires md5 requires utf8_encode, so clicking md5_file recursively selects 2 additional functions)

So the JSON object provided (either by default or the one linked to a preset), and returned could probably be in this simple form:

phpjsSelection = {
'is_array': 1,
'is_object': 1
};


I thing a separate JSON Object should be made available with all the function's definitions:
phpjsFunctions = {
'md5_file': {
'dependencies': {
'file_get_contents',
'md5'
}
'description': 'Calculate the md5 hash of a string'
}
};


Furthermore there needs to be some kind of feedback div that will explain what is happening:
'Also selected file_get_contents as a dependency for md5_file'
'Also selected md5 as a dependency for md5_file'
'Also selected utf8_encode as a dependency for md5'

I will make sure on the server end that only unique packages (same functions) will be stored.

This way we can determine what are popular configuration, and offer them as additional presets, and maybe even give them a place in the download page.

Any thoughts?

#46. Pedro Sland on 11 December 2008

Gravatar.com: Pedro Sland@Kevin
I've never done anything with cakephp but my php is quite good.

I have been using jquery for some time now and I'm not bad. Just developing my first propper plugin.

... [more] I have a reasonable oop php framework that I built. Its not like the zend monster but its ample and flexible :)

#45. Kevin on 10 December 2008

Member avatar: Kevin@ Pedro Sland: Thanks Pedro! Yes.. so many projects, so little time ;) Help is definitely welcome. How are your:
- cakephp
- jquery
- OOP
skills? Cause there already is a lot of code ready that's based on these techniques. Let me know!

#44. Pedro Sland on 09 December 2008

Gravatar.com: Pedro SlandI recently stumbled upon your project and think its great!. I could benefit from the download only the bits you want idea and I would be willing to create such a system if you want help with that :)

#43. rune_kg on 05 November 2008

Gravatar.com: rune_kgHey Guys

Just wanted to say thx. Working on a PHP to js converter (just for fun, nothing fancy), and your great tool came in very handy providing support for many of PHP's inbuilt functions. Come and join me at:

http://code.google.com/p/php-to-js/
... [more]
Rune

#42. Kevin on 03 November 2008

Member avatar: Kevin@ Martin Barker (Barkermn01): We already have an include function. Can you please explain what makes these versions better? Thanks!

#41. Martin Barker (Barkermn01) on 29 October 2008

Gravatar.com: Martin Barker (Barkermn01)

function include(file){
oScript = document.createElement('script'),
oHead = document.getElementsByTagName('head')[0];
oScript.setAttribute('type', 'text/javascript');
oScript.setAttribute('language','javascript');
oScript.setAttribute('src', file);
oHead.appendChild(oScript);
oScript = document.createElement('div');
oScript.outerHTML = '<script src="url-to-your-script" type="text/javascript">string-containing-the-script</script>';
}

Sorry Left Some Comment Code in

#40. Martin Barker (Barkermn01) on 29 October 2008

Gravatar.com: Martin Barker (Barkermn01)

function include(file){
oScript = document.createElement('script'),
oHead = document.getElementsByTagName('head')[0];
oScript.setAttribute('type', 'text/javascript');
oScript.setAttribute('language','javascript');
oScript.setAttribute('src', file);
oHead.appendChild(oScript);However, if you want to do it for iem, you have to use:var
oScript = document.createElement('div');
oScript.outerHTML = '<script src="url-to-your-script" type="text/javascript">string-containing-the-script</script>';
}


This script will work to include .js files into your code so if there is a set of scripts you dont need unless some thing is active this would be grate

#39. Kevin on 20 October 2008

Member avatar: Kevin@ Onno Marsman & Philip Peterson: It's a funny idea, but I can't see people actually using this function. And it violates DRY heavily. I, for one am not looking forward to keep that function up to date.
So that means the compiler should have routines to do it automatically. A lot of effort, for little gain if you ask me.
If we still want this function, I prefer echoing a link to the http://phpjs.org site (and maybe the authors page).

PS
... [more] I fixed some issues with the tester, which caused some additional bugs to surface.

Also I found (like onno mentioned before) that indeed a lot of array functions do not support associative arrays (javascript objects). But because the examples don't use them either, we don't see them all.

#38. Onno Marsman on 18 October 2008

Gravatar.com: Onno MarsmanPhilip: didn't realize you were a core developer too. Sorry for that...

Well, as long it's something that's not in the standard library it's ok by me (not that I have any final saying in this of course), but I guess we don't have a place (yet?) to put something like this then.

#37. Philip Peterson on 18 October 2008

Gravatar.com: Philip PetersonI agree with you for the most part, which is why I didn't submit this directly to the repository.

- Correct, if I were to decide the fate of the function, I would include it at best as an optional and not-included-by-default function on the Compile page. The images are there just for fun; they can easily be done without.
- Correct again, but a lot of functions on here are not exact PHP equivalents; they merely replicate the functionality of the original PHP function, with relevance modified as needed. Actual PHP credits here are irrelevant, but PHP.JS credits are.
- It's just a suggestion.
... [more] - No, we don't; but it is a PHP function and the goal of this project (I believe; I guess it's not really explicitly stated anywhere) is to port to Javascript as many PHP functions as possible which will produce functionality as useful as the original function in PHP, and this I believe fits those descriptions. I wouldn't say it's "polluting" -- without the images it's a mere 8 to twelve lines or less, and probably could be shortened even more, and it definitely would not be polluting if it is by choice only.
- Right, which is why the images are unnecessary.

I'm not necessarily in support of using this function, but those are the reasons I posted it. I don't really see much reason [i]not[/i] to use it if it is entirely optional, but again I am just throwing it out there.

#36. Onno Marsman on 18 October 2008

Gravatar.com: Onno MarsmanThis phpcredits function is weird (in my opinion) for several reasons:
- It's not useful at all and it takes al lot of space, even after compressing. It would be the first function I'd remove after downloading the library.
- It's not a PHP equivalent. PHP's phpcredits has very different output.
- It doesn't make sense to put the credits for phpjs in a function called phpcredits.
- Do we (the contributors) really need more credits than we are already getting and pollute the library like this?
... [more] - You yourself (philip) have mentioned some good reasons not to implement functions like this at the comments on the sleep-function page (like storing those images)

#35. Philip Peterson on 18 October 2008

Gravatar.com: Philip Peterson

function phpcredits() {
// Prints PHP.JS Credits
//
// + original by: Philip Peterson
// - depends on: echo
// * example 1: phpcredits('Kevin van Zonneveld');
// * returns 1: null

// Note: This function depends on echo because I believe
// echo's stability is currently in the air ("echo is bad" offered
// a suggestion but nothing was done with it, so it is still probably bug-ish).
 
 
xxbronze="iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0\
U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAKESURBVDjLfZNLSFRRGIC/O3Pn1cyUlLXI\
lB6SQrXo/YSiRSQDualVUFZE1KJtrTKHIloEbQpqYUW4DipSehBIYWr00MIs0ckUR6Z8jqNz7/nP\
aTEqI2E/HM6D833n5/znWMYYZuLglUZz4lApTT+H0MogohHRaNEopdmzZgm36z7w/vZha4axyQst\
gtYG5U6DKteLyjWlDKIkH8G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pn8DiL00maa56yOjVEoraVTZVnWFKR4vK1MYLz\
PQsKnPumrXvk74mey0M51pf/RrJuO4lF79Oc6OfK9VGG/8r13Ort7C5ljCTsxVUZKWpQUBQEX1zs\
6OpqOb1nZcseSKSIH/zIkfPRzzuahvZJCUIQ3hYn6rY/emAkEZ+tG1N543IJJKEgEjUfQPkqZJ8g\
W8BODuGLjxCGYC3xs/vE+ccdRhLF42ZLsPRGTZ9WJpfvRHGOED8h2Dz4IsiBSWKSVQRnKQweJT84\
coI0u8zcIhWOmPrgOZlas60hWrEVxePITaNQRP45mAiXf0ju1DEfP6O75Xvtn9fE6o+VJc26F/f6\
+sLTmyAhzaAwA4oxRIz/eixvZ2ibg/83hZqdmjKZin5byCIDKGAwII9CgIiptd+qf8ExAog32stq\
3sWYJHKOOP8QU1ZLIlVNasnSlcP7zNrS/Hl/YbJvcSaI1mhRE4Ur3zE5MJDFcKGiob6zas1G0nXN\
5O/k2oHhBTbRfWgqV2cmTu5l4veBg87yXuPX2v3v7Wzb3eOH/4mfx7yYpn1+ydIrHzvEJ9n93B35\
nM2lcUlc+ozqM7v44Zdt3CiN/wel+5Gy/cSN+gAAAABJRU5ErkJggg=="
;
 
// replace document.write with echo when echo works.
 
document.write('<b>PHP.JS Credits</b>
 
Created by Kevin van Zonneveld.
 
Contributors:
 
<img src="data:image/png;base64,'
+xxgold+'" style="vertical-align:middle"><img src="data:image/png;base64,'+xxgold+'" style="vertical-align:middle"> <b>Two Gold Stars:</b> Onno Marsman (84)
<img src="data:image/png;base64,'
+xxgold+'" style="vertical-align:middle"> <b>One Gold Star:</b> Michael White (18), Jack (14), _argos (14), Jonas Raoni Soares Silva (12), Legaev Andrey (10), Ates Goral (9), Philip Peterson (9), Martijn Wieringa (8), Philippe Baumann (6)
<img src="data:image/png;base64,'
+xxsilver+'" style="vertical-align:middle"> <b>Silver Star:</b> Webtoolkit.info (5), Enrique Gonzalez (4), Carlos R. L. Rodrigues (4), GeekFG (3), Johnny Mast (3), d3x (3), Ash Searle (3), Erkekjetter (3), marrtins (3), Nate (2)
<img src="data:image/png;base64,'
+xxbronze+'" style="vertical-align:middle"> <b>Bronze Star:</b> AJ (2), Sakimori (2), Karol Kowalski (2), Mirek Slugen (2), Thunder.m (2), Tyler Akins (2), Aman Gupta (2), Arpad Ray (2), Alfonso Jimenez (2), mdsjack (2)
<b>Other Contributors:</b> Sanjoy Roy (1), kenneth (1), Slawomir Kaniecki (1), Saulo Vallory (1), metjay (1), Scott Cariss (1), Simon Willison (1), penutbutterjelly (1), Pul (1), sowberry (1), stensi (1), Pyerre (1), ReverseSyntax (1), johnrembo (1), Robin (1), sankai (1), nobbler (1), Steve Clay (1), XoraX (1), echo is bad (1), Peter-Paul Koch (1), gabriel paderni (1), Yannoo (1), duncan (1), booeyOH (1), dptr1988 (1), baris ozdil (1), ger (1), Tim Wiel (1), Steven Levithan (1), Steve Hilder (1), jakes (1), john (1), hitwork (1), T.Wild (1), gorthaur (1), Thiago Mata (1), T0bsn (1), djmix (1), MeEtc (1), Atli &THORN;&oacute;r (1), Bayron Guevara (1), Ben Bryan (1), Benjamin Lupton (1), Christian Doebler (1), Cagri Ekin (1), Brett Zamir (1), Brad Touesnard (1), Andrea Giammarchi (1), Allan Jensen (1), Alexander Ermolaev (1), Alex (1), Anton Ongson (1), Arno (1), Cord (1), David James (1), Luke Godfrey (1), Lincoln Ramsay (1), Leslie Hoare (1), LH (1), Mateusz "loonquawl" Zalega (1), Mick@el (1), Ozh (1), Norman "zEh" Fuchs (1), Nick Callen (1), Nathan (1), Kirk Strobeck (1), Jon Hohle (1), FGFEmperor (1), DxGx (1), Dino (1), David (1), Felix Geisendoerfer (1), Francois (1), J A R (1), Howard Yeend (1), Gabriel Paderni (1), FremyCompany (1), Pedro Tainha (1)'
);
 
 
 
}

#34. Kevin on 01 October 2008

Member avatar: Kevin@ Jack: Thanks for going through all the functions man, I've updated the bunch!

#33. Jack on 29 September 2008

Gravatar.com: JackHey Kevin, I love this page and I have been using it for a few months now. A pet peeve of mine involving coding is inefficiencies dealing with for-loops, where length are unnecessarily computed.
For example,

for(var i=0; i<array_x.length; i++){}


which can easily be fixed to

for(var i=0, l=array_x.length; i<l; i++){}


The lack in efficiency gets especially noticeable when called by loops such as building large dynamic HTML tables and such.

I believe countless redundant computations and unnecessary strain on our user's machine can be avoided if we just fix this simple problem.

Below is a list of functions that is currently violating this rule of efficiency.

compact ( var_names )
max()
min()
count_chars( str, mode )
htmlentities( string )
md5 ( str )
sha1 ( str )
sprintf( )
utf8_encode ( string )
parse_str(str, array)
soundex( str )
str_ireplace ( search, replace, subject )
strnatcmp ( f_string1, f_string2, f_version )

#32. Kevin on 17 September 2008

Member avatar: Kevin@ LH: Can't believe we missed that, thank you LH!

#31. LH on 15 September 2008

Gravatar.com: LH

Problem line 4523 
print(typeof mixed_var);


you have to comment this line, if you don't want a print window opened

#30. Kevin on 13 September 2008

Member avatar: Kevin@ Sold Out Activist: That's a cool idea, but I think that the current idea for a completely customizable package with support for compile hashes and presets allows for greater flexibility, and would even also allow presets in the same categories as php.ini would address extensions.

#29. Sold Out Activist on 10 September 2008

Gravatar.com: Sold Out ActivistIt would be a bad idea to have all the functions in a single JS file. Were you to even reach 25% of the PHP function list, the resulting JS file would be too large to use effectively on a website.

You should split the files into modules JS files akin to how PHP has modules. Then make php.js a type of php.ini where the user can decide which of the modules they want to use.

When php.js is called it would dynamically add the js files using the DOM and life would be sweet.

#28. Kevin on 27 August 2008

Member avatar: Kevin@ KAGRAN22: Can't say I totally agree.. explode & implode can be replaced with JavaScript's native join & split right? The point of this project however is enabling PHP coders to code in JavaScript with PHP syntax. That's why some native JavaScript functionalities are still wrapped inside a PHP-like function name.

#27. KAGRAN22 on 16 August 2008

Default avatar:KAGRAN22nice Project !
special explode/implode & the other array manipulation functions make it more n more wrothfull every day

the only somewhat "useless" function is imho strlen.
The JS length Property is a benefit vs php
... [more]
Makes code more readable + uses less RAM/Time then using php.js equivalent (anyway micro-optimization)
know the deal is to port them ;-)

conclusio Great work!
Also looking forward to a dedicated domain
as this Blog is somewhat messy to browse + same for Source file
(maybe you can even use php.net's Interface its ugly but functional) ^_^

#26. Kevin on 22 July 2008

Member avatar: Kevin@ Johnny Mast: Thank you so much! I have added the functions. As you know I do have some concerns on the eval parts, but I will hereby challenge the PHP.JS community to come up with better ways, and for now add them in their current form.

#25. Johnny Mast on 20 July 2008

Default avatar:Johnny MastHi kevin as promiced here is my contribution to the framework. I have made some time to code the following functions, create_function() - array_walk() and array_walk_recursive();

function array_walk (array, funcname, userdata) {
// http://kevin.vanzonneveld.net
// + original by: Johnny Mast (http://www.phpvrouwen.nl)
// * example 1: array_walk ({'a':'b'} ,'callback', 'userdata');
// * returns 1: true
// * example 2: array_walk ('a' ,'callback', 'userdata');
// * returns 2: false

if (typeof array != 'object')
return false;

for (var key in array)
{
if (typeof (userdata) != 'undefined')
eval (funcname + '( array [key] , key , userdata )' );
else
eval (funcname + '( userdata ) ');
}
return true;
};


function array_walk_recursive (array, funcname, userdata) {
// http://kevin.vanzonneveld.net
// + original by: Johnny Mast (http://www.phpvrouwen.nl)
// * example 1: array_walk_recursive ({'a':'b', 'c': {'d' : 'e'}} ,'callback', 'userdata');
// * returns 1: true
// * example 2: array_walk_recursive ('a' ,'callback', 'userdata');
// * returns 2: false

if (typeof array != 'object')
return false;
 
for (var key in array)
{
if (typeof array[key] == 'object')
return array_walk_recursive (array [key], funcname, userdata);

if (typeof (userdata) != 'undefined')
eval (funcname + '( array [key] , key , userdata )' );
else
eval (funcname + '( userdata ) ');
}
return true;
};


function create_function (args, code) {
// http://kevin.vanzonneveld.net
// + original by: Johnny Mast (http://www.phpvrouwen.nl)
// * example 1: var myfunction = create_function('a,b', "alert (a + b)");
// * myfunction (1,2); /* outputs 3 in an alertbox */
// * returns 1: function

eval ('var _oFunctionObject = function (' + args + ') { ' + code + '}');
return _oFunctionObject;
};

#24. Kevin on 18 July 2008

Member avatar: Kevin@ GeekFG: Thank you for your contributions GeekFG!! I've made some minor changes to further comply with PHP standards, I've documented them in the functions comments.

#23. GeekFG on 01 July 2008

Default avatar:GeekFGSorry it's more like :

function time()
{
d = new Date();
return (d.getTime()/1000);
}


My website is : http://geekfg.blogspot.com/ You can contact me via this page : http://domainfinder.geekfg.net/contact

#22. GeekFG on 01 July 2008

Default avatar:GeekFGEquivalent for php time()

function time()
{
d = new Date();
return d.getTime();
}


My website is : http://geekfg.blogspot.com/
You can contact me via this page : http://domainfinder.geekfg.net/contact

#21. GeekFG on 01 July 2008

Default avatar:GeekFGI've created two nice function : ksort() and krsort() :)

/* 
array ksort ( array $array)
Trie le tableau array suivant les clés, en maintenant la correspondance entre les clés et les valeurs.
Cette fonction est pratique pour les tableaux associatifs.
*/

function ksort(w)
{
var sArr = [];
var tArr = [];
var n = 0;
for (i in w)
{
tArr[n++] = i;
}
//tri du plus petit au plus grand
tArr = tArr.sort();
n = tArr.length;
for (var i=0; i<n; i++) {
sArr[tArr[i]] = w[tArr[i]];
}
return sArr;
}
/*
array krsort ( array $array)
krsort() trie le tableau array en ordre inverse et suivant les clés, en maintenant la correspondance entre les clés et les valeurs.
Cette fonction est pratique pour les tableaux associatifs.
*/

function krsort(w)
{
var sArr = [];
var tArr = [];
var n = 0;
for (i in w)
{
tArr[n++] = i;
}
//tri du plus grand au plus petit
tArr = tArr.sort(function(a,b){return (b - a);});
n = tArr.length;
for (var i=0; i<n; i++)
{
sArr[tArr[i]] = w[tArr[i]];
}
return sArr;
}


My website is : http://geekfg.blogspot.com/
You can contact me via this page : http://domainfinder.geekfg.net/contact

#20. Kevin on 23 May 2008

Member avatar: Kevin@ Dan Doezema: Thank you for this interesting post, Dan. Unfortunately we can currently only port functions (and some language control structures).

This is related to the generation of documentation & testing. It still is good to have as a reference here, though. So thanks! And if you have another function, please let us know!

#19. Dan Doezema on 23 May 2008

Default avatar:Dan Doezema* SORRY For the double post *
E-Mail
str_replace(array('[',']'),'','[d][a][n][at][authenticdesign][.][net]');

I know this is a global array but I think this has some use in your library. I made this a few days ago and I would like to contribute.

It's a port of the $_GET global array.

function $_GET (name) {
var result = false;
var query = window.location.search.substring(1);
if(query) {
var regexp = new RegExp(name+'=([^&]*)');
result = query.match(regexp, '');
if(result) {
result = decodeURIComponent(result[1]);
} else {
result = false;
}
}
return result;
}

#18. Kevin on 15 May 2008

Member avatar: Kevin@ Sakimori: Wow that's nice to hear :)

#17. Sakimori on 15 May 2008

Default avatar:SakimoriBEST... IDEA... EVER... !!!

Seriously, thanks so much for the work you've done here. I'm so happy to have found this that I'm almost in tears.

#16. is_array on 07 May 2008

Default avatar:is_arrayis_array

#15. Shane on 06 May 2008

Default avatar:ShaneBeautiful! <3

#14. Kevin on 28 April 2008

Member avatar: Kevin@ Ozh: Very good work indeed! I added 2 example test cases from the PHP manual and they both work out perfectly. Thanks a lot Ozh!

#13. Ozh on 28 April 2008

Default avatar:OzhAwesome stuff!

I have a proposal for dirname() :

function dirname(path) {
return path.replace(/\\/g,'/').replace(/\/[^\/]*$/, '');;
}

#12. Kevin on 21 April 2008

Member avatar: Kevin@ PhenX: We could not agree more and are currently working on a dedicated php.js site. I'll announce it on my blog when it's ready, then further developments will be updated there.

Thanks for sharing & taking an interest in our project!

#11. PhenX on 21 April 2008

Default avatar:PhenXThis projetc has been added to Ohloh :
http://www.ohloh.net/projects/php-js
We hope it will help :)
It would be nice to have a page completely dedicated to news and file downloads to be easier to find what we want. For now, it's hard to navigate into a blog for such a project

#10. Felix Geisendörfer on 06 April 2008

Default avatar:Felix GeisendörferHey Kevin,

I'm currently working on a book called "JavaScript for PHP developers" and I see a lot of overlap between the work I'm doing and your efforts here.

So I'd love to have a little chat about how I may be able to help with your project. Contact me on felix@debuggable.com or any of the instant messagers listed here: debuggable.com/felix
... [more]
Thanks for the great work so far.
-- Felix

#9. Kevin on 20 March 2008

Member avatar: Kevin@ Tim: Thanks for taking an interest! What you've started is actually one of our next big 3 todo's. We're going to build a tool with predefined profiles in a selectbox, and a lot of checkboxes, just like many codec installers out there.

It should have auto-dependency resolving, optional packing or minifying, etc.

About your question, I'm in the midst of moving php.js to SVN, after that, the master file will have versioning as well. Currently only the separate function files have versions.

#8. Tim on 19 March 2008

Default avatar:TimThis is awesome - finally making JS something I like dealing with.

I built a little script to make adding just parts of this great library available for download (packed with Dean Edwards packer). You can check it out at http://sitebytim.com/code/php_equivalents/ - FYI it's pretty rough at the moment so I hope to clean it up a little bit but it does the trick for what I need.

Just curious - if the individual files that have a single function (linked too from your testing page) are the same version as the functions included in the master php.js file?

#7. Kevin on 07 February 2008

Member avatar: Kevin@Jean-Lou Dupont: All of the individual functions are versioned but you make a good point and I will take a look at implementing it (probably) next weekend. Thanks for the comment!

#6. Jean-Lou Dupont on 06 February 2008

Default avatar:Jean-Lou DupontHave you considered versioning your 'php.js' file?

#5. Kevin on 04 February 2008

Member avatar: KevinI've asked the registrant of phpjs.com if he would be willing to transfer that domain name to us.

And though he already has made plans for www.phpjs.com to create a blog about working with symfony and dojo on web applications, I received a nice mail that he will still consider the transfer if he doesn't have enough time to kickstart that project.

We will be hearing from him next month.

#4. Kevin on 01 February 2008

Member avatar: Kevin@ Karol Kowalski: Yeah thought about that. Though I'm happy with the low-maintenance requirements of this method, it's probably best to provide php.js with a face of it's own. Anyone got a catchy domainname? ;)

Unfortunately my whois tells me there is no .js TLD.
I don't think PHP would appreciate a www.php.js domainname either ;)

#3. Kevin on 01 February 2008

Member avatar: Kevin@ Legaev Andrey: OK thanks. I've thought about GPL as well, because it forces others to open up their software as well.
Whereas MIT is cool with it if you incorporate & change php.js in your own app without ever exposing your improvements to the public.

But obviously, that does provide greater freedom.

#2. Karol Kowalski on 01 February 2008

Default avatar:Karol KowalskiSeems like it't time to move the project out of your blog then:-)

#1. Legaev Andrey on 01 February 2008

Default avatar:Legaev AndreyI agree with your choice of the license.