Spiga

‘ Programing ’ category archive

[php class review] Relink – Rewrite URLs based on mod_rewrite configuration

November 02, 08 by Gabi Solomon

view this article in romanian

I have an email subscription to phpclasses email newsletter, and read it to see what new classes have been added to the site. And once in a while i will find interesting and innovative classes. Like today when between the classes that won the Innovation award was one that caught my attention.

The class developed by Benjamin Falk that he called Relink is a very interesting and useful tool in my opinion.

Lets say that you have a website and after you build it you want to make some SEO for it. That usually involves modifying all the links in the website. And that is quite a task. But what if you are like me and know a few things about SEO but are no expert, and somewhere down the line you either hire a SEO expert or receive an expert advice and want to change all those links ? Another time spent on tedious task of find and replace. And if we are talking about a larger project than that could be quite a big time.

Well what this class enables you to do is to make your links dynamically generated based on your .htaccess configuration. Let be more specific, first you must initialize the class

PHP:
  1. require_once 'class.relink.php';
  2.  
  3. $htaccessFile    = './htaccess-example';
  4. $c_relink        = new RELINK($htaccessFile);
  5.  
  6. // If you leave the $htaccessFile empty it will automatically take the .htaccess file from the current directory.

Then everywhere in the script where you have a link you will put something like

PHP:
  1. echo '<a href="'.$c_relink-&gt;replaceLink('?page=blog').'">View blog</a> | ';
  2. echo '<a href="'.$c_relink-&gt;replaceLink('?page=blog&amp;mode=edit').'">Edit Blog</a> | ';
  3. echo '<a href="'.$c_relink-&gt;replaceLink('?info&amp;value=all').'">Show all information</a>';

I didn't use it in any projects so far but I think i will do it on my next project.
Hope this new class is as interesting to you as it was to me.

Cheers

PHP – convert Microsoft word doc to pdf

September 08, 08 by Gabi Solomon

A lot of people are searching for solution to do this conversion on the fly. I dont know any other programing languages except PHP so i will write only about how you can do this in PHP.

Now to do this there is 2 major situations:
1. Doing it on a windows Server
2. Doing it on a linux Server

In both cases the chanses are that you need to have root access to the server in order to do all the settings required for this conversion.

In case of windows you can use COM objects to acces either Word or OpenOffice and do the conversion. Here peek of a code to access OpenOffice API to do the conversion:

PHP:
  1. <?php
  2. function MakePropertyValue($name,$value,$osm){
  3. $oStruct = $osm->Bridge_GetStruct("com.sun.star.beans.PropertyValue");
  4. $oStruct->Name = $name;
  5. $oStruct->Value = $value;
  6. return $oStruct;
  7. }
  8. function word2pdf($doc_url, $output_url){
  9. //Invoke the OpenOffice.org service manager
  10. $osm = new COM("com.sun.star.ServiceManager") or die ("Please be sure that OpenOffice.org is installed.\n");
  11. //Set the application to remain hidden to avoid flashing the document onscreen
  12. $args = array(MakePropertyValue("Hidden",true,$osm));
  13. //Launch the desktop
  14. $oDesktop = $osm->createInstance("com.sun.star.frame.Desktop");
  15. //Load the .doc file, and pass in the "Hidden" property from above
  16. $oWriterDoc = $oDesktop->loadComponentFromURL($doc_url,"_blank", 0, $args);
  17. //Set up the arguments for the PDF output
  18. $export_args = array(MakePropertyValue("FilterName","writer_pdf_Export",$osm));
  19. //Write out the PDF
  20. $oWriterDoc->storeToURL($output_url,$export_args);
  21. $oWriterDoc->close(true);
  22. }
  23. $output_dir = "C:/dev/openofficeintegration/docconverter/";
  24. $doc_file = "C:/dev/openofficeintegration/docconverter/DpmR5Reqv1.20.doc";
  25. $pdf_file = "DpmR5Reqv1.20.pdf";
  26. $output_file = $output_dir . $pdf_file;
  27. $doc_file = "file:///" . $doc_file;
  28. $output_file = "file:///" . $output_file;
  29. word2pdf($doc_file,$output_file);
  30. ?>

Now in case of linux things get a little more tricky, not by much but they do. You cant user COM objects any more but you can still install OpenOffice and its API in extension with a python script.

PyODConverter, for Python OpenDocument Converter, is a Python script that automates office document conversions from the command line using OpenOffice.org.

The script does basically the same thing as the command line tool that comes with JODConverter but is much simpler. In fact the Python script was released for the people who use JODConverter only from the command line (not as a Java library or web service) and would like a simpler alternative.

To check out the full documentation and download the script go here.

Covertor for php5

As i was doing research to do this post i found out of yet another solution, but this is only available for php5, but it works for both lynux and windows. Its a php module written in C++ called Punno.

This project is a PHP5 module written in C++ that brings the OpenOffice.org UNO Programming API to the PHP userspace.

You can use it to write scripts that create, modify, read and save OpenOffice.org documents (Writer, Spreadsheet, Drawing). Also, you can export these documents in various formats, like PDF or HTML for example.

It can be installed on any Linux/Unix or Windows platform where PHP5 and OpenOffice.org are also available.

It is released under PHP License 3.01.

That is it.

Do you know of any other solutions to do a doc to pdf conversion using php ?

How to protect your php applications for free ?

August 25, 08 by Gabi Solomon

Did you developed a very cool application, and maybe thought about selling it ?
If you did you might have thought: How will i protect my code ?
Because the php code is visible and can be distributed really easy, once it has been downloaded once.

Well there are solutions to do this, but most of them are not free, and if your application is not a really expensive one it doesn't make sense to pay more on the software to protect the code then the actual selling price.

Well you are in luck, because there is a php class called PADL (PHP Application Distribution License System) that generates PHP application license keys.

This class can used to generate license style keys to control the distribution and functionality of PHP applications.

It generates license strings that can bind PHP applications to specific domains, specific servers, can only be executed during limited time period, or to restrictions placed on a home server within the license key.

The binding to server process attempts to use the server network card MAC address. This feature was tested on servers are Mac OS X (Darwin), Linux, Windows XP, although it may also work for FreeBSD, NetBSD, Solaris.

PADL also attempts to use information from $_SERVER variable to encode that server name, server IP, server application path and server application url to the license key. Part of the process also binds the IP Address from the $_SERVER variable if found, but it also attempts to parse the server config file (the same used to get the MAC address) for any more IPs.

The server binding can be disabled if required, and it also possible to block the key being generated for the localhost address (127.0.0.1).

The time limiting of the license uses a start period (and a given start offset to allow for time discrepancies) and an expiry date if required.

If required when validating a key it is also possible to dial home to check the license key on your own PADL License Server, examples are given.

The PHP_OS and PHP_VERSION of the php that the key was generated for is also encrypted into the key.

It is also possible to encrypt additional information into the license key to enable you to place restrictive features in your application to allow the creation of trialware or demoware.

This class is still in development however it is stable. A GUI is to follow.

This class received the Php Classes Innovation Award, and is ranked 98 in the same website, so this is why i highly recommend this class to protect your code.

Hope like this class as well,
Cheers

MYSQL: make a combination of 2 columns unique

August 19, 08 by Gabi Solomon

Here is a recently situation i came across, what if you have a table and you want to make a combination of 2 columns unique. The columns Individually are not unique, but combination is.

To alter 1 column to a unique key you would use :

SQL:
  1. ALTER TABLE user MODIFY COLUMN id INT NOT NULL UNIQUE;

Well for a combination of 2 or more columns to be unique you would use:

SQL:
  1. ALTER TABLE user ADD UNIQUE (id,domain);

Hope this helps you.
Cheers

SQL Query : Copy one Column to another column in MySQL

by Gabi Solomon

I wanted to do add a new column to a table and to copy the values from that a diferent to column ( from the same table ) to the new column. And even though i thought of very integrates query's at first, the solution was quite simple :D ( as always ).

SQL:
  1. ALTER TABLE `table_name` ADD `new_column` TEXT NOT NULL;
  2.  UPDATE `table_name` SET `new_column` = `old_column`;

Nice and simple.
Cheers

how to: Generating XML from PHP

August 15, 08 by Gabi Solomon

I had to do a small REST application on a project recently and i wanted to find a small easy way of returning the response in XML.

After a little searching find this rather old post ( but just what i was looking for ) on Simon Willison’s Weblog. It featured a small php class to generate XML.

Example Code

PHP:
  1. $array = array(
  2.     array('monkey', 'banana', 'Jim'),
  3.     array('hamster', 'apples', 'Kola'),
  4.     array('turtle', 'beans', 'Berty'),
  5. );
  6. $xml = new XmlWriter();
  7. $xml->push('zoo');
  8. foreach ($array as $animal) {
  9.     $xml->push('animal', array('species' => $animal[0]));
  10.     $xml->element('name', $animal[2]);
  11.     $xml->element('food', $animal[1]);
  12.     $xml->pop();
  13. }
  14. $xml->pop();
  15. print $xml->getXml();

XML returned

XML:
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <zoo>
  3.   <animal species="monkey">
  4.     <name>Jim</name>
  5.     <food>banana</food>
  6.   </animal>
  7.   <animal species="hamster">
  8.     <name>Kola</name>
  9.     <food>apples</food>
  10.   </animal>
  11.   <animal species="turtle">
  12.     <name>Berty</name>
  13.     <food>beans</food>
  14.   </animal>
  15. </zoo>

Attention

A little heads up, if your running php you might encounter this error:

Fatal error: Cannot redeclare class xmlwriter in /var/www/web4/cgi-bin/includes/XmlWriter.class.inc on line 6

Thats because php already has a built in php class called xmlwriter, to fix it all you need to do is rename it.

hope this helps somebody.
Cheers

How to Find and Replace Text in MySQL Table using SQL

August 05, 08 by Gabi Solomon

The database engine MySQL has a string function called REPLACE that performes similar to the php function str_replace(). This really comes in handy when you want a certain text replaced in a table data, either being a name or a certain uinique number or maybe some speling mistake.

Syntax

MySQL reference :

REPLACE(str,from_str,to_str)

Returns the string str with all occurrences of the string from_str replaced by the string to_str. REPLACE() performs a case-sensitive match when searching for from_str.

This function is multi-byte safe.

Examples:

update `orders_table` set `traking_id` = replace(`traking_id`, ‘1111111’, ‘999999999’);
// this will replace all the 1111111 with 999999999 in the table orders_table for the column traking_id

SELECT REPLACE(’www.mysql.com’, ‘w’, ‘Ww’);
Above statement will return ‘WwWwWw.mysql.com’ as result.

It is easy to work around a web development software, all you need to know is the basis of website design. Hire a web design manager if you cannot figure that out and proceed with website hosting. Once done with that, you can move on with internet marketing.

How to make money online

August 04, 08 by Gabi Solomon

Sorry for those of you that got hear thinking you will get a great scheme on how to make easy / no work money online, this is how to make money working :D .

This article is for people who are Programmers, designers or editors.
Some companies want to subcontract some of there work to other smaller companies, process called outsourcing.
But instead of doing to a different company's instead of outsourcing works to a company , plan to outsource the work directly to programmers like you using specialized websites that act like a market place for company's and freelancers .

There are a lot of such websites out there, but a few have managed to climb and stay in the Top 5. I will try and do a small review of them. As a note this is my personal top 5, not an official one.

1. Odesk

The On Demand Global Workforce - oDesk
This is one of may favorite freelancing websites, and it got good reviews from a lot of websites and magazines. It is very popular because it has some build in features that are not found on other websites like:
- hourly payd jobs ( that are guaranted );
- desktop client that tracks hours worked for hourly projects
- free professional test for providers to show theyr skills
and much more

You can see a more detailed tour of odesk here.

2. getafreelancer.com

Get custom programming done at GetAFreelancer.com!

A very well famous website, which is very nice because you will get many projects to choose from. It suports escrow payments wich is nice to limit your "do the job, not get payed" situations, and has a few payment methods such as GetAFreelancer.com Debit card, PayPal, Moneybookers.com, E-Gold, Wired Transfer.

3. eufreelance.com

Earn Money with EUFreelance.com!

This is the same company as getafreelancer.com but its intead for europe because the currency you get payed is euros wich is nice especially for me because in my country the dollar has sunk to quite a low rate.

4. rentacoder.com

Yet another famous website, RAC features literally thousands of open projects, available in fields ranging from Data Entry to Writing to Web Design to Programming. RentACoder is probably one of the best freelance web site around, so be sure to sign up here.

5. scriptlance.com

Find freelance programmers at ScriptLance.com - Search worldwide

This a new websites i signed on for, havent really tested it out. ScriptLance is a project web site in which freelancers can bid on projects and then complete them and get paid. This site isn’t quite as
reliable as RentACoder, as funds aren’t always escrowed like on RAC, but it is still a site worth checking out. Project fees are usually $5, which is very cheap.

That is it about making money online and freelancin, hope you enjoyed it.

I know some of you might not like these these websites, because of the low quotes that are found there, but i believe they have there purpose, and by making some projects on this website you can potentially find some contractors that will give you constant flow of projects in the future and you will build your online reputation in the process as well.

I might be wrong, but this is my perspective on freelancing websites.
Cheers.

How to Create a zip file with php on the fly

July 31, 08 by Gabi Solomon

For a future project I needed these days some easy to use zip or gzip class to create a zip file from files / folders inside a specified directory. A short search on Google has lead me to the Create ZIP File PHP class from Rochak Chauhan.

This class can create ZIP archives from lists of files.

The class provides means to add individual files or whole directories to the list of files packed into a ZIP archive.

The class can generate the packed archive as a string value.

The class can also output the necessary request response headers to serve the generated ZIP archive for download.

The supplied example demonstrates how to use the class to store the ZIP archive in a file, serve it for download and delete the file after it is served.

Example of usage

PHP:
  1. <?php
  2.  
  3. include_once("createZip.inc.php");
  4. $createZip = new createZip; 
  5.  
  6. $createZip -> addDirectory("dir/");
  7.  
  8. $fileContents = file_get_contents("img.jpg")
  9. $createZip -> addFile($fileContents, "dir/img.jpg")
  10.  
  11.  
  12. $fileName = "archive.zip";
  13. $fd = fopen ($fileName, "wb");
  14. $out = fwrite ($fd, $createZip -> getZippedfile());
  15. fclose ($fd);
  16.  
  17. $createZip -> forceDownload($fileName);
  18. @unlink($fileName);
  19. ?>

How to learn computer programming with Alice ?

July 30, 08 by Gabi Solomon

As most of you know computer programming is not an easy subject and most of the time people dont get into it because they cant understand teh concepts or they find it to boring.

Well Carnegie Mellon University has thought about this and developed and is distributing for free a praject call Alice. Alice is "designed to be a student's first exposure to object-oriented programming." The original version is designed for high school and college students; there's also a modified version geared for middle school students.

With the original version of Alice, kids can create movies and simple video games; the drag-and-drop design makes syntax errors less likely and easier to correct.

Alice is an innovative 3D programming environment for building animations in the form of stories, games, and web-ready videos. Alice teaches programming. Alice version 2.0 is in common use. Alice 3.0 is in active development with a projected launch date of August 2009.

Alice 2.0 has been very successful and enjoyed an adoption rate of 10% in US colleges and is expanding rapidly into high schools. We expect Alice 3.0 to surpass this mark considerably.

You can watch a full presentation and demostration of Alice 3.0, Introductory Programming in 3D on youtube by cliking this link.

Alice presentation video

Alice FPS game example