Add and Remove items with jQuery

jQuery has been around for a while but only about a year ago I started to use it and understanding how easier life can be when using and implementing solutions with jQuery.
Creating web apps nowadays means creating something the user can control and many times that means letting them create, add and remove something from the interface you conceived.

Today I’m sharing a short and simple tutorial that will teach how to add and remove items from your HTML code using the functions appendTo(); and remove(); from jQuery.
For this particular example I’m not going to be careful creating valid markup although I recommend you to always follow the W3C directives.

Creating the markup

In this example I’m going to create text field and 2 buttons that will allow me to add and remove text fields. Similar to online apps that allow you to create web form.

<a href="#" id="add">Add</a>
<a href="#" id="remove">Remove</a>

<p><input type="text" value="1" /></p>

The <p> around the input is just to add a new line when I add now input’s.


Applying jQuery to the markup


First you need to get jQuery. You can download it from the official jQuery website or use the link from Google Code: http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js


Now you need to call jQuery in the <head> section of you HTML Template using the script tag:


<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js">&lt/script>

Now you need to add the jQuery under the script you just called:


<script type="text/javascript">

$(function() { // when document has loaded

var i = $('input').size() + 1; // check how many input exists on the document and add 1 for the add command to work

$('a#add').click(function() { // when you click the add link
$('<p><input type="text" value="' + i + '" /></p>').appendTo('body'); // append (add) a new input to the document.
// if you have the input inside a form, change body to form in the appendTo
i++; //after the click i will be i = 3 if you click again i will be i = 4
});

$('a#remove').click(function() { // similar to the previous, when you click remove link
if(i > 1) { // if you have at least 1 input on the form
$('input:last').remove(); //remove the last input
i--; //deduct 1 from i so if i = 3, after i--, i will be i = 2
}
});

$('a.reset').click(function() {
while(i > 2) { // while you have more than 1 input on the page
$('input:last').remove(); // remove inputs
i--;
}
});

});
</script>

Here you have it a simple . You need to keep in mind that every time you refresh the page the items will be gone. You’ll need more codding in order to keep the variables on a database. This is just to cover the basic add / remove functions from jQuery.

Labels:

Compress CSS files using PHP

In order to save your precious bandwidth, you should compress your css files. Doing so is not hard at all using this snippet.

header('Content-type: text/css');
ob_start("compress");
function compress($buffer) {
/* remove comments */
$buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer);
/* remove tabs, spaces, newlines, etc. */
$buffer = str_replace(array("\r\n", "\r", "\n", "\t", ' ', ' ', ' '), '', $buffer);
return $buffer;
}

/* your css files */
include('master.css');
include('typography.css');
include('grid.css');
include('print.css');
include('handheld.css');

ob_end_flush();

Usage


Paste the code in a file named style.php. Don’t forget to include your css files (As seen on line 11 in the example). Once done, open your HTML document and import style.php as you’ll import a css stylesheet:


<link rel="stylesheet" href="style.php" type="text/css" media="all">

style.php will contain all your css stylesheets, compressed.

Labels:

PHP Date Range by week and by month

Get date range by this week, last week, this month, and last month options by providing offsets.

<?php
function getWeekRange(&$start_date, &$end_date, $offset=0) {
$start_date = '';
$end_date = '';
$week = date('W');
$week = $week - $offset;
$date = date('Y-m-d');

$i = 0;
while(date('W', strtotime("-$i day")) >= $week) {
$start_date = date('Y-m-d', strtotime("-$i day"));
$i++;
}

list($yr, $mo, $da) = explode('-', $start_date);
$end_date = date('Y-m-d', mktime(0, 0, 0, $mo, $da + 6, $yr));
}

function getMonthRange(&$start_date, &$end_date, $offset=0) {
$start_date = '';
$end_date = '';
$date = date('Y-m-d');

list($yr, $mo, $da) = explode('-', $date);
$start_date = date('Y-m-d', mktime(0, 0, 0, $mo - $offset, 1, $yr));

$i = 2;

list($yr, $mo, $da) = explode('-', $start_date);

while(date('d', mktime(0, 0, 0, $mo, $i, $yr)) > 1) {
$end_date = date('Y-m-d', mktime(0, 0, 0, $mo, $i, $yr));
$i++;
}
}

getWeekRange($start, $end);
echo "$start $end";

getMonthRange($start, $end);
echo "$start $end";

?>
Labels:

Simple jQuery Timeout

I needed jQuery to fadeout an item after a certain timeout, and I found it odd that I couldn’t find a native jQuery way to do it.

Whatever. jQuery is so awesome that it doesn’t matter, because here’s what I came up with.

(function($){
$.doAfter = function(time,f) {
$('body').animate({ opacity: 1 }, time, f);
};
})(jQuery);
$(document).ready(function(){
$.doAfter(2500,function() {
$('.fadeout').fadeOut('slow');
});
});
Labels:

Easy payments using Paypal IPN

There are several PHP scripts and classes to process PayPal payments using their native IPN (Internet payment notification) feature. Because the whole process is based on the data you need to send via a web form to the PayPal payment processor these script look very similar.

The payment / notification process is shown via the following graphic:

paypal-graphic

Inside the form there are several required values to process a payment. PayPal gives the advice to post them all to get everything working. The following variables get some special attention:

business = your PayPal email address
cmd = single payments or subscription service (_xclick or _xclick-subscriptions)
return = the URL where the buyer get back after the payment is processed
cancel_return = the URL where the buyer get back if he has cancelled the payment
notify_url = the location where your IPN script is located
rm = how you need the data submitted from PayPal to your IPN script (1=get, 2=post)
currency_code = the currency you accept for your payment
lc = the country version of PayPal where your buyer is send to

There are much more variables, but we think that the other variables (product, order and shipment information) speak for themselves. Find a complete form provided with the example files.

To run some IPN enabled payment process we need a small script which will double check if the data which is send to the IPN script is valid according the data which is stored on the PayPal server. This feature is very important if your e-commerce accepts automatic payments.

The following code is able to check if the payment is valid against the PayPal server. Use this test to decide if the payment is valid or not.

$url = 'https://www.paypal.com/cgi-bin/webscr';
$postdata = '';
foreach($_POST as $i =&gt; $v) {
$postdata .= $i.'='.urlencode($v).'&amp;';
}
$postdata .= 'cmd=_notify-validate';

$web = parse_url($url);
if ($web['scheme'] == 'https') {
$web['port'] = 443;
$ssl = 'ssl://';
} else {
$web['port'] = 80;
$ssl = '';
}
$fp = @fsockopen($ssl.$web['host'], $web['port'], $errnum, $errstr, 30);

if (!$fp) {
echo $errnum.': '.$errstr;
} else {
fputs($fp, "POST ".$web['path']." HTTP/1.1\r\n");
fputs($fp, "Host: ".$web['host']."\r\n");
fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");
fputs($fp, "Content-length: ".strlen($postdata)."\r\n");
fputs($fp, "Connection: close\r\n\r\n");
fputs($fp, $postdata . "\r\n\r\n");

while(!feof($fp)) {
$info[] = @fgets($fp, 1024);
}
fclose($fp);
$info = implode(',', $info);
if (eregi('VERIFIED', $info)) {
// yes valid, f.e. change payment status
} else {
// invalid, log error or something
}
}

As mentioned before there are some complete solutions available on the internet. If your e-copmmerce site doesn’t have a complex product catalog you should use some static code from the PayPal website. For this guide we checked the PHP toolkit provided by PayPal.


Code condition

The first thing I noticed the code is not very clean and is using a coding style which is based on older PHP versions (f.e. for systems using register globals = On)


Implementation

After some code clean-up it was possible to use the included file together with my shopping cart script. Static variables are defined in one central configuration file and dynamic files are posted via the form in your web application.


IPN features

This script is written to handle the IPN validation process with different methods: cURL, fsockopen, and libcURL. I tried only the fsockopen option because this method looks good to me and should work on almost every web platform.


Documentation

There is a “Readme” file with the information about the most important features. A complete guide is not included and the information about subscription payments is missing in all files and documents. If you decide to start with the original files you should check also the comments within the configuration and example files.

Labels:

Parse html with PHP preg_match_all()

For the most of the PHP developer which are using preg_match or preg_replace frequently is the function preg_match_all a smaller advantage, but for all others it’s maybe hard to understand. The biggest difference between preg_match_all and the regular preg_match is that all matched values are stored inside a multi-dimensional array to store an unlimited number of matches. With the following example I will try to make clear how its possible to store the image paths inside a web page:

$data = file_get_contents("http://www.finalwebsites.com");
$pattern = "/src=[\"']?([^\"']?.*(png|jpg|gif))[\"']?/i";
preg_match_all($pattern, $data, $images);

We take a closer look to the pattern:


"/src=[\"']?([^\"']?.*(png|jpg|gif))[\"']?/i"


The first part and the last part are searching for everything that starts with src and ends with a optional quote or double quote. This could be a long string because the outer rule is very global. Next we check the rule starts within the first bracket:


"/src=[\"']?([^\"']?.*(png|jpg|gif))[\"']?/i"


Now we are looking inside this long string from the outer rule for strings starting with an optional quote or double quote followed by any characters. The last part inside the inner brackets is the magic:


"/src=[\"']?([^\"']?.*(png|jpg|gif))[\"']?/i"


We are looking next for a string that is followed by a file extension and match we get all the paths from the html file.


We need all the rules to isolate the string parts (image paths) from the rest of the html. The result looks like this (access the array $images with these indexes, or just use print_r($images)):


$images[0][0] -> src="/images/english.gif"

$images[1][0] -> /images/english.gif

$images[2][0] -> gif


The index 1 is the information we need, try this example with other part of html code for a better understanding.

Labels:

Create custom backups from your website using cURL

These days I needed a script to backup only a part of a customers website using a CRON. Most of the control panels I know allow only a complete website backup and this is not what I needed. While plaaning the script, I thought about a solution for webmaster without full SSH access to their hosting account. A typical situation could be:

  • A shared hosting account that allows only backups for the whole site incl. database, emails and other settings
  • No administration rights via SSH
  • A FTP host for the storage of the the backup files
  • Support for cURL and a default PHP5 configuration (sorry no more code for PHP4).

First of all we need to create a variable to define the local source directory on your website where you like to start the backup from:

define('BASEPATH', $_SERVER['DOCUMENT_ROOT'].'/');

The next code is to create a new class including the constructor function and some variables used in that class:


class Curl_ftp_backup {

public $basePath, $errors, $ftp_server, $ftp_user_pw , $msg, $email;

public function __construct($ftp_server, $ftp_userpw, $email_adr) {
$this->basePath = BASEPATH;
$this->errors = '';
$this->ftp_server = $ftp_server;
$this->ftp_user_pw = $ftp_userpw;
$this->email = $email_adr;
$this->msg = '';
}
}


Our class will store file and directories on the remote FTP server, the next function will create a directory if it not already exists:



	private function curl_create_ftp_directory($name, $curr_dir = '') {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->ftp_server);
curl_setopt($ch, CURLOPT_USERPWD, $this->ftp_user_pw);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$cmd = array();
if ($curr_dir != '') $cmd[] = 'CWD '.$curr_dir;
$cmd[] = 'MKD '.$name;
curl_setopt($ch, CURLOPT_POSTQUOTE, $cmd);
curl_exec ($ch);
return;
}

The following function will open a file and uploads the data to specified directory on the target server. For each file that is not stored the error number is returned, this information is used later to build up an error string.


	private function curl_put_file($path) {
$ch = curl_init();
$fp = fopen($this->basePath.$path, "r");
curl_setopt($ch, CURLOPT_URL, $this->ftp_server.$path);
curl_setopt($ch, CURLOPT_USERPWD, $this->ftp_user_pw);
curl_setopt($ch, CURLOPT_UPLOAD, 1);
curl_setopt($ch, CURLOPT_INFILE, $fp);
curl_setopt($ch, CURLOPT_INFILESIZE, filesize($this->basePath.$path));
curl_exec ($ch);
$error = curl_errno($ch);
curl_close ($ch);
if ($error != 0) $this->errors .= $path.PHP_EOL;
return;
}

Now we need a function that will loop through the specified base directory and will switch between directories and files; the previous functions will create the directory or upload the file.


	public function backupfiles($directory) {
if ($handle = opendir($this->basePath.$directory)) {
$this->curl_create_ftp_directory($directory);
while (false !== ($file = readdir($handle))) {
if (is_file($this->basePath.$directory.$file) &amp;&amp; $file != '.htaccess') {
$this->curl_put_file($directory.$file);
} elseif ($file != '.' &amp;&amp; $file != '..' &amp;&amp; is_dir($this->basePath.$directory.$file)) {
$this->backupfiles($directory.$file.'/', $directory);
}
}
closedir($handle);
if ($this->errors != '') {
$this->msg = 'Missing files: '.PHP_EOL.$this->errors;
} else {
$this->msg = 'FTP upload successful.';
}
} else {
$this->msg = 'Can\'t open local directory.';
}
}

public function send_emailmsg() {
if ($this->msg != '') {
$body = PHP_EOL.'Backup result:'.PHP_EOL.PHP_EOL.$this->msg;
mail($this->email, 'Your Backup on '.date('Y-m-d H:i:s'), $body);
}
}

At last there is a tiny function that will send you some short email message about the backup result. You can call the class in your PHP script:


$cb = new Curl_ftp_backup('ftp://ftp.yourserver.com/source_folder/', 'user:password', 'your@email.com');
$cb->backupfiles('includes/');
$cb->send_emailmsg
();

Thats all, now you need to create a CRON job for the file that will execute the backup. If your hosting provider doesn’t provide CRON jobs, just google for “free cron jobs”.


Disclaimer:

We tested the script “successful” on two modern Linux web servers with ~100 files between 10kb and 300MB. If you have a backup with a lot of files you should think about a different solution. With every file or directory a new CURL function is called, this could result in a high server load. We are not responsible for any damage and/or data loss as the result off using this script.

Labels:

FTP Upload via cURL

FTP hosting is often much cheaper than regular web hosting. The upload with an ftp client is for sure the most common way, but could be a problem for people behind a firewall or without enough rights (capabilities) to install a FTP client. For those a upload via a web form is the best solution.

Upload limitations by your web server

The default value for file uploads within PHP is 2MB, if you need to upload bigger files you need to change your PHP configuration or need to create a .htaccess file with this code to upload files of max. 16MB:

php_value upload_max_filesize 16M
php_value post_max_size 20M

The value for the post_max_size is larger than the value for the upload_max_size because we want to be able to upload more than just a file (also other data via text fields or text areas). The .htaccess file needs to be in the same directory than your upload script.


Using cURL for file transmissions

cURL is a great library for file transmissions via different types of protocols. The library supports the transport via POST, GET, FTP upload and much more. cURL is also able to authenticate on the target server or website.


In this tutorial we want to upload a file to some (password protected) remote FTP server via a web form.


<form action="curlupload.php" method="post" enctype="multipart/form-data">
<div>
<label for="upload">Select file</label>
<input name="upload" type="file" />
<input type="submit" name="Submit" value="Upload" />
</div>
</form>

The form is simple and has only one file field and the submit button. Don’t forget to protect this kind of pages.


Next we need some PHP code to handle the upload and opens a stream to send the file via cURL to the remote FTP server (place this code above the html code):


if (isset($_POST['Submit'])) {
if (!empty($_FILES['upload']['name'])) {
$ch = curl_init();
$localfile = $_FILES['upload']['tmp_name'];
$fp = fopen($localfile, 'r');
curl_setopt($ch, CURLOPT_URL, 'ftp://ftp_login:password@ftp.domain.com/'.$_FILES['upload']['name']);
curl_setopt($ch, CURLOPT_UPLOAD, 1);
curl_setopt($ch, CURLOPT_INFILE, $fp);
curl_setopt($ch, CURLOPT_INFILESIZE, filesize($localfile));
curl_exec ($ch);
$error_no = curl_errno($ch);
curl_close ($ch);
if ($error_no == 0) {
$error = 'File uploaded succesfully.';
} else {
$error = 'File upload error.';
}
} else {
$error = 'Please select a file.';
}
}

After the user has selected a file, the data is uploaded to the web server. We open the temp file with fopen and the cURL session is initialized. Together with the URL for the remote FTP server, we send the FTP login and password to the target location. The other cURL settings are required to send the file via the FTP protocol to the target server. If the returned error code is equal “0″, the upload was successful.


This small PHP snippet is responsible for the upload to some remote FTP server. We suggest using more validation routines in a production environment.

Labels:

Uploading a file using Curl in PHP

Here's how to upload files using curl in php: (it's very easy)

notice the @ infront of the file path, this is the magic part.

<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_VERBOSE, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible;)");
curl_setopt($ch, CURLOPT_URL, _VIRUS_SCAN_URL);
curl_setopt($ch, CURLOPT_POST, true);
// same as <input type="file" name="file_box">
$post = array(
"file_box"=>"@/path/to/myfile.jpg",
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$response = curl_exec($ch);
?>
Labels:

PHP: Random string with numbers and letters

I thought that some of you might find it useful to learn how to generate a random string or a random number with PHP. I wrote a quick function to use PHP to generate random. See it below :

function genRandomString() {
$length = 10;
$characters = ’0123456789abcdefghijklmnopqrstuvwxyz’;
$string = ”;

for ($p = 0; $p < $length; $p++) {
$string .= $characters[mt_rand(0, strlen($characters))];
}

return $string;
}
Labels:
2010 WEBSITE20. All rights reserved.