Spiga

‘ php&mysql 101 ’ category archive

determining the application root path and url in php

December 13, 08 by Gabi Solomon

If you buid any web application you will eventually need to find a way to specify the application root path and URL. This is inevitable if you don't build your links in a relative way ( by unsing ./ and ../ combinations ), and also if you want to have a way of keeping things organized and working even if you move script to a new server or in a folder.

Well there are several ways you can do this. The first one would be to write them in a config file by hand, and edit them as you move the project.

PHP:
  1. define('ROOT_PATH', '/home/user/public_html/folder/');
  2. define('PROJECT_DIR', '/folder/');
  3. define('BASE_URL', 'http://' . $_SERVER['HTTP_HOST'] . PROJECT_DIR);

But even if that works well, it will give a bit of work when you move the application since you have to edit them by hand.
So the next method would be to have them be generated automatically. The ROOT_PATH is relatively easy to determine . What i do is have a directory called config in wich i place my config files, in it i have one called main_config.php which includes the rest of the config files. One of them is called paths.php.
Now to determine the root_path i use a function called dirname() and the __FILE__ constant.

PHP:
  1. define('ROOT_PATH', dirname(dirname(__FILE__)));
  2. define('PROJECT_DIR', '/folder/');
  3. define('BASE_URL', 'http://' . $_SERVER['HTTP_HOST'] . PROJECT_DIR);

Now we have the root_path solved and base_url to some extend, but need to specify the project directory.
We can solve that too automatically.

PHP:
  1. define('ROOT_PATH', '/home/user/public_html/folder/');
  2. $projectDir = implode('/', array_intersect(explode('/', $_SERVER["REQUEST_URI"]), explode('/', str_replace('\\', '/', ROOT_PATH))));
  3. if ($projectDir[strlen($projectDir)-1] != '/') {
  4.         $projectDir .= '/';
  5. }
  6. define('PROJECT_DIR', $projectDir);
  7. define('BASE_URL', 'http://' . $_SERVER['HTTP_HOST'] . PROJECT_DIR);

What that code does is take the ROOT_PATH that we defined and the REQUEST_URI from the server global variable and do an intersection of them to determine the project dir.

Hope this small snippet helped you.
Cheers

Connection Interrupted

November 16, 08 by Gabi Solomon

A few weeks ago as i was working on a project i got a message in firefox that said :

Connection Interrupted
The connection to the server was reset while the page was loading.
The network link was interrupted while negotiating a connection. Please try again.

I was a little puzzled since i never saw this one before. So i did a little googling search and debugging i find out the cause :D

There was a infinite loop in my code.

I know silly me, but hope you manage to stumble upon this when you get in the same situation.
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

SQL Query : Copy one Column to another column in MySQL

August 19, 08 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 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. ?>

List Files In A Directory Using PHP

May 29, 08 by Gabi Solomon

Usually Apache will list all the files in a directory that doesnt have an index, unless the -indexes option is activated. Never the less sometimes in your programing you will need to list the files that are in a directory, not on the screen necessarily but at least save those files in a variable.

But enough small talk lets gets on with the actual code :

PHP:
  1. <?php
  2. $fileList=array();
  3. $dirPath='/path/to/your/dir/';
  4.  
  5.  if ($handle = opendir($dirPath)) {
  6.    while (false !== ($file = readdir($handle)))
  7.       {
  8.           if ($file != "." && $file != "..")
  9.       {
  10.             $fileList[] = $file;
  11.           }
  12.        }
  13.   closedir($handle);
  14.   }
  15. ?>
  16. <h3>List of files:</h3>
  17. <?php foreach ( $fileList as $f ) : ?>
  18. <P><?=$f?></p>
  19. <?php endforeach; ?>

Is that simple.

Cheers

Custom Error Documents with .htacces

May 24, 08 by Gabi Solomon

Some people only know about .htaccess utility in apache rewrite, but it can do more than that. For example it can help you specify your own Error Documents. When ever a browser makes a request for a web document ( webpage, files, images, css files etc) the server returns a header that contains an error code that tells the browser details about the requests. I will list this codes below:

Successful Client Requests
200 OK
201 Created
202 Accepted
203 Non-Authorative Information
204 No Content
205 Reset Content
206 Partial Content
Client Request Redirected
300 Multiple Choices
301 Moved Permanently
302 Moved Temporarily
303 See Other
304 Not Modified
305 Use Proxy

Client Request Errors
400 Bad Request
401 Authorization Required
402 Payment Required (not used yet)
403 Forbidden
404 Not Found
405 Method Not Allowed
406 Not Acceptable (encoding)
407 Proxy Authentication Required
408 Request Timed Out
409 Conflicting Request
410 Gone
411 Content Length Required
412 Precondition Failed
413 Request Entity Too Long
414 Request URI Too Long
415 Unsupported Media Type

Server Errors
500 Internal Server Error
501 Not Implemented
502 Bad Gateway
503 Service Unavailable
504 Gateway Timeout
505 HTTP Version Not Supported

In order to In order to specify your own ErrorDocuments, you need to know these error codes, since you will need to specify for wich error code you want to assign a page.

But you wont need to specify an error page for all those codes, You only might want to do a custom error page for the most common of them like 404 and 500. Also most people do a custom Error Document for
401 - Authorization Required ( for sections of the site that are protected by a folder password and somebody tries to enter a protected area without corect login details ),
403 - Forbidden ( for example when someone is trying to access a folder withough an index option )
400 - Bad Request, which is one of those generic kind of errors that people get to by doing some weird stuff with your URL or scripts.

The advantage of having custom error documents is that you can display to the user a custom page with the site layout ( instead of the simple default one ) and you can even build a script to make custom logs of this errors.

You shouldn't make custom pages for all error codes, for example an ErrorDocument for code 200 would cause an infinite loop, whenever a page was found...this would not be good.

To specify your custom error documents, you will add a special command for this in the htaccess file:
ErrorDocument [code] /directory/errorDocument.html

For example an error document for 404 would be:
ErrorDocument 404 /errors/404.html

Now you told the server that when it has an error code of 404 to return the page http://yoursite.com/errors/notfound.html. The same principle apply's to all the codes.

As a small advice i would recommend you make a special folder for your error documents and also name them something that will show theyr error code and purpose. I put 404.html but you can do notFound.html for example. Also the error documents do not need to be html they can also be php,asp or other types of files.

If you dont want to make a special file you can add the html directly in .htaccess file
ErrorDocument 401 "<body> You have to to be a member to view this page.

To do this you need to keep in mind :
the ErrorDocument starts with a " but does not end with one ... that was not a typo :)
the command should be on one line, including the HTML