Friday, December 4, 2009

PHP - Youtube to mp3 Conversion PART-2

In the previous part we have generated the downloading url.

There are some technical facts. You have to download the video on the server to actually convert the videos into mp3.

Tempvids is the directory to store temporary flv videos before conversion

So here is the code which can be used to download the video file on your server.

$data = file_get_contents($download_link);

$gets=$_GET['vid'].'.mp3';

$new_flv_path = dirname(_FILE_).'/tempvids/'.$_GET['vid'].'.flv' ;

file_put_contents($new_flv_path, $data);

At last you must require ffmpeg to convert flv into mp3 and provide them to the user for download.

exec("ffmpeg -i tempvids/".$_GET['vid'].".flv -vn -acodec copy ".$_GET['vid'].".mp3");

Few Tips:

  • The download of the video is a time consuming process so the speed of the script depends on your server's downloading/transfer rate.

Sunday, September 20, 2009

Build Spider/Crawler with PHP




PHPCrawl is a set of classes written in PHP for crawling/spidering websites, so just call it a webcrawler-library for PHP.



SOLUTION




The crawler "spiders" websites and delivers information about all found pages, links, files and so on to users of the library. By overriding a special method of the main-class users now decide what should happen to the pages and their content, files and other information the crawler finds.

PHPCrawl povides a lot of options to specify the behaviour of the crawler like URL- and Content-Type-filters, cookie-handling, limiter-options and much more.


Download: http://sourceforge.net/projects/phpcrawl/


PHP Example:

The following code is an complete example for using the class.
The listed script "crawls" a site and just prints out some information about found pages.

Please note that this example-script also comes in a file called "example.php" with the phpcrawl-package.

<?php

// It may take a whils to crawl a site ...
set_time_limit(10000);

// Inculde the phpcrawl-mainclass
include("classes/phpcrawler.class.php");

// Extend the class and override the handlePageData()-method
class MyCrawler extends PHPCrawler
{
function handlePageData(&$page_data)
{
// Here comes your code.
// Do whatever you want with the information given in the
// array $page_data about a page or file that the crawler actually found.
// See a complete list of elements the array will contain in the
// class-refenence.
// This is just a simple example.

// Print the URL of the actual requested page or file
echo "Page requested: ".$page_data["url"]."<br>";

// Print the first line of the header the server sent (HTTP-status)
echo "Status: ".strtok($page_data["header"], "\n")."<br>";

// Print the referer
echo "Referer-page: ".$page_data["referer_url"]."<br>";

// Print if the content was be recieved or not
if ($page_data["received"]==true)
echo "Content received: ".$page_data["bytes_received"]." bytes";
else
echo "Content not received";

// ...

// Now you should do something with the content of the actual
// received page or file ($page_data[source]), we skip it in this example

echo "<br><br>";
flush();
}
}

// Now, create an instance of the class, set the behaviour
// of the crawler (see class-reference for more methods)
// and start the crawling-process.

$crawler = &new MyCrawler();

// URL to crawl
$crawler->setURL("www.php.net");

// Only receive content of files with content-type "text/html"
// (regular expression, preg)
$crawler->addReceiveContentType("/text\/html/");

// Ignore links to pictures, dont even request pictures
// (preg_match)
$crawler->addNonFollowMatch("/.(jpg|gif|png)$/ i");

// Store and send cookie-data like a browser does
$crawler->setCookieHandling(true);

// Set the traffic-limit to 1 MB (in bytes,
// for testing we dont want to "suck" the whole site)
$crawler->setTrafficLimit(1000 * 1024);

// Thats enough, now here we go
$crawler->go();


// At the end, after the process is finished, we print a short
// report (see method getReport() for more information)

$report = $crawler->getReport();

echo "Summary:<br>";
if ($report["traffic_limit_reached"]==true)
echo "Traffic-limit reached <br>";

echo "Links followed: ".$report["links_followed"]."<br>";
echo "Files received: ".$report["files_received"]."<br>";
echo "Bytes received: ".$report["bytes_received"]."<br>";

?>


Characters Calculation of PDF Document with PHP




In this tutorial, We wil convert the document format also. We will convert pdf to text file
through php and then read its content to calculate the number of characters in the file.



SOLUTION




It is quite simple to calculate characters of a pdf document. To accomplish this task. I will
use pdf2html Linux Library.
Please download and install pdf2html library from http://sourceforge.net/projects/pdftohtml/


Code to execute pdf conversion and characters calculation.

Linux command execution to convert the pdf to text format.

'/usr/bin/pdftotext ' . $file_path; //File path must be the absolute server path.

PHP
shell_exec('/usr/bin/pdftotext ' . $file_path);


Complete code to upload a file to the processed folder in your root directory.

if(move_uploaded_file($_FILES[$filen]['tmp_name'],'processed/'.$_FILES[$filen]['name'])){

$file_name=$_FILES[$filen]['name'];
$file_path=$_SERVER['DOCUMENT_ROOT'].'/processed/'.$_FILES[$filen]['name'];


$file_name=str_replace('.pdf','.txt',$file_name);

$output=shell_exec('/usr/bin/pdftotext ' . $file_path);

sleep(2);
$handle = fopen($file_name, "r");
$contents = fread($handle, filesize($file_name));
fclose($handle);
$file_count = strlen(str_replace(' ','',$contents));



}

TroubleShooting

1. shell_exec function will not execute. If you don't have permission to run ssh commands
and also if your php is running in the safe mode.

2. This script will generate a text file with same name and directory where you have placed
the pdf file. So if the file isn't create in that directory and your program will work you
will able to track the file in the root directory. This means you have to correct your
file path.

3. Cannot count the calulation and upload the file. It is necessary to change the rights
of processed folder to 777.

If you have further questions about this post, kindly post your comments.


Define Constants in Codeigniter.




Defining contants in codeigniter is easy but according to my point of view, I don't like the procedure. But I have to provide solution to those who want to use constants.



SOLUTION




You can define the constants in the index.php present in the root directory of codeigniter. You can also include constant files in the index file.



Codeigniter has define some in its core constants in the index file.

define('EXT', '.'.pathinfo(__FILE__, PATHINFO_EXTENSION));

define('FCPATH', __FILE__);

define('SELF', pathinfo(__FILE__, PATHINFO_BASENAME));

define('BASEPATH', $system_folder.'/');

Tuesday, September 1, 2009

Magento 5 Common Errors and Solutions.


Five Common Errors in Magento. Tweak your application for better performance

INTRODUCTION



Magento is an Ecommerce platform built for open-source technology.It is build on zend frame work.While using MAGENTO you face very common errors for example installation errors or Magento cannot login to the admin etc. which may create problems in application. Here are five common errors and their solutions

Error 404 after installation of sample data (while home page is OK)

solution:

You will need to do one of two things:

  1. Refresh catalog rewrites - Admin > System > Cache > Refresh catalog rewrites. If this doesn’t work then >

  2. Turn off URL Rewrites - Admin > System > Web > SEO > NO


When you go the Magento Connect Manager in your Admin Panel, you may get the following error message:

Error: Please check for sufficient write file permissions

solution:-

Magento Connect requires write permissions to the Magento files in order to install new extensions or upgrade the software to a new version. You can change your file/folder permissions either thru your FTP Client (like FileZilla) OR thru a SSH client (like Putty).

Go inside your Magento folder & change permissions of ALL FILES & FOLDERS RECURSIVELY to "777".

Here's how to do this thru your SSH client. Log in to your SSH account and then execute the following commands:

cd
find . -type d -exec chmod 777 {} \;
chmod 666 downloader/config.ini

You should now be able to access the Magento Connect Manager. When you have finished the installation/upgrade, you should reset the permissions by executing the following SSH commands:

find . -type d -exec chmod 755 {} \;
find . -type f -exec chmod 644 {} \;
chmod o+w var media app/etc/use_cache.ser

Magento error — Notice: Undefined index: 0 in app/code/core/Mage/Core/Model/Mysql4/Config.php on line 92

Solution:-


This will most likely occur when migrating Magento from one host to another. The fix, while not so obvious and easy t find turned out to be quite easy ;) During the installation, Magento sets two IDs to 0 in its database. However, when importing the database dump to your new host, MySQL doesn’t like this and changes these ID’s to 2, which of course is not what Magento needs to load, thus the error. The fix is quite easy — set these IDs back to 0.

The IDs, we need are for ‘admin’ in the tables:

* core_store
* core_website

Just open phpMyAdmin and change 2 to 0, clear Magento’s cache by deleting the contents of the /var/cache folder and Voila!

Also, it will be a good idea to check the box for “Disable foreign key checks”, when exporting it in the firt place, as you will surely receive an error for this when importing ;)

Mgento commerce: object not found:-

solution:-

If you just installed Magento and receive an “Object Not Found” 404 error with ever link you click, it’s because mod_rewrite is not enabled on your server. Tell your hosting provider to turn it on if you’re on shared hosting. If you’re using XAMPP,

By default mod_rewrite module is not enabled in apache with XAMPP.

To enable mod_rewrite in xampp first go to the directory of installation \apache\conf and edit httpd.conf. Find the line that contains
#LoadModule rewrite_module modules/mod_rewrite.so
uncomment this(should be):

LoadModule rewrite_module modules/mod_rewrite.so

Also find AllowOverride None

Should be:

AllowOverride All

AllowOverride appears 2 or 3 times on the configuration file. Change all of them.

Magento cannot Login to the admin:-

solution:-

The solution is to add the following line to your hosts file so you can access your localhost as www.localhost.com.

C:Windows\System32\drivers\etc\hosts (edit this file in notepad)

127.0.0.1 magento.localhost.com www.localhost.com

Also worth mentioning, if you need to reset a password manually in the database use the following:

UPDATE admin_user SET password=MD5(‘mypassword’) WHERE username=‘admin’;

If none of the above works, install the browser Opera and use it. Opera seems to work out of the box whereas IE, Firefox, and Google Chrome do not.

Monday, August 31, 2009

PHP Welcome Java


Java Integration with php is a lot easier with PHP/JAVA Bridge.


INTRODUCTION




The PHP/Java Bridge is an implementation of a streaming, XML-based network protocol, which can be used to connect a native script engine, for example PHP, Scheme or Python, with a Java or ECMA 335 virtual machine. It is more than 50 times faster than local RPC via SOAP, requires less resources on the web-server side. It is faster and more reliable than direct communication via the Java Native Interface, and it requires no additional components to invoke Java procedures from PHP or PHP procedures from Java. Download it from: PHP/JAVA BRIDGE


PHP/Java integration


The Java.inc PHP library sets up an autoload handler to import Java into PHP's environment. The following example autoloads the standard Java classes from Java and makes them available to PHP.


<?php
use java\lang\String as JString;
use java\lang\ArrayList as JList;

class String extends JString {
function toString () {
return "hello " . parent::toString();
}
}
$str = new String("Java");

$list = new JList();
$list->add (java_closure($str));
$list->add ("from PHP");
$ar = java_values ($list->toArray());

var_dump($ar);
?>

=>array ["hello Java", "from PHP"]



It makes use of the syntax transformer built into PHP 5.3 and above to import and extend the functionality of Java classes. In the above example java.lang.String is extended by a PHP class, overriding the functionality of its toString() method. An instance of this class is then passed to a java.lang.ArrayList. The entire list is then converted into a PHP scalar value using java_values.


Oh! Please don't blame Joomla.


A Fatal Error which is becoming a cause to avoid Joomla. I have tested and find the exact problem.


INTRODUCTION




"Fatal Error: Call to a member function call() on a non-object". I have checked several blogs and also joomla community is discussing this issue. This issue is not related to php,Joomla version etc. So don't blame your hosting service provider and Joomla. A thing which is very surprising that Professional Joomla Developers are also not abl to figure out this problem.


This issue is directly related with the template of joomla. This fatal error can occur when the template configuration file will get delete or not uploaded at the server by you. Kindly confirm that you have uploaded params.ini. Place this file in the template folder and Joomla will not show error like this in the future.


Friday, August 28, 2009

PDF to HTML Conversion.

Convert PDF to HTML. Boost your online proofreading business and add pdf as an automated format for your proofreading website.


INTRODUCTION



It was difficult to calculate or to convert any pdf document to html. It is quite easy approach to convert from html to pdf. Now it is also possible on both of the system to create html files from pdf with php.

Automation Process
You need to install an executable based on xpdf to accomplish this task.
Here is the url of the package: PDFTOHTML PACKAGE
After the installation of the package use the following command to execute it.

There are 2 ways or commands I will prefer.

You can also execute these commands from SSH or PHP script. We will focus at php script command execution.

Lets consider the installed files are present in /usr/bin.


  • system('/usr/bin/pdftohtml /var/www/website/processed/example.pdf') // This will create a HTML file in the processed folder.


  • system('/usr/bin/pdftohtml /var/www/website/processed/example.pdf -') // This command will not create an HTML file but it will show the output of the file at screen.


Few Common Errors

  1. BAD Color Error: This error usually appear if the package doesn't install properly.
  2. Execution Error: It is also a common error that php doesn't execute the command and output file doesn't generate. To solve this error you need to confirm few things.
    • Confirm php is not running in the safe mode.
    • You must execute the command as root. So you also need to set the apache securities.


Uploading huge sql files.

Insert huge data into mysql database. It is very simple to upload the big sql files by accessing and executing through SSH.

INTRODUCTION

It is a common practice for the developers to upload huge sql data at remote server. Sometimes it become a very big problem, when phpmyadmin has max upload size 2MB and also php upload size is set at 2MB. You can do it very easily with SSH.




Upload a file through your ftp account in any directory.

For Example:

backup.sql to /htdocs/sqlcommand/

Now connect through SSH using putty.

Use the following command to upload the database.


mysqldump --opt --user=username --password database < backup.sql


This will upload the data present in your mysql file with in no time.

Parameters Details:

--user=username // Database Username

--password // Database password

database // Database Name

backup.sql // Sql file you want to upload.


Wednesday, August 26, 2009

Fix PNG issue IE6

IE6 doesn’t have the ability to render png. To fix the png issue of CSS and HTML images and DIV tags Kindly use approved and tested techniques that we will discuss today.

We are going to implement iepngfix. You can download it for free from http://www.twinhelix.com/css/iepngfix/

This uses CSS "behaviors", a custom Microsoft extension to CSS. As such, it will not affect any other browsers like Mozilla and Opera which already implement good PNG support. It will also not help IE4.0 and IE5.0, which don't include the necessary IE filter, and does nothing with IE5/Mac (which natively supports translucent PNG foreground images, however).

Installation:

Follow these simple steps to add this to your page:

  1. Copy and paste iepngfix.htc and blank.gif into your website folder.
  2. Copy and paste this into your website's CSS or HTML:

That CSS selector must include the tags/elements on which you want PNG support -- basically, give it a comma-separated list of tags you use. It must also include the correct path to the .HTC relative to the HTML document location (not relative to the CSS document!). For instance, yours may look like this:

  1. If your site uses subfolders, open the .HTC file in a text editor like Windows Notepad and change the blankImg variable to include a correct path to blank.gif like so:

var blankImg = '/images/blank.gif';

Again the path is relative to the HTML file. Otherwise, you will see a "broken image" graphic!

  1. Sit back and enjoy! Perhaps consider making a donation to support this script's development if you like what you see, as I have spent hundreds of hours developing, testing and supporting it :). Alternatively, I would certainly appreciate a crediting link on your site back to mine!

If you are interested in more details or an alternative activation method for the script that maintains CSS validation compatibility, see the source code to this demonstration file.

How to fix common problems

I've pasted in the CSS but my PNGs aren't transparent!

Make sure you remember that the path to the HTC file is relative to the HTML file, not the CSS file (like CSS background images are). If you want to test the path, insert this: alert('This works!'); into the .HTC file.

It works offline but not online.

First try unzipping this default demonstration and uploading to your web server as-is. If it doesn't work, you may have a MIME type problem. You must ensure your server is sending the correct MIME type of "text/x-component" for .HTC files. Try one of these two easy fixes:

1. Upload the ".htaccess" file from within this script's download ZIP to your webserver, which will make Apache send the correct MIME type.

2. Instead of calling "IEPNGFIX.HTC" from your CSS, upload IEPNGFIX.PHP to the same folder and call that instead, which also sends the right MIME type.

My PNGs are transparent but have a funny border or red "X" icon.

Check that the blankImg variable is set correctly in the .HTC file, again this should be relative to the HTML document containing the PNGs.

Images are distorted, or this script breaks my page layout.

When applied to images without set dimensions, this script will try and "guess" the correct image size and apply that. If it gets it wrong, give your images a definite width and height.

Links or form elements within a PNG'd element aren't clickable.

Due to an IE bug, if you are putting links within an element with a transparent background, the element must not have a CSS relative/absolute position. Otherwise the links will likely be un-clickable. The script will warn you with a popup alert dialog if this occurs. There is an excellent article on PNG filters and links you might want to read if you are a CSS expert that contains more info and workarounds.

It works, but breaks another application like Google Maps on my page.

You'll need to stop applying this behavior to the third-party element that presumably contains its own PNG fix. Try making your CSS selector more specific, or put a manual override for the element in your CSS like so: * html div#map img { behavior: none; }

I have IE6 installed "alongside" IE7+, and this script fails.

Either try on a computer with IE6 installed system-wide, or make sure that you copy the required DLLs into your IE6 folder. You will need dxtrans.dll and dxtmsft.dll for filter support, try Googling for them or finding them on your Windows install CD. Note that I can't support your setup here, sorry!

I have lots of images and page loading is slow.

With a lot of images, it can certainly slow down your page! Make sure that you apply the script as narrowly as possible. Consider applying only to elements of a particular CLASS perhaps, rather than all tags...

It still won't go.

Try running the self-test at the bottom of the list of demo images. If that throws any errors, you'll know where to start fixing!

Limitations and known isses with the script

  • Background repeat and position are largely unsupported, this is due to a limitation in the IE transparency filter. If your background is set to repeat, the PNG will stretch to fill the element, and if it's 'no-repeat', the PNG will display once (untiled) pixel-for-pixel.
  • Padding and borders don't indent the PNG image and can sometimes contribute to the distortion problem. An easy fix is to use 'margin' instead.
  • A:HOVER transparent images are not supported out of the box. If you want this functionality, I recommend you download the excellent Whatever:hover script. This script will then enable :hover PNG background changes on all page elements when both are applied to the page.
  • IE 4.0/5.0 are not supported. MSIE/Mac has native support for IMG SRC but no background PNG support. The scripts does nothing in MSIE7 as it supports PNGs natively.
  • Users can't right-click-save processed PNG images, they'll save the blank GIF file if they try that. In some cases this might be a feature, not a bug...
  • The script detects the ".png" extension in image URLs. So if you have a CGI script that generates a PNG image, you may have to rewrite parts of the script, or just cache them as PNG files somewhere.
  • There may be about a short time as soon as the image loads when images are not transparent, before the IE filter kicks in.

Zipcode Locator / Proximity search with PHP.

You will require a database to setup for zip proximity search. The database will contain zip codes, latitude and longitude information.

Here is the link you can download for free: http://sourceforge.net/projects/zips/

You need a class from phpclasses to apply zipcode / proximity search for your website:

http://www.phpclasses.org/browse/package/3156.html

Example code:

HTML FORM

<html>

<head>
<title>Zipcode Proximity Search</title>
</head>
<body>
<form action="zipsearch.php" method="post">
<input type="text" name="zip" value="" />
</form>
</body>
</html>

Code of zipsearch.php



<?php

if(!empty($_GET['zip']))
$zipcode=$_GET['zip'];
else
header('LOCATION:index.html');

$miles=’50’;
//initialization, pass in DB connection, from zip code, distance in miles.
$zip = new ZipCodesRange($appconf['dbconnection'],$zipcode,$miles);

//configuration
$zip->setTableName('zip_codes'); //optional, default is zips.
$zip->setZipColumn('zip'); //optional, default is zip.
$zip->setLonColumn('longitude'); //optional, default is lon.
$zip->setLatColumn('latitude'); //optional, default is lat.

//do the work
$zip->setZipCodesInRange(); //call to initialize zip array

//zip code output, other processing can be done from this array.
$zipArray = $zip->getZipCodesInRange();

// NOW WE WILL USE IT TO RETRIEVE THE RECORDS FROM THE SQL TABLE.
// FOR EXAMPLE TABLE 'cars_lot' CONTAINS ZIPCODE AND INFORMATIONAL FIELDS.

// Starts from writing where clause. We will use these zipcodes in the where clause to query.

$where_string='';
$array_count=count($zipArray);
$count=0;
foreach($zipArray as $key=>$value){

if($count!=$array_count)
$where_string.="echo zip_code='".$value."' OR "; zip_code is field in cars_lot
// it will display zip_code='908033' OR
if($count==$array_count)
$where_string.="echo zip_code='".$value."'"; zip_code is field in cars_lot
// it will display zip_code='908033'

$count++;

}
$sql="SELECT * FROM car_lot WHERE ".$where_string."";

// THIS RECORDSET WILL RETURN ZIP PROXIMITY SEARCH RESULTS.
return $result=mysql_query($sql) or die (mysql_error());

?>


All rights are reserved. Nobleatom.com
Software Development Services.
Contact me: khubabmazhar596@hotmail.com

Web Design Increase Page Rank Internet blogs DigNow.net web directory1Abc DirectorySeo friendly web directory