When working with strings and you need to check that the string is either of a certain length you’d understandably would want to use the strlen() function. This function is pretty quick since it’s operation does not perform any calculation but merely return the already known length of a string available in the zval structure (internal C struct used to store variables in PHP). However because strlen() is a function it is still somewhat slow because the function call requires several operations such as lowercase & hashtable lookup followed by the execution of said function. In some instance you can improve the speed of your code by using an isset() trick.
<?
if (strlen($foo) < 5) { echo "Foo is too short"; }
if (!isset($foo{5})) { echo "Foo is too short"; }
?>
Calling isset() happens to be faster then strlen() because unlike strlen(), isset() is a language construct and not a function meaning that it’s execution does not require function lookups and lowercase. This means you have virtually no overhead on top of the actual code that determines the string’s length.
Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts
Tuesday, March 24, 2009
40 Tips for optimizing your php code
- If a method can be static, declare it static. Speed improvement is by a factor of 4.
- echo is faster than print.
- Use echo's multiple parameters instead of string concatenation.
- Set the maxvalue for your for-loops before and not in the loop.
- Unset your variables to free memory, especially large arrays.
- Avoid magic like __get, __set, __autoload
- require_once() is expensive
- Use full paths in includes and requires, less time spent on resolving the OS paths.
- If you need to find out the time when the script started executing, $_SERVER[’REQUEST_TIME’] is preferred to time()
- See if you can use strncasecmp, strpbrk and stripos instead of regex
- str_replace is faster than preg_replace, but strtr is faster than str_replace by a factor of 4
- If the function, such as string replacement function, accepts both arrays and single characters as arguments, and if your argument list is not too long, consider writing a few redundant replacement statements, passing one character at a time, instead of one line of code that accepts arrays as search and replace arguments.
- It's better to use switch statements than multi if, else if, statements.
- Error suppression with @ is very slow.
- Turn on apache's mod_deflate
- Close your database connections when you're done with them
- $row[’id’] is 7 times faster than $row[id]
- Error messages are expensive
- Do not use functions inside of for loop, such as for ($x=0; $x <>
- Incrementing a local variable in a method is the fastest. Nearly the same as calling a local variable in a function.
- Incrementing a global variable is 2 times slow than a local var.
- Incrementing an object property (eg. $this->prop++) is 3 times slower than a local variable.
- Incrementing an undefined local variable is 9-10 times slower than a pre-initialized one.
- Just declaring a global variable without using it in a function also slows things down (by about the same amount as incrementing a local var). PHP probably does a check to see if the global exists.
- Method invocation appears to be independent of the number of methods defined in the class because I added 10 more methods to the test class (before and after the test method) with no change in performance.
- Methods in derived classes run faster than ones defined in the base class.
- A function call with one parameter and an empty function body takes about the same time as doing 7-8 $localvar++ operations. A similar method call is of course about 15 $localvar++ operations.
- Surrounding your string by ' instead of " will make things interpret a little faster since php looks for variables inside "..." but not inside '...'. Of course you can only do this when you don't need to have variables in the string.
- When echoing strings it's faster to separate them by comma instead of dot. Note: This only works with echo, which is a function that can take several strings as arguments.
- A PHP script will be served at least 2-10 times slower than a static HTML page by Apache. Try to use more static HTML pages and fewer scripts.
- Your PHP scripts are recompiled every time unless the scripts are cached. Install a PHP caching product to typically increase performance by 25-100% by removing compile times.
- Cache as much as possible. Use memcached - memcached is a high-performance memory object caching system intended to speed up dynamic web applications by alleviating database load. OP code caches are useful so that your script does not have to be compiled on every request
- When working with strings and you need to check that the string is either of a certain length you'd understandably would want to use the strlen() function. This function is pretty quick since it's operation does not perform any calculation but merely return the already known length of a string available in the zval structure (internal C struct used to store variables in PHP). However because strlen() is a function it is still somewhat slow because the function call requires several operations such as lowercase & hashtable lookup followed by the execution of said function. In some instance you can improve the speed of your code by using an isset() trick.
Ex.
if (strlen($foo) < 5) { echo "Foo is too short"; }
vs.
if (!isset($foo{5})) { echo "Foo is too short"; }
Calling isset() happens to be faster then strlen() because unlike strlen(), isset() is a language construct and not a function meaning that it's execution does not require function lookups and lowercase. This means you have virtually no overhead on top of the actual code that determines the string's length.
more about isset() vs strlen() here - When incrementing or decrementing the value of the variable $i++ happens to be a tad slower then ++$i. This is something PHP specific and does not apply to other languages, so don't go modifying your C or Java code thinking it'll suddenly become faster, it won't. ++$i happens to be faster in PHP because instead of 4 opcodes used for $i++ you only need 3. Post incrementation actually causes in the creation of a temporary var that is then incremented. While pre-incrementation increases the original value directly. This is one of the optimization that opcode optimized like Zend's PHP optimizer. It is a still a good idea to keep in mind since not all opcode optimizers perform this optimization and there are plenty of ISPs and servers running without an opcode optimizer.
- Not everything has to be OOP, often it is too much overhead, each method and object call consumes a lot of memory.
- Do not implement every data structure as a class, arrays are useful, too
- Don't split methods too much, think, which code you will really re-use
- You can always split the code of a method later, when needed
- Make use of the countless predefined functions
- If you have very time consuming functions in your code, consider writing them as C extensions
- Profile your code. A profiler shows you, which parts of your code consumes how many time. The Xdebug debugger already contains a profiler. Profiling shows you the bottlenecks in overview
- mod_gzip which is available as an Apache module compresses your data on the fly and can reduce the data to transfer up to 80%
- Excellent Article about optimizing php by John Lim
Disclamer: This was article wasn't really mine, someone emailed this to me and I just found it useful.
$HTTP_SERVER_VARS
Basic surfer information variables (from HTTP_SERVER_VARS)
<?php
$surfer_info[ip] = $HTTP_SERVER_VARS["REMOTE_ADDR"];
// $surfer_info[real_ip] will only contain something if the surfer used a transparent proxy
$surfer_info[real_ip] = $HTTP_SERVER_VARS["X_FORWARDED_FOR"];
$surfer_info[port] = $HTTP_SERVER_VARS["REMOTE_PORT"];
$surfer_info[browser_lang] = $HTTP_SERVER_VARS["HTTP_ACCEPT_LANGUAGE"];
$surfer_info[user_agent] = $HTTP_SERVER_VARS["HTTP_USER_AGENT"];
$surfer_info[request_path] = $HTTP_SERVER_VARS["PATH_INFO"];
$surfer_info[request_query] = $HTTP_SERVER_VARS["QUERY_STRING"];
$surfer_info[request_method] = $HTTP_SERVER_VARS["REQUEST_METHOD"];
$surfer_info[http_referrer] = $HTTP_SERVER_VARS["HTTP_REFERER"];
?>
It is just a row of variables, - it is up to you to decide how they are useful to your script and how to integrate them.
But if you want to see something happening any way, add
print_r($surfer_info);
to the bottom of the script (but before the closing ?>). Doing so will cause the script to show you what information the variables picked up.
<?php
$surfer_info[ip] = $HTTP_SERVER_VARS["REMOTE_ADDR"];
// $surfer_info[real_ip] will only contain something if the surfer used a transparent proxy
$surfer_info[real_ip] = $HTTP_SERVER_VARS["X_FORWARDED_FOR"];
$surfer_info[port] = $HTTP_SERVER_VARS["REMOTE_PORT"];
$surfer_info[browser_lang] = $HTTP_SERVER_VARS["HTTP_ACCEPT_LANGUAGE"];
$surfer_info[user_agent] = $HTTP_SERVER_VARS["HTTP_USER_AGENT"];
$surfer_info[request_path] = $HTTP_SERVER_VARS["PATH_INFO"];
$surfer_info[request_query] = $HTTP_SERVER_VARS["QUERY_STRING"];
$surfer_info[request_method] = $HTTP_SERVER_VARS["REQUEST_METHOD"];
$surfer_info[http_referrer] = $HTTP_SERVER_VARS["HTTP_REFERER"];
?>
It is just a row of variables, - it is up to you to decide how they are useful to your script and how to integrate them.
But if you want to see something happening any way, add
print_r($surfer_info);
to the bottom of the script (but before the closing ?>). Doing so will cause the script to show you what information the variables picked up.
Friday, March 20, 2009
Detecting Mobile Browsers in PHP
I used the following block of code to redirect site to a page when it is been accessed via mobile phone browser and to another page when it is accessed via desktop browsers. This is tested in ie, firefox, netscape, opera, chrome and some mobile phone browser simulator. This works well for me.
<?
$site1 = "http://coffeeandpaste.blogspot.com/";
$site2 = "http://monkeetech.blogspot.com/";
$BrowserSplit = explode("/",$HTTP_SERVER_VARS["HTTP_USER_AGENT"]);
$Machine = $BrowserSplit[0];
if($Machine == "Opera" || $Machine == "Mozilla") {
header("location: $site1");
}
else {
header("location: $site2");
}
?>
<?
$site1 = "http://coffeeandpaste.blogspot.com/";
$site2 = "http://monkeetech.blogspot.com/";
$BrowserSplit = explode("/",$HTTP_SERVER_VARS["HTTP_USER_AGENT"]);
$Machine = $BrowserSplit[0];
if($Machine == "Opera" || $Machine == "Mozilla") {
header("location: $site1");
}
else {
header("location: $site2");
}
?>
Tuesday, March 17, 2009
Passing JavaScript variables to PHP
JavaScript is mainly used as a client side scripting language, while PHP is a server side technology. Unlike Java or ASP.Net, PHP doesn't have tools to make it work client side. That is why you need to combine JavaScript and PHP scripts to develop powerful web-applications.
One of the frequent problems is defining visitor’s screen resolution using JavaScript tools and passing this data to PHP-script. The following script provides solution for this problem:
<script type=&qout;text/javascript&qout;>
width = screen.width;
height = screen.height;
if (width > 0 && height >0) {
window.location.href = &qout;http://localhost/main.php?width=&qout; + width + &qout;&height=&qout; + height;
} else
exit();
</script>
Copy and paste this code snippet in the text editor, save it as index.htm and run it in your browser. After this code has been executed, a user is automatically redirected to the main.php page where screen resolution is displayed in the browser window.
The main.php looks as follows:
<?php
echo &qout;<h1>Screen Resolution:</h1>&qout;;
echo &qout;Width : &qout;.$_GET['width'].&qout;<br>&qout;;
echo &qout;Height : &qout;.$_GET['height'].&qout;<br>&qout;;
?>
As you can see, passing JavaScript variables in PHP is similar to sending data using GET method.
[source]
One of the frequent problems is defining visitor’s screen resolution using JavaScript tools and passing this data to PHP-script. The following script provides solution for this problem:
<script type=&qout;text/javascript&qout;>
width = screen.width;
height = screen.height;
if (width > 0 && height >0) {
window.location.href = &qout;http://localhost/main.php?width=&qout; + width + &qout;&height=&qout; + height;
} else
exit();
</script>
Copy and paste this code snippet in the text editor, save it as index.htm and run it in your browser. After this code has been executed, a user is automatically redirected to the main.php page where screen resolution is displayed in the browser window.
The main.php looks as follows:
<?php
echo &qout;<h1>Screen Resolution:</h1>&qout;;
echo &qout;Width : &qout;.$_GET['width'].&qout;<br>&qout;;
echo &qout;Height : &qout;.$_GET['height'].&qout;<br>&qout;;
?>
As you can see, passing JavaScript variables in PHP is similar to sending data using GET method.
[source]
Thursday, March 12, 2009
single-quote( ' ) vs double-quote ( " ) in PHP
Difference between single-quote( ' ) and double-quote ( " ) strings in php
Briefly:
In double-quoted strings, variables are replaced by their values:
PHP Code:
$word = "Hello".
echo "$word there!"
The above code will output:
Hello there!
Doing the same with single quotes:
PHP Code:
$word = "Hello".
echo '$word there!'
...will print:
$word there!
Using single quotes where possible, will be slightly more efficient to process, because PHP doesn't have to search single quoted strings for variables.
Briefly:
In double-quoted strings, variables are replaced by their values:
PHP Code:
$word = "Hello".
echo "$word there!"
The above code will output:
Hello there!
Doing the same with single quotes:
PHP Code:
$word = "Hello".
echo '$word there!'
...will print:
$word there!
Using single quotes where possible, will be slightly more efficient to process, because PHP doesn't have to search single quoted strings for variables.
PHP Arrays
PHP Arrays provide a way to group together many variables such that they can be referenced and manipulated using a single variable. An array is, in many ways, a self-contained list of variables.
Once an array has been created items can be added, removed and modified, sorted and much more. The items in an array can be of any variable type, and an array can contain any mixture of data types - it is not necessary to have each element in the array of the same type.
Elements of an array are accessed using a key. There are two types of array, and the type of key that is used to access an array element dictates the array type. In a numerical key array, elements are accessed by specifying the numerical position of the item in the array. The first item in an array is element 0, the second is element 1 and so on. The second type of array is the associative array where a name is given to each element, and that name is used to access the corresponding array element.
Advantages of Using Functions
Functions are basically named scripts that can be called upon from any other script to perform a specifc task. Values (known as arguments) can be passed into a function so that they can be used in the function script, and functions can, in turn, return results to the location from which they were called.
What are the advantages of using functions?
Debugging is easier
It is easier to understand the logic involved in the program
Testing is easier
Recursive call is possible
Irrelevant details in the user point of view are hidden in functions
Functions are helpful in generalizing the program
What are the advantages of using functions?
Debugging is easier
It is easier to understand the logic involved in the program
Testing is easier
Recursive call is possible
Irrelevant details in the user point of view are hidden in functions
Functions are helpful in generalizing the program
Differences between constants and variables
1. Constants do not have a dollar sign ($) before them;
2. Constants may only be defined using the define() function, not by simple assignment;
3. Constants may be defined and accessed anywhere without regard to variable scoping rules;
4. Constants may not be redefined or undefined once they have been set; and
5. Constants may only evaluate to scalar values.
2. Constants may only be defined using the define() function, not by simple assignment;
3. Constants may be defined and accessed anywhere without regard to variable scoping rules;
4. Constants may not be redefined or undefined once they have been set; and
5. Constants may only evaluate to scalar values.
$_GET vs $_POST in PHP Forms
All information sent from a form with a GET method is visible to others and has a limit on the amount of information to send (100 max char). Whereas the $_POST variable, the information sent from the form with POST method is invisble to others and has no limits on the amount of information to send.
require() vs include() in PHP
require() and include() are identical in every way except how they handle failure. include() produces a Warning while require() results in a Fatal Error. In other words, don’t hesitate to use require() if you want a missing file to halt processing of the page. include() does not behave this way, the script will continue regardless. Be sure to have an appropriate include_path setting as well.
Monday, February 23, 2009
Where is php.ini?
The quick way to find out (assuming php4.3+) is
bash-2.05a$ php -r "phpinfo();" | grep Configuration
Configuration File (php.ini) Path => /etc
Configuration
If you can't do that (because you are using pre 4.3, for shame!) then try the <?php phpinfo() ?> script
bash-2.05a$ php -r "phpinfo();" | grep Configuration
Configuration File (php.ini) Path => /etc
Configuration
If you can't do that (because you are using pre 4.3, for shame!) then try the <?php phpinfo() ?> script
Wednesday, February 18, 2009
Retrieving Japanese Text from MySQL using PHP
Our client's website is a multi-language website including Japanese and English.
It was working well until I was asked to develop a simple database ap for the site.
I have run into this problem.
It was working well until I was asked to develop a simple database ap for the site.
I have run into this problem.
When I try to retrieve the data from MySql using PHP. The data become "??????".(Question Marks)
* The data inside have Japanese and English.
So my db and table is defined as CHARSET=utf8 COLLATE=utf8_unicode_ci
* It display in the mySQL administration tools without any problem.
* It display normally in phpMyAdmin(web browser) too.
I know many developers also have run into this problem, so here's the block of code that did the trick for me.
Put this after the database connection.
mysql_query("SET NAMES 'utf8'")
* It display in the mySQL administration tools without any problem.
* It display normally in phpMyAdmin(web browser) too.
I know many developers also have run into this problem, so here's the block of code that did the trick for me.
Put this after the database connection.
mysql_query("SET NAMES 'utf8'")
Thursday, February 12, 2009
PHPMailer: SMTP Authentication
Most of the hosting providers today disable anonymous user on their server or do not allow to send mail through script without SMTP authentication to stop the spamming from their servers. In such cases, you have to use SMTP authentication to send mail through PHP, ASP, or ASP.Net script. Below is the sample SMTP authentication script to send mail through PHP script using PHPMailer:
<?php
require("class.phpmailer.php");
$mail = new PHPMailer();
$mail->IsSMTP(); // send via SMTP
$mail->Host = "smtp.domain.com"; // SMTP servers
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->Username = "email@domain.com"; // SMTP username
$mail->Password = "password"; // SMTP password
$mail->From = "email@domain.com";
$mail->FromName = "Name";
$mail->AddAddress("Recipient@emailaddress.com","Name");
$mail->AddReplyTo("yourname@domain.com","Your Name");
$mail->WordWrap = 50; // set word wrap
$mail->IsHTML(true); // send as HTML
$mail->Subject = "Here is the subject";
$mail->Body = "This is the HTML body";
$mail->AltBody = "This is the text-only body";
if(!$mail->Send())
{
echo "Message was not sent";
echo "Mailer Error: " . $mail->ErrorInfo;
exit;
}
echo "Message has been sent";
?>
<?php
require("class.phpmailer.php");
$mail = new PHPMailer();
$mail->IsSMTP(); // send via SMTP
$mail->Host = "smtp.domain.com"; // SMTP servers
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->Username = "email@domain.com"; // SMTP username
$mail->Password = "password"; // SMTP password
$mail->From = "email@domain.com";
$mail->FromName = "Name";
$mail->AddAddress("Recipient@emailaddress.com","Name");
$mail->AddReplyTo("yourname@domain.com","Your Name");
$mail->WordWrap = 50; // set word wrap
$mail->IsHTML(true); // send as HTML
$mail->Subject = "Here is the subject";
$mail->Body = "This is the HTML body";
$mail->AltBody = "This is the text-only body";
if(!$mail->Send())
{
echo "Message was not sent";
echo "Mailer Error: " . $mail->ErrorInfo;
exit;
}
echo "Message has been sent";
?>
For more info about the PHPMailer Class, visit phpmailer.codeworxtech.com
Monday, January 12, 2009
Creating PDF using PHP
Portable Document Format (PDF) is an open file format created and controlled by Adobe Systems.
PDF files are very useful for data reporting. bcoz now every system having a pdf file reader.
The PDF functions in PHP can create PDF files using the PDFlib library created by Thomas Merz.
All of the functions in PDFlib and the PHP module have identical function names and parameters.
Using HTML2PDF we can convert html page to pdf.
HTML2PDF is a simple HTML to PDF tool which can quickly and easily convert thousands of HTML pages into PDF reports.
HTML2PDF (include PDFcamp + DocConverter COM) is the easiest way to convert your web pages and DOC, RTF, TXT, PPT, XLS files into PDF documents, HTML2PDF quickly and accurately transforms well-formed HTML, DOC, RTF, TXT, PPT, XLS files into PDF files, the HTML2PDF supports both server and client sides, the end-user doesn't need any software (Adobe Acrobat and Reader NOT required).
HTML2PDF (include PDFcamp + DocConverter COM) offers you the flexibility and speed you need to convert multiple HTML, DOC, RTF, TXT, PPT, XLS files into PDF format. Whatever the reason, pdf files can be created directly from MS Internet Explorer (or at background) and even emailed to a recipient/recipients simultaneously.
HTML2PDF Features:
* HTML2PDF can create page headers, footers and page numbers
* HTML2PDF can convert HTML, DOC, RTF, TXT, PPT, XLS files to PDF files on the fly
* HTML2PDF supports adjust paper orientation and size to accommodate HTML documents
* HTML2PDF supports nested tables
* HTML2PDF supports all elements in HTML document, include asp, cgi, css, Java Applets, flash, cookie etc.
* HTML2PDF supports dynamic page breaks with headers and footers
* HTML2PDF supports convert a URL or local file to PDF file
* HTML2PDF can convert .doc/.html/.rtf/.txt/.xls etc files to PDF files from a Command Line Tool, this Tool without any user intervention
* HTML2PDF supports command line operation (for manual use or inclusion in scripts)
How convert a HTML, DOC, RTF, TXT, PPT, XLS files to PDF files with DocConverter COM?
Step 1:
Please download and install the PDFcamp (PDF Writer) software,
http://www.verypdf.com/pdfcamp/pdfcamp_setup.exe
Step 2:
Please download and register the DocConverter COM software,
http://www.toppdf.com/pdfcamp/doc2pdf_com_trial.zip
Please register the pdfout.dll file in your system, for example,
~~~~~~~~~~~
regsvr32 pdfout.dll
~~~~~~~~~~~
Step 3:
Please run the html2pdf.exe software from the Command Line Window to try, the html2pdf.exe software is included in the DocConverter COM package,
For example:
html2pdf.exe "http://www.yahoo.com" "c:\yahoo.pdf"
html2pdf.exe "http://www.google.com/search?sourceid=navclient&ie=UTF-8&oe=UTF-8&q=pdf" "c:\google.pdf"
html2pdf.exe "C:\example.doc" "C:\example.pdf"
html2pdf.exe "C:\example.xls" "C:\example.pdf"
Now You have converted HTML, DOC, RTF, TXT, PPT, XLS files to PDF documents.
Step 5:
Now, you can call the html2pdf.exe software from your Delphi, C++, VB, BCB etc. applications.
HTML2PDF - Converting your HTML, DOC, RTF, TXT, PPT, XLS files to PDFs has never been easier! Combine several of your HTML, DOC, RTF, TXT, PPT, XLS files into a single PDF file. Convert a HTML file into a PDF file, or convert ANY file format to PDF file!
But f you want a simplier method to create PDF file without doing the above installations on your server to use PDF function in your scripts, then use FPDF.
FPDF is a PHP class which allows to generate PDF files with pure PHP, that is to say without using the PDFlib library. F from FPDF stands for Free: you may use it for any kind of usage and modify it to suit your needs.
Advantages: high level functions. Here is a list of its main features:
* Choice of measure unit, page format and margins
* Page header and footer management
* Automatic page break
* Automatic line break and text justification
* Image support (JPEG and PNG)
* Colors
* Links
* TrueType, Type1 and encoding support
* Page compression
FPDF requires no extension (except zlib to activate compression) and works with PHP4 and PHP5.
What languages can I use?
The class can produce documents in many languages other than the Western European ones: Central European, Cyrillic, Greek, Baltic and Thai, provided you own TrueType or Type1 fonts with the desired character set. Chinese, Japanese and Korean are supported too.
What about performance?
Of course, the generation speed of the document is less than with PDFlib. However, the performance penalty keeps very reasonable and suits in most cases, unless your documents are particularly complex or heavy.
Here, we are going to see on converting HTML 2 PDF using PHP. we would be seeing how to use some free open source PHP scripts to accomplish this file conversion.
FPDF: The PDF Generator
The first and the main base for this file conversion is FPDF library. FPDF is a pure PHP class to generate PDF files on the fly. Let us start the PDF generation with a simple Hello world display.
PHP Code:
AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>
To generate a pdf file, first we need to include library file fpdf.php. Then we need to create an FPDF object using the default constructor FPDF(). This constructor can be passed three values namely page orientation (portrait or landscape), measure unit, and page size (A4, A5, etc.,). By default pages are in A4 portrait and the measure unit is millimeter. It could have been specified explicitly with:
PHP Code:
$pdf=new FPDF('P','mm','A4');
It is possible to use landscape (L), other page formats (such as Letter and Legal) and measure units (pt, cm, in).
Then we have added a page to our pdf document with AddPage(). The origin is at the upper-left corner and the current position is by default placed at 1 cm from the borders; the margins can be changed with the function SetMargins().
To print a text, we need to first select a font with SetFont(). Let us select Arial bold 16:
PHP Code:
$pdf->SetFont('Arial','B',16);
We use Cell() function to output a text. A cell is a rectangular area, possibly framed, which contains some text. It is output at the current position. We specify its dimensions, its text (centered or aligned), if borders should be drawn, and where the current position moves after it (to the right, below or to the beginning of the next line). To add a frame, we would do this:
PHP Code:
$pdf->Cell(40,10,'Hello World !',1);
Finally, the document is closed and sent to the browser with Output(). We could have saved it in a file by passing the desired file name.
There are lot more functions in FPDF.
Need more info? click here.
HTML2FPDF: The Converter
HTML2FPDF is a PHP Class library that uses the FPDF class library to convert HTML files to PDF files. This library consist of three classes namely PDF, HTML2FPDF and FPDF (modified FPDF class). The class PDF extends the class HTML2FPDF that extends the class FPDF.
Now let us see, how to convert a sample html page into a PDF file using HTML2FPDF Library. The html page contains a table that lists a few nations with their corresponding national flags. Below is the code for the conversion.
PHP Code:
AddPage();
$fp = fopen("sample.html","r");
$strContent = fread($fp, filesize("sample.html"));
fclose($fp);
$pdf->WriteHTML($strContent);
$pdf->Output("sample.pdf");
echo "PDF file is generated successfully!";
?>
First, we need to include the html2fpdf.php file that contains the HTML2FPDF class and an object is created using the constructor HTML2FPDF(). Then a new page is added to the pdf document using the function AddPage(). The html contents are read from the sample.html file using file functions. Then the html contents are written in to the pdf format using WriteHTML() function. The above sample code with the sample html file and images and the html2fpdf class libraries can be downloaded here.
The HTML2FPDF class library will be working best with the XHTML 1.0. Also the class does not support all the features available with HTML. To know the supported HTML tags and other features, Please refer HTML 2 (F)PDF Project.
PDF files are very useful for data reporting. bcoz now every system having a pdf file reader.
The PDF functions in PHP can create PDF files using the PDFlib library created by Thomas Merz.
All of the functions in PDFlib and the PHP module have identical function names and parameters.
Using HTML2PDF we can convert html page to pdf.
HTML2PDF is a simple HTML to PDF tool which can quickly and easily convert thousands of HTML pages into PDF reports.
HTML2PDF (include PDFcamp + DocConverter COM) is the easiest way to convert your web pages and DOC, RTF, TXT, PPT, XLS files into PDF documents, HTML2PDF quickly and accurately transforms well-formed HTML, DOC, RTF, TXT, PPT, XLS files into PDF files, the HTML2PDF supports both server and client sides, the end-user doesn't need any software (Adobe Acrobat and Reader NOT required).
HTML2PDF (include PDFcamp + DocConverter COM) offers you the flexibility and speed you need to convert multiple HTML, DOC, RTF, TXT, PPT, XLS files into PDF format. Whatever the reason, pdf files can be created directly from MS Internet Explorer (or at background) and even emailed to a recipient/recipients simultaneously.
HTML2PDF Features:
* HTML2PDF can create page headers, footers and page numbers
* HTML2PDF can convert HTML, DOC, RTF, TXT, PPT, XLS files to PDF files on the fly
* HTML2PDF supports adjust paper orientation and size to accommodate HTML documents
* HTML2PDF supports nested tables
* HTML2PDF supports all elements in HTML document, include asp, cgi, css, Java Applets, flash, cookie etc.
* HTML2PDF supports dynamic page breaks with headers and footers
* HTML2PDF supports convert a URL or local file to PDF file
* HTML2PDF can convert .doc/.html/.rtf/.txt/.xls etc files to PDF files from a Command Line Tool, this Tool without any user intervention
* HTML2PDF supports command line operation (for manual use or inclusion in scripts)
How convert a HTML, DOC, RTF, TXT, PPT, XLS files to PDF files with DocConverter COM?
Step 1:
Please download and install the PDFcamp (PDF Writer) software,
http://www.verypdf.com/pdfcamp/pdfcamp_setup.exe
Step 2:
Please download and register the DocConverter COM software,
http://www.toppdf.com/pdfcamp/doc2pdf_com_trial.zip
Please register the pdfout.dll file in your system, for example,
~~~~~~~~~~~
regsvr32 pdfout.dll
~~~~~~~~~~~
Step 3:
Please run the html2pdf.exe software from the Command Line Window to try, the html2pdf.exe software is included in the DocConverter COM package,
For example:
html2pdf.exe "http://www.yahoo.com" "c:\yahoo.pdf"
html2pdf.exe "http://www.google.com/search?sourceid=navclient&ie=UTF-8&oe=UTF-8&q=pdf" "c:\google.pdf"
html2pdf.exe "C:\example.doc" "C:\example.pdf"
html2pdf.exe "C:\example.xls" "C:\example.pdf"
Now You have converted HTML, DOC, RTF, TXT, PPT, XLS files to PDF documents.
Step 5:
Now, you can call the html2pdf.exe software from your Delphi, C++, VB, BCB etc. applications.
HTML2PDF - Converting your HTML, DOC, RTF, TXT, PPT, XLS files to PDFs has never been easier! Combine several of your HTML, DOC, RTF, TXT, PPT, XLS files into a single PDF file. Convert a HTML file into a PDF file, or convert ANY file format to PDF file!
But f you want a simplier method to create PDF file without doing the above installations on your server to use PDF function in your scripts, then use FPDF.
FPDF is a PHP class which allows to generate PDF files with pure PHP, that is to say without using the PDFlib library. F from FPDF stands for Free: you may use it for any kind of usage and modify it to suit your needs.
Advantages: high level functions. Here is a list of its main features:
* Choice of measure unit, page format and margins
* Page header and footer management
* Automatic page break
* Automatic line break and text justification
* Image support (JPEG and PNG)
* Colors
* Links
* TrueType, Type1 and encoding support
* Page compression
FPDF requires no extension (except zlib to activate compression) and works with PHP4 and PHP5.
What languages can I use?
The class can produce documents in many languages other than the Western European ones: Central European, Cyrillic, Greek, Baltic and Thai, provided you own TrueType or Type1 fonts with the desired character set. Chinese, Japanese and Korean are supported too.
What about performance?
Of course, the generation speed of the document is less than with PDFlib. However, the performance penalty keeps very reasonable and suits in most cases, unless your documents are particularly complex or heavy.
Here, we are going to see on converting HTML 2 PDF using PHP. we would be seeing how to use some free open source PHP scripts to accomplish this file conversion.
FPDF: The PDF Generator
The first and the main base for this file conversion is FPDF library. FPDF is a pure PHP class to generate PDF files on the fly. Let us start the PDF generation with a simple Hello world display.
PHP Code:
AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>
To generate a pdf file, first we need to include library file fpdf.php. Then we need to create an FPDF object using the default constructor FPDF(). This constructor can be passed three values namely page orientation (portrait or landscape), measure unit, and page size (A4, A5, etc.,). By default pages are in A4 portrait and the measure unit is millimeter. It could have been specified explicitly with:
PHP Code:
$pdf=new FPDF('P','mm','A4');
It is possible to use landscape (L), other page formats (such as Letter and Legal) and measure units (pt, cm, in).
Then we have added a page to our pdf document with AddPage(). The origin is at the upper-left corner and the current position is by default placed at 1 cm from the borders; the margins can be changed with the function SetMargins().
To print a text, we need to first select a font with SetFont(). Let us select Arial bold 16:
PHP Code:
$pdf->SetFont('Arial','B',16);
We use Cell() function to output a text. A cell is a rectangular area, possibly framed, which contains some text. It is output at the current position. We specify its dimensions, its text (centered or aligned), if borders should be drawn, and where the current position moves after it (to the right, below or to the beginning of the next line). To add a frame, we would do this:
PHP Code:
$pdf->Cell(40,10,'Hello World !',1);
Finally, the document is closed and sent to the browser with Output(). We could have saved it in a file by passing the desired file name.
There are lot more functions in FPDF.
Need more info? click here.
HTML2FPDF: The Converter
HTML2FPDF is a PHP Class library that uses the FPDF class library to convert HTML files to PDF files. This library consist of three classes namely PDF, HTML2FPDF and FPDF (modified FPDF class). The class PDF extends the class HTML2FPDF that extends the class FPDF.
Now let us see, how to convert a sample html page into a PDF file using HTML2FPDF Library. The html page contains a table that lists a few nations with their corresponding national flags. Below is the code for the conversion.
PHP Code:
AddPage();
$fp = fopen("sample.html","r");
$strContent = fread($fp, filesize("sample.html"));
fclose($fp);
$pdf->WriteHTML($strContent);
$pdf->Output("sample.pdf");
echo "PDF file is generated successfully!";
?>
First, we need to include the html2fpdf.php file that contains the HTML2FPDF class and an object is created using the constructor HTML2FPDF(). Then a new page is added to the pdf document using the function AddPage(). The html contents are read from the sample.html file using file functions. Then the html contents are written in to the pdf format using WriteHTML() function. The above sample code with the sample html file and images and the html2fpdf class libraries can be downloaded here.
The HTML2FPDF class library will be working best with the XHTML 1.0. Also the class does not support all the features available with HTML. To know the supported HTML tags and other features, Please refer HTML 2 (F)PDF Project.
Thursday, January 8, 2009
Insert Images to Excel Spreadsheets with PHP on Linux
Have you ever faced a situation when you need to manipulate Excel spreadsheets(ex. insert or embed pictures) with PHP on the server that is running Linux (so COM is not an option)? With Open XML and PHPExcel you can do that now. :)!
PHPExcel uses OpenXML which is compatible only in OpenOffice3.0 which would not show any embeded images on your spreadsheet. I don't know if there's a workaround for this but I think if there are plugin for openoffice to work with Office2007 then it should make it work. yah..maybe.
BTW, this library works in windows too...
Monday, December 15, 2008
Simple php pagination
What is Pagination?
Think about if you have a mysql table with a thousand rows, and you want to allow the user to browse through the entire table. Displaying all the records in that table in one page would not be a good idea. Instead you should break the table up into smaller parts and let the user navigate through it. This is what pagination is, it allows you to break up large results from a database query, and displays a better navigation for the users.
The following code is a quick and dirty example of php/mysql pagination but if you are familiar with CSS, you can easily style the way the page navigation looks.
<?php
if(!empty($_GET["start"])){
$start = $_GET['start'];// To take care global variable if OFF
}else{
$start = 0;
}
if(!($start > 0)) { // This variable is set to zero for the first page
$start = 0;
}
$eu = ($start - 0);
$limit = 5; // No of records to be shown per page.
$whathis = $eu + $limit;
$back = $eu - $limit;
$next = $eu + $limit;
// to check the total number of records
$query = mysql_query(" SELECT * FROM <tablename> ") or die (mysql_error());
$total_rows = mysql_num_rows($query);
//select the record with limitation
$query = mysql_query(" SELECT * FROM <tablename> limit $eu, $limit ") or die (mysql_error());
//code for previous
if($back >=0) {
echo "<a href='yourpage.php?start=$back'><font face='Verdana' size='2'>PREV</font></a> ";
}
//code for the number of page with links
$i = 0;
$x = 1;
for($i=0;$i < $total_rows;$i=$i+$limit){
if($i != $eu){
echo "<a href='yourpage.php?start=$i'><font face='Verdana' size='2'>$x</font></a> ";
}else {
echo "<font face='Verdana' size='4' color=red>$x</font>";
} // Current page is not displayed as link and given font color red
$x = $x+1;
}
//code for next
if($whathis < $total_rows) {
echo "<a href='yourpage.php?start=$next'><font face='Verdana' size='2'>NEXT</font></a>";
}
?>
Think about if you have a mysql table with a thousand rows, and you want to allow the user to browse through the entire table. Displaying all the records in that table in one page would not be a good idea. Instead you should break the table up into smaller parts and let the user navigate through it. This is what pagination is, it allows you to break up large results from a database query, and displays a better navigation for the users.
The following code is a quick and dirty example of php/mysql pagination but if you are familiar with CSS, you can easily style the way the page navigation looks.
<?php
if(!empty($_GET["start"])){
$start = $_GET['start'];// To take care global variable if OFF
}else{
$start = 0;
}
if(!($start > 0)) { // This variable is set to zero for the first page
$start = 0;
}
$eu = ($start - 0);
$limit = 5; // No of records to be shown per page.
$whathis = $eu + $limit;
$back = $eu - $limit;
$next = $eu + $limit;
// to check the total number of records
$query = mysql_query(" SELECT * FROM <tablename> ") or die (mysql_error());
$total_rows = mysql_num_rows($query);
//select the record with limitation
$query = mysql_query(" SELECT * FROM <tablename> limit $eu, $limit ") or die (mysql_error());
//code for previous
if($back >=0) {
echo "<a href='yourpage.php?start=$back'><font face='Verdana' size='2'>PREV</font></a> ";
}
//code for the number of page with links
$i = 0;
$x = 1;
for($i=0;$i < $total_rows;$i=$i+$limit){
if($i != $eu){
echo "<a href='yourpage.php?start=$i'><font face='Verdana' size='2'>$x</font></a> ";
}else {
echo "<font face='Verdana' size='4' color=red>$x</font>";
} // Current page is not displayed as link and given font color red
$x = $x+1;
}
//code for next
if($whathis < $total_rows) {
echo "<a href='yourpage.php?start=$next'><font face='Verdana' size='2'>NEXT</font></a>";
}
?>
Saturday, December 13, 2008
Create Image Thumbnails Using PHP and GD
The following PHP code will create thumbnail images on the fly and since it uses the PHP GD2 library, you will need an installation of PHP with at least GD 2.0.1 enabled.. Some says that the only drawback to using PHP for image creation is that the thumbnails don’t look as good as thumbnails created in Photoshop or GIMP but this simple block of code would prove them wrong...
<?php
header ("Content-type: image/jpeg");
$image = $_GET['img'];
if (!$im)
readfile($image);// return the actual message if error occurs.
else {
// Create the resized image destination
$thumb = @ImageCreateTrueColor ($w, $h);
// Copy from image source, resize it, and paste to image destination
@ImageCopyResampled ($thumb, $im, 0, 0, 0, 0, $w, $h, $sw, $sh);
// Output resized image
@ImageJPEG ($thumb);
}
?>
save the above code as image_thumb.php.
Usage:
<--without specifying the width and height-->
<img src="http://www.example.com/image_thumb.php?img=example.jpg" />
<--with height and width-->
<img src="http://www.example.com/image_thumb.php?img=example.jpg&w=200&h=200" />
<?php
header ("Content-type: image/jpeg");
$image = $_GET['img'];
if(!isset($w) && !isset($h)){
$w = 100; //default width if $w is not set
$h = 125; //default height if $h is not set
}
$x = @getimagesize($image);// get image size
$sw = $x[0];// width
$sh = $x[1];// height
$im = @ImageCreateFromJPEG ($image) or // Read JPEG Image
$im = false; // If image is not JPEG
$w = 100; //default width if $w is not set
$h = 125; //default height if $h is not set
}
$x = @getimagesize($image);// get image size
$sw = $x[0];// width
$sh = $x[1];// height
$im = @ImageCreateFromJPEG ($image) or // Read JPEG Image
$im = false; // If image is not JPEG
if (!$im)
readfile($image);// return the actual message if error occurs.
else {
// Create the resized image destination
$thumb = @ImageCreateTrueColor ($w, $h);
// Copy from image source, resize it, and paste to image destination
@ImageCopyResampled ($thumb, $im, 0, 0, 0, 0, $w, $h, $sw, $sh);
// Output resized image
@ImageJPEG ($thumb);
}
?>
save the above code as image_thumb.php.
Usage:
<--without specifying the width and height-->
<img src="http://www.example.com/image_thumb.php?img=example.jpg" />
<--with height and width-->
<img src="http://www.example.com/image_thumb.php?img=example.jpg&w=200&h=200" />
Subscribe to:
Posts (Atom)
