Archive for 'Scripts'

PHP pdf generator from html

I will explain in this article how to make a pdf generator from html in php.
We will use a command tool that will generate the pdf. It’s an open source shell utility that is called wkhtmltopdf that uses webkit rendering engine, and qt – go here for more information for wkhtmltopdf. I suggest to use the version 0.9.9, which I think it’s a stable version right now. I tested the version 0.11.0_rc1 and I got some problems with downloading the images from html img tag.
Steps to generate the pdf from html:
1. Download the tool.
2. Install the tool.
3. Use the tool from your php code to create a pdf from html.

1. Depending on your operating system you should download from the following page:

2. To install on Windows should download the .exe from the website, launch the setup and follow the steps. In order to test if you installed correctly the tool you should go to the folder of where you installed it and launch in command prompt the following command: wkhtmltopdf http://www.test.com test.pdf

To install on Linux you should find out the operating system launching the command uname -a that will tell you the operating system you are using and download the apropiate version of the tool.
To install on 32 bits Linux operating system you should use the following code:

//get the file from server
wget http://wkhtmltopdf.googlecode.com/files/wkhtmltopdf-0.9.9-static-i386.tar.bz2
tar xvjf wkhtmltopdf-0.9.9-static-i386.tar.bz2
// move the application to bin folder
mv wkhtmltopdf-i386 /usr/local/bin/wkhtmltopdf
//change permission for install it
chmod +x /usr/local/bin/wkhtmltopdf
// install it
/usr/local/bin/wkhtmltopdf
//To test if you installed correctly the tool
wkhtmltopdf-i386 http://www.test.com test.pdf

To install on 64 bits Linux operating system you should use the following code:

//get the file from server
wget http://wkhtmltopdf.googlecode.com/files/wkhtmltopdf-0.9.9-static-amd64.tar.bz2
tar xvjf wkhtmltopdf-0.9.9-static-amd64.tar.bz2
// move the application to bin folder
mv wkhtmltopdf-amd64/usr/local/bin/wkhtmltopdf
//change permission for install it
chmod +x /usr/local/bin/wkhtmltopdf
// install it
/usr/local/bin/wkhtmltopdf
//To test if you installed correctly the tool
wkhtmltopdf-amd64 http://www.test.com test.pdf

3. In php you should execute the tool using shell_exec:

shell_exec("/usr/local/bin/wkhtmltopdf-i386 http://test.com test.pdf");
//for Linux 32 bits operating system
//for Linux 64 bits operating system use wkhtmltopdf-amd64
//for windows just put the path of the exe file.
$allfile = file_get_contents("test.pdf");
header('Content-Type: application/pdf');
header('Content-Length: '.strlen($allfile));
header('Content-Disposition: inline; filename="test.pdf"');
header('Cache-Control: private, max-age=0, must-revalidate');
header('Pragma: public');
ini_set('zlib.output_compression','0');

PHP database logging

In order to make database logging in php we should first create a table with 2 fields: the message that we log and the date that the log was made. After creating the database we should create a php class that will have to pass the instance of the MySQL database to the log class contructor. After that as previous example of php log file we should call a function that inserts a new row in a table database. Here is the class for php database logging:


class DBLog {
private $_db;

public function __construct($db) {
$this->_db = $db;
}

public function WriteLogToDB($message) {
if(!empty($message)){
$date = date("Y-m-d h:m:s");
mysql_query ("INSERT INTO DBLog VALUES('".$message."', '$date')", $this->_db);
}
}
}

In order to call the function of database logging we should first make a connection to the database and then call the function to save row log to database:


$connection = mysql_connect("localhost", "username", "password")
or die("Unable to connect to MySQL server");
mysql_select_db('DatabaseName', $connection) or die ("Database not found.");
$filel = new DBLog($connection);
$filel->WriteLogToDB('Here is my first log.');

We only need the mysql script that creates the table in our database:


CREATE TABLE IF NOT EXISTS `dblog` (
`Message` text NOT NULL,
`DateCreated` datetime NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

Tags: ,

If you thought how to build rss feed parser you should think first think about what php xml parse you should use. If we examine the parser that we have built in then you will find expat, simple xml and xml dom manupulation. In order to parse a feed from a url you should first validate the feed url , get the contents of the xml through file_get_contents, and loop through nodes of xml and get the nodes values.
So here are steps the in order to build our class:
1. Validate url
2. Get contents using file_get_contents

3.Set the limit of how many items to return
4. Parse results. We should replace the spaces of the node values.

Class Description
Variables
$url – the url of the feed that will be parsed.
$doc – the DOM Document that will load the xml parsed from url.
$limit – Limits the number of items to be retrieved.
$isValidUrl – Verifies if the link is valid.
$items – the RSS items that would be returned.

Constructor
Initialize the url of the feed and all class variables with empty variables. We initialize the limit to 5 items.
Methods
SetLimit – sets the limit of the items to be parsed
ValidateUrl – validates the url of the rss feed. It checks if the feed url begins with ‘http://’
ExecuteRssParser – fetches the feed url and loads into a php variable. After that it loads the xml and parses the rss nodes values and returns the results into the variable ‘feeds’.

<?
class RssFeedParser
{
private $url, $doc, $limit;
public $isValidUrl, $items;
 
public function __construct($url) {
$this->url = $url;
$this->items = array();
$this->doc = new DOMDocument();
$this->limit = 5;
}
 
private function ValidateUrl()
{
if (stristr( $this->url, 'http://') === FALSE)
{
return false;
}
else
{
return true;
}
}
 
public function SetLimit($limit)
{
$this->limit = $limit;
}
 
public function ExecuteRssParser()
{
$this->isValidUrl = $this->ValidateUrl();
if ($this->isValidUrl)
{
  $xmlText = preg_replace("/>\s+</", "><", file_get_contents($this->url));
  $this->doc->loadXML($xmlText);
 
  if ($this->doc->getElementsByTagName('item'))
  {
	  $count = 0;
	  foreach ($this->doc->getElementsByTagName('item') as $node) {
		$itemRSS = array ( 
		  'title' => $node->getElementsByTagName('title')->item(0)->nodeValue,
		  'description' => $node->getElementsByTagName('description')->item(0)->nodeValue,
		  'link' => $node->getElementsByTagName('link')->item(0)->nodeValue,
		  'pubDate' => $node->getElementsByTagName('pubDate')->item(0)->nodeValue
		  );
		array_push($this->items, $itemRSS);
		$count++;
		if ($count>=$this->limit)
		{
			break;
		}
	  }
  }
}
}
}
?>

You can easy modificate this class in order to fit your needs. Good luck!!!

PHP cpanel scripts

Intro

To automate an action in PHP for cpanel it’s very easy. You just need to know some information about your cpanel. You can find this information on your browser link bar.

$cpanel_user – the username that you use to log into your cpanel
$cpanel_password – the password for cpanel.
$cpanel_host – your cpanel host. You can find this after you login to cpanel, right before ‘http://’ until ‘:’.
$cpanel_skin – cpanel skin. You can find this after ‘/frontend/’, default is ‘x’.

HTML Form

You can use this html forms to make the scripts for cpanel, you can add your own fields that you need.

<form action="cpaneladd.php" method="POST">
<table>
<tr><td colspan="2" align="center">
<b>Cpanel info</b></td></tr><tr><td align="right">Cpanel host:
</td><td align="left">
<input type="text" name="cpanelhost"></td></tr>
<tr><td align="right">Cpanel username:</td><td align="left">
<input type="text" name="cpaneluser"></td></tr>
<tr><td align="right">Cpanel password:</td><td align="left">
<input type="text" name="cpanelpass"></td></tr>
<tr><td align="right">Cpanel skin:</td><td align="left">
<input type="text" name="cpanelskin" values="x"></td></tr>
</table>
</form>

I made a list with some useful functions that you can use for cpanel:

1. Adding a database in cpanel

 $newdb = "db_name";
 $curl = curl_init();
 curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
 curl_setopt ($curl, CURLOPT_URL, "http://$cpanel_user:
$cpanel_password@$cpanel_host:2082/frontend/$cpanel_skin
/sql/adddb.html?db=$new_db");
 $result=curl_exec ($curl);
 curl_close ($curl);

2. Adding a user to database in cpanel

      $db_user = "dbuser";
      $db = "database";
      $curl = curl_init();
      curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
      curl_setopt ($curl, CURLOPT_URL, "http://$cpanel_user:
$cpanel_password@$cpanel_host:2082/frontend/$cpanel_skin/
sql/addusertodb.html?user={$cpanel_user}_{$db_user}
&db={$cpanel_user}_{$db}&ALL=ALL");
      $result=curl_exec ($curl);
       curl_close ($curl);

3. Delete a user in cpanel

     $userdb="userdb";
     $curl = curl_init();
     curl_setopt ($curl, CURLOPT_URL, "http://$cpanel_user:
$cpanel_password@$cpanel_host:2082/frontend/$cpanel_skin/
sql/deluser.html?user=".$cpanel_user."_".$userdb);
     curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
     $result=curl_exec ($curl);
     curl_close ($curl);

4. Delete a database in cpanel

     $db="db";
     $curl = curl_init();
     curl_setopt ($curl, CURLOPT_URL, "http://$cpanel_user:
$cpanel_password@$cpanel_host:2082/frontend/$cpanel_skin
/sql/deldb.html?db=".$cpanel_user."_".$db);
     curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
     $result=curl_exec ($curl);
     curl_close ($curl);
Tags: ,

PHP xml to csv

To create a csv file from a xml in PHP 5.0 it’s very simple, we will just have to write some lines.
We will use the SimpleXML extension that come from PHP 5.0.
SimpleXML reads an entire xml into an object that we can iterate through his properties.
To write to the csv output file we will use fputcsv.
fputcsv formats a line as csv and writes it to the file.
Suppose we are having this xml named cars.xml:

<?xml version='1.0'?>
<cars>
<car>
 <color>blue</color>
 <price>2000</price>
</car>
<car>
 <color>red</color>
 <price>10000</price>
</car> 
<car>
 <color>black</color>
 <price>5000</price>
</car>
</cars>

First we should read our xml using simplexml_load_file passing the name of the file and returns an object with all the properties and values of the csv:

    $xml = simplexml_load_file($filexml);

After reading it we should iterate through all the child nodes of cars and write it to the output file using fputcsv specifying the object,delimiter and enclosure. We should first convert the object into an array in order to write it to the csv:

foreach ($xml->car as $car) 
fputcsv($f, get_object_vars($car),',','"');

Here is the complete source code that converts xml to csv in php 5.0:

<?
$filexml='cars.xml';
if (file_exists($filexml)) {
    $xml = simplexml_load_file($filexml);
$f = fopen('cars.csv', 'w');
foreach ($xml->car as $car) {
    fputcsv($f, get_object_vars($car),',','"');
}
fclose($f);
}
?>

Download php source code for converting xml into a csv

Tags: ,

To do cascading drop down in php using mysql we can use AJAX. The name AJAX is from asynchronous JavaScript and XML and it’s a new technique for web development to build rich interactive web application. The power of this technique comes from the fact that it can send to server requests from the client side, in order to not reload the page. The object that is using AJAX to send and retrieve data between server and the client is named XmlHttpRequest.
To build a cascading drop down in php to retrieve data from a mysql server we will first populate a drop down with the results from a first table from a mysql database. The first table is linked with a second table by a field. When we change the drop down we should assign to OnChanging event an Javascript function that will populate the second drop down . The function will create a new XmlHttpRequest object and make a call to other php script, grab data and populate the second drop down. The script that it’s called will fetch the results for that field that was changed.

Watch a demo here:populate drop down using ajax

Download php cascading drop down using mysql

Tags: , ,

PHP ftp upload tutorial

To upload a file to ftp you need a html form where you can insert the ftp details, like the ones described above:
server – is the server on which he wanna upload the file
username – is the user for which he makes the connection to ftp server
password - is the user password for ftp username
path to server – is the path on the ftp server which he wanna upload his file.
user file – is the file of the you wanna upload to ftp server

Hint: If you want to offer to your website members a form where he will upload his file, you should take the ftp server details and path, from a config file. Here we made a complete example how to upload through ftp putting all the details.

We will have a POST form and an enctype of multipart/form-data because we have a file on our form.
The user form that the user will insert info is like that:

<form action="upload.php" method="POST" enctype="multipart/form-data">
<table align="center">
<tr>
<td align="right">
Server:
</td>
<td>
<input size="50" type="text" name="server" value="">
</td>
</tr>
<tr>
<td align="right">
Username:
</td>
<td>
<input size="50" type="text" name="user"  value="">
</td>
</tr>
<tr>
<td align="right">
Password:
</td>
<td>
<input size="50" type="text" name="password" value="" >
</td>
</tr>
<tr>
<td align="right">
Path on the server:
</td>
<td>
<input size="50" type="text" name="pathserver" >
</td>
</tr>
<tr>
<td align="right">
Select your file to upload:
</td>
<td>
<input name="userfile" type="file" size="50">
</td>
</tr>
</table>
<table align="center">
<tr>
<td align="center">
<input type="submit" name="submit" value="Upload image" />
</td>
</tr>
 
</table>
</form>

Now, when the user submits the form, we should get all the details that he inputed and then upload the file to the ftp server.

// the file name that should be uploaded
$filep=$_FILES['userfile']['tmp_name']; 
// ftp server
$ftp_server=$_POST['server'];
//ftp user name
$ftp_user_name=$_POST['user'];
//ftp username password
$ftp_user_pass=$_POST['password'];
//path to the folder on which you wanna upload the file
$paths=$_POST['pathserver'];
//the name of the file on the server after you upload the file
$name=$_FILES['userfile']['name'];

To upload the file , first we should establish a connection to the ftp server using ftp_connect and specifing as a parameter the ftp servver. This function return a connection id.

$con_id=ftp_connect($ftp_server);

After connecting to server we should login using the function ftp_login passing three parameters: connection id, ftp user, ftp user password and checking if the login was sucessfull

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
// check connection
if ((!$conn_id) || (!$login_result)) {
       echo "FTP connection has failed!";
       echo "Attempted to connect to $ftp_server for user $ftp_user_name....";
       exit;
   } else {
       echo "Connected to $ftp_server, for user $ftp_user_name".".....";
   }

After loging in we can upload the file to the server and after that check if the file was uploaded correctly:

// upload the file
$upload = ftp_put($conn_id, 'public_html/'.$paths.'/'.$name, $filep, FTP_BINARY);
 
// check upload status
if (!$upload) {
       echo "FTP upload has failed!";
   } else {
       echo "Uploaded $name to $ftp_server ";
   }

In the end we should close the ftp connection using ftp_close passing the connection id:

ftp_close($conn_id);

For uploading big files you should set the time limit of the server in order not to finish the script while it’s uploading:

set_time_limit(300);

Here is the complete code:

<?
if(!isset($_POST["submit"])){?>
 
<form action="upload.php" method="POST" enctype="multipart/form-data">
<table align="center">
<tr>
<td align="right">
Server:
</td>
<td>
<input size="50" type="text" name="server" value="">
</td>
</tr>
<tr>
<td align="right">
Username:
</td>
<td>
<input size="50" type="text" name="user"  value="">
</td>
</tr>
<tr>
<td align="right">
Password:
</td>
<td>
<input size="50" type="text" name="password" value="" >
</td>
</tr>
<tr>
<td align="right">
Path on the server:
</td>
<td>
<input size="50" type="text" name="pathserver" >
</td>
</tr>
<tr>
<td align="right">
Select your file to upload:
</td>
<td>
<input name="userfile" type="file" size="50">
</td>
</tr>
</table>
<table align="center">
<tr>
<td align="center">
<input type="submit" name="submit" value="Upload image" />
</td>
</tr>
 
</table>
</form>
<?}
else 
{
 
	set_time_limit(300);//for setting 
 
$paths=$_POST['pathserver'];
 
$filep=$_FILES['userfile']['tmp_name'];
 
$ftp_server=$_POST['server'];
 
$ftp_user_name=$_POST['user'];
 
$ftp_user_pass=$_POST['password'];
 
$name=$_FILES['userfile']['name'];
 
 
 
// set up a connection to ftp server
$conn_id = ftp_connect($ftp_server);
 
// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
 
// check connection and login result
if ((!$conn_id) || (!$login_result)) {
       echo "FTP connection has encountered an error!";
       echo "Attempted to connect to $ftp_server for user $ftp_user_name....";
       exit;
   } else {
       echo "Connected to $ftp_server, for user $ftp_user_name".".....";
   }
 
// upload the file to the path specified
$upload = ftp_put($conn_id, $paths.'/'.$name, $filep, FTP_BINARY);
 
// check the upload status
if (!$upload) {
       echo "FTP upload has encountered an error!";
   } else {
       echo "Uploaded file with name $name to $ftp_server ";
   }
 
// close the FTP connection
ftp_close($conn_id);	
 
}
?>

Download source code

Tags: ,

PHP paging tutorial

In this tutorial I want to make a paging tutorial in php.

A friend of mine tell me to help him with a script to do paging in php from a mysql database and I would like to share with all.
If you wanna take data from a xls,csv or other files, from a database like mysql,mssql and you wanna list the results on the page, you may have many results for your result.
I want to present an example so you can understand how a paging can be made in php. I made an example about how to search results from a mysql database and make pagination on the results.

You should first have a form in html from where the user can input the search field:

<form action="Search.php" method="POST">
<table align="center">
<tr><td>Name:</td><td><input type="text" name="search" width="40"></td><td><input name=submit type=submit value=Search><input type=hidden name=hiddensearch value=yes></td></tr>
</table>
</form>

You should now put the code before the html form for verifying if the user submits the form through a POST, if not show the html form. So we will have 2 cases, when when we first post the form we will show the first page and links to all other pages. The links to other pages will look something like search.php?search=Name&page=10 -> this will fetch the results from database for the page number 10 with the search query ‘Name’. Each page will have a number of results say 20, which we will call it pagesize.

First we should connect to the mysql server and make a query on the database. We discuss previously how we can connect to a database and how to make a query, go here for learning how to connect and fetch results from mysql. After we make a query we get each row of the query result and verify if it is on the current page( if it is a post then we will get the first $pagesize records). To select records for a page we should use verify a condition for every row:

if ($nr>=($pagesize*($page-1)+1)&&($nr<=($pagesize*$page)))
{
 //write the result
}

Where $nr – is the current record
$pagesize – is the size of a page
$page – is the page number

In the end we should write all the links to other pages( the navigation through result pages part ):

<?
	echo '<tr>';
	echo '<td>';
	for ($i=1;$i<=ceil($nr/$pagesize);$i++)
	if ($i!=$page)
	  echo '<a href="Search.php?search='.urlencode($name).'&page='.$i.'">'.$i.'</a> | ';
	else
	  echo $i.' | ';  
	echo '</td>';
	echo '<tr>';
?>

Here is the complete code:

<?
 
$server="";
$user="";
$pass="";
$database="";
 
include("header.php");
 
 if($_POST['hiddensearch'] == 'yes'|| isset($_GET['search']))
  {
 
    $connect=mysql_connect($server, $user, $pass)
      or die ("Database Connection Error");
 
$pagesize=20;//how many results will be on a page	   
$page=$_GET['page'];//curent page
if ($page=="")
   $page=1;
 
//we 
if ( $_POST['hiddensearch'] == 'yes')  
$name=$_POST['search'];
else
$name=$_GET['search'];
 
//we write the query
$result = mysql_db_query($database, "SELECT * FROM Table Where Name='".$name."'");
 
 
if(mysql_num_rows($result) > 0)
{
 
    ?>
<br>
<center>Results  <?=mysql_num_rows($result);?> with <b><?echo $name;?> parameter</b></center>
 
 
 
 <TABLE align="center" cellspacing="0" cellpadding="0">
<?
$nr=0;
//fetch every row and verify if it is in the current page
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{ 
 $nr++;
 if ($nr>=($pagesize*($page-1)+1)&&($nr<=($pagesize*$page)))
 {
 
   echo '<tr>'; 
 
	echo '<td>'.$row['Name'].'</td>';
   echo '</tr>';
 }
}
 
//build the navigation links to other pages
  if ($pagesize<$nr)
   {
 
 
	echo '<tr>';
	echo '<td>';
	for ($i=1;$i<=ceil($nr/$pagesize);$i++)
	if ($i!=$page)
	  echo '<a href="Search.php?search='.urlencode($name).'&page='.$i.'">'.$i.'</a> | ';
	else
	  echo $i.' | ';  
	echo '</td>';
	echo '<tr>';
   }
echo '</table>';
 
}
else
  {
   echo 'No results found.';
 
  }
mysql_close($connect);
}
else
{
?>
<center><b>Search </b></center><br><br>
<form action="Search.php" method="POST">
<table align="center">
<tr><td>Name:</td><td><input type="text" name="search" width="40"></td><td><input name=submit 
 
type=submit value=Search><input type=hidden name=hiddensearch value=yes></td></tr>
</table>
</form>
 
<?
}
include("footer.php");
?>

Download code here

Tags: ,

1. Description

This is a beta release of my first wordpress plugin. I called it Mass Mail because it can help you sending mass mails to a custom group from your blog. This is the first version of the plugin ( 1.0).
After you install the plugin to your blog, it is setup to send emails to you users from your blog.

2. Install

Here is a description on how to install this mass mail plugin:

1. Put MassMail.php into [wordpress_dir]/wp-content/plugins/
2. Go into the WordPress admin interface and activate the plugin
3. Optional: Go to Settings panel and click on Mass Mail, fill the group you wanna send emails and your email detail.

The plugin it’s very customizable because you can specify on which table(group) you send emails. You can for example send messages to your blog users, people that made a donation for you, people that subscribed to your blog and many other groups that you wanna send a mail.

Using Mass Mail Plugin

Mass Mail Setup

After installing the plugin you should go to Settings panel, click on Mass Mail and enter the details that you are requested.
At first it is setup to use the table wp_users that means it will send mails to all your blog users. To modify the first two values to fit to your group you should look in your Mysql wordpress database and see what table are the users stored to which you wanna send messages.
Table name: – is the table name to which you wanna send mass mails.
Table email field: – is the email field table of users specified in Table name.
Sender email: – is the sender email, that will appear in the header of the user.
Sender email will be something like name@domain.com . If you want to appear more user friendly to user headers you should customize Sender email like this Name

Send Mass Mail

After you setup the details of the group you should click on Save & Send Mails -> and fill the Subject and Message and Seconds between messages.
This will be the subject and body that every user of the group will receive in his mail and the seconds that will pass between emails that will be sent. This option is to not overload the smtp server if you send many emails.

Download WordPress Plugin Mass Mail

Tags: ,

Why SFMMS?

I just made a simple mass mailer sender in php, which can help you to easily send mass mail to your members. It’s very simple to setup and very useful.

This is a first version of the script, if people will like it, I will make other modify to it.

What is SFMMS?

This is a simple but very usefull Mass Mailer Sender script, that you can use from your server to send mass mails.You can for example use it to send annoncements for your members, that you have an offer for them. You can also use it as mass mailer subscriber to send weekly mails to yours subcribers.

How to install it?

To install SFMMS you should unzip the sfmms.zip to a folder of your choice to your hard disk  and modify the config.php in order to fit to your needs.

$server – it’s the server of your mysql database, which is ussually ‘localhost’

$database – is the name of your database on which your table is stored from the server

$db_user – the user of the database

$db_pass – the password for the user of the database

$fromadmin – email which the users will receive in his email

$table – the table from database where the users are stored

$table_email – the name field for the email of the $table(ex. ‘email’,'Email’)

You can customize the header.php and footer.php to fit with your website.

Upload all the files to a folder from your server.

 

How to use it?

Access http://www.mywebsites.com/folder/massmail.php and put all the details you wanna send to users.

 

Subject – is the subject that will appear in email subject to users.

Message – the message that you will send to users.

Seconds between messages – time to pass between each email that is sent to users(leave it 0.1). This is used when you send lots of messages to not overload smtp server.

Download Simple Free Mass Mailer Sender PHP

Tags: ,
Back to top