Archive for the ‘PHP’ Category

Using Uploadify with Zend Framework

Sunday, August 30th, 2009

If you're new here, you may want to subscribe to my RSS feed.
Thanks for reading my blog!

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;
?>

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

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;
}

PHP code that returns array elements from array2 that are not present in array1

Saturday, February 28th, 2009
<?php
// PHP code that returns array elements from array2 that are not present in array1

$array1 = array(1, 2);
$array2 = array(1, 2, 3, 4);
$result = array_diff($array2, array_intersect($array1, $array2));

/*
// Result
Array
(
[2] => 3
[3] => 4
)
*/

?>

How to get the first element of an associative array in PHP

Saturday, January 10th, 2009

I've been always wondering how to get the first element of an associative array in PHP.
For numeric keys you could just do $arr[0] but it'll a little bit different for associative arrays.

Solutions

[code]
$arr = array('one' =&amp;gt; 'hello', 'two' =&amp;gt; 'world');
[/code]

Solution #1
[code]
reset($arr);
list ($key1, $val1) = each($arr);
[/code]

Solution #2
[code]
$i = 0;
foreach ($arr as $key =&amp;gt; $value) {
if (++$i == 1)
echo $key;
break;
}
}
[/code]

Solution #3
[code]
reset($arr);
echo key($arr);
[/code]

Solution #4
[code]
reset($arr);
echo @array_shift(array_keys($arr));
[/code]

Suppressing Warnings such as:
Debug Strict (PHP 5): PHPDocument1 line 6 - Only variables should be passed by reference

Solution #5
[code]
reset($arr);
echo end(array_keys(array_reverse($arr)));
[/code]

Most of solutions can be found on http://www.webmasterworld.com/forum88/3811.htm

Related

Can you come up other solutions ?
Feel free to share your experience by commenting this posting below.

How to Remove Empty Elements From An Array in PHP

Tuesday, January 6th, 2009

Sometimes arrays get filled with empty values and we need to remove them.
Here is a function that removes all empty values in an array.
The text is cleaned by HTML if any.

Notes:

  1. There is not a check for duplicate elements.
  2. This function may break UTF-8 strings.

[code]
$a[5] = 777;
$a[4] = array(
1 => 'test3',
2 => '',
3 => '',
4 => 'test2',
9 => 'test',
17 => '',
);
$a[9] = 'test';
$a[1] = 111;
$a[2] = 222;
$a[7] = '';
$a['axa'] = 'sfaf';
$a['axgga'] = '';
$a['gsdgsdg'] = 'sfaf';
[/code]

// Output
[code]
array(7) {
[0]=>
string(3) "777"
[1]=>
array(3) {
[0]=>
string(5) "test3"
[1]=>
string(5) "test2"
[2]=>
string(4) "test"
}
[2]=>
string(4) "test"
[3]=>
string(3) "111"
[4]=>
string(3) "222"
["axa"]=>
string(4) "sfaf"
["gsdgsdg"]=>
string(4) "sfaf"
}
[/code]

[code]
/**
* Removes empty values from an array. Also the numeric keys get reordered.
* If a value is an array the process of cleaning is repeated recursively.
* Elements start from 1 not from 0 if $non_zero_start is set to 1. Defaults to 0.
* Values are cleaned by HTML and also by leading/trailing whitespaces.
*
* @param array $arr
* @param bool $non_zero_start if 1 is supplied the array will start from 1
* @return array
* @author Svetoslav Marinov
* @copyright January 2009
* @license LGPL
*/
function cleanupArray($arr, $non_zero_start = 0) {
$new_arr = array();
foreach ($arr as $key => $value) {
if (!empty($value)) {
if (is_array($value)) {
$value = cleanupArray($value, $non_zero_start);

// If after the cleaning there are not elements do not bother to add this item
if (count($value) == 0) {
continue;
}
} else {
$value = trim(strip_tags($value));
if (empty($value)) {
continue;
}
}

$new_arr[$key] = $value;
}
}
// Reordering elements
if (!empty($new_arr)) {
if (!empty($non_zero_start)) {
$new_arr = array_merge_recursive(array("") + $new_arr);

// We don't need an empty first element.
// This was used to shift other elements to start from 1 instead of 0
unset($new_arr[0]);
} else {
$new_arr = array_merge_recursive($new_arr);
}
}
return $new_arr;
}
[/code]

Related: