JavaTechie

Its all about Technology

howto create csv file in php February 12, 2009

Filed under: Apache, PHP — javatechie @ 10:34 am
Tags: ,

<?
$dbconnection;
$table=”members”;

$csv = NULL;
/* link identifier from db connection */

$r = mysql_query(“SHOW COLUMNS FROM “.$table);
while ($row = mysql_fetch_assoc($r)) {
$csv .= $row['Field'].’,';
}
$csv = substr($csv, 0, -1).”n”;
$r = mysql_query(“SELECT * FROM “.$table);
while ($row = mysql_fetch_assoc($r)) {
$csv .= ‘”‘.join(‘”,”‘, str_replace(‘”‘, ‘”"‘, $row)).”"n”;
}
header(“Content-type: application/vnd.ms-excel”);
header(“Content-disposition: csv; filename=” . date(“Y-m-d”) .”_”.$table.”.csv; size=”.strlen($csv));
echo $csv;
exit;
?>

 

Apache HTTPD Virtual Hosts and SSL September 25, 2008

Filed under: Apache, PHP — javatechie @ 6:29 am
Tags: ,

Apache HTTPD Virtual Hosts allow a single server to host many web sites with different addresses.

Virtual hosts are easy to set up, just check the documentation at http://httpd.apache.org/docs/ . That said, there are two main ways to configure virtual hosting, which you have to keep in mind when starting out. One method involves matching the request host name, IP address, port, or any combination of them to a separate block of HTTPD configuration statements. The other method specifies a directory pattern to use for the document root and cgi-bin based on parts of the host name.

For the former method of configuring virtual hosts, all one needs to do is add a wildcard ServerAlias directive to the VirtualHost block for your domain name.

<VirtualHost 1.2.3.4>
 ServerName domain.tld
 ServerAlias *.domain.tld
 DocumentRoot /var/www/
</VirtualHost>

For the latter, all one needs to do is match against only the domain name, or include subdomains in the pattern, making sure to create the appropriate directory structure.

VirtualDocumentRoot /var/www/%-2/
VirtualDocumentRoot /var/www/%-2/%-3/

Web hosts tend to use the larger VirtualHost method. Smaller shops, or generic mass hosts (departmental or employee hosting within an organization,for example) will find the latter very helpful, particularly when serving out of user’s home directories.

All this is great, but what about SSL? You could start up a separate instance of Apache HTTPD to serve over an SSL connection, but you probably don’t want to do that. There are some advantages, which but that is beyond the scope of this piece. The easiest way is to use a VirtualHost block to match against connections on port 443, the default HTTPS port. Contrary to popular belief, you do not need a separate IP address to do this.

<VirtualHost *:443>
 SSLEngine On
 SSLCertificateFile /etc/httpd/ssl.pem
 DocumentRoot /var/www/
</VirtualHost>

This works just fine if you are only serving one site over HTTPS. The problem comes in when you have multiple domain names being served from the same server which need SSL. Since the SSL certificate needs to be used before the web browser sends a request to the server, the server has no way of picking a domain-specific SSL certificate to use. Name-based matching just won’t work for SSL. This is why proprietors of shared web hosting services demand that you purchase a dedicated IP address if you want to use SSL. IP addresses are known before SSL certificates are used, so by matching based on IP address, we can use domain-specific SSL certificates.

<VirtualHost 1.2.3.4:443>
 SSLEngine On
 SSLCertificateFile /etc/httpd/dom1-ssl.pem
 DocumentRoot /var/www/dom1/
</VirtualHost>

<VirtualHost 1.2.3.5:443>
 SSLEngine On
 SSLCertificateFile /etc/httpd/dom2-ssl.pem
 DocumentRoot /var/www/dom2/
</VirtualHost>

So, to recap, you do not need a separate IP address to use HTTPS. You do need separate IP addresses to use HTTPS on servers with multiple domains using SSL.

 

Find absolute path in PHP September 25, 2008

Filed under: PHP — javatechie @ 6:04 am
Tags:

<?php
$p = getcwd();
echo $p;
?>

 

URL REWRITE MOD_REWRITE IN PHP June 14, 2008

Filed under: PHP — javatechie @ 6:47 am
Tags:

What is mod_rewrite?

Mod_rewrite is an Apache extension which allows you to “rewrite” the URLs of your web pages.

If your server supports this technology (most linux webhosts do nowadays) you are able to rewrite virtually any URL into anything you like. Most often it is used to rewrite the URLs of dynamicly generated webpages such as www.mywebsite.com/index.php?par1=1&par2=2&par3=2… This can easy be ‘translated’ into www.mywebsite.com/par1/par2/par3

Why mod_rewrite?

- Search engine optimization – there are a lot of debates on this topic, but it is still true that the static-looking links rank better than the dynamic ones.

Here is a comfirmation from Google on that topic:

“Your pages are dynamically generated. We’re able to index dynamically generated pages. However, because our web crawler could overwhelm and crash sites that serve dynamic content, we limit the number of dynamic pages we index. In addition, our crawlers may suspect that a URL with many dynamic parameters might be the same page as another URL with different parameters. For that reason, we recommend using fewer parameters if possible. Typically, URLs with 1-2 parameters are more easily crawlable than those with many parameters.”

- User-friendlyness – Some users remember the URLs visally. Even if they bookmark, they can easier recognize a link like www.mywebsite.com/services.html than www.mywebsite.com/index.php?task=12 for example.

- Security – mod_rewrite helps you hide the parametters passed in the application. Basicly your dynamic pages should be secure enough even without mod_rewrite. But hiding the parametters will decrease the danger of attack

How to use it?

Mod_rewrite is really powerful if you are familiar with the regular expressions which it uses.

But learning the whole pattern syntax can be quite complicated, especially for the non-technical user. Thats why i’ll teach you at several simple patterns which are pretty enough to get your website URLs rewritten.

Lets start:

First you need to create a file called .htaccess and place it exactly in the folder where you want the rewriting to take effect (it will also take effect over all subfolders). In case you already have a .htaccess file you can simply add the lines to it (if it already has mode_rewrite directives you can mess them however).

Open it in a simple text editor an start with:

Options +FollowSymLinks
RewriteEngine on

Now the rewrite engine is switched on. You can now start adding as many rewrite rules as you want. The format is simple:

RewriteRule rewrite_from rewrite_to

Here “RewriteRule” is static text, i.e. you should not change. “rewrite_from” is the address which will be typed in the browser and “rewrite_to” – which page the server will actually activate. Both of these can contain “masks”, but in “rewrite_to” we will only use $ and will discuss more or “rewrite_from” part. Let me “meet you” with the very few masks you’ll need and bring you some samples. You’ll see how easy is it.

Let’s stop talking theory and see an example. Let’s imagine your server runs an e-shop, which uses URLs like index.php?task=categories to list the categories, index.php?task=category&id=5 to show a category contents and other parametters in ‘task’ to do other things.

RewriteRule ^(.*).html index.php?task=$1

What does all that mean? This is a rewrite rule which allows you to make your URLs looking as “static”. In this example categories.html will be “translated” to index.php?task=categories.

So you no longer need dynamic URL to list ther categories, but can write categories.html

But what do all these strange characters mean?

- ^ character marks the beginning. I.e. you tell the server that it should not expect anything before it.

- (.*) – This combination is the most often used and it means literally “everything”. So everything you type before “.html” (i.e. your fake file name) will be passed as:

- $1 – This is a parametter, saying where the first mask should be put. If you have more than one masks (masks are everything which you use to represent dynamich text or file names) you can use $2, $3 etc. You’ll seemor ein the following examples.

So, if you have categories.html it will be translated info index.php?task=categories, services.html into index.php?task=services etc…

What if you have more than one parametter? First, you should use some characters as delimiter:

RewriteRule ^(.*)-(.*).html index.php?task=$1&language=$2

Here how you can also pass task and language. For example: categories-englist.html will be translated into index.php?task=categories&language=english.

IMPORTANT: If you first write RewriteRule ^(.*).html index.php?task=$1 The second one may not work. You need to always start from the most complicated rule to the simplest one.

Make it Better:

The rule (.*) is too general and often may prevent you of making more complicated rewriting rules. So it is recommended that you “limit” the rules into something more concrete. Here are a couple of advices:

- Use the “OR” operator. In our e-shop example we have only few possible “tasks” passed to index.php. Lets say:

index.php?task=categories
index.php?task=category
index.php?task=product
index.php?task=services

What will happen if you want to use your static file about.html? It will be rewritten into index.php?task=about and won’t work. So you can use the OR operator and limit the rewriting only to the cases you need:

RewriteRule ^(categories|category|product|services).html index.php?task=$1

This tells the server to rewrite only if the file name is categories.html OR category.html OR product.html OR services.html

- Using “numbers”. You can easy limit the rewriter to rewrite if it meets only numbers at a certain place:

RewriteRule ^category-([0-9]*).html index.php?task=category&id=$1

With ([0-9]*) mask you tell the rewrite engine that on the mask place it should expect onlly numbers. So if it see category-english.html it won’t rewrite to index.php?task=category&id=english, but to index.php?task=category&language=english (because of the rule we have shown above – RewriteRule ^(.*)-(.*).html index.php?task=$1&language=$2.).

Complete example: Here is how will look the final .htaccess file for our imaginary e-shop:

--------
Options +FollowSymLinks
RewriteEngine on

RewriteRule ^(.*)-(.*).html index.php?task=$1&language=$2.
RewriteRule ^(categories|category|product|services).html index.php?task=$1
RewriteRule ^category-([0-9]*).html index.php?task=category&id=$1

 

validate email – Regular expression May 30, 2008

Filed under: PHP — javatechie @ 7:05 am
Tags:

$email = “someone@example.com”;

if(eregi(“^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+
(\.[a-z0-9-]+)*(\.[a-z]{2,3})$”, $email)) {

echo “Valid email address.”;

}

else {

echo “Invalid email address.”;

}

 

image resize with php May 30, 2008

Filed under: PHP — javatechie @ 6:24 am
Tags:

// This is the temporary file created by PHP
$uploadedfile = $_FILES['photo']['tmp_name'];

// Create an Image from it so we can do the resize
$image = $_FILES['photo'];
$ext = strtolower(substr(strrchr($image['name'], “.”), 1));

if($ext==’jpg’ || $ext==’jpeg’)
{
$src = imagecreatefromjpeg($uploadedfile);
}
else if($ext==’gif’)
{
$src = imagecreatefromgif($uploadedfile);
}
else if($ext==’png’)
{
$src = imagecreatefrompng($uploadedfile);
}
// Capture the original size of the uploaded image
list($width,$height)=getimagesize($uploadedfile);

// For our purposes, I have resized the image to be
// 100 pixels wide, and maintain the original aspect
// ratio. This prevents the image from being “stretched”
// or “squashed”. If you prefer some max width other than
// 100, simply change the $target variable
$target=100;
if ($width > $height)
{
$percentage = ($target / $width);
}
else
{
$percentage = ($target / $height);
}
$newwidth = round($width * $percentage);
$newheight = round($height * $percentage);

$tmp=imagecreatetruecolor($newwidth,$newheight);

// this line actually does the image resizing, copying from the original
// image into the $tmp image
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);

// now write the resized image to disk. I have assumed that you want the
// resized, uploaded image file to reside in the ./images subdirectory.
$filename = “images/”. $_FILES['photo']['name'];
imagejpeg($tmp,$filename,100);

imagedestroy($src);
imagedestroy($tmp); // NOTE: PHP will clean up the temp file it created when the request
// has completed.

return $filename;

 

To parse a date which may be delimited with slashes, dots, or hyphens: May 28, 2008

Filed under: PHP — javatechie @ 1:06 pm
Tags:

<?php
// Delimiters may be slash, dot, or hyphen
$date = “04/30/1973″;
list($month, $day, $year) = split(‘[/.-]‘, $date);
echo “Month: $month; Day: $day; Year: $year
\n”;
?>

 

PHP: Upload and Resize an Image May 28, 2008

Filed under: PHP — javatechie @ 1:02 pm
Tags:

You have created a cool contact directory and you want to allow people to upload their own photos, or you want to create an image repository which you upload images and create thumbnails out of them. Whatever it is, you need to be able to upload images and resize them.

PHP has the ability to upload files such as documents or images using the multipart/form-data protocol, but how do you use this and how do you resize the images after they are uploaded?

What you need:

* PHP installed properly
* *NIX OS such as Linux
* djpeg, cjpeg and pnmscale UNIX utility programs (see below)

This script works only with JPEG images. Also I’ll resize the uploaded image only if it is larger than 250×200. Else, I’ll leave it as it is.

Create Upload Form
First we need to create the form to upload the image. The MAX_FILE_SIZE variable needs to be set to the maximum allowable file size (in bytes) for upload. This is set using a hidden field and for this example will set to 50,000 bytes (approx. 50 kb).

Upload Image:
Click browse to upload a local file

Process Uploaded Data
Next we need to process the uploaded information when it is submitted. I’ll do it all on the same page checking for the REQUEST_METHOD to know if the page was POSTed to.

PHP uploads the file to a temp location on your server (defined in php.ini) It also includes the following:

Variable Name Description
$imgfile temporary filename (pointer)
$imgfile_name original filename
$imgfile_size size of uploaded file
$imgfile_type mime-type of uploaded file

NOTE: imgfile is the name given on the form

Before copying the file, we check that a malicious user is not trying to abuse the script by trying to work on files it should not be, such as /etc/passwd. We do this with the PHP function is_uploaded_file(). More detail about this function is at the PHP.net site.

If is_uploaded_file returns TRUE, copy the file from its temp location to where you want it using the PHP copy() function.

if (is_uploaded_file($imgfile))
{
$newfile = $uploaddir . “/” . $final_filename”;
if (!copy($imgfile, $newfile))
{
// if an error occurs the file could not
// be written, read or possibly does not exist
print “Error Uploading File.”;
exit();
}
}

Re-Sizing the Uploaded Image
To resize the uploaded image we use the pnmscale function which scales images in the PNM format. We use djpeg to convert the JPEG images to PNM, and cjpeg to convert them back. Here’s the code to convert, scale and write out a scaled JPG image.

/*== where storing tmp img file ==*/
$tmpimg = tempnam(“/tmp” “MKPH”);
$newfile = “$uploaddir/scaled.jpg”;

/*== CONVERT IMAGE TO PNM ==*/
if ($ext == “jpg”) { system(“djpeg $imgfile >$tmpimg”); }
else { echo(“Extension Unknown. Please only upload a JPEG image.”); exit(); }

/*== scale image using pnmscale and output using cjpeg ==*/
system(“pnmscale -xy 250 200 $tmpimg | cjpeg -smoo 10 -qual 50 >$newfile”);

The above functions are just the basics of the script. There are a few little things added to complete the script. Such as checking the file extension, handling where to copy the file, and changing the upload filename.

Download the complete Script Source
The directory this script runs in (or the upload directory) must be writable by the server

Things to Look Out For

* UNIX does not like filenames with spaces, though it’s fine in Windows and Mac.

* It would be better to not use the filename submitted but instead use a unique id. For example, “EMPID.jpg” where EMPID is the unique id of the employee’s record.

* Make sure your web server has write access to the upload directory

* Pay attention to file locations and paths. Most of the functions in the script use the full filename path. So a slash at the front is much different than a slash at the front for your web server.

Relevant PHP Functions

On php.net, there are User Contributed Notes for all PHP fuctions. These are incredibly helpful. I highly recommend them.

is_uploaded_file()

Handling file uploads (a simple example)

Getting Required Software

The djpeg and cjpeg programs are provided in the libjpeg library package.

The pnmscale programs are provided in the libgr-progs library package.

Both of these packages are available as RPMs for RedHat-compatible systems and can be found at your local RPM Repository such as RPM Find.

 

How can we encrypt the username and password using PHP? May 28, 2008

Filed under: PHP — javatechie @ 5:04 am
Tags:

You can use the MySQL PASSWORD() function to encrypt username and password. For example,
INSERT into user (password, …) VALUES (PASSWORD($password”)), …);

 

How can we know the number of days between two given dates using PHP? May 28, 2008

Filed under: PHP — javatechie @ 5:02 am
Tags:

$date1 = date(’Y-m-d’);
$date2 = ‘2006-07-01′;
$days = (strtotime($date1) – strtotime($date2)) / (60 * 60 * 24);
echo “Number of days since ‘2006-07-01′: $days”;