Tuesday, August 7, 2012

Increase PHP Script Execution Time Limit Using ini_set()

Every once in a while I need to process a HUGE file. Though PHP probably isn't the most efficient way of processing the file, I'll usually use PHP because it makes coding the processing script much faster. To prevent the script from timing out, I need to increase the execution time of the specific processing script. Here's how I do it.

The PHP

copyini_set('max_execution_time', 300); //300 seconds = 5 minutes
Place this at the top of your PHP script and let your script loose!

5 Ways to Make Ajax Calls with jQuery

There are at least five ways to make AJAX calls with the jQuery library. For beginners, however, the differences between each can be a bit confusing. In this tutorial, we’ll line them up and make a comparison. Additionally. we’ll review how to inspect these AJAX calls with Firebug as well.

What is AJAX

This section is for those who have no idea what AJAX is. If you don’t fall into this category, feel free to skip to the next section.
AJAX stands for asynchronous JavaScript and XML. If you see another term XHR, which is shorthand for XML HTTP request, it’s the same thing. Don’t be afraid of this jargon; AJAX is not rocket science.
  • In Gmail, switch from inbox to draft. Part of the page is changed, but the page is not refreshed. You remain on the same page. Url has not changed (except for the #draft at the end of the url, but that’s still the same webpage).
  • In Google Reader, select a feed. The content changes, but you are not redirected to another url.
  • In Google Maps, zoom in or zoom out. The map has changed, but you remain on the same page.
The key to AJAX’s concept is “asynchronous”. This means something happens to the page after it’s loaded. Traditionally, when a page is loaded, the content remains the same until the user leaves the page. With AJAX, JavaScript grabs new content from the server and makes changes to the current page. This all happena within the lifetime of the page, no refresh or redirection is needed.

Caching AJAX

Now we should know what AJAX actually is. And we know that, when Gmail refreshes some content without redirection, an AJAX call is made behind the scenes. The requested content can either be static (remains exactly the same all the time, such as a contact form or a picture) or dynamic (requests to the same url get different responses, such as Gmail’s inbox where new mails may show up any time).
For static content, we may want the response cached. But for dynamic content, which can change in a second’s time, caching AJAX becomes a bug, right? It should be noted that Internet Explorer always caches AJAX calls, while other browsers behave differently. So we’d better tell the browser explicitly whether or not AJAX should be cached. With jQuery, we can accomplish this simply by typing:
  1. $.ajaxSetup ({  
  2.     cache: false  
  3. });  

1. load(): Load HTML From a Remote URL and Inject it into the DOM

The most common use of AJAX is for loading HTML from a remote location and injecting it into the DOM. With jQuery’s load() function, this task is a piece of cake. Review this demo and we’ll go over some uses one by one.

Minimal Configuration

Click on the first button named “load().” A piece of HTML is injected into the page, exactly what we were talking about. Let’s see what’s going on behind the scenes.
Below is the JavaScript code for this effect:
  1.     $.ajaxSetup ({  
  2.         cache: false  
  3.     });  
  4.     var ajax_load = "loading...";  
  5.       
  6. //  load() functions  
  7.     var loadUrl = "ajax/load.php";  
  8.     $("#load_basic").click(function(){  
  9.         $("#result").html(ajax_load).load(loadUrl);  
  10.     });  
  1. $.ajaxSetup forces the browser NOT to cache AJAX calls.
  2. After the button is clicked, it takes a little while before the new HTML is loaded. During the loading time, it’s best to show an animation to provide the user with some feedback to ensure that the page is currently loading. The “ajax_load” variable contains the HTML of the loading sign.
  3. “ajax/load.php” is the url from which the HTML is grabbed.
  4. When the button is clicked, it makes an AJAX call to the url, receives the response HTML, and injects it into the DOM. The syntax is simply $(“#DOM”).load(url). Can’t be more straightforward, hah?
Now, let’s explore more details of the request with Firebug:
  1. Open Firebug.
  2. Switch to the “Net” tab. Enable it if it’s disabled. This is where all HTTP request in the browser window are displayed.
  3. Switch to “XHR” tab below “Net”. Remember the term “XHR?” It’s the request generated from an AJAX call. All requests are displayed here.
  4. Click on the “load()” button and you should see the following.
The request is displayed, right? Click on the little plus sign to the left of the request, more information is displayed.
Click on the “Params” tab. Here’s all parameters passed through the GET method. See the long number string passed under a “_” key? This is how jQuery makes sure the request is not cached. Every request has a different “_” parameter, so browsers consider each of them to be unique.
Click on the “Response” tab. Here’s the HTML response returned from the remote url.

Load Part of the Remote File

Click on “load() #DOM” button. We notice that only the Envato link is loaded this time. This is done with the following code:
  1. $("#load_dom").click(function(){  
  2.     $("#result")  
  3.         .html(ajax_load)  
  4.         .load(loadUrl + " #picture");  
  5. });  
With load(url + “#DOM”), only the contents within #DOM are injected into current page.

Pass Parameters Through the GET Method

Click on the “load() GET” button and open firebug.
  1. $("#load_get").click(function(){  
  2.     $("#result")  
  3.         .html(ajax_load)  
  4.         .load(loadUrl, "language=php&version=5");  
  5. });  
By passing a string as the second param of load(), these parameters are passed to the remote url in the GET method. In Firebug, these params are shown as follows:

Pass Parameters Through the POST Method

Click on the “load() POST” button and open Firebug.
  1. $("#load_post").click(function(){  
  2.     $("#result")  
  3.         .html(ajax_load)  
  4.         .load(loadUrl, {language: "php", version: 5});  
  5. });  
If parameters are passed as an object (rather than string), they are passed to the remote url in the POST method.

Do Something on AJAX Success

Click on “load() callback” button.
  1. $("#load_callback").click(function(){  
  2.     $("#result")  
  3.         .html(ajax_load)  
  4.         .load(loadUrl, nullfunction(responseText){  
  5.             alert("Response:\n" + responseText);  
  6.         });  
  7. });  
A function can be passed to load() as a callback. This function will be executed as soon as the AJAX request is completed successfully.

2. $.getJSON(): Retrieve JSON from a Remote Location

Now we’ll review the second AJAX method in jQuery.
JSON (JavaScript Object Notation) is a lightweight data-interchange format. It’s very convenient when exchanging data programmatically with JSON.
Let’s review an example.
Find the $.getJSON() section in the demo page, type in some words in your native language, and click detect language.
  1. //  $.getJSON()  
  2.     var jsonUrl = "ajax/json.php";  
  3.     $("#getJSONForm").submit(function(){  
  4.         var q = $("#q").val();  
  5.         if (q.length == 0) {  
  6.             $("#q").focus();  
  7.         } else {  
  8.             $("#result").html(ajax_load);  
  9.             $.getJSON(  
  10.                 jsonUrl,  
  11.                 {q: q},  
  12.                 function(json) {  
  13.                     var result = "Language code is \"" + json.responseData.language + "\"";  
  14.                     $("#result").html(result);  
  15.                 }  
  16.             );  
  17.         }  
  18.         return false;  
  19.     });  
Let’s jump to Line 9:
  1. $.getJSON doesn’t load information directly to the DOM. So the function is $.getJSON, NOT $(“#result”).getJSON. (There are pairs of similar looking functions in jQuery such as $.each() and each(). Check out their respective documentation for more information.)
  2. $.getJSON accepts three parameters. A url, parameters passed to the url and a callback function.
  3. $.getJSON passes parameters in GET method. POSTing is not possible with $.getJSON.
  4. $.getJSON treats response as JSON.
$.getJSON’s function name is NOT camel-cased. All four letters of “JSON” are in uppercase.
Look at the response in JSON format in Firebug. It’s returned from Google Translate API. Check out ajax/json.php in source files to see how language detection works.

3. $.getScript(): Load JavaScript from a Remote Location

We can load JavaScript files with $.getScript method. Click on “Load a Remote Script” button in the demo page; let’s review the code for this action.
  1. //  $.getScript()  
  2.     var scriptUrl = "ajax/script.php";  
  3.     $("#getScript").click(function(){  
  4.         $("#result").html(ajax_load);  
  5.         $.getScript(scriptUrl, function(){  
  6.             $("#result").html("");  
  7.         });  
  8.     });  
  1. $.getScript accepts only two parameters, a url, and a callback function.
  2. Neither the GET nor POST params can be passed to $.getScript. (Of course you can append GET params to the url.)
  3. JavaScript files don’t have to contain the “.js” extension. In this case, the remote url points to a PHP file. Let your imagination fly and you can dynamically generate JavaScript files with PHP.
See the response JavaScript in Firebug.

4. $.get(): Make GET Requests

$.get() is a more general-purpose way to make GET requests. It handles the response of many formats including xml, html, text, script, json, and jonsp. Click on the “$.get()” button in the demo page and see the code.
  1. //  $.get()  
  2.     $("#get").click(function(){  
  3.         $("#result").html(ajax_load);  
  4.         $.get(  
  5.             loadUrl,  
  6.             {language: "php", version: 5},  
  7.             function(responseText){  
  8.                 $("#result").html(responseText);  
  9.             },  
  10.             "html"  
  11.         );  
  12.     });  
  1. $.get() is completely different, as compared to get(). The latter has nothing to do with AJAX at all.
  2. $.get accepts the response type as the last parameter, which makes it more powerful than the first functions we introduced today. Specify response type if it’s not html/text. Possible values are xml, html, text, script, json and jonsp.

5. $.post(): Make POST Requests

$.post() is a more general-purpose way to make POST requests. It does exactly the same job as $.get(), except for the fact that it makes a POST request instead.
  1. //  $.post()  
  2.     $("#post").click(function(){  
  3.         $("#result").html(ajax_load);  
  4.         $.post(  
  5.             loadUrl,  
  6.             {language: "php", version: 5},  
  7.             function(responseText){  
  8.                 $("#result").html(responseText);  
  9.             },  
  10.             "html"  
  11.         );  
  12.     });  
The use of $.post() is the same as its brother, $.get(). Check the POST request in Firebug (shown in the following image).

Finally… $.ajax():

Up to this point, we’ve examined five commonly used jQuery AJAX functions. They bear different names but, behind the scenes, they generally do the exact same job with slightly different configurations. If you need maximum control over your requests, check out the $.ajax() function.
This is jQuery’s low-level AJAX implementation. See $.get, $.post etc. for higher-level abstractions that are often easier to understand and use, but don’t offer as much functionality (such as error callbacks). -jQuery’s official Documentation
In my opinion, the first five functions should satisfy most of our needs. But if you need to execute a function on AJAX error, $.ajax() is your only choice.

Conclusion

Today, we took an in-depth look of five ways to make AJAX calls with jQuery.
  • load(): Load a piece of html into a container DOM.
  • $.getJSON(): Load a JSON with GET method.
  • $.getScript(): Load a JavaScript.
  • $.get(): Use this if you want to make a GET call and play extensively with the response.
  • $.post(): Use this if you want to make a POST call and don’t want to load the response to some container DOM.
  • $.ajax(): Use this if you need to do something when XHR fails, or you need to specify ajax options (e.g. cache: true) on the fly.
Before we conclude, here’s a comparison table of these functions. I hope you enjoyed this lesson! Any thoughts?

PostFinance Error Messages

unknown order/1/r
This error means that the referrer we detected is not a URL the merchant has entered in the URL field in the “Data and origin verification” tab, “Checks for e-Commerce” section of his Technical Information page. The merchant is sending us the form with the hidden fields containing the order information from a differ-¬ ent page from the one(s) entered in the URL field in the “Data and origin verification” tab, “Checks for e-Commerce” section.
unknown order/0/r
This error means our server has not detected a referrer in the request we received. The merchant is send-¬ ing us order details, but we do not know where they originated from. Please ensure that no methods are being used that blocking the referrer information (payment page in pop up, special web server configuration, customer’s browser configuration, …). If the customer’s browser does not send the referrer information, we can bypass the referrer check if a SHASign is present and correct. (See Chapter 6.2)
unknown order/1/s
You will receive this error message if the SHASign sent in the hidden HTML fields for the transaction does not match the SHASign calculated at our end using the details of the order and the additional string (password/pass phrase) entered in the SHA-¬1-¬IN Signature field in the “Data and origin verification” tab, “Checks for e-Commerce” section of the Technical Information page.
unknown order/0/s
You will receive this error message if the “SHASign” field in the hidden HTML fields is empty but an additional string (password/pass phrase) has been entered in the SHA-¬1-IN Signature field in the “Data and origin verification” tab, “Checks for e-Commerce” section of the Technical Information page, indicating you want to use a SHA signature with each transaction.
PSPID not found or not active
This error means the value you have entered in the PSPID field does not exist in the respective environ-¬ ment (test or prod) or the account has not yet been activated. no(for instance: no PSPID) This error means the value you sent for the obligatoryfield is empty.
too long (for instance: currency too long)
This error means the value in yourfield exceeds the maximum length.
amount too long or not numeric: … OR Amount not a number
This error means the amount you sent in the hidden fields either exceeds the maximum length or contains invalid characters such as . or , for intance.
not a valid currency : …
This error means you have sent a transaction with a currency code that is incorrect or does not exist.
The currency is not accepted by the merchant
This error means you have sent a transaction in a currency that has not been registered in your account details.
ERROR, PAYMENT METHOD NOT FOUND FOR: …
This error means the PM value you sent in your hidden fields does not match any of the payment methods you have selected in your account, or that the payment method has not been activated in your payment methods page.

HTML to PDF with PHP, Java or ASP

HTML to PDF with PHP

Using open-source HTML2FPDF project

This solution uses HTML2PDF project (sourceforge.net/projects/html2fpdf/). It simply gets a HTML text and generates a PDF file. This project is based upon FPDF script (www.fpdf.org), which is pure PHP, not using the PDFlib or other third party library. Download HTML2PDF, add it to your projects and you can start coding.
Code example

require("html2fpdf.php");
$htmlFile = "http://www.dancrintea.ro";
$buffer = file_get_contents($htmlFile);
$pdf = new HTML2FPDF('P', 'mm', 'Letter');
$pdf->AddPage();
$pdf->WriteHTML($buffer);
$pdf->Output('test.pdf', 'F');


HTML to PDF with Java

Using OpenOffice.org

You can use OpenOffice.org(must be available on the same computer or in your network) for document conversion.

Besides HTML to PDF, there are also possible other conversions:
doc --> pdf, html, txt, rtf
xls --> pdf, html, csv
ppt --> pdf, swf
Code example

import officetools.OfficeFile;
// this is my tools package ...
FileInputStream fis = new FileInputStream(new File("test.html"));
FileOutputStream fos = new FileOutputStream(new File("test.pdf"));
// suppose OpenOffice.org runs on localhost, port 8100
OfficeFile f = new OfficeFile(fis,"localhost","8100", true);
f.convert(fos,"pdf");

How to get my Java tools package for OpenOffice.org

If you want to use this solution in your projects, please contact me:
Contact

HTML to PDF with ASP

Using ASPPDF

You can use AspPDF (www.asppdf.com), an ActiveX server component for dynamically creating, reading and modifying PDF files.
Code example(VB)

Set Pdf = Server.CreateObject("Persits.Pdf")
Set Doc = Pdf.CreateDocument Doc.ImportFromUrl "http://www.dancrintea.ro" Filename = Doc.Save( Server.MapPath("test.pdf"), False )

noty : a jQuery plugin

Hi!

noty is a jQuery plugin that makes it easy to create alert - success - error - warning - information - confirmation messages as an alternative the standard alert dialog. Each notification is added to a queue. (Optional)
The notifications can be positioned at the;
top - topLeft - topCenter - topRight - center - centerLeft - centerRight - bottom - bottomLeft - bottomCenter - bottomRight
There are lots of other options in the API to customise the text, animation, speed, buttons and much more.
It also has various callbacks for the buttons, opening closing the notifications and queue control.


Please find the following link to know the installation details of noty

http://needim.github.com/noty/

Ruby on Rails tutorials

Ruby on Rails is an excellent framework to learn not only because it’s a great web application framework, but also because it has a large and helpful community. In fact, chances are you can learn how to use Rails in a multitude of ways, just by searching the web.
We’ve taken it upon ourselves to compile some excellent tutorials that Rails beginner’s and zealots alike can use while working in the popular web app framework and continue exploring the endless possibilities of Rails.

GETTING STARTED

1. How to Install Rails

A getting started guide on how to set up Rails in multiple environments, from the official Ruby on Rails site.

2. Ruby on Rails for Web Development in Mac OS X

Apple has an official guide on how to get started with Rails on a Mac.

3. Installing Ruby on Rails with Lighttpd and MySQL on Fedora Core 4

Extensive documentation on how to get this great cocktail of software working for Rails.

4. Four Days on Rails

Four Days on Rails is an impressive 40-page eBook that provides a handy toolbox for Rails development.

5. Why Rails?

Rails Envy gives an argument in favor of the Rails framework.

6. Rolling with Ruby on Rails Revisited, Part 2

A “storytelling” example on the effectiveness of Rails in web applications.

7. Fast-track your Web apps with Ruby on Rails

Fast-track your Web apps with Ruby on Rails is a somewhat dated but excellent overview of how the web framework works.

8. Ruby Study Notes

If you’re not familiar with the Ruby language, check out Ruby Study Notes, a web-based tutorial on the basics of Ruby.

9. Ruby in 20 Minutes

The official Ruby site has a quickstart that will get you well underway into Ruby programming.

10. Ruby on Rails Cheat Sheet

A quick reference for Rail’s directory structure, pre-defined variables, syntax and more.

RAILS TUTORIALS

11. Ruby Loops

Dev Articles has a quick look at Ruby Loops, Methods and Blocks.

12. Rails To-Do List

A tutorial on how to create a simple to-do list with Rails. (Note: it’s slightly dated so be aware of when the advice goes against current best practices – still a useful exercise though.)

13. Send Emails with Rails

This quick guide shows how to use Rails’ mailer functionality to send emails within a web application.

14. Rails for Designers

A great starting point for learning how things like Rails and the MVC framework can be a great thing for a designer.

15. Easy Image Attachments in Rails

How to use Paperclip to swiftly attach images to an Event in Rails.

16. How to Use Gmail as Your Mail Server For Rails

An innovative strategy for using ActionMailer to farm out email sending with (almost) everybody’s favorite email host, Gmail.

17. Building a Social Network Site in Rails

A collection of plugins, tips and advice to help build your own social networking site in Rails. The article doesn’t go over all the code needed to make a social networking site, but rather touches on the most important aspects and functionality.

18. Ruby on Rails Security Guide

An excellent primer on the types of security attacks your Rails app might encounter, and how to combat them.

19. Rails and Ajax Table Pagination, Sorting and Searching

Sorting table data is incredibly useful for most data-heavy applications. Nozav.org has put together a comprehensive guide on how to make a sortible AJAX table in Rails, complete with a demo application.

20. Restful Authentication with Rails 2

The Restful Authentication plugin is a hugely popular plugin for doing all things user-releated. Avnet labs has a great tutorial on how to implement Restful Authentication with your Rails app, with many helpful screenshots and example code.

21. Converting Videos with Rails

A 2-part series on converting video in a Rails app with the FFMPEG.

DISTRIBUTING RAILS

22. Distributing Ruby Applications

Everything you’ll need to know about packing and distributing Rails applications with Tar2RubyScript and RubyScript2EXE.

23. Rails Ajax

A dated but fundamentally useful overview on how to use Ajax technologies with the Rails framework.

24. Rails and jQuery

An episode from the excellent Railscasts site going over how to use jQuery in a Rails application.

25. Dropping and Sorting with Ajax and Scriptaculous

A quick tutorial on creating a drag-n-drop interface in Rails and the popular Javascript framework Scriptaculous.

26. Auto-complete Association

A screencast on how to create a text field auto-complete experience, much like Google’s newly-revamped search functionality.

27. Getting Started with Instant Rails on Windows (screencast)

O’Reilly media has a nice 17 minute video primer on RoR for Windows users.

28. Complex forms

A slightly more advanced tutorial that focuses on making complex forms without unwieldy controllers. The tutorial has two other parts that build on the first. (Part 2, part 3)

29. Creating Plugins in Rails

The basics on creating a plugin with the Rails API. The tutorial is very extensive and thorough.

30. Paypal Basics

Railscasts has another excellent episode on how to integrate Paypal into your application for handling money transactions.

31. Active Merchant Basics

If you’re wanting to roll your own money processing system and use something other than Paypal, then you might want to try Active Merchant, a payment processing library for Rails Screencasts has an Active Merchant Basics, complete with source code.

How to setup yiic on WAMP (XP/Vista)

This page assumes that you have installed Wampserver on your MS Windows computer.
Start with downloading Yii and deploy the framework in your webroot/vhost (C:\wamp\www\).
Open the Environment Variables window by going to: Start -> My Computer (right click!) -> Advanced Tab -> Environment Variables -> Click Path in System variables -> Edit.
In Windows 7, press the Win key and type "env". You should see a control panel section with a shortcut to "Edit the system environment variables". Select it and then click on "Environment Variables...".
Click on the variable called PATH and click "Edit...". Do not delete the paths already there! Separate each path with semicolons.
Now you have to add the following PATHs in Windows: "C:\wamp\bin\php\php5.2.8" and "C:\wamp\www\framework". The former path should lead where your php.exe resides, and the latter where your yiic.bat resides.
After entering the paths, type cmd in your startmenus searchfield, and go to the webroot. You may have to restart the computer if this does not work for you so that Windows can register the new variables.
yiic webapp mywebsite
Will generate a Yii skeleton for your web application inside the directory "mywebsite" in your WAMP webroot folder. One reason that you should stand in your WAMP webroot when giving the yiic commands is that you don't have to specify where you want the web application generated.

Accessing yiic for the local web applicaton

After you have created your webapp you want to use the yiic command shell to generate model classes and using the CRUD functionality.
For this you should go to "C:\wamp\www\mywebsite\protected". The reason you should stand here is that you want to use the local yiic command for the application. This is necessary if you want to create models and CRUD using the database schema as a template. The yiic command will use the configuration of the web application!
yiic shell ..\index.php
This command will start the local yiic shell that gives you access to the CRUD commands and even the commands that you build into your webapp.