Archive for the ‘Programming’ Category

Using Uploadify with Zend Framework

Sunday, August 30th, 2009

A quote from http://www.uploadify.com site.

Uploadify is a jQuery plugin that allows the easy integration of a multiple (or single) file uploads on your website.  It requires Flash and any backend development language.  An array of options allow for full customization for advanced users, but basic implementation is so easy that even coding novices can do it.

This article assumes that you've already read the Uploadify docs and tried to integrate it.

Everything is pretty simple however you need to overcome one obstacle with flash and cookies.
More on the flash and cookies topic go to http://swfupload.org/forum/generaldiscussion/383

My Solution:

This article can be downloaded (TXT format)

Here is how to use the uploadify
I use a variable called "__tkn" in the url to pass the session variable.
Some of you may try to use 'scriptData' which didn't work for me.

<script type="text/javascript">
jQuery(document).ready(function() {
if (jQuery("#upl_feed_file_progress")) {
jQuery("#upl_feed_file_progress").uploadify({
'uploader': '/site/share/jquery/plugins/jquery.uploadify-v2.1.0/uploadify.swf',
//                'cancelImg': '/site/share/jquery/plugins/jquery.uploadify-v2.1.0/images/cancel.png',
'script': '/mymodule/mycontroller/myaction/__tkn/<?php echo Zend_Session::getId(); ?>',
'multi': false,
'simUploadLimit': 1,
'fileExt': '*.csv;*.txt',
'fileDesc': 'Feed Files (*.csv;*.txt)',
/                'fileDataName' : 'upl_feed_file', // in $_FILES
//                'scriptData': {'PHPSESSID' : '<?php echo Zend_Session::getId(); ?>'}, // This didn't work for me.
'height': 24,
'auto': true,
'onCancel' : function (event, queueID, fileObj, data) {
alert('Error: You have cancelled the file upload.');
},
'onError' : function (event, queueID, fileObj, errorObj) {
alert('Error during file upload. Maybe the file is too big ? Size: ' +  fileObj.size + ' Error:' +  errorObj.info());
},
'onComplete' : function (event, queueID, fileObj, response, data) {
if (response == '' || response == 0 || response == "0") {
alert('Error during with the upload');
} else {
perf_error('Success!');
}
}
});
}
});

</script>

This one goes in the template ..

....
<div id="upl_feed_file_progress">You have a problem with your javascript</div>
....

Insert this in the boostrap (usually index.php) file
It should be inserted before "Zend_Session::start();"

// ------------------------------------------ START -------------------------------------------

$sessName = "PHPSESSID";
$sessOptions = array('name' => $sessName);

// Flash has problems with cookies so we pass the PHPSESSID variable via get
// it'll be injected if it doesn't exist in _SERVER["HTTP_COOKIE"] e.g. '; PHPSESSID=hdi5u83hfnu7ltlvp5q3bb53k4'
if ((stripos($_SERVER['REQUEST_URI'], '__tkn') !== false)
//    &amp;&amp; preg_match('#^[a-z\d]{25,30}$#si', $_GET[$sessName])
&amp;&amp; preg_match('#__tkn/([a-z\d]{25,30})#si', $_SERVER['REQUEST_URI'], $matches)
&amp;&amp; (stripos($_SERVER["HTTP_COOKIE"], $matches[1]) === false)) {
$sid = $matches[1];

$prefix = '';
if (!empty($_SERVER["HTTP_COOKIE"])) {
$prefix = '; ';
}

$_SERVER["HTTP_COOKIE"] .= $prefix . $sessName . '=' . $sid;
$_COOKIE[$sessName] = $sid;

Zend_Session::setId($sid);
}

Zend_Session::setOptions($sessOptions);
// ------------------------------------------ END -------------------------------------------

Your 'myaction' (/mymodule/mycontroller/myaction) should return 0 or 1.

The following code should be useful.

$viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer');
$viewRenderer->setNoRender();

// Skipping the templates
Zend_Layout::getMvcInstance()->disableLayout();

Please share your thoughts.
Are there any security holes in this approach ?


Related Resources

Quick ‘n’ Dirty Way to Debug without showing debug info to your visits.

Thursday, August 27th, 2009

Sometimes we are required to do some troubleshooting on a production site.
In order to do that *safely* we'll show debug information only for us.
This could be put into a safe_debug function for later use by the way.
On development/staging servers I recommend installing debuggers such as Zend Debugger, xdebug etc and enabling errors (E_ALL).

if ($_SERVER['REMOTE_ADDR'] == '1.2.3.4' || preg_match('#^192\.#', $_SERVER['REMOTE_ADDR'])) {
echo "Dev dump";
echo "<pre>";
var_dump($params);
echo "</pre>";
echo __FILE__ . ':' . __LINE__;
}

Of course one should be extra careful for opening and closing php tags otherwise this will product fatal errors.

Happy debugging!

How to (always) get your server’s IP address

Tuesday, August 25th, 2009

Here is how to (always) get your server's a IP address. Works on Unix/Linux.

<?php
if (empty($_SERVER['SERVER_ADDR'])) {
$server_host = `hostname -f`;
$server_ip = `host $server_host`;

if (preg_match('#(\d+\.\d+\.\d+\.\d+)#', $server_ip, $matches)) {
$server_ip = $matches[1];
} else {
$server_ip = '127.0.0.1';
}
} else {
$server_ip = $_SERVER['SERVER_ADDR'];
}

echo $server_ip;
?>

How to delete .SVN files/directories

Thursday, August 13th, 2009

This is so common situation when somebody decides to copy a directory that contains SVN files which also has locally modified files.
Therefore a clean export won't do the job.
Here is what I do to clean up the new folder from the SVN files.

This command will display all the .SVN folders starting from the current folder.

Be yourself i.e. not root :D just in case.

find . -type d -name '*.svn' -print

Example Output:

./js/.svn
./templates/.svn
./.svn
./css/.svn
./images/.svn

What I do is check the folders visually and then use my editor to search & replace:
"./" and replace it with "rm -rf ./"

Result:

rm -rf ./js/.svn
rm -rf ./templates/.svn
rm -rf ./.svn
rm -rf ./css/.svn
rm -rf ./images/.svn

Then I paste this in the console window.

rm is a dangerous command so be careful!
Your precious work could be gone in a fraction of a second!

How to find which flash player version you have ?

Friday, July 17th, 2009

In order to find the currently installed flash player version go to http://kb2.adobe.com/cps/155/tn_15507.html

Get the first and the last day of the current month in PHP

Thursday, May 21st, 2009

Here is how to get the first and the last day of the current month in PHP

<?php

if (function_exists('date_default_timezone_set')) {
date_default_timezone_set('America/Toronto');
}

$start_data = date("Y-m-01");
$end_data = date("Y-m-d", strtotime("-1 day +1 month", strtotime(date("Y-m-01"))));

echo $start_data . " " .  $end_data;
// Outputs: 2009-05-01 2009-05-31
?>

Related

Multiple ways to do the same thing in software development

Thursday, March 19th, 2009

Today I've tried installing Drupal 5.16.
It couldn't pass the database settings screen.
The fix applied for Drupal 6 couldn't fix it.

I created a ticket: http://drupal.org/node/407342

We all know that in every software product contains errors. This is *normal*.

I think that a better software product should allow different options for doing one action depening on the different personas.
E.g. experienced linux guru, designer, complete newbie etc.

For example php, MySQL and other offer installers as well as manual installation instructions.
This way bugs in the installer won't prevent people from using the software.
An early bug can easily turn many clients down.

Setting up php, mysql, phpMyAdmin on Friday 13th

Friday, March 13th, 2009

I start setting up my new machine - Sony VAIO and this time it didn't go well the first time.
Keep reading...

I downloaded the latest php (PHP 5.2.9-1 (cli) (built: Mar  5 2009 20:02:28),
mysql (mysql-5.1.32-winx64.msi) and phpmyadmin (phpMyAdmin-3.1.3-english.tar.bz2).

Round #1
When I first logged in I saw a warning at the bottom of the first screen of phpmyadmin

Your PHP MySQL library version 5.0.50a differs from your MySQL server version 5.1.32.
This may cause unpredictable behavior.

Because I was already using the latest php I decided to downgrade MySQL to 5.0.51a

Round #2
http://downloads.mysql.com/archives.php?p=mysql-5.0&v=5.0.51a

Round #2.5
For some strange coinsidence (or maybe because it's Friday 13th :D) the configuration
wizard wouldn't start.

The error was caused by a bad configuration setting in MySQLInstanceConfig.exe.
By the way I have disabled UAC because of the constant prompting is quite
annoying but I still like Windows ;) (This was for my friends who like Mac).

MySQLInstanceConfig.exe Error in manifest or policy file on line 6.
The value "
asAdministrator" of attribute "level" in requestedPrivileges" is invalid.

Here is how to fix it by editing the file resource using Resource Hacker program (free).
http://bugs.mysql.com/bug.php?id=34340

I am not done yet :D

Round #3
Now the latest phpMyAdmin produced an error:

SHOW PLUGINS

MySQL said: Documentation
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'PLUGINS' at line 1
Open new phpMyAdmin windowOpen new phpMyAdmin window

It seems this is a caching problem (see http://www.wampserver.com/phorum/read.php?2,46184,46227 )
Restart your browser and try again.

Happy Web Development ;)

Related:

HTML dropdown menu function

Tuesday, March 10th, 2009

If you have some sites that do not rely on a framework you could use this function to generate a simple HTML select.
Note: It won't preselect multiple values.
You could download the code because it usually doesn't look good in wordpress.

//echo getHTMLSelect('dropdown', array(0 => "", 1 => "'test'\"", 2 => "test2"), @$_REQUEST['sel']);

/**
* Returns an HTML dropdown menu.
*
* @param string $name HTML select name
* @param array $values options key value
* @param int $selected_id currently selected ID
* @param string $attr several attributes that will be added in <select ....>
* @return string
*/
function getHTMLSelect($name = 'dropdown', $values = array(), $selected_id = 0, $attr = '') {
$buff = "<select name=\"$name\" $attr>\n";
foreach($values as $k => $v) {
$s = ($selected_id == $k) ? " selected='selected'" : '';
$k = intval($k);
$v = htmlentities($v, ENT_QUOTES, 'UTF-8');
$buff .= "<option value=\"$k\" $s>$v</option>\n";
}

$buff .= "</select>\n";
return $buff;
}

How to implement a timed effect with jQuery

Tuesday, March 10th, 2009

By a timed effect here I mean do some animation and then redirect the user to a page.
Requirements: jQuery (and Javascript)
Download the file: timed_effect_jquery

Here is how to accomplish that:

Implementation

/*
This function performs some effects on a target_obj and after 2.5 sec redirects to a location defined by ahref_obj
Usage: in shopping carts e.g. when someone adds a product then some animation is perfomed to make the user aware that something is happening.
License: LGPL
Author: Svetoslav Marinov
Site: http://slavi.biz
*/
function my_timed_effect(target_obj, ahref_obj) {
jQuery(target_obj).attr('style', 'font-weight:bold;').fadeOut("slow").fadeIn("slow").show('slow');
setTimeout('document.location="' + ahref_obj.href + '"', 2000);
}

Usage:

<a href="/cart/add/1" onclick="my_timed_effect(jQuery('#my_status_container_id'), this); return false;">Add a product</a> <br />
<a href="http://google.com" onclick="my_timed_effect(jQuery('#my_status_container_id'), this); return false;">Add a product</a> (go to http://google.com after the animation)

This example will perform the animation and then redirect where the link points.

How would you do the same effect ?
Are there any other option(s) ?