Friday, December 7, 2007

PHP force file download

How to force file download in PHP



Here is how you can force a client to download a file.

$text = 'force me to download';

header("Content-Length: " . strlen($text) );
header('Content-Type: text/plain');
header('Content-Disposition: attachment; filename=downloadme.txt');

This will force browser to download/save the file named 'downloadme.txt'

You you want to download other types of files here is a small list of types of files that you can use in Content-Type field:

  • "pdf": "application/pdf"
  • "exe": "application/octet-stream"
  • "zip": "application/zip"
  • "xls": "application/vnd.ms-excel"
  • "ppt": "application/vnd.ms-powerpoint"
  • "gif": "image/gif"
  • "png": "image/png"
  • "jpg": "image/jpg"


Thursday, November 29, 2007

MySQL order by rand() optimization

Optimize Order by RAND() in MySQL



Where when are dealing with large databases, and you want to query you database using ORDER BY RAND(), you will your query is very slow. This article shows you how to speed up this kind of queries.

http://akinas.com/pages/en/blog/mysql_random_row/

Your optimized ORDER BY RAND() queries will be hundreds time faster now.

Wednesday, November 28, 2007

MySQL Data Types

MySQL Data Types



I found a great link, where MYSQL Data Types are detailed. If you need to know just how much space each data type takes, you should read this great article about mysql data types. It will help you to create the best structure (optimized structure) for your database. The database structure and optimization is important when you deal with large amount of data(millions of records for example).


Here is the link http://www.peachpit.com/articles/article.aspx?p=30885&seqNum=7

Friday, November 16, 2007

Smarty format date

How to format date in Smarty



When you extract a date field from database, it is in the format yyyy-mm-dd. But maybe you want to list it other format, for example dd-mm-yyyy. You can retrieve this format directly from database, usign MySQL function DATE_FORMAT, or if you are using Smarty you can use date_format function.

Here is an example of Smarty date formatting:

{$smarty.now|date_format:"%d:%m:%Y"}

This will format current time, in dd-mm-yyyy format.
You can find all date conversions on smarty website.


Formatting dates using Smarty

Tuesday, November 13, 2007

Disabling magic quotes in PHP

How to disable magic quotes




You cannot disable magic quotes from .htaccess or php.ini, only from apache httpd.conf file.

You can use PHP to disable magic quotes at runtime. Here is the function:

if (get_magic_quotes_gpc()) {
function
stripslashes_deep($value)
{
$value = is_array($value) ?
array_map('stripslashes_deep', $value) :
stripslashes($value);

return
$value;
}

$_POST = array_map('stripslashes_deep', $_POST);
$_GET = array_map('stripslashes_deep', $_GET);
$_COOKIE = array_map('stripslashes_deep', $_COOKIE);
$_REQUEST = array_map('stripslashes_deep', $_REQUEST);
}

This function will strip slashes for all REQUEST values. If you make SQL queries with these values, you have to use mysql_real_escape_string function in order to prevent sql injection.


Disabling magic quotes, using Apache and PHP

Monday, November 12, 2007

Change text link in Javascript

How to change a link text in Javascript



Let's say you have a link, with the anchor text 'mylink', and you want to change this text using Javascript. For this we will use innerHTML attribute. Here it is:

document.getElementByID( 'mylinkid' ).innerHTML = 'my new link text';

You will probably need this if youn need to show/hide some html elements.


Changing text in a link using Javascript

Saturday, November 10, 2007

Javascript explode function

Javascript function like PHP explode function



Looking for an explode function in Javascript? JS has such a function, called split. Split take a string, and splits it by a separator, then return an array containing the result. So it works just like explode PHP function.

Example:

var mystring = 'test explode split string';
var myarray = mystring.split(" ");

Split array would have 4 elements: test, explode, split, string.

So javascript split function is the equivalent of explode function in PHP.

Thursday, November 8, 2007

Form Validation with PHP

Validating forms in PHP


Using validation class from PEAR http://pear.php.net/package/Validate, it's very easy to validate forms. Forms validation is neede in order to protect your website from xss injection, sql injection, email injection. For example if you are expecting an email address in a field, you should validate that field for an email address.

This class validation from PEAR has the following validation methods:
  • number
  • email
  • date
  • string
  • and more
All you have to do is download this validation class from PEAR, and you now can have a safe website by validationg user input. Open downloaded class, and you will see all the methods, with all the parameters required for each validation method.

How to validate form submission in PHP

Tuesday, November 6, 2007

How to check if a text exists in a string

How to check if a substring exists in a string in PHP



Having a string:

$mystring = 'teststringforme';

I want to know if, for example, 'for' exists in $mystring. Using PHP function strpos, it's very easy.

if( strpos( $mystring, 'for' ) !== false )
{
echo 'string exists';
}
else
{
echo 'string does not exist';
}


Find if a text exists in a string using PHP

Monday, November 5, 2007

Replace string in MySQL

Replacing a string in MySQL



So you have hundreds of records in a table, and you want to replace a string in a single query.
You could use the REPLACE MySQL function. Here is your replace query:

UPDATE yourtable SET yourfield = REPLACE(yourfield,"some_string","some_new_string")
WHERE yourconditions.

This query replaces "some_string" with "some_new_string" in "yourfield" field. You can also add some conditions in WHERE statement.

How to replace a string in mySQL

Friday, November 2, 2007

How to parse CSV files in PHP

Parsing CSV files in PHP



CSV - comma separated values. Values in a CSV file are separated by comma.

Eg:

name, score
john, 10
brian, 5
jane, 8

So how do you get values from a CSV file in PHP? The easiest way to is to use PHP function fgetcsv . Read the documentation about this function, and there is also an easy example there.

Using CSV files, is a good option if you don't have access or you don't want to use a database. After you parse the CSV file, you can get the values in an array, and then display them any way you want on the web page.

PHP parse csv file

Thursday, November 1, 2007

Sending mail with PHP

How to send mail using PHP



Using phpmailer class, you can send email with PHP very easy. You can download phpmailer from here. PHP has many options, mail can be sent using SMTP or php mail function. You can also add attachments, add BCCs, CCs and send HTML email. I've been using this class for a while, and I am very happy with it. Some examples can be found here.

Send mail in PHP tutorial

How to alternate row colors with php

Alternate colors in table rows with php



Alternating colors in php, it's simple. Here is the code:



foreach( $array_values as $value )
{
$counter++;
$background_color = ( $counter % 2 == 0 ) ? ('blue') : ('red');

echo '<tr><td style="background-color:'.$background_color.'">' . $value . '</td></tr>';
}


As you can see it's simple. If the current row number is even the color is blue, if the row number is odd, background color is red. This is just an example, you can alternate what colors you want using php. $array_values array can be an array coming from a database query.

Sunday, October 28, 2007

Store images on disk or database?

Should you store uploaded images on disk or database?



I store my uploaded images on disk, and not in database. Why? One thing is that most hosting providers limit the mysql database. So if you have a large number of images, the database won't be enough for you. In database I keep the path and the filename, and the file is kept on the disk.
Also, having the images stored on the disk, you can access them very easy with ftp clients for example. Showing the image in the browser, does not affect database server's performance, having the image stored on the disk.

Thursday, October 18, 2007

Get number of characters in Javascript

How to count number of characters in a string in Javascript

length javascript's function returns the length (number of characters) of a given string.

For example:



var mystring = 'test string';

alert( mystring.length ) ;


This will alert a window with the number of characters of mystring variable.

If you want to get number of characters in a textfield using javascript, that you need to call the same function, length this way:


alert( document.yourform.yourfieldname.value.length );

Tuesday, October 16, 2007

PHP MySQL Calendar Class

PHP MySQL Calendar Class



PEAR has this great calendar class . There is no need for you to waste your time by building a calendar class, this is a great one. Documentation for this class can be found here.

Some working examples of this calendar class written in php and mysql can be found here. As you can see it is really easy to work with this class, and it is well documented. You can easily extend it and use it for your own needs.

Javascript open centered popup window

How to open a centered pop-up window in Javascript


Here is a Javascript function that allows you to open a centered window, no matter what resolution the visitor uses.

function OpenCenteredWindow( url, width, height )
{
var left = Math.floor( (screen.width - width) / 2);
var top = Math.floor( (screen.height - height) / 2);
var winParms = "top=" + top + ",left=" + left + ",height=" + height + ",width=" + width;
winParms += ",toolbar=no,status=no,scrollbars=yes,menubar=no,resizable=no,location=no,directories=no";
var win = window.open(url, '', winParms);
if (parseInt(navigator.appVersion) >= 4) { win.window.focus(); }
return win;
}

There are three parameters:
  • url - the address you want to open in the new window
  • width - the width of the new popup window
  • height - the height of the new centered window
Also you can set what parameters the new window will have: toolbar, status, scrollbars, menubar, resizable, location, directories.

Change upload file size apache

How to change the PHP maximum upload file size



The default maximum upload size for files is 2MB. If you have access to .htaccess files, you can change the maximum upload size from there. Here is what you should write in .htaccess files for apache:

php_value max_execution_time 1200
php_value memory_limit 30M
php_value post_max_size 10M
php_value upload_max_filesize 10M

In the first line you increase maximum execution time from 30 seconds (default) to 1200 seconds. This way if the file is large, you won't get a timeout browser error.
In the second line you increase memory limit to 30MB.
The third line increases post maximum size to 10MB.
And the last line increases upload maximum filesize to 10MB.

Friday, October 12, 2007

Upload and image manipulation class

So you want to upload your files, but also validate extensions, size. You can use PEAR's HTTP_Upload class for that.

And then if you want to only upload images, and create thumbnails, resize images or crop the uploaded images, you can use the above upload class and this great Thumbnailer Class

This two classes make a powerful tool for uploading ,validating, resizing, cropping, rotating images or pictures.

PEAR MDB2 get array rows

This tip is for those who use PEAR MDB2 as your database abstraction layer. There are two nice methods, that are not in documentation, queryRow($query) and queryAll($query).

queryRow($query) - returns an associative array for one record
queryAll($query) - return an associative array for all found records

So for those who like to use arrays (like myself) you don't have to use fetchRow() anymore.

Documentation for this class can be found here.

Tuesday, October 9, 2007

Permanent redirect to www domain

You have a domain anydomain.com, and you want a permanent redirect (301) to www.anydomain.com. You can do this using a .htaccess file. Here it is:

RewriteEngine on
RewriteCond %{HTTP_HOST}!^www.anydomain.com
RewriteRule ^(.*)$ http://www.anydomain.com/$1 [R=301,L]

So if someone types anydomain.com, he will be redirected to www.anydomain.com. easy.

Javascript change element visibility

Want to change an element visibility from javascript. Here is an example.

document.getElementById("your_element_id").style.visibility = "hidden";
document.getElementById("your_element_id").style.visibility = "visible";

As you can see the visibility for an element can be hidden or visible. Make sure you have set an ID for your element.

Monday, October 8, 2007

MySQL get date from string

Let's say you have a string, like '18-Sep-2007' and you want to format it in date format %Y-%m-%d. You can use STR_TO_DATE function. First parameter is your string, and the second parameter is the format of your string, in this case %d-%b-%Y. You can see the format values here:
http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_date-format

So STR_TO_DATE('18-Sep-2007','%d-%b-%Y') = 2007-09-18

You can use this result to compare dates, to order dates, or other date operations.

Saturday, October 6, 2007

PHP useful classes

Here is a list of PHP tools or classes I use to develop my projects.

PHP MySQL Blog

Hello,

Here I will post tips and tricks about PHP and MySQL. Everything I will find useful you will find here, so you won't have to search lots of pages on the internet. Also if you have any question please post a message, and I will try to help you.