Skip to main content

Posts

Showing posts from April 6, 2012

Best way to determine user"s locale within browser

I have a website (Flash) localized into a dozen of languages and I want to auto-define a default value depending on the user's browser settings in order to minimize the steps to access the content. FYI, I cannot use server-scripts due to proxy restrictions, so I guess JavaScript or ActionScript would be appropriate to solve the problem. Questions: What would be the best method to 'guess' the user's locale ? Are there any existing simple classes/functions that could help me out (no complex localization bundles) ? Specially to break down all the possible languages into a smaller number (the translations I have) on a smart way . To which point can I trust such a solution ? Any other workarounds or suggestions ? Thanks in advance! Source: Tips4all

jQuery/JavaScript "this” pointer confusion

The behavior of "this" when function bar is called is baffling me. See the code below. Is there any way to arrange for "this" to be a plain old js object instance when bar is called from a click handler, instead of being the html element? // a class with a method function foo() { this.bar(); // when called here, "this" is the foo instance var barf = this.bar; barf(); // when called here, "this" is the global object // when called from a click, "this" is the html element $("#thing").after($("<div>click me</div>").click(barf)); } foo.prototype.bar = function() { alert(this); } Source: Tips4all

JavaScript : Good tool to "minify" jQuery based js files

We are using jQuery in our project. We have numerous custom javascript files in our web-app that have UDFs utilizing the jQuery features. We need to reduce the size (as a part of performance improvement activities) and I am looking for a reliable 'minifier' for these files (it would be great if the same tool could minify the CSS files too) We tried JSLint and JSMin - but JSLint does not complete and throws many exceptions as soon as it encounters jQuery code. Regards, - Ashish Source: Tips4all

Is JS lint available for offline use?

I'd like to use JSLint but am wary of tools that have access to my unfiltered source-code. Is there an offline version or is there another similar tool that does " lint error checking" for JavaScript offline? Edit: One with a GUI / shows you a styled list of errors, instead of command line? Source: Tips4all

Is client-side UI rendering via Javascript a good idea?

The "classic" approach to web development has been for some time a thin client and a thick server: the server generates HTML and spits it out for the browser to render only. But with current browsers (and also due to the availability of good libraries and frameworks) Javascript now works. Web devs can now pretty much assume that their Javascript code will work and stop bothering. This certainly opened new possibilities for web development. Apps could now be composed mostly of HTML content returned from the server and rendered by the browser with some UI manipulation being done client-side. The client could even query the server for fresh data for updating parts of the UI. But can we go down all the other way? An app can certainly be designed as a server that spits only the most minimalist JSON glued together to a thick Javascript client responsible for building and controlling the whole user interface. Yeah, this approach can seriously break URLs to the extent that people

Pass mouse events through absolutely-positioned element

I'm attempting to capture mouse events on an element with another absolutely-positioned element on top of it. Right now, events on the absolutely-positioned element hit it and bubble up to its parent, but I want it to be "transparent" to these mouse events and forward them on to whatever is behind it. How should I implement this? Click here for an example page . All its divs flash on mousedown. Source: Tips4all

howto benchmark javascript code?

Is there a package that helps me benchmark JS code ? Im not referring the Firebug and such tools. I need to compare 2 different JS functions that I have implemented. Im very familiar with perl's Benchmark ( http://search.cpan.org/~tty/kurila-1.19_0/lib/Benchmark.pm ) module and Im looking for something similar in javascript. Is the emphasis on benchmarking the JS code overboard ? Can I get away with timing just one run of the functions ? Source: Tips4all

Click Entire Row (preserving middle click and ctrl+click)

I have an HTML table, with a link in the first column. I want to allow the user to click on anywhere in the row to activate that link. At the same time I would like to preserve the middle click and ctrl+click functionality of opening a new tab/window. Here is an example of the table: <table id="row_link"> <tbody> <tr> <td><a href="link1.html">link</a></td> <td>info 1</td> </tr> <tr> <td><a href="link2.html">link</a></td> <td>info 2</td> </tr> </tbody> </table> Using jQuery I can allow the user to left click anywhere in a row: $("table#row_link tbody tr").click(function () { window.location = $(this).find("a:first").attr("href"); }); This of course disables the standard middle click and ctrl+click functionality of opening a new tab. Is there a b

What is the best Javascript XML-RPC client library?

What is the best Javascript XML-RPC client library in your opinion and why? I'am making a JQuery app and I need to communicate with my xmlrpc server with it. Found following libraries, but I have no idea what are their pros and cons: http://www.zentus.com/js/xmlrpc.js.html http://www.scottandrew.com/xml-rpc/ http://phpxmlrpc.sourceforge.net/jsxmlrpc/ http://www.vcdn.org/Public/XMLRPC/ http://mimic-xmlrpc.sourceforge.net/ Source: Tips4all

Creating heatmaps using <canvas> element?

Are there any JavaScript libraries out there that allow you to create heatmaps using in-browser graphic rendering features such as <canvas> or SVG? I know about HeatMapAPI.com, but their heat maps are generated on the server side. I think that in the era of <canvas> element we don't need that anymore! If there is nothing like this yet, are there any volunteers to participate in creating such a tool? Source: Tips4all

MVP pattern with Javascript framework?

Has anyone been able to implement the MVP model with any javascript frameworks? I'm having trouble figuring out how to have the presenter -> view inversion from server code to javascript. I have some ideas, but kind of hackish and would like to see what others are doing. Source: Tips4all

When is a PHP project too small for a framework?

I'm about to start on a small, static website project: no database or CMS required. Basically, a brochure website. I used the CodeIgniter framework recently to develop a full-blown web application, and I'm wondering if it appropriate to also use CI for smaller, simpler sites. Typically for a static brochure site I would write regular PHP pages with a few includes thrown in to save on repetition (i.e. HTML with a sprinking of PHP), but this time around I'm wondering if my new friend CodeIgniter might be able to streamline the development process. Is it sensible to consider a framework for such a simple project, or is it overkill? I'm worried that I might be the proverbial carpenter whose only tool is a hammer, and sees every problem as a nail! Source: Tips4all

Are there any differences between SQL Server and MySQL when it comes to preventing SQL injection?

I am used to developing in PHP/MySQL and have no experience developing with SQL Server. I've skimmed over the PHP MSSQL documentation and it looks similar to MySQLi in some of the methods I read about. For example, with MySQL I utilize the function mysql_real_excape_string() . Is there a similar function with PHP/SQL Server? What steps do I need to take in order to protect against SQL injection with SQL Server? What are the differences between SQL Server and MySQL pertaining to SQL injection prevention? also - is this post accurate? is the escape string character for SQL Server a single quote? Source: Tips4all

How do you use scripting language (PHP, Python, etc) to improve your productivity?

I'm a Delphi developer on the Windows platform, recently read the PHP tutorial at W3CSchools, it looks interesting. We all know scripting languages are very good at web site development, but I also want to utilize it to improve my productivity or get some tedious tasks done quickly, maybe some quick-and-dirty string/file processing? What do you usually do with scripting languages apart from software development? And we need a responsive, decent IDE/editor in order to gain productivity when writing scripts for this purpose? Source: Tips4all

"Did you mean&rdquo; feature on a dictionary database

I have a ~300.000 row table; which includes technical terms; queried using PHP and MySQL + FULLTEXT indexes. But when I searching a wrong typed term; for example "hyperpext"; naturally giving no results. I need to "compansate" little writing errors and getting nearest record from database. How I can accomplish such feaure? I know (actually, learned today) about Levenshtein distance, Soundex and Metaphone algorithms but currently not having a solid idea to implement this to querying against database. Best regards. (Sorry about my poor English, I'm trying to do my best) Source: Tips4all

Did I find a bug in PHP"s `crypt()`?

I think I may have found a bug in PHP's crypt() function under Windows. However : I recognize that it's probably my fault . PHP is used by millions and worked on by thousands; my code is used by tens and worked on by me. (This argument is best explained on Coding Horror .) So I'm asking for help: show me my fault. I've been trying to find it for a few days now, with no luck. The setup I'm using a Windows server installation with Apache 2.2.14 (Win32) and PHP 5.3.2. My development box runs Windows XP Professional; the 'production' server (this is an intranet setup) runs Windows Storage Server 2003. The problem happens on both. I don't see anything in php.ini related to crypt() , but will happily answer questions about my config. The problem Several scripts in my PHP app occasionally hang: the page sits there on 'waiting for localhost' and never finishes. Each of these scripts uses crypt to hash a user's password before

Mysterious dbboon folder with proxy.php file on my godaddy account

When doing some web maintenance today, I noticed a strange new folder on my GoDaddy hosting account at the root level named "dbboon", with a single file inside, called proxy.php. It's code is listed below, and seems to be some sort of proxy function. I was kind of troubled because I didn't put it there. I googled all this to learn more, but didn't find anything, except for the proxy file happened to be also stored at pastebin.com: http://pastebin.com/PQsSPbCr I called GoDaddy and they confirmed that it belonged to them, said it was put there by their advanced hosting group for testing purposes but didn't have any more information. I thought this was all really weird: why would they put something in my folder without giving me a heads-up, and why would they need to do something like this? anybody know anything about this? <?php $version = '1.2'; if(isset($_GET['dbboon_version'])) { echo '{"version":"' . $version

Zend_Session / Zend_Auth randomly throws Error Message ps_files_cleanup_dir: opendir(/var/lib/php5) failed: Permission denied (13)

I'm currently working on a new Application using (among other things) Zend_Auth but, for whatever reason, this Error Message is showing up at any location totally randomly (or so it seams) Zend_Session::start() - /home/hannes/workspace/develop/library/Zend/Session.php(Line:480): Error #8 session_start() [function.session-start]: ps_files_cleanup_dir: opendir(/var/lib/php5) failed: Permission denied (13) Array #0 /home/hannes/workspace/develop/library/Zend/Session/Namespace.php(143): Zend_Session::start(true) #1 /home/hannes/workspace/develop/library/Zend/Auth/Storage/Session.php(87): Zend_Session_Namespace->__construct('Zend_Auth') #2 /home/hannes/workspace/develop/library/Zend/Auth.php(91): Zend_Auth_Storage_Session->__construct() #3 /home/hannes/workspace/develop/library/Zend/Auth.php(141): Zend_Auth->getStorage() #4 /home/hannes/workspace/develop/xxxxxxx/application/controllers/AdminController.php(10): Zend_Auth->hasIdentity() #5 /ho

Lightweight CMS in PHP

I am building a site which will require some very limited content management for a client. There are only a few areas of the site which will require the client to be able to update the content themselves. Would it be better to create a very simple custom admin page for the client to log in and say add a news story etc or would it be best using a fully fledged CMS like Drupal etc which seems overkill to me. Source: Tips4all

"AND" vs "&&" as operator

Actually, I am facing a codebase where developpers decided to use ' AND ' and ' OR ' instead of ' && ' and ' || '. I know that there is difference in operators precedence ( && goes before ' and '), but with given framework (prestashop to be precise) is clearly not a reason. So, my question: which version are you using? Is ' and ' more readable than ' && '? || there is ~ difference? Source: Tips4all

Deliverables for PHP web designer

I'm in the design phase of a medium-sized PHP web application (not a static website). Since I'm a programmer with the creativity of an eggplant I'd like to contract with a freelancer to design the look and feel of the application. What deliverable should I ask for from the designer? HTML files? PHP files? How do I apply the look and feel from the designer to my app? Source: Tips4all

Tiny PHP "standalone&rdquo; server (or framework) for local debug without Apache/Nginx/Lighttpd/etc

There's manage.py runserver in Django or ruby script/server in Ruby on Rails — those familiar with one of those frameworks should already get the idea what I'm looking for. They run tiny "standalone" web server, which is perfectly enough to debug the application locally, without any need for other software (Apache/Nginx/Lighttpd/etc). I wonder is there any PHP implementation of such tool, or, maybe, some PHP framework has such feature? Surely, I can pack pre-built pre-configured static nginx executable, but this would not be pretty, and certainly not cross-platform. Having standalone debug webserver written in PHP itself will make the package self-contained. I.e. I'd like to type something like php tools/runserver.php , point browser to http://localhost:8000/ and see the site up and running, ready to debug. My Google-fu has failed me, but I strongly suspect that there is such project already. Source: Tips4all

POST a file string using cURL in PHP?

I was wondering if it is possible to post a file - along with other form data - when the file is just a string? I know that you can post a file that is already on the filesystem by prefixing the filepath with "@". However I'd like to bypass creating a temporary file and send just the file as a string, but I am unsure how to construct the request using cURL in PHP. Cheers $postFields = array( 'otherFields' => 'Yes' ,'filename' => 'my_file.csv' ,'data' => 'comma seperated content' ); $options = array( CURLOPT_RETURNTRANSFER => true ,CURLOPT_SSL_VERIFYPEER => false ,CURLOPT_SSL_VERIFYHOST => 1 ,CURLOPT_POSTFIELDS => $postFields ,CURLOPT_HTTPHEADER => array( 'Content-type: multipart/form-data' ) ); Source: Tips4all

To PHP Namespace or not to PHP Namespace

ok, I'm relatively new to PHP programming and have been plodding along quite unaware that it is possible to actually use namespaces in PHP as I can in c# etc. It's really ugly though as they have decided to use backslashes - why!? Anyway, I am interested in other PHP programmers' views on whether namespaces will catch on in PHP and whether I should begin to use them now? Source: Tips4all

Is Google the only OpenID provider that requires "identifier_select&rdquo;?

I am developing an OpenID consumer in PHP and am using the fantastic LightOpenID library ( http://gitorious.org/lightopenid ). Basing my code off of that found in the example client script I have successfully created a consumer. However, I've run across a snag: Google requires the openid.identity and openid.claimed_id to be set to "http://specs.openid.net/auth/2.0/identifier_select" (see here ). If I do that it works but other providers (i.e. AOL) don't. Here are my questions: Is Google a corner case –– is it the only OpenID provider where identifier_select is required, contrary to the OpenID specs? Is there a shortcoming in the LightOpenID library? Is my understanding of how OpenID works incorrect? If Google is not the only provider that requires identifier_select are there a finite number of them which I'll just hardcode in, or is there someway to determine this through the OpenID spec? I'm new to the internals of OpenID so I wou

Send SOAP XML via curl, PHP

This has been bugging me for days, i'm trying to send a SOAP post via curl but i just keep getting a 'couldn't connect to host' error but i really cant see how. I have an asp version which works fine with the same url and data, i think it's just a php/curl thing...? I currently have the following code (the CURLOPT_POSTFIELDS data is a valid soap envelope string) $soap_do = curl_init(); curl_setopt($soap_do, CURLOPT_URL, "https://xxx.yyy.com:517/zzz.asmx" ); curl_setopt($soap_do, CURLOPT_CONNECTTIMEOUT, 10); curl_setopt($soap_do, CURLOPT_TIMEOUT, 10); curl_setopt($soap_do, CURLOPT_RETURNTRANSFER, true ); curl_setopt($soap_do, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($soap_do, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($soap_do, CURLOPT_POST, true ); curl_setopt($soap_do, CURLOPT_POSTFIELDS, '<soap:Envelope>...</soap:Envelope>'); curl_setopt($soap_d

Is this sufficient to protect against a CSRF for an ajax-driven application?

I'm working on a completely ajax-driven application where all requests pass through what basically amounts to a main controller which, at its bare bones, looks something like this: if(strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') { fetch($page); } Is this generally sufficient to protect against cross-site request forgeries? It's rather inconvenient to have a rotating token when the entire page isn't refreshed with each request. I suppose I could pass and update unique token as a global javascript variable with every request -- but somehow that feels clumsy and seems inherently unsafe anyway. EDIT - Perhaps a static token, like the user's UUID, would be better than nothing? EDIT #2 - As The Rook pointed out, this might be a hair-splitting question. I've read speculation both ways and heard distant whispers about older versions of flash being exploitable for this kind of shenanigans. Since I know nothing about that

Very illogical php value comparisons

I stumbled upon a very strange bit of PHP code. Could someone explain why this is happening? ** BONUS POINTS ** if you can tell my why this is useful. <?php if(0=='a'){ print ord(0)." should NEVER equal ".ord('a')."<br>"; } if(false==0){ print "false==0<br>"; } if('a'==false){ print "a==false<br>"; } ?> And the resulting output: 48 should NEVER equal 97 false==0 Source: Tips4all

Convert/cast an stdClass object to another class

I'm using a third party storage system that only returns me stdClass objects no matter what I feed in for some obscure reason. So I'm curious to know if there is a way to cast/convert an stdClass object into a full fledged object of a given type. For instance something along the lines of: //$std_class is an stdClass instance $converted = (BusinessClass) $stdClass; I am just casting the stdClass into an array and feed it to the BusinessClass constructor, but maybe there is a way to restore the initial class that I am not aware of. Note: I am not interested in 'Change your storage system' type of answers since it is not the point of interest. Please consider it more an academic question on the language capacities. Cheers Source: Tips4all

Is this safe for providing JSONP?

<?php header('content-type: application/json'); $json = json_encode($data); echo isset($_GET['callback']) ? "{$_GET['callback']}($json)" : $json; Or should I for example filter the $_GET['callback'] variable so that it only contains a valid JavaScript function name? If so, what are valid JavaScript function names? Or is not filtering that variable a bit of the point with JSONP? Current solution: Blogged about my current solution at http://www.geekality.net/?p=1021 . In short, for now, I have the following code, which hopefully should be pretty safe: <?php header('content-type: application/json; charset=utf-8'); function is_valid_callback($subject) { $identifier_syntax = '/^[$_\p{L}][$_\p{L}\p{Mn}\p{Mc}\p{Nd}\p{Pc}\x{200C}\x{200D}]*+$/u'; $reserved_words = array('break', 'do', 'instanceof', 'typeof', 'case', 'else', 'new', '

Why strings in $_POST can not contain a dot ".&rdquo;?

Basicaly the title say's it all. i had an hidden input on my page where i wanted to set the name to "some.major.uber.setting" for example: <input type="hidden" name="some.major.uber.setting" value="dummy value" /> and when i looked at the $_POST data it contained "some_major_uber_setting". Can anybody explain this behaviour Source: Tips4all

A CMS on 2 DIFFERENT frameworks?

I'm not sure if this is possible, but let's say you want to build a CMS, but you're torn between 2 frameworks because each has some features that you like. Is it possible to create the CMS with both framewoks? Does this approach have merits or pitfalls? Source: Tips4all

Symfony 2 or Lithium?

The answer may be based on 4 aspects: 1.- simplicity: we all hate write tons of code for simple tasks like in java, this is the reason why we use php, importing design patterns from java/university world is good, but usually independent developers like me need dev speed more than enterprise employees. 2.- backend: how easy will be building a backend in symfony 2 vs lithium?. not always we build a facebook like project and we need our preferred framework to get the job done on little projects too. 3.- community and docs 4.- performance: scale good with the minimum Source: Tips4all

trying to send mail using swift mailer, gmail smtp, php

Here is my code: <?php require_once 'Swift/lib/swift_required.php'; $transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 465) ->setUsername('me@ff.com') ->setPassword('pass'); $mailer = Swift_Mailer::newInstance($transport); $message = Swift_Message::newInstance('Wonderful Subject') ->setFrom(array('me@ff.com' => 'MY NAME')) ->setTo(array('you@ss.com' => 'YOU')) ->setBody('This is the text of the mail send by Swift using SMTP transport.'); //$attachment = Swift_Attachment::newInstance(file_get_contents('path/logo.png'), 'logo.png'); //$message->attach($attachment); $numSent = $mailer->send($message); printf("Sent %d messages\n", $numSent); ?> AFter RUNNING GOT THIS ERROR... Fatal error: Uncaught exception 'Swift_TransportException' with message 'Expected response code 220 but got code "", with me

ACL implementation

First question Please, could you explain me how simpliest ACL could be implemented in MVC. Here is the first approach of using Acl in Controller... <?php class MyController extends Controller { public function myMethod() { //It is just abstract code $acl = new Acl(); $acl->setController('MyController'); $acl->setMethod('myMethod'); $acl->getRole(); if (!$acl->allowed()) die("You're not allowed to do it!"); ... } } ?> It is very bad approach, and it's minus is that we have to add Acl piece of code into each controller's method, but we don't need any additional dependencies! Next approach is to make all controller's methods private and add ACL code into controller's __call method. <?php class MyController extends Controller { private function myMethod() { ... } public function __call($name, $params) { //It is just abstract code $acl = new Acl();

What are the benefits (and drawbacks) of a weakly typed language?

I'm a big fan of PHP and it's obviously a very weakly-typed language. I realize some of the benefits include the general independence of changing variable types on the fly and such. What I'm wondering about are the drawbacks. What can you get out of a strongly-typed language like C that you otherwise can't get from a weakly-typed one like PHP? Also with type setting (like double($variable)), one could argue that even a weakly-typed language can act just like a strongly-typed one. So. Weak-type. What are some benefits I didn't include? More importantly, what are the drawbacks? Source: Tips4all