Follow me on Twitter to receive updates, free scripts and ongoing announcements!

PHP downloadable file

Written by Codes Tips on November 18, 2009 – 1:40 pm -

Text downloadable file

Last days I needed to create a file which had to be downloaded by many users. The file had to be in plain text and contents from file come from database. Because I didn’t had a separate folder for each user I couldn’t write the information to a file to the server and put a link in order the user to download it. I thought a little bit how to handle it and found a very simple solution to to make a file downloadable to users. I even try to other popular formats like .doc, .xls,.csv,.dat and it works really nice. Extension that I tested it and didn’t worked are .xlsx and .pdf.

In order to make a file downloadable you should modify the header of the page to make Content-type: application/octet-stream and Content-Disposition: attachment; filename=\”downloadableFile.extension\” in order to inform the browser that there is an attachment binary file. The file will open in a window to inform the user it to open it with a default application or save it to disk.
Code for downloadable file:

<?
		header("Content-type: application/octet-stream");
		header("Content-Disposition: attachment; filename=\"downloadablefile.txt\"");
		echo 'Contents of plain text downloadable file';  
?>

CSV downloadable file

The real magic comes when you wanna make csv file downloadable. You can read data from a mysql table and write the contents to a csv file. You should only read contents from a table and using echo output to the file.

<?
		header("Content-type: application/octet-stream");
		header("Content-Disposition: attachment; filename=\"downloadablefile.csv\"");
		$connect = mysql_connect($server, $user, $password)
			or die ("Database CONNECT Error"); 
 		$resultcsv = mysql_db_query($database, "select * from $csvTable");
		while ($query = mysql_fetch_array($resultcsv)) 
		{ 
			echo $query["Name"].",".$query["City"]."\n";
		}
		mysql_close($connect);
?>

Excel downloadable file

Code for generating a excel downloadble file:

<?
		header("Content-type: application/octet-stream");
		header("Content-Disposition: attachment; filename=\"downloadableFile.xls\"");
		$connect = mysql_connect($server, $user, $password)
			or die ("Database CONNECT Error"); 
 		$resultxls = mysql_db_query($database, "select * from $xlsTable");
		while ($query = mysql_fetch_array($resultxls)) 
		{ 
			echo $query["Name"]."\t".$query["City"]."\n";
		}
		mysql_close($connect);
?>

You can look through records from database and output as I did for csv

Doc downloadable file

You can even make a downloadable .doc files by changing the file extension to doc.

<?
		header("Content-type: application/octet-stream");
		header("Content-Disposition: attachment; filename=\"downloadablefile.doc\"");
		echo 'Contents of Word Document.';  
?>

Tags: ,
Posted in PHP/MYSQL | No Comments »

PHP string manipulation 3

Written by Codes Tips on August 1, 2009 – 1:00 pm -

This is the third part about how to manipulate strings in PHP.

Replace all occurrences of sub strings with a replacement string

If you wanna replace all occurrence of a substring inside a string you should use the function str_replace passing as first argument the string(or array of strings) you wanna search, second argument the string(or array of strings) you wanna make the replace, the third is the string you wanna search in and the fourth argument is the number of replacements the function should make. It returns a string after all replacements have been made.
Declaration: mixed str_replace ( mixed $SearchFor, mixed $ReplaceWith , mixed $String[, int &$number] )
Example:

<?php
$string= "This is a str_replace Function Test";
$searchFor = array("Function","Test");
$replaceWith = array("function","test");
echo str_replace($searchFor,$replaceWith,$string);
?>

Output: This is a str_replace function test

Split string one by one

To tokenize string in php you can you the function strtok in order to split a string. Each smaller string it’s separated by a delimeter. It takes as a first argument the string that will be split and the second the delimeter that it is used to split it.
You should call the first time the function as strtok($String,$delimiter) and returns the first string that is delimited. Any subsequent calls of the function should be like strto($delimiter(s)), because the function keeps into memory the variable $String that it’s delimited.
You can specify multiple delimiter
Declaration: string strtok(string $String, string $delimiter(s))
Example:

<?
$string = "This is an strtok Function Test";
$tok = strtok($string, " ");
 
while ($tok !== false) {
    echo "String=$tok<br />";
    $tok = strtok(" ");//returns the next splitted string in the $string variable
}
?>

Output:
String=This
String=is
String=an
String=strtok
String=Function
String=Test

Split a string by a delimeter

Disadvantage of strtok function it’s that you should call it every time you wanna split the string. You can use explode function in order to split the string and returns an array of string with all the string splitted. The first argument is the delimiter, the second the string you wanna split and you can also specify an optional integer argument that specify the limit of strings splitted.
Declaration: array xplode(string $delimiter , string $String[, int $limit ])
Example:

<?
$string = "This is an explode Function Test";
$explodedstring = explode(" ", $string,3);
 
foreach($explodedstring as $substring)
 echo $substring.'<br />';
?>

Output:
This
is
an explode Function Test

Union elements of array in a string

If you wanna join array elements into 1 string you should call the function implode. The first argument that you should pass to the function is the separation and the second one the array of string.
Declaration: string implode ( string $separator , array $Strings)
Example:

<?
$strings = array('This','is','a', 'implode','function','test');
$separator = " ";
echo implode($separator,$strings);
?>

Output:
This is a implode function test

Replace a string by regular expression

You can use regular expression in php to replace using the function preg_replace. You should pass the first argument as a regular expression pattern - it can be a string or an array of string, the second is the string or array of string that you use to replace the pattern, third argument is the string you search in. The final two arguments are optional, first parameter is the limit of replacement you should make and the final one is the value of replacements that have been made in the string.
Declaration: mixed preg_replace (mixed $regularExpression, mixed $replaceWith, mixed $String [, int $limit= -1 [, int &$count ]] )
Example:

<?
$string = "This is a preg_replace bad, words, Function Test";
$pattern = "(\w+,)";
$replaceWith = "";
echo preg_replace($pattern, $replaceWith, $string)."<br />";
?>

Output:
This is a preg_replace Function Test

PHP string manipulation - part 2


Tags: ,
Posted in Codes, PHP/MYSQL | 1 Comment »

PHP string manipulation 2

Written by Codes Tips on July 31, 2009 – 2:34 pm -

This is the second part of the how you can manipulate string in PHP.

Find length of a string

If you want to find out how many characters have a string you can use the function strlen. If you have to pass 1 argument as the string you wish you find out the length and it returns an integer.
Declaration: int strlen(string text)
Example:

Output: 31

Find a sub string inside a string

To find a first occurrence of a string inside other you should use the function strstr and pass it 2 arguments. First argument should be the string in which you wanna look and the second should be the string you search. It returns part of the first occurrence until the end of the string you search in.
Declaration: string strstr(string searchIn,string lookfor)
Example:

Output: strstr Function Test

Find a string inside other string(case insensitive)

To find an occurrence of a string inside another with case insensitive activated you should use the function stristr. It has the same parameters as the strstr, but it also finds case insensitive strings.
Declaration: string stristr(string SearchIn, string lookFor)
Example:

Output: StrStr Function Test

Find position of first occurrence of a string inside another

To find the position of the first occurrence of a string you can use the function strpos. You should pass two arguments. The first parameter is the string you wanna search in and the second is a the string you are looking for. You can specify an additional argument, an offset that indicates from where position the search should begin.
Declaration: int strpos ( string $SearchIn, mixed $SearchFor[, int $offset= 0 ] )
Example:

Output: 11

Find a position of a string inside another(case insensitive)

You can use the function strripos and it has the same arguments as strpos, but it searches for case insensitives.
Declaration: int strripos ( string $SearchIn, mixed $SearchFor[, int $offset= 0 ] )

How to return parts of a string

To return parts of a string you should use the substr function and pass it 2 arguments and 1 optional. The first argument is the string you wanna return a part of a string, second is the start position from where you wanna begin crop the string. You can also specify an argument with the length that the function should crop.
Declaration: string substr ( string $SearchIn , int $from [,int $length])
Example:

Output: is a substr

Insert after each end of line in string a html br tag

To insert html tag br after the new lines in a string you can use the function nl2br. Function takes one neccessary argument and one optional. First is a string where it will be inserted the br tag and the second one is a boolean that indicates if the replacement is a XHTML compatible line breaks(default value is TRUE).
Declaration: string nl2br(string $InsertIn [,bool $isXHTML= true])
Example:

Output:
This is a nl2br<br /> Function<br /> Test

PHP string manipulation - part 1 - PHP string manipulation - part 3


Tags: ,
Posted in Codes, PHP/MYSQL | 2 Comments »

PHP string manipulation

Written by Codes Tips on July 28, 2009 – 2:53 pm -

This is a first part of PHP string manipulation.
It’s extremelly useful to know how to manipulate strings in PHP. This tutorial will guide you through how to use the functions that PHP offers.
A string in PHP it’s defined in php in a variable assigning a single or double quote value like:
$string = ‘This is a test string’;
$string = “This is a test string”;

Make all letters from string lowercase

To make every letter of a string in lowercase you should use the function strtolower like this:

<?
$string= "This is a  strtolower Function Test";
echo strtolower($string);
?>

The ouput will be: this is a strtolower function test

Make all letters of a string uppercase

You should use the function strtoupper in order to make every letter of the string in uppercase:

<?
$string= "This is a  strtoupper Function Test";
echo strtoupper($string);
?>

The ouput of will be: THIS IS A STRTOUPPER FUNCTION TEST

Capitalize first letter of each word in a sentence with ucwords

To make a sentence more estetic we can capitalize first letter of each word in a sentence with the function ucwords().

<?
$string= "This is a  ucwords Function Test";
echo ucwords($string);
?> 
Output: This Is A Ucwords Function Test

This function touch only the first letter of each word and leave other characters like they are. We can improve the way how the string is displayed by combining with the strtolower function.

<?
$string= "ThiS is a  ucwords FunctioN Test";
echo ucwords(strtolower($string));
?>

Output will be:This Is A Ucwords Function Test

Remove tabs,spaces,new lines from beginning and end of a string

To remove spaces,tabs and new lines from the beginning and end of a string you should use the function trim(). This function accepts as an input a string, that will be cleaned and returns a string without spaces,tabs and new lines.

<?
$string= "\t \nThis is a  trim Function Test   ";
echo trim($string);
?>

Output: This is a trim Function Test

Remove spaces,tabs and new lines from begining of a string

Similar like trim we can use ltrim to remove spaces,tabs and new lines from the beginning of a string

<?php
$string= "\t \nThis is a  trim Function Test \t\t  ";
echo ltrim($string);
?>

Output: This is a trim Function Test

Remove spaces,tabs and new lines from the end of a string

Similar like ltrim we can use rtrim to remove characters that we don’t need:

<?
$string= "\t \nThis is a  rtrim Function Test \t\t  ";
echo rtrim($string);
?>

Remove tags from a string

To remove tags from a string you should use strip_tags to have a clean string without tags

<?php
$string= "<pre>This is a  trim Function Test</ pre>";
echo strip_tags($string);
?>

PHP string manipulation - part 2


Tags: ,
Posted in Codes, PHP/MYSQL | 1 Comment »

PHP cpanel scripts

Written by Codes Tips on June 1, 2009 – 8:50 am -

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: ,
Posted in Codes, PHP/MYSQL, Scripts | No Comments »

PHP xml to csv

Written by Codes Tips on May 23, 2009 – 7:48 am -

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: ,
Posted in Codes, PHP/MYSQL, Scripts | No Comments »

PHP multithreading using cURL

Written by Codes Tips on May 23, 2009 – 3:00 am -

If you wanna get some information from servers using the protocols like http or ftp in PHP you can use cURL to do multithreading.
Multithreading is a term used when we do more jobs in parallel.
First I assume you know what cURL is and what you can it. If you are new to cURL, you can check one of my article on posting data with cURL , it will give you a brief intro to cURL.
To create this with cURL you should know what the following PHP functions do:
curl_multi_init - initialize a new cURL multi handle. It will return the cURL handle on success and FALSE on error.
curl_multi_add_handle — Add a cURL handle to a cURL multi handle.
curl_multi_exec — Runs all the curl handle in the cURL multi handle in parallel.
curl_multi_remove_handle — Removes a cURL handle from a cURL multi handle.
curl_multi_close — close the cURL multi handle.
You will need at least PHP 5.0 installed on your server in order this cURL function to work.

So now that you know what this functions do, we should first create the links to the servers from were we wanna get info. I will assume that we wanna get information from 3 servers simultaneous:

$list[1] = "http://www.example1.com";
$list[2] = "ftp://example.com";
$list[3] = "http://www.example2.com";

After creating the list of links we should initialize the cURL multi handle and adding the cURL handles.

$curlHandle = curl_multi_init();
for ($i = 1;$i <= 3; $i++)
 $curl[$i] = addHandle($curlHandle,$list[$i]);

Now we should execute the cURL multi handle retrive the content from the sub handles that we added to the cURL multi handle.

ExecHandle($curlHandle);
for ($i = 1;$i <= 3; $i++)
{
 $text[$i] =  curl_multi_getcontent ($curl[$i]);
 echo $text[$i];
}

In the end we should release the handles from the cURL multi handle by calling curl_multi_remove_handle and close the cURL multi handle:

 
for ($i = 1;$i <= 3; $i++)//remove the sub - handles
  curl_multi_remove_handle($curlHandle,$curl[$i]);
curl_multi_close($curlHandle);

Here is the complete code for doing multithreading in php with cURL:

<?
//add a url to the handler
function addHandle(&$curlHandle,$url)
{
$cURL = curl_init();
curl_setopt($cURL, CURLOPT_URL, $url);
curl_setopt($cURL, CURLOPT_HEADER, 0);
curl_setopt($cURL, CURLOPT_RETURNTRANSFER, 1);
curl_multi_add_handle($curlHandle,$cURL);
return $cURL;
}
//execute the handle until the flag passed
// to function is greater then 0
function ExecHandle(&$curlHandle)
{
$flag=null;
do {
//fetch pages in parallel
    curl_multi_exec($curlHandle,$flag);
} while ($flag > 0);
}
 
 
$list[1] = "http://www.example1.com";
$list[2] = "ftp://example.com";
$list[3] = "http://www.example2.com";
$curlHandle = curl_multi_init();
for ($i = 1;$i <= 3; $i++)
 $curl[$i] = addHandle($curlHandle,$list[$i]);
ExecHandle($curlHandle);
for ($i = 1;$i <= 3; $i++)
{
 $text[$i] =  curl_multi_getcontent ($curl[$i]);
 echo $text[$i];
}
for ($i = 1;$i <= 3; $i++)//remove the handles
  curl_multi_remove_handle($curlHandle,$curl[$i]);
curl_multi_close($curlHandle);
?>

Download complete source


Tags:
Posted in Codes, PHP/MYSQL | 1 Comment »

PHP ajax cascading dropdown using MySql

Written by Codes Tips on May 16, 2009 – 5:31 pm -

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: , ,
Posted in AJAX, Codes, PHP/MYSQL, Scripts | 15 Comments »

PHP copy directory from source to destination

Written by Codes Tips on May 2, 2009 – 1:02 pm -

To copy a directory source to a destination directory you will need to scan the source directory with all files and directory and copy to the destination. To accomplish this we should make a recursive function that will copy the files from source to target dir. If it is not a directory in the source dir we should just copy the file to target. If it is a directory in the source dir then we should create a new dir in the target directory and apply the same mechanism, so we need to recall again the same function.
Here is the code to do this:

<?
function copy_directory( $source, $destination ) {
	if ( is_dir( $source ) ) {
		@mkdir( $destination );
		$directory = dir( $source );
		while ( FALSE !== ( $readdirectory = $directory->read() ) ) {
			if ( $readdirectory == '.' || $readdirectory == '..' ) {
				continue;
			}
			$PathDir = $source . '/' . $readdirectory; 
			if ( is_dir( $PathDir ) ) {
				copy_directory( $PathDir, $destination . '/' . $readdirectory );
				continue;
			}
			copy( $PathDir, $destination . '/' . $readdirectory );
		}
 
		$directory->close();
	}else {
		copy( $source, $destination );
	}
}
?>

Calling the function:

copy_directory('dirnameSource','dirnameDestination');

Download copy directory code


Tags: ,
Posted in Codes, PHP/MYSQL | 1 Comment »

PHP logout script

Written by Codes Tips on April 25, 2009 – 4:19 pm -

This is a short php logout script for logging out a user that you previously logged in through your website:

<?
function redirect($url)
{
  echo "<META HTTP-EQUIV=\"Refresh\" CONTENT=\"0;URL=$url\">";
  echo "Click <a href=$url>".here.'</a> if you not get redirected';
}
  session_start();//initialize the session data
  $_SESSION['session_user'] = '';//clear the session user that you created on login
  unset($_SESSION['session_user']);//destroy the session variable of the user
  //redirect to home page
  redirect('index.php');
?>

Tags: ,
Posted in Codes, PHP/MYSQL | No Comments »

Plugintaylor.com - Plugintaylor and Google Adsense