Tuesday, December 20, 2011

.htaccess file for http authentication

Linux

Create a .htaccess file with the following values

AuthType Basic
AuthName "Massagebook"
AuthUserFile /path/.htpasswd
Require valid-user


Now create a .htpasswd file using the following command

htpasswd -c .htpasswd username

now the system will prompt for password
after giving the password, it will be encrypted and saved in a file

:

For windows follow the same method
but the password will not be saved in encryted form but will be saved as it is in the .htpasswd file.

:

Monday, December 19, 2011

php_network_getaddresses: getaddrinfo failed: --Error

uncaught exception: Invalid JSON:
Warning: getimagesize() [function.getimagesize]: php_network_getaddresses: getaddrinfo failed: Name or service not known in


If you get this type of error please check whether you have host entries in your host/driver file.

Wednesday, December 14, 2011

make_sock: could not bind to address 0.0.0.0:80

Centos, apache restart i got the following error

Starting httpd: (98)Address already in use: make_sock: could not bind to address

can anyone tell me what this error means?

# /etc/init.d/httpd restart

Stopping httpd: [ OK ]

Starting httpd: (98)Address already in use: make_sock: could not bind to address [::]:80

(98)Address already in use: make_sock: could not bind to address 0.0.0.0:80

no listening sockets available, shutting down

Unable to open logs

Fix for this problem

just run these 4 commands

# for i in `ps auwx | grep -i nobody | awk {'print $2'}`; do kill -9 $i; done
# for i in `lsof -i :80 | grep http | awk {' print $2'}`; do kill -9 $i; done
# for i in `lsof -i :80 | grep http | awk {' print $2'}`; do kill -9 $i; done
# service httpd restart

Wednesday, December 7, 2011

favicon for website site

We can use the following ways to add <b>favicon </b>for a website

<link rel="icon" href="images/2/mail_icon_32.png" sizes="32x32">
<link ="shortcut icon" href="../images/favicon.ico" type="image/x-icon">

Friday, December 2, 2011

Getting MAC Address using PHP

<?php
/*
* Getting MAC Address using PHP*
*/

ob_start(); // Turn on output buffering
system(‘ipconfig /all’); //Execute external program to display output
$mycom=ob_get_contents(); // Capture the output into a variable
ob_clean(); // Clean (erase) the output buffer

$findme = “Physical”;
$pmac = strpos($mycom, $findme); // Find the position of Physical text
$mac=substr($mycom,($pmac+36),17); // Get Physical Address

echo $mac;
?>

This works in windows XP

Tuesday, November 29, 2011

Drop down Box Selected

<select id="mySelect" multiple="multiple">
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option>
<option value="4">Fourth</option>
</select>

<script type="text/javascript">
$(document).ready(function() {
if (!$("#mySelect option:selected").length)
$("#mySelect option[value='3']").attr('selected', 'selected');
});
</script>

How to get Current year with javascript

var d = new Date();
var curr_date = d.getDate();
var curr_month = d.getMonth();
var curr_year = d.getFullYear();
document.write(curr_date + "-" + m_names[curr_month]
+ "-" + curr_year);

Monday, November 28, 2011

CSS: How to write CSS rules to detect or target Chrome, Safari or Opera browsers only?

It’s easy to target firefox, just write as expected by the standards, at least most of the time. It’s also easy to target IE and any specific versions of them by a few of the famous hacks or the IE conditional comments to selectively include style sheets by version numbers. But how does one write CSS rules and make the browsers to recognize that they are particularly for Chrome, Safari or Opera?

Use PHP to distinguish the browsers.

echo $_SERVER['HTTP_USER_AGENT'];

Put this line in a .php file, upload the file to your server and browse to it by all the different browsers you have. From the server side, $_SERVER['HTTP_USER_AGENT'] contains all the information PHP knows about the source of the request, namely your browser. Now that the server is able to recognize the client browser, you can serve up different versions of a web page by PHP and include different CSS classes according to the browser type:

if (strpos($_SERVER['HTTP_USER_AGENT'], 'Safari') !== false) {
// Chrome user agent string contains both 'Chrome' and 'Safari'
if (strpos($_SERVER['HTTP_USER_AGENT'], 'Chrome') !== false) {
echo '';
} else {
echo '';
}
} elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'Opera') !== false) {
echo '';
} else {
echo '';
}

The rest is very simple. Just cascade your styles by additional classes to adapt your design to Safari, Chrome or Opera specifically. You can do a lot more than this by the server side variable $_SERVER['HTTP_USER_AGENT'], such as detecting browser versions and operating systems or writing your own web traffic statistics software.

Howto recover gnome-panel

disappeared Application Menu, Places Menu and System Menu in ubuntu / debian Linux

Reseting Gnome Settings

If your gnome-panel corrupt , Application Menu, Places Menu and System Menu and some other menu items will disappear.
How to recover it

Boot the system upto Login Window. Press Ctrl + Alt+F1

Now You will get a Text based login screen

login with your username and password

now you will get a $ prompt.

Type the following Command

$ rm -rf .gnome .gnome2 .gconf .gconfd

Now Press Ctrl + Alt+F7

and login Gnome. Every thing appear in the menu bar.

Thursday, November 17, 2011

Rotate image using canvas

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr" lang="fr">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>rotate()</title>

<style type="text/css" media="screen">
img, canvas { border: 1px solid black; }
</style>


<script type="text/javascript">

function rotate(p_deg) {
if(document.getElementById('canvas')) {
/*
Ok!: Firefox 2, Safari 3, Opera 9.5b2
No: Opera 9.27
*/
var image = document.getElementById('image');
var canvas = document.getElementById('canvas');
var canvasContext = canvas.getContext('2d');
switch(p_deg) {
default :
case 0 :
canvas.setAttribute('width', image.width);
canvas.setAttribute('height', image.height);
canvasContext.rotate(p_deg * Math.PI / 180);
canvasContext.drawImage(image, 0, 0);
break;
case 90 :
canvas.setAttribute('width', image.height);
canvas.setAttribute('height', image.width);
canvasContext.rotate(p_deg * Math.PI / 180);
canvasContext.drawImage(image, 0, -image.height);
//alert(image.height);
break;
case 180 :
canvas.setAttribute('width', image.width);
canvas.setAttribute('height', image.height);
canvasContext.rotate(p_deg * Math.PI / 180);
canvasContext.drawImage(image, -image.width, -image.height);
break;
case 270 :
case -90 :
canvas.setAttribute('width', image.height);
canvas.setAttribute('height', image.width);
canvasContext.rotate(p_deg * Math.PI / 180);
canvasContext.drawImage(image, -image.width, 0);
break;
};

} else {
/*
Ok!: MSIE 6 et 7
*/
var image = document.getElementById('image');
switch(p_deg) {
default :
case 0 :
image.style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(rotation=0)';
break;
case 90 :
image.style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(rotation=1)';
break;
case 180 :
image.style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(rotation=2)';
break;
case 270 :
case -90 :
image.style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(rotation=3)';
break;
};

};
};


window.onload = function() {
var image = document.getElementById('image');
var canvas = document.getElementById('canvas');
if(canvas.getContext) {
image.style.visibility = 'hidden';
image.style.position = 'absolute';
} else {
canvas.parentNode.removeChild(canvas);
};

rotate(0);
};

</script>

</head>

<body>


<p>
rotate:
<input type="button" value="0? onclick="rotate(0);" />
<input type="button" value="90? onclick="rotate(90);" />
<input type="button" value="180? onclick="rotate(180);" />
<input type="button" value="-90? onclick="rotate(-90);" />
</p>


<p>
<img id="image" src="http://www.google.com/intl/en_ALL/images/logo.gif" alt=""/>
<canvas id="canvas"></canvas>
</p>


</body>
</html>

Friday, October 7, 2011

Onbeforeunload event using jQuery

JavaScript: window.onbeforeunload Event - Show “Are you sure you want to leave this page?” Message


Handle window.onbeforeunload event using jQuery

$(window).bind('beforeunload', function() {
return 'You have unsaved changes. If you leave the page these changes will be lost.';
});

Handle window.onbeforeunload event using straight JavaScript

window.onbeforeunload = function(e) {
return 'You have unsaved changes. If you leave the page these changes will be lost.';
};

How to Loop through all elements in a form using javascript

This is a simple method to Loop through all elements in a form using javascript
















Friday, September 30, 2011

Insert all the records from one table to another table

Insert all the records from one table to another table


Insert into new_table_name (select * from old_table_name [where (is needed)])

create table with structure of another table

QUERY TO create table with structure of another table

CREATE TABLE new_tablename LIKE available_table

Monday, September 26, 2011

SSL Encrypt the Transmission of Passwords with https - Xampp

If you don’t have encryption enabled on a password protected folder, the password will be sent in cleartext - meaning that it can be seen by anyone using a network sniffer. It is a good idea to encrypt the transmission of these passwords. There are 2 steps to this process, first we need to create SSL certificates, and then we need to make sure that the password protected pages are only accessed with encryption. It’s also a good idea to import your certificates into any browsers on all machines that you plan to use to access your server, otherwise you’ll get a warning about an untrusted certificate authority.
Create SSL Certificate and Server Private Key

In order to enable the encryption of your password, you must create an SSL certificiate (containing your public key) and a server private key. XAMPP provides a default certificate/key that can be used, but it is better to create a new one since the default key is available to anyone who downloads XAMPP. If someone knows your key, they can decrypt your packets.

XAMPP provides a batch file for creating a new certificate/key with random encryption keys. To execute this batch file, do the following:

Open a command window (Start->Run, type “cmd” and press “OK)
cd c:\xampp\apache
makecert

You will then see this:

C:\xampp\apache>newcert
Loading 'screen' into random state - done
Generating a 1024 bit RSA private key
............................++++++
.....................................++++++
writing new private key to 'privkey.pem'
Enter PEM pass phrase:

Enter in a pass phrase for decrypting your private server key, and press Enter. Write down this passphrase so you don’t forget it. Now you will be asked to verify it:

Verifying - Enter PEM pass phrase:

Enter your passphrase a second time and hit Enter. Now, you’ll see this:

-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:

Enter in your 2 letter country code. You’ll be asked for a few more items (shown below). Enter is what you think is most appropriate, but stop when you are asked for “Common Name”

State or Province Name (full name) [Some-State]:NY
Locality Name (eg, city) []:New York
Organization Name (eg, company) [Internet Widgits Pty Ltd]:Rob's Great Company
Organizational Unit Name (eg, section) []:
Common Name (eg, YOUR name) []:

For “Common Name”, you need to enter in the DNS name or IP address of your website. The name that you enter in here will need to match the server name that is entered into the browser that is accessing the page. It is important that this common name match the address that goes into a browser, otherwise you will get extra warnings when navigating to your secure web pages. If you are running this website over the public internet on an IP address that changes sometimes, you can use a Dynamic DNS service such as dyndns.org to get a free domain name that always points to your server. After you enter in the “Common Name”, you are asked for more information. Fill in what you think is appropriate, but it is OK to just hit ENTER to accept the defaults. Eventually, you will be asked for the pass phrase for privkey.pem:

Email Address []:

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:
Enter pass phrase for privkey.pem:

Enter the pass phrase that you created earlier, and now you will see this:

writing RSA key
Loading 'screen' into random state - done
Signature ok
subject=/C=xx/ST=xx/L=xxxx/O=xxx/CN=commonname
Getting Private key

—–
Das Zertifikat wurde erstellt.
The certificate was provided.

Press any key to continue . . .

C:\xampp\apache>

You are now finished creating your SSL certificate and private key. The makecert.bat script will move your server private key and certificates in the appropriate directories for you.
Import the certificate into the browser for each client

Since this certificate is self signed, and is not signed by a well known Certificate Authority (CA), when you browse to the protected pages you’ll get a warning. To turn off this warning, the certificate should be imported as a trusted CA into any browsers that you will use to access your server.
Importing the certificate into IE 7

Here are the steps to import the certificate into IE 7:

Tools->Internet Options
Content Tab->Certificates Button
Trusted Root Certification Authorities Tab->Import Button

Now you’ll see the “Certificate Import Wizard”
Click Next
Provide file name: c:\xampp\apache\conf\ssl.crt\server.crt
Click Next
Leave default to Place all Certificates in Certificate store: Trusted Root Certification Authorities, and click Next
Click Finish
Importing the certificate into Firefox 2:

Here are the steps to import the certificate into Firefox 2:

Tools->Options
Advanced->Encryption Tab->View Certificates Button
Authorities Tab->Import Button
Select file: c:\xampp\apache\conf\ssl.crt\server.crt, and click “Open”
Check “Trust this CA to identify web sites”
Click “OK’
Click “OK” in Certificate manager
Click “OK” In original Options window to get back into Firefox
Edit Apache config for encryption only access to password protected folders.

Now we will instruct Apache to access the password protected folders with SSL encryption exclusively. This is done in 2 steps. First, we setup the Apache config files for these folders to say they can only be accessed with SSL encryption. Next, we redirect any “http” traffic to these pages to “https” (this is optional).
Make folders accessible with SSL encryption only

First, we need to inform Apache that the folders you want to encrypt should use always use encryption (and never go in the clear). This is accomplished by putting an SSLRequireSSL directive inside of each desired listing in the config files (it is ok to put it at the end, just before the ). The red text below shows what to do.

Alias /web_folder_name “C:/xampp/foldername”



SSLRequireSSL


I suggest doing this for the following folders (if you still have them):

Config File: c:\xampp\apache\conf\extra\httpd-xampp.conf
c:\xampp\phpmyadmin
c:\xampp\htdocs\xampp
c:\xampp\webalizer
c:\xampp\security\htdocs
Config File: c:\xampp\webdav
c:\xampp\webdav

Redirect “http” to “https” for certain folders

This next optional step is to redirect “http” requests to “https” requests for the pages we want to secure. This is more user friendly and allows you to still use http when you type in the address (and automatically switch to https:// and encryption). If you don’t do this, and you used SSLRequireSSL, you will only be able to access these pages by typing https://. This is fine and probably a little bit more secure, but is not so user friendly. To accomplish the redirection, we will use mod_rewrite so that we don’t have to use the server name in this part of the config file. This helps keep small the number of places in the config files where the server name is written (making your config files more maintainable).

First, we need to make sure that mod_rewrite is enabled. To do this, edit c:\xampp\apache\conf\httpd.conf and get rid of the comment (# character) in this line:

#LoadModule rewrite_module modules/mod_rewrite.so

to make it look like this:

LoadModule rewrite_module modules/mod_rewrite.so

Now, paste the following text into the top of c:\xampp\apache\conf\extra\httpd-xampp.conf:


RewriteEngine On

# Redirect /xampp folder to https
RewriteCond %{HTTPS} !=on
RewriteCond %{REQUEST_URI} xampp
RewriteRule ^(.*) https://%{SERVER_NAME}$1 [R,L]

# Redirect /phpMyAdmin folder to https
RewriteCond %{HTTPS} !=on
RewriteCond %{REQUEST_URI} phpmyadmin
RewriteRule ^(.*) https://%{SERVER_NAME}$1 [R,L]

# Redirect /security folder to https
RewriteCond %{HTTPS} !=on
RewriteCond %{REQUEST_URI} security
RewriteRule ^(.*) https://%{SERVER_NAME}$1 [R,L]

# Redirect /webalizer folder to https
RewriteCond %{HTTPS} !=on
RewriteCond %{REQUEST_URI} webalizer
RewriteRule ^(.*) https://%{SERVER_NAME}$1 [R,L]


If you have other folders you want to redirect to https://, add the generic text below (but substitute your folder name):

# Redirect /folder_name folder to https
RewriteCond %{HTTPS} !=on
RewriteCond %{REQUEST_URI} folder_name
RewriteRule ^(.*) https://%{SERVER_NAME}$1 [R,L]

If you are going to host a webdav server, it is probably best to not have this redirection and to just require https://. This way, people can only use https:// when addressing your webdav folder. I tried using redirection for a webdav server and giving http:// in both XP and MAC OS X, and it didn’t work when encryption is required.

One thing to keep in mind with this redirection is that if you have virtual hosts, you need to place the redirection code (with the RewriteCond and RewriteRule) inside of your virtual host declarations, otherwise the redirection won’t work.

Friday, August 26, 2011

Configuration Directives in httpd.conf for file caching in Centos

The Apache HTTP Server configuration file is /etc/httpd/conf/httpd.conf. The httpd.conf file is well-commented and mostly self-explanatory. The default configuration works for most situations; however, it is a good idea to become familiar some of the more important configuration options.

# 480 weeks

Header set Cache-Control "max-age=290304000, public"


also like this

Options FollowSymLinks MultiViews
AllowOverride All
Order allow,deny
Allow from all
ExpiresDefault A300

Expires A86400


Expires A2592000





Wednesday, August 24, 2011

MySQL prep

MySQL prep makes user input safe to use in SQL queries. MySQL prep should be used whenever user input is piped directly into the SQL query to prevent SQL Injection.

The code below is written in Perl but the same concepts apply to any language.

The code does the following:
Removes whitespace at the beginning and end of the string.
Replaces backslashes (\) with double backslash (\\).
Replaces single quotes (') with backslashed single quote (\').
Replaces percent signs (%) with backslashed percent signs (\%) to prevent wildcard errors with MySQL.
Removes all charactors that are not alpha-numeric, whitespace, or special charactors.
sub mysqlprep {
local ($string) = @_;
$string =~ s/^\s+//g;
$string =~ s/\s+$//g;
$string =~ s/\\/\\\\/g;
$string =~ s/\'/\\\'/g;
$string =~ s/\%/\\\%/g;
$string =~ s/[^\w\s\~\`\!\@\#\$\%\^\&\*\(\)\+\-\=\[\]\\\{\}\|\;\'\"\:\,\.\/\?\<\>]//g;
return $string;
}

Tuesday, August 9, 2011

Change datetime in Ubuntu

View Time

To view the current date and time, the following command will be enough

date
Set Time

To change time means to set a new time. To set time in Ubuntu (or any Linux), just run the following command

sudo date newdatetimestring

where newdatetimestring has to follow the format nnddhhmmyyyy.ss which is described below

nn is a two digit month, between 01 to 12
dd is a two digit day, between 01 and 31, with the regular rules for days according to month and year applying
hh is two digit hour, using the 24-hour period so it is between 00 and 23
mm is two digit minute, between 00 and 59
yyyy is the year; it can be two digit or four digit: your choice. I prefer to use four digit years whenever I can for better clarity and less confusion
ss is two digit seconds. Notice the period ‘.’ before the ss.

Let’s say you want to set your computer’s new time to December 6, 2007, 22:43:55, then you would use:

sudo date 120622432007.55

Tuesday, August 2, 2011

Creating a MySQL View directly in phpMyAdmin

It's simple really; create, run, and verify the SQL SELECT statement that generates the results of the view you're looking to create, and then use that to create the view.

After executing the query in SQL :

In the very bottom right corner of the result is a link for creating the view!

You will have to supply:

VIEW name
Column names - a comma delimited list of the names to use for each column in the view

Once you're done, click the Go button to create the view!

OR in sqlyog type :

create view as test select * from categories

Tuesday, July 5, 2011

Find date between 2 date fields

Query to find the date exists between 2 date fields

SELECT *
FROM `hours_of_operation`
WHERE DATE( `schedule_start_date` ) <= '2011-07-06' AND DATE( `schedule_end_date` ) >= '2011-07-06'
LIMIT 0 , 30

Change the collation for a table

query to change the collation of a table.

alter table collate utf8_unicode_ci

To change the default character set and collation of a table including those of existing columns (note the convert to clause):

alter table convert to character set utf8 collate utf8_unicode_ci;

Monday, July 4, 2011

How to assign values in dropdown using jquery

This method gets all the select boxes in the view page.

$("select").each(function(key){
if($(this).attr('id')=='first_name') {
$(this).val('my_first_name');
}

});

Wednesday, June 29, 2011

Issue in APC

Site seems to function without issues, but our error logs just fill with the following PHP errors after enabling APC.

PHP Notice: include() [function.include]: 1. h->opened_path=[null] h-

Windows Server 2008 R2
Apache 2.2
PHP 5.2.17 THREAD-SAFE VC6

For this just changed the error_reporting variable in php.ini to -

error_reporting = E_ALL & ~E_DEPRECATED & ~E_NOTICE

I am getting an error saying The mysql driver is not currently installed

PDO, unlike the mysql_* functions, supports a number of database engines. To do this it needs a driver library for each one.

You have the "core" of PDO installed but not the MySQL driver - just get that installed (called pdo_mysql) and everything will be OK.

Your php.ini should have one of these (windows or linux):

extension=php_pdo_mysql.dll
extension=php_pdo_mysql.so

Enable Short tags in PHP

you need to turn on short_open_tags.

short_open_tag = On

Restart apache..

Friday, June 17, 2011

Install Mcrypt in linux

Command to install Mcrypt is as usual

sudo apt-get install php5-mcrypt
sudo /etc/init.d/apache2 restart

You can install Mcrypt from the PHP Source Tree as a module if you choose.

You first need to ensure you have libmcrypt, libmcrypt-devel, and mcrypt installed, then do:

# cd php-5.x.x/ext/mcrypt
# phpize
# aclocal
# ./configure
# make && make install

Enable the module by adding: 'extension=mcrypt.so' to PHP.ini.
Now restart Apache and you can see Mcrypt working :)

Install APC for PHP on Linux

APC is the Alternative PHP Cache, which is a free, open, and robust framework for caching and optimizing PHP intermediate code. What this means is that APC reads your PHP files, parses them into a more efficient binary format and then caches them in memory so that each request for your PHP files and PHP library files can be fed from the parsed cache. This will generally lead to a speed increase when serving a PHP site, especially one with a lot of library files. This post looks at how to install APC for PHP on Linux. The Linux distribution I used was CentOS 5, but it should be fairly similar for most distros.

First of all you need to download the APC code from the PHP PECL library. So change directory to somewhere like /tmp and then get the latest version like so:

$ wget http://pecl.php.net/get/APC
This will always get the latest version, and in my case when I installed it just now downloaded APC-3.0.16.tgz like so:

Now you need to extract the files:

$ tar -zxf APC-3.0.16.tgz

and change into the APC directory:

$ cd APC-3.0.16
The next step is to run the "phpize" command. This requires that you have PHP development package installed. On CentOS this is php-devel (installed by running "yum install php-devel") and it should have a similar name on other Linux distros.

$ phpize
Configuring for:
PHP Api Version: 20041225
Zend Module Api No: 20050922
Zend Extension Api No: 220051025
You then configure APC, telling it where the executable file php-config is. If you don't know where this is, then do this:

$ whereis php-config

which will return something like:

php-config: /usr/bin/php-config /usr/share/man/man1/php-config.1.gz

and then run the configure command like so:

./configure --enable-apc --enable-apc-mmap --with-apxs --with-php-config=/usr/bin/php-config



$ make


$ make install


/etc/init.d/httpd restart
The APC cache will now be enabled. You can confirm this by creating a script which calls the phpinfo() command and looking for the APC section. It will have been switched on by default by adding a "extension=apc.so" line to your /etc/php.ini file, but you may want to add more settings to configure it more. The INSTALL file suggests this (I have put the default values at the end of each line which is what is set if you don't set anything in the php.ini file):

apc.enabled=1 # default = 1
apc.shm_segments=1 # default = 1
apc.shm_size=128 # default = 30
apc.ttl=7200 # default = 0
apc.user_ttl=7200 # default = 0
apc.num_files_hint=1024 # default = 1000
apc.mmap_file_mask=/tmp/apc.XXXXXX # default = no value
apc.enable_cli=1 # default = 0

And that's all there is to it. There is also a monitoring script available so you can see what's being cached and how much memory is being used etc.

Tuesday, June 14, 2011

APC with PHP 5.3 on Xamp Windows

The php_apc.dll version 3.1.3 in 1.7.3 is for php version 5.3.1 and so would not be compatible.

You could download this file:
php_apc-3.1.5-5.3-vc6-x86.zip
from here:
http://downloads.php.net/pierre/
which may be more compatible.

Just follow the procedure to include that you used with the one you copied from XAMPP 1.7.3.

Tuesday, May 24, 2011

Password Protect Sites by .htaccess

Configuration of .htaccess file.
First we must create was is known as the .htaccess authentication file. This file is the key to providing who has access to the files in the directory and what types of operations they are allowed to perform within the directory. This tutorial will restrict who is able to view (GET) files from the directory and upload (POST) files into the directory. For more elaborate security measures, check out Apache's web site.

Open your favorite editor

Using the text below as a guideline, create a text file where /var/www/html/private/ is the absolute path of the directory where you would like to store your authentication usernames/passwords

AuthUserFile /var/www/html/private/.htpasswd
AuthGroupFile /dev/null
AuthName "My Private Directory"
AuthType Basic


require valid-user



Note: the absolute path to the .htpasswd file is very important. If unsure about this path, ask your hosting provider or telnet into the server and from the directory you want to keep your usernames/passwords, type pwd at the shell prompt.

Note: the .htaccess file also protects subdirectories of the directory in which it is placed.

Save this file as .htaccess.

The .htaccess file needs to be placed inside the directory you would like protected. If the file was created on your local workstation, ftp the file into the directory you want protected. If a Unix editor like vi was used, use the mv command to move the file to the required directory.



Configuration of the .htpasswd file


Second we must create the .htpasswd file. This file contains the usernames and passwords of those individuals who we authorize access to our directory, and subdirectories.

In order to create this file you must telnet into your server.

Go to the directory, using the cd command, you specified your AuthUserFile (in this example, we specified /var/www/html/private/).

Type htpasswd -c .htpasswd username to create the .htpasswd file and add "username" to list of authorized users. The program will initially prompt you for a password and then ask you to verify it.


To add new users, use the same command without the -c switch. For example, to add the user foo, type htpasswd .htpasswd foo.

To delete users, open the .htpasswd file, using your favorite unix editor, like vi, and delete the row(s) associated with the specific user(s) that you want to remove.




Test your configuration

Open your browser and type the URL and path to the directory where you placed the .htaccess file. For example, if you placed the .htaccess file in a subdirectory called private that is contained within your web directory, then you would type . If you were successful, you should get a dialog box prompting you for a username and password.



Troubleshooting your configuration
The most common mistake is not using the correct path to the .htpasswd file in step one above. To be certain that you are using the correct absolute path, follow these steps:
Telnet into your server.
Use the change directory command, cd, to access the directory where your .htpasswd file is located.
Use the list files command with the and options (ls -la) to be sure your .htpasswd file is present.
Use the print working directory command (pwd) to display the absolute path to your .htpasswd file. This path should be identical to the path listed in Step 1 (/var/www/html/private/ in the example above).


Another common mistake is misconfiguration of the Apache config file.
If you have a hosting provider, contact technical support to verify that they allow their users to use .htaccess authentication.
If you host your own server, open your Apache config file using your favorite editor (in RedHat® Linux 7.1, the file can be found in /etc/httpd/conf/httpd.conf).
Scroll down the file and make sure the AllowOverride option is set to All.

Wednesday, May 4, 2011

Configuring Zend in Ubuntu

Today when i tried to configure Zend Framework in Ubuntu i felt little difficult at first. But then after i configured it successfully it was an easy task actually. I will explain the step what i followed to do this.

First i downloaded the latest version of zend framework from their website.

http://framework.zend.com/download/latest

Then next i changed my include path in my php.ini file to

include_path = ".:/var/www/ZendFramework/library/Zend/:/usr/share/php5:/usr/share/pear"

and restarted my apache webserver.

The next step was in the terminal create a project. Since i didnt install Zend framework tool i followed the following command.

/var/www/ZendFramework/bin/zf.sh create project myprojectname

and then copied the library folder from my ZendFramework to the project i created.


Successfully my project was launched.

http://localhost/ZendFramework/myprojectname/public/index.php

Thursday, April 28, 2011

Install libphp-phpmailer in Ubuntu

The only PHP function that supports this is the mail() function. However, it does not expose any of the popular features that many email clients use nowadays like HTML-based emails and attachments. There are two proprietary development tools out there that have all the functionality built into easy to use classes: AspEmail(tm) and AspMail. Both of these programs are COM components only available on Windows. PhpMailer implements the same methods (object calls) that the Windows-based components do. Class Features: – Send emails with multiple TOs, CCs, BCCs and REPLY-TOs – Redundant SMTP servers – Multipart/alternative emails for mail clients that do not read HTML email – Support for 8bit, base64, binary, and quoted-printable encoding – Uses the same methods as the very popular AspEmail active server (COM) component – SMTP authentication – Native language support – Word wrapTo install this package in Ubuntu,

$ sudo apt-get install libphp-phpmailer

Monday, April 25, 2011

Function to get client IP address

function get_ip_address() {
foreach (array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR') as $key) {
if (array_key_exists($key, $_SERVER) === true) {
foreach (explode(',', $_SERVER[$key]) as $ip) {
if (filter_var($ip, FILTER_VALIDATE_IP) !== false) {
return $ip;
}
}
}
}
}

or

function getRealIpAddr()
{
if (!empty($_SERVER['HTTP_CLIENT_IP'])) //check ip from share internet
{
$ip=$_SERVER['HTTP_CLIENT_IP'];
}
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) //to check ip is pass from proxy
{
$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
}
else
{
$ip=$_SERVER['REMOTE_ADDR'];
}
return $ip;
}

mysql data directory

Mysql data directory is important part where all the mysql databases storage location.By default MySQL data default directory located in /var/lib/mysql.If you are running out of space in /var partition you need to move this to some other location.

Path to the default data directory of mysql in Ubuntu


/var/lib/mysql

Friday, April 22, 2011

htaccess file to run the two compression scripts and cache images for wordpress

Add entries to your Website .htaccess file to run the two compression scripts and cache images

Add the following to the end of the .htaccess file (usually at the root of your Website). If a file named .htaccess doesn’t exist then create a file named .htaccess in a text editor, add the text below and then transfer to the root of your Site.

# BEGIN Compression and Caching Script per http://wordpresspartner.com

# This calls the ‘compress-css.php’ and ‘compress-js.php’ files


RewriteEngine on
RewriteRule ^(.*\.(css))$ compress-css.php?file=$1
RewriteRule ^(.*\.(js))$ compress-js.php?file=$1


# This enables caching


Header set Cache-Control “max-age=2592000, public”


Header set Cache-Control “max-age=216000, public, must-revalidate”


Header set Cache-Control “max-age=1, private, must-revalidate”



# End Compression Script

The method as described above has been tested with WordPress Sites hosted by Godaddy

Create a PHP file to compress JavaScript for wordpress

?

ob_start(“ob_gzhandler”);

header(“content-type: text/javascript; charset: UTF-8″);

header (“expires: ” . gmdate (“D, d M Y H:i:s”, time() + 302400) . ” GMT”);

header(“Cache-Control: max-age=302400, private, must-revalidate”, true);

echo “/*\n”;

echo file_get_contents($_GET['file']);

?
save the file created in a file for future use

Create a PHP file to compress CSS for Wordpress

Here is the code for that
?
ob_start("ob_gzhandler");
header("content-type: text/css; charset: UTF-8");
header ("expires: " . gmdate ("D, d M Y H:i:s", time() + 302400) . " GMT");
header("Cache-Control: max-age=302400, public, must-revalidate", true);
echo "/*\n";
echo "*/\n";
echo file_get_contents('filename.css');
?

Monday, April 18, 2011

.htaccess file – Increase execution time, session expiry time and file upload size limit



php_value post_max_size 5M

php_value upload_max_filesize 5M

php_value memory_limit 300M

php_value max_execution_time 259200

php_value max_input_time 259200

php_value session.gc_maxlifetime 1200




php_value memory_limit 300M - Set higher default php_value memory_limit in .htaccessupload_max_filesize 5M - it increases default upload limit. The default upload limit is 2MB. the above htaccess increase increases file limit 2mb to 5 mbphp_value max_execution_time: Set the number of seconds a script is allowed to run. If this is reached,the script returns a fatal error. The default limit is 30 seconds or, if itexists, the max_execution_time value defined in the configuration file. Ifseconds is set to zero, no time limit is imposed.php_value session.gc_maxlifetime: The session.gc_maxlifetime only sets the age of the session files that will be deleted whengarbage collection runs.If you have a busy web site with a lot of sessions being created, garbage collection willrun based on session.gc_probability/session.gc_divisor. Despite this being called"probability" I tested this and it is strictly a count. Using the defaultgc_probability/gc_divisor of 1/100, this means that garbage collection will run every 100new sessions (Edit: Actually this occurs within the session_start() coding and would countre-started sessions as well) and delete any existing session files that are older than thesession.gc_maxlifetime. There is no file locking on the session files, so active sessionfiles will be deleted and things like users getting logged out will occur.If this is on shared hosting and the session files are all kept in the default location andsomeone else is using a smaller session.gc_maxlifetime or a more frequentgc_probability/gc_divisor, then any of the session files will get deleted based on thelowest value of gc_maxlifetime and the most frequent gc_probability/gc_divisor.You need to increase session.gc_maxlifetime or make session.gc_divisor larger and if this ison shared hosting, set session.save_path to be a location within your web space.

Tuesday, April 12, 2011

How can i get back the archived emails in gmail

Archiving lets you tidy up your inbox by moving messages from your inbox into your All Mail label, so you don't have to delete anything. Any message you've archived can be found in All Mail, in any labels you've applied to it, and in Gmail search results. When someone responds to a message you've archived, the conversation containing that message will reappear in your inbox.

To archive messages:

1. In your inbox, select a message by checking the box next to the sender's name.
2. Click Archive. (If you have a message open, you can also archive it by clicking the Archive button.

To move an archived message back to your inbox, follow these steps:

1. Click All Mail. (If you don't see All Mail along the left side of your Gmail page, click the More drop-down menu at the bottom of your labels list.
2. Check the box next to the sender's name.
3. Click the Move to Inbox button.

Thursday, April 7, 2011

How to set screen resolution in Ubuntu

In ubuntu 9.1

Goto System->Preferences->Display

IN the screen displayed you can change the resolution.


In ubuntu 10

Goto System->Preferences->Monitor

IN the screen displayed you can change the resolution.

How do I set system time and date from terminal ubuntu ?

you can do that by typing in the following format:

sudo date mmddHHMMYYyy

so
sudo date 060702031980
Sat Jun 7 02:03:00 IST 1980

or

Set hwclock manually:
# hwclock --set --date="9/22/96 16:45:05"

Yes for some reason debian and ubuntu are very date sensitive.

Monday, March 28, 2011

php json_encode returning null if empty

If i am converting an empty array into json using json_encode it is comming as null object.

My output was :

Networkcheckins":[null]

To avoid that we can use this :

/*** create an object ***/
$checkinObjNew = new stdClass;
$checkinObj = array();
$encodedArray = array_map(utf8_encode, $checkinObj);
$checkinObjNew->Networkcheckins = $encodedArray;
print_r(json_encode($checkinObjNew));


Now it will return :
Networkcheckins":[]

Enable Popups in google Chrome

When Google Chrome blocks pop-ups for you, a small blue and white icon with a red "X"on it appears in the far right side of the address bar.

If you click on this icon, you can see a list of the pop-ups blocked for that page. You can click on the items in this list to view them, and you can also select the box to "Always allow pop-ups" from the site you're on (refresh for this change to take effect).

To manage the sites on this pop-up "whitelist," or to disable the pop-up blocker entirely, go to Tools > Options > Under the Hood > Content settings... > Pop-ups.

Wednesday, March 16, 2011

Convert Object To Array With PHP

Converting an object to an array using PHP comes with a small gotcha. One would be forgiven for thinking it is merely a task of casting the object and the job can be completed with a single line of code. This works well for simple objects, however, the task increases in complexity in line with the objects complexity.

Consider the following object that is cast to an array.

/*** create an object ***/
$obj = new stdClass;
$obj->foo = 'foo';
$obj->bar = 'bar';
$obj->baz = 'baz';

/*** cast the object ***/
$array = (array) $obj;

/*** show the results ***/
print_r( $array );
?>

The result from the code above produces an array representation of the object.

Array
(
[foo] => foo
[bar] => bar
[baz] => baz
)

Lets now increase the complexity of the object, so that the object bar is itself an object.

/*** a slightly more complex array ***/
$obj = new stdClass;
$obj->foo = 'foo';
$obj->bar = new stdClass;
$obj->bar->baz = 'baz';

/*** cast the object to array ***/
$array = (array) $obj;

/*** show the results ***/
print_r( $array );
?>

From the code above, the issue becomes a little clearer, as the resulting array contains an instance of stdClass, and not an array.

Array
(
[foo] => foo
[bar] => stdClass Object
(
[baz] => baz
)
)


To remedy this situation, some recursion is required to check for an object, and if an object is found, it is give an array representation.

/*** a complex object ***/
$obj = new stdClass;
$obj->foo = new stdClass;
$obj->foo->baz = 'baz';
$obj->bar = 'bar';

/**
*
* Convert an object to an array
*
* @param object $object The object to convert
* @reeturn array
*
*/
function objectToArray( $object )
{
if( !is_object( $object ) && !is_array( $object ) )
{
return $object;
}
if( is_object( $object ) )
{
$object = get_object_vars( $object );
}
return array_map( 'objectToArray', $object );
}

/*** convert the array to object ***/
$array = objectToArray( $obj );

/*** show the array ***/
print_r( $array );
?>

Now the results show a multi-dimensional array which is a true array representation of the object.

Array
(
[foo] => Array
(
[baz] => baz
)

[bar] => bar
)

Thursday, March 10, 2011

Read mails using Imap

// enter gmail username below e.g.--> $m_username = "yourusername";
$m_username = "gmail username";

// enter gmail password below e.g.--> $m_password = "yourpword";
$m_password = "gmail password";

// enter the number of unread messages you want to display from mailbox or
//enter 0 to display all unread messages e.g.--> $m_acs = 0;
$m_acs = 15;

// How far back in time do you want to search for unread messages - one month = 0 , two weeks = 1, one week = 2, three days = 3,
// one day = 4, six hours = 5 or one hour = 6 e.g.--> $m_t = 6;
$m_t = 0;

//----------->Nothing More to edit below
//open mailbox..........please
$m_mail = imap_open ("{imap.gmail.com:993/imap/ssl}INBOX", $m_username . "@gmail.com", $m_password)


// or throw a freakin error............you pig
or die("ERROR: " . imap_last_error());

// unix time gone by or is it bye.....its certanly not bi.......or is it? ......I dunno fooker
$m_gunixtp = array(2592000, 1209600, 604800, 259200, 86400, 21600, 3600);

// Date to start search
$m_gdmy = date('d-M-Y', time() - $m_gunixtp[$m_t]);

//search mailbox for unread messages since $m_t date
$m_search=imap_search ($m_mail, 'ALL' . $m_gdmy . '');

//If mailbox is empty......Display "No New Messages", else........ You got mail....oh joy
if($m_search < 1){
$m_empty = "No New Messages";}
else {

// Order results starting from newest message
rsort($m_search);

//if m_acs > 0 then limit results
if($m_acs > 0){
array_splice($m_search, $m_acs);
}

//loop it
foreach ($m_search as $what_ever) {

//get imap header info for obj thang
$obj_thang = imap_headerinfo($m_mail, $what_ever);
$message = imap_fetchbody($m_mail,$what_ever,2);

echo "Subject : ".$obj_thang->Subject;
echo "From : ".$obj_thang->fromaddress;
echo "To : ".$obj_thang->toaddress;
echo "
";
echo "Message : ".$message ;
echo "
";
echo date("F j, Y, g:i a", $obj_thang->udate);

//close mailbox bi by bye
imap_close($m_mail);

Recursively create folder

This is an easy way to recursively create folders in PHP

$oldumask = umask(0);
mkdir('./backupfiles/depth1/depth2/depth3/', 0777, true); // or even 01777 so you get the sticky bit set
umask($oldumask);

Wednesday, March 9, 2011

Recordmydesktop in Ubuntu

http://recordmydesktop.sourceforge.net
a nice screen/desktop video recorder, try it

note: you can now install it from the repository through ADD/REMOVE

installation command: sudo apt-get install gtk-recordmydesktop

you can find it in Applications menu --> sound and video --> gtk-recordmydesktop


Using Recordmydesktop

in command line console type the command recordmydesktop
you can stop the recording by pressing ctrl-c
or in gui-front just click record, and just click the white square on system tray to stop
the output is in ogg video format however you can convert it to avi by mencoder

example

Quote:
mencoder -idx input.ogg -ovc lavc -oac mp3lame -o output.avi
*note install mencoder if its not installed by doing
Code:
sudo aptitude install mencoder
then you can upload it to youtube or wherever.

utfencode and utfdecode

Everybody has a file where the database connection is established. They key is to add one more line to set the char encoding to utf8!


$database = mysql_connect($host, $user, $password);
mysql_select_db($db, $database);

mysql_set_charset('utf8', $database);

NOTE: don’t forget that your web page must contain the following meta tag:

meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /

Sample code:


$str = "L'élèvevaà";
$s1 = utf8_encode($str);
$s2 = utf8_decode($s1);
echo $s1;
echo $s2;

Wednesday, March 2, 2011

Imap Install in Ubuntu

Commands to install imap in Ubuntu

sudo apt-get install libc-client2007b libc-client2007b-dev


While installing i got an error in crossplatformui. So i removed this package using

sudo apt-get remove crossplatformui

Then give the following commands to continue the installation

sudo apt-get install php5-imap
sudo /etc/init.d/apache2 start


When I run phpinfo(), I get the following imap values:

IMAP c-Client Version: 2004
SSL Support: enabled
Kerberos Support: enabled

Wednesday, February 23, 2011

Broadcom Wireless Setup for Ubuntu 8.04

I used the following steps to enable my Broadcom Wireless

Step 1 (run in terminal)

echo 'blacklist bcm43xx' | sudo tee -a /etc/modprobe.d/blacklist
sudo apt-get install ndiswrapper-utils-1.9
mkdir ~/bcm43xx; cd ~/bcm43xx

For Step 2, You can check your Broadcom wireless version with this command in terminal : "lspci | grep Broadcom\ Corporation",if your wireless device is different from BCM4312 (rev 02), please refer to the following link for this step and you can continue again with step 3 onwards:

https://help.ubuntu.com/community/Wi...f971ca757b2851


Step 2 (run in terminal)

sudo apt-get install cabextract
wget ftp://ftp.compaq.com/pub/softpaq/sp3...00/sp34152.exe
cabextract sp34152.exe

Step 3 (run in terminal)

sudo ndiswrapper -i bcmwl5.inf
ndiswrapper -l
sudo depmod -a
sudo modprobe ndiswrapper
sudo cp /etc/network/interfaces /etc/network/interfaces.orig
echo -e 'auto lo\niface lo inet loopback\n' | sudo tee /etc/network/interfaces
sudo ndiswrapper -m
echo 'ndiswrapper' | sudo tee -a /etc/modules
echo 'ENABLED=0' | sudo tee -a /etc/default/wpasupplicant

Step 4 (run in terminal)

sudo aptitude remove b43-fwcutter

Step 5 (run in terminal)

sudo gedit /etc/init.d/wirelessfix.sh

Step 6

Paste the followings in the opened file(wirelessfix.sh)and make sure you save it before continuing Step 7

#!/bin/bash
modprobe -r b44
modprobe -r b43
modprobe -r b43legacy
modprobe -r ssb
modprobe -r ndiswrapper
modprobe ndiswrapper
modprobe b44

Step 7 (run in terminal)

Run this :

cd /etc/init.d/ && sudo chmod 755 wirelessfix.sh

Step 8 (run in terminal)

finally run this:

sudo update-rc.d wirelessfix.sh defaults

Step 9

Restart your machine and enjoy the freedom from those wires....

Friday, February 18, 2011

phpMyAdmin: No activity within 1440 seconds; please log in again

phpMyAdmin’s “No activity within 1440 seconds; please log in again” message is slowly but definitely driving you crazy. How to remain sane?

Solution

Increase the time limit. Open the file /etc/phpmyadmin/config.inc.php and add the following line to its end:


$cfg['LoginCookieValidity'] = 60 * 60 * 8; // in seconds (8 hours)
Here I set 8 hours, but you can change that.

When you log in again in phpMyAdmin, this new value will be taken into account.

Please make sure that gc_maxlifetime in php.ini is set greater than the given value

Thursday, February 10, 2011

Time Difference

We can find the days, hours, minutes, year difference


SELECT TIMESTAMPDIFF( HOUR , '2011-02-10 11:14:36' , NOW( )) ;

Also this,

SELECT TIMEDIFF( NOW( ) , '2011-02-10 14:06:36' ) ;



There is also a way to add values to date using

SELECT TIMESTAMPADD( HOUR , '2011-02-10 11:14:36' , NOW( )) ;

Wednesday, February 9, 2011

Fix : Could not reliably determine the server’s fully qualified domain name, using 127.0.1.1 for ServerName

Many of us face the same following error we restarting the Apache server on Ubuntu.


sudo /etc/init.d/apache2 restart
* Restarting web server apache2 apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.1.1 for ServerName
... waiting apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.1.1 for ServerName


To fix that problem, you need to edit the httpd.conf file. Open the terminal and type

sudo gedit /etc/apache2/httpd.conf

By default httpd.conf file will be blank. Now, simply add the following line to the file

ServerName localhost

Save the file and exit from gEdit.

Finally restart the server.

sudo /etc/init.d/apache2 restart

Friday, February 4, 2011

xml output using DOM

//http://codeigniter.com/wiki/Amfphp_and_CI/

$dom=new DomDocument("1.0",'utf-8');

$themes = $dom->createElement('zoggin');

$dom->appendChild($themes);


$theme = $dom->createElement('theme');

$themes->appendChild($theme);



//blog template Id

$template = $dom->createAttribute('themeId');

$theme->appendChild($template);



$idValue = $dom->createTextNode($themeId);

$template->appendChild($idValue);



//height of image snapshot

$imageHeight = $dom->createAttribute('height');

$theme->appendChild($imageHeight);



$heightValue = $dom->createTextNode($height);

$imageHeight->appendChild($heightValue);



//width of image snapshot

$imageWidth = $dom->createAttribute('width');

$theme->appendChild($imageWidth);



$widthValue = $dom->createTextNode($width);

$imageWidth->appendChild($widthValue);



//open Path

$path = $dom->createAttribute('path');

$theme->appendChild($path);



$pathValue = $dom->createTextNode($openPath);

$path->appendChild($pathValue);





$dom->formatOutput = true;

header("content-Type: text/xml");

$service = $dom->saveXML();

//Image Snapshot

/*$snapshot = $dom->createAttribute('snapshot');

$theme->appendChild($snapshot);



$snapValue = $dom->createTextNode($snapShot);

$snapshot->appendChild($snapValue);*/



//thumbnail Path

$path = $dom->createAttribute('thumbnailPath');

$theme->appendChild($path);



$pathValue = $dom->createTextNode($imagePath);

$path->appendChild($pathValue);


$dom->formatOutput = true;

header("content-Type: text/xml");

$service = $dom->saveXML();



echo $service;

?>

creating json or xml based services

/* require the user as the parameter */
if(isset($_GET['user']) && intval($_GET['user'])) {

/* soak in the passed variable or set our own */
$number_of_posts = isset($_GET['num']) ? intval($_GET['num']) : 10; //10 is the default
$format = strtolower($_GET['format']) == 'json' ? 'json' : 'xml'; //xml is the default
$user_id = intval($_GET['user']); //no default

/* connect to the db */
$link = mysql_connect('localhost','username','password') or die('Cannot connect to the DB');
mysql_select_db('db_name',$link) or die('Cannot select the DB');

/* grab the posts from the db */
$query = "SELECT post_title, guid FROM wp_posts WHERE post_author = $user_id AND post_status = 'publish' ORDER BY ID DESC LIMIT $number_of_posts";
$result = mysql_query($query,$link) or die('Errant query: '.$query);

/* create one master array of the records */
$posts = array();
if(mysql_num_rows($result)) {
while($post = mysql_fetch_assoc($result)) {
$posts[] = array('post'=>$post);
}
}

/* output in necessary format */
if($format == 'json') {
header('Content-type: application/json');
echo json_encode(array('posts'=>$posts));
}
else {
header('Content-type: text/xml');
echo '';
foreach($posts as $index => $post) {
if(is_array($post)) {
foreach($post as $key => $value) {
echo '<',$key,'>';
if(is_array($value)) {
foreach($value as $tag => $val) {
echo '<',$tag,'>',htmlentities($val),'';
}
}
echo '';
}
}
}
echo '
';
}

/* disconnect from the db */
@mysql_close($link);
}

Tuesday, January 11, 2011

Rewrite php file extensions to HTML

Most of the developers like to show PHP files as HTML. This can be done via htaccess. .htaccess files (or “distributed configuration files”) provide a way to make configuration changes on a per-directory basis. In htaccess, we have Rewrites. Htaccess Rewrites are enabled by using the Apache module mod_rewrite, which is one of the most powerful Apache modules and features availale. Htaccess Rewrites through mod_rewrite provide the special ability to Rewrite requests internally as well as Redirect request externally. So, if URL comes like http://www.vijayakumar.org/example.html. This URL will be rewritten as http://www.vijayakumar.org/example.php. To do this, we want to place the below line into htaccess, which was presented in root directory(htaccess will be hidden, try accessing hidden files in your root directory. If not presented?, please create a new htaccess file in root directory).

RewriteRule (.*)\.html $1.php

Friday, January 7, 2011

Send mail with attachment

function

function mail_attachment($filename, $path, $mailto, $from_mail, $from_name, $replyto, $subject, $message) {
$file = $path.$filename;
$file_size = filesize($file);
$handle = fopen($file, "r");
$content = fread($handle, $file_size);
fclose($handle);
$content = chunk_split(base64_encode($content));
$uid = md5(uniqid(time()));
$name = basename($file);
$header = "From: ".$from_name." <".$from_mail.">\r\n";
$header .= "Reply-To: ".$replyto."\r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n";
$header .= "This is a multi-part message in MIME format.\r\n";
$header .= "--".$uid."\r\n";
$header .= "Content-type:text/plain; charset=iso-8859-1\r\n";
$header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$header .= $message."\r\n\r\n";
$header .= "--".$uid."\r\n";
$header .= "Content-Type: application/octet-stream; name=\"".$filename."\"\r\n"; // use different content types here
$header .= "Content-Transfer-Encoding: base64\r\n";
$header .= "Content-Disposition: attachment; filename=\"".$filename."\"\r\n\r\n";
$header .= $content."\r\n\r\n";
$header .= "--".$uid."--";
if (mail($mailto, $subject, "", $header)) {
echo = "mail send ... OK"; // or use booleans here
} else {
echo = "mail send ... ERROR!";
}
}

function to sent mail with attachment

$my_file = "somefile.zip";
$my_path = $_SERVER['DOCUMENT_ROOT']."/your_path_here/";
$my_name = "Olaf Lederer";
$my_mail = "my@mail.com";
$my_replyto = "my_reply_to@mail.net";
$my_subject = "This is a mail with attachment.";
$my_message = "Hallo,\r\ndo you like this script? I hope it will help.\r\n\r\ngr. Olaf";
mail_attachment($my_file, $my_path, "recipient@mail.org", $my_mail, $my_name, $my_replyto, $my_subject, $my_message);

Unzip recursive

$file = "lightbox.zip";
$dir = getcwd();
function Unzip($dir, $file, $destiny="")
{
$dir .= DIRECTORY_SEPARATOR;
$path_file = $dir . $file;
$zip = zip_open($path_file);
$_tmp = array();
$count=0;
if ($zip)
{
while ($zip_entry = zip_read($zip))
{
$_tmp[$count]["filename"] = zip_entry_name($zip_entry);
$_tmp[$count]["stored_filename"] = zip_entry_name($zip_entry);
$_tmp[$count]["size"] = zip_entry_filesize($zip_entry);
$_tmp[$count]["compressed_size"] = zip_entry_compressedsize($zip_entry);
$_tmp[$count]["mtime"] = "";
$_tmp[$count]["comment"] = "";
$_tmp[$count]["folder"] = dirname(zip_entry_name($zip_entry));
$_tmp[$count]["index"] = $count;
$_tmp[$count]["status"] = "ok";
$_tmp[$count]["method"] = zip_entry_compressionmethod($zip_entry);

if (zip_entry_open($zip, $zip_entry, "r"))
{
$buf = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
if($destiny)
{
$path_file = str_replace("/",DIRECTORY_SEPARATOR, $destiny . zip_entry_name($zip_entry));
}
else
{
$path_file = str_replace("/",DIRECTORY_SEPARATOR, $dir . zip_entry_name($zip_entry));
}
$new_dir = dirname($path_file);

// Create Recursive Directory
$oldumask = umask(0);
@mkdir($new_dir, 0777);


$fp = @fopen($dir . zip_entry_name($zip_entry), "w+");
fwrite($fp, $buf);
@fclose($fp);
umask($oldumask);
zip_entry_close($zip_entry);
}
echo "\n";
$count++;
}

zip_close($zip);
}
}
Unzip($dir,$file);

Thursday, January 6, 2011

Unzip files - Zip_open

Simple script to unzip files using zip_open functions

$filename = basename("check1.zip");
$name = explode('.',$filename);

$zip = zip_open("check1.zip");
if ($zip) {
while ($zip_entry = zip_read($zip)) {
$oldumask = umask(0);
@mkdir($name[0], 0777);
umask($oldumask);
$fp = @fopen(zip_entry_name($zip_entry), "w+");
if (zip_entry_open($zip, $zip_entry, "r")) {
$buf = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
@fwrite($fp,"$buf");
zip_entry_close($zip_entry);
@fclose($fp);
}
}
zip_close($zip);
}