This is official blog of Jawed Shamshedi. You can check http://www.jawedweb.in for more info about me.
Wednesday, July 29, 2009
Time difference in php
{
$uts['start'] = strtotime( $start );
$uts['end'] = strtotime( $end );
if( $uts['start']!==-1 && $uts['end']!==-1 )
{ if( $uts['end'] >= $uts['start'] )
{
$diff = $uts['end'] - $uts['start'];
if( $days=intval((floor($diff/86400))) )
$diff = $diff % 86400;
if( $hours=intval((floor($diff/3600))) )
$diff = $diff % 3600;
if( $minutes=intval((floor($diff/60))) )
$diff = $diff % 60;
$diff = intval( $diff );
return( array('days'=>$days, 'hours'=>$hours, 'minutes'=>$minutes, 'seconds'=>$diff) );
}
else
{
trigger_error( "Ending date/time is earlier than the start date/time", E_USER_WARNING );
}
}
else
{
trigger_error( "Invalid date/time data detected", E_USER_WARNING );
}
return( false );
}
--------------------------------------------------------------------------------
// a START time value
$start = '09:00';
// an END time value
$end = '10:30';
// what is the time difference between $end and $start?
if( $diff=@get_time_difference($start, $end) )
{
echo "Hours: " .
sprintf( '%02d:%02d', $diff['hours'], $diff['minutes'] );
}
else
{
echo "Hours: Error";
}
?>
Currency Converter in php
{
$googleQuery = $amount . ' ' . $currency . ' in ' . $exchangeIn;
$googleQuery = urlEncode( $googleQuery );
$askGoogle = file_get_contents( 'http://www.google.com/search?q=' . $googleQuery );
$askGoogle = strip_tags( $askGoogle );
$matches = array();
preg_match( '/= (([0-9]|\.|,|\ )*)/', $askGoogle, $matches );
return $matches[1] ? $matches[1] : false;
}
echo exchangeRate( 1, 'dollars','rupee');
if(isset($from2) && trim($from2)!="" && isset($to) && trim($to)!=""){
?>
}else{
?>
}
?>
image slideshow with loader
2) http://www.dhtmlgoodies.com/index.html?whichScript=image_slideshow
3) http://www.developphp.com/
4) sliding window code ( http://www.panic.com/coda/ )
Upload images with resize or thumb image in php
global $config;
$filename_parts = explode(".",strrev($filename),2);
$filename_base = strrev($filename_parts[1]);
$filename_ext = strrev($filename_parts[0]);
$unique_filename_base = strtolower(sanitize_filename($filename_base));
$final_filename = $unique_filename_base . "." . $filename_ext;
// final fully qualified file name
$final_fqfn = $config["basedir"].'images/images_story/'.$final_filename;
if (is_uploaded_file($tmpname)) {
if (!move_uploaded_file($tmpname,$final_fqfn)) {
$result['errors'] .= sprintf(plog_tr('Could not move uploaded file! %s to %s'),$tmpname,$final_fqfn);
return $result;
}
}
@unlink($tmpname);
$res = chmod($final_fqfn, 0755);
$destination= $config["basedir"].'images/images_story/thumb_story/'.$final_filename;
$imagename = $final_filename;
$height =111;
$width =158;
if(isset($filename) && trim($filename)!=""){
image_thumb($final_fqfn,$destination,$imagename,$height,$width);
}
$update_story = mysql_query("update plogger_stories SET image_story ='$final_filename' where id='$story_id'");
}
function image_thumb($filename,$destination,$imagename,$height,$width)
{
$length=strlen($imagename);
$newpos=strrpos($imagename,".")+1;
$type=substr($imagename,$newpos,$length-$newpos);
$imagetype=strtolower($type);
$th_height=$height;
$th_width=$width;
$new = imagecreatetruecolor($th_width, $th_height);
if(strtolower($imagetype)=="png")
{
$source = imagecreatefrompng($filename);
imagecopyresampled($new, $source, 0, 0, 0, 0, $th_width, $th_height,
imagesx($source), imagesy($source));
imagepng($new, $destination);
}
elseif(strtolower($imagetype)=="gif")
{
$source = imagecreatefromgif($filename);
imagecopyresampled($new, $source, 0, 0, 0, 0, $th_width, $th_height,
imagesx($source), imagesy($source));
imagegif($new, $destination);
}
else
{
$source = imagecreatefromjpeg($filename);
imagecopyresampled($new, $source, 0, 0, 0, 0, $th_width, $th_height,
imagesx($source), imagesy($source));
imagejpeg($new, $destination);
}
}
Create xml using database
$query = "SELECT * FROM user_record";
$result = mysql_query($query);
$num = mysql_num_rows($result);
$somecontent = '';
for($n=0; $n < $num-1; $n++)
{
$i=$n+1;
$name = mysql_result($result,$i,'name');
$email = mysql_result($result,$i,'email');
$address = mysql_result($result,$i,'address');
$city = mysql_result($result,$i,'city');
$state = mysql_result($result,$i,'state');
$phone = mysql_result($result,$i,'phone');
$cuntery = mysql_result($result,$i,'cuntery');
$image_add = mysql_result($result,$i,'image_add');
$somecontent .= "<$i>";
$somecontent .= "$name";
$somecontent .= "$email";
$somecontent .= "
$address
";
$somecontent .= "$city";
$somecontent .= "$state";
$somecontent .= "$cuntery";
$somecontent .= "$phone";
$somecontent .= "$image_add";
$somecontent .= "";
}
/////////////////////////////////write data in file ////////////////////
$filename = 'c:\webserv\wwwroot\htdocs\san\record.xml';
if (!$handle = fopen($filename, 'a')) {
echo "Cannot open file ($filename)";
exit;
}
if (fwrite($handle, $somecontent) === FALSE) {
echo "Cannot write to file ($filename)";
exit;
}
fclose($handle);
//////////////////////////////////////////// end///////////////////////
?>
conn.php
$localhost = "localhost";
$username = "root";
$password = "";
$database = "record";
mysql_connect($localhost,$username,$password) or die("unable to connect");
mysql_select_db($database);
?>
Create xml using database
$query = "SELECT * FROM user_record";
$result = mysql_query($query);
$num = mysql_num_rows($result);
$somecontent = '';
for($n=0; $n < $num-1; $n++)
{
$i=$n+1;
$name = mysql_result($result,$i,'name');
$email = mysql_result($result,$i,'email');
$address = mysql_result($result,$i,'address');
$city = mysql_result($result,$i,'city');
$state = mysql_result($result,$i,'state');
$phone = mysql_result($result,$i,'phone');
$cuntery = mysql_result($result,$i,'cuntery');
$image_add = mysql_result($result,$i,'image_add');
$somecontent .= "<$i>";
$somecontent .= "$name";
$somecontent .= "$email";
$somecontent .= "
$address
";
$somecontent .= "$city";
$somecontent .= "$state";
$somecontent .= "$cuntery";
$somecontent .= "$phone";
$somecontent .= "$image_add";
$somecontent .= "";
}
/////////////////////////////////write data in file ////////////////////
$filename = 'c:\webserv\wwwroot\htdocs\san\record.xml';
if (!$handle = fopen($filename, 'a')) {
echo "Cannot open file ($filename)";
exit;
}
if (fwrite($handle, $somecontent) === FALSE) {
echo "Cannot write to file ($filename)";
exit;
}
fclose($handle);
//////////////////////////////////////////// end///////////////////////
?>
conn.php
$localhost = "localhost";
$username = "root";
$password = "";
$database = "record";
mysql_connect($localhost,$username,$password) or die("unable to connect");
mysql_select_db($database);
?>
Valid Date in javascript
{
// date formate 12-27-2007 mm-dd-yyyy
/* var currentTime = new Date();
var month = currentTime.getMonth() + 1
var day = currentTime.getDate();
var year = currentTime.getFullYear();
var currentDate = month + "-" + day + "-" + year;
alert(currentDate); */
var currentTime = new Date();
var currentDate = currentTime.format('m-d-Y');
//alert(currentDate);
if(trim(currentDate)!="" && trim(date2)!="")
{
var str1 = currentDate;
var str2 = date2;
var mon1 = parseInt(str1.substring(0,2),10);
var dt1 = parseInt(str1.substring(3,5),10);
var yr1 = parseInt(str1.substring(6,10),10);
var mon2 = parseInt(str2.substring(0,2),10);
var dt2 = parseInt(str2.substring(3,5),10);
var yr2 = parseInt(str2.substring(6,10),10);
var date11 = new Date(yr1, mon1, dt1);
var date22 = new Date(yr2, mon2, dt2);
if(date22 < date11) return true;
}
}
Trim in javascript remove left & right space
{
return str.replace(/^\s*|\s*$/g,"");
}
Date comparison in javascript
var str1 = date_arrival;
var str2 = date_departur;
if(trim(str1)!="" && trim(str2)!="")
{
var yr1 = parseInt(str1.substring(0,4),10);
var mon1 = parseInt(str1.substring(5,7),10);
var dt1 = parseInt(str1.substring(8,10),10);
var yr2 = parseInt(str2.substring(0,4),10);
var mon2 = parseInt(str2.substring(5,7),10);
var dt2 = parseInt(str2.substring(8,10),10);
var date_arrival1 = new Date(yr1, mon1, dt1);
var date_departur2 = new Date(yr2, mon2, dt2);
if(date_departur2 < date_arrival1)
{
return false;
}
}
return true;
}
if(trim(g.date_of_departure.value)=="")
{
alert("");
g.date_of_departure.focus();
return false;
}
var date1 = g.date_of_arrival.value;
var date2 = g.date_of_departure.value;
if(trim(g.date_of_departure.value)!="" && !validDeparturDate(date1,date2))
{
alert("Date of departure should be grater then date of arrival!");
g.date_of_departure.focus();
return false;
}
Multiple Checkbox Validation in javascript
var checkSelected=0;
for(var i=0; i < g.elements.length; i++) {
if(g.elements[i].name && g.elements[i].name.substr(0, 8) == "category" && g.elements[i].checked == true && g.elements[i].name != "categoryname") {
checkSelected = 1;
break;
}
}
if( checkSelected == 0 ){
alert("");
g.elements[i].focus();
return false;
}
Valid phone no. like 222-222-2222 in javascript
if(trim(g.phone.value)=="")
{
alert("Please enter phone no.");
g.phone.value = trim(g.phone.value);
g.phone.focus();
return false;
}
if(!validatePhone(g.phone.value))
{
alert("Please enter valid phone no. like 222-222-2222.");
g.phone.value = trim(g.phone.value);
g.phone.focus();
return false;
}
function validatePhone(number)
{
var textV = number;
var reg = new RegExp("^[0-9]{3}-[0-9]{3}-[0-9]{4}$", "i")
if(textV.match(reg)) {
return true;
} else {
return false;
}
}
IsNumeric in javascript
{
var ValidChars = "0123456789.";
var IsNumbe r= true;
var Char;
for (i = 0; i < sText.length && IsNumber == true; i++)
{
Char = sText.charAt(i);
if (ValidChars.indexOf(Char) == -1)
{
IsNumber = false;
}
if (Char =='.' && ValidChars.indexOf(Char)!= ValidChars.lastIndexOf(Char))
{
IsNumber=false;
}
}
return IsNumber;
}
Thursday, July 23, 2009
Upcoming changes in PHP 6.0
- The register_globals, safe_mode and the various magic quotes options will be removed.
- The ereg extension is removed, while the XMLReader, XMLWriter and Fileinfo extensions are added to the core, and by default are on.
- Another addition I find particularly exciting is that APC (Alternative PHP Cache) will be added to the core, though will be off by default. APC can provide serious performance benefits.
- All E_STRICT messages will be merged into E_ALL, another positive change that will encourage good programming practice.
- ASP style <% tags will no longer be supported.
- Addition of a new 64-bit integers. The current integer type remains as is, 32 or 64-bit dependent on the platform.
- Use of foreach with multi-dimensional arrays, for example foreach($array as $k => list($a, $b)).
- A new switch in php.ini will allow you to disable Unicode semantics (by default they will be on).
- There will also be various string improvements related to Unicode.
- The microtime() function will return the full floating point number, rather than microseconds unix_timestamp, as at present, probably making the function more readily useful for most people.
- The {} notation for string indexes will no longer be supported, while the [] version will get added substr() and array_slice() functionality. Previously [] was deprecated, but most developers, including myself, seem to use [].
- FastCGI will always be enabled for the CGI SAPI, and will not be able to be disabled.
- The ancient HTTP_*_VARS globals will no longer be supported. Everyone should have had more than enough time to remove any traces of these.
- var will alias public. var was permitted with PHP4 classes, but in PHP 5 this raised a warning. In PHP 6 var will simply be an alias for public, so no warning is necessary.
- The ze1 compatibility mode, which tried to retain PHP 4 behaviour but had some bugs, will be removed.
- Dynamic functions will no longer be permitted to be called with static syntax.
Friday, July 17, 2009
Interface in Php
An Interface is like a template similar to abstract class
with a difference where it uses only abstract methods.
In simple words, an interface is like a class using
interface keyword and contains only function
declarations(function with no body).
An Interface should be implemented in the class and all the
methods or functions should be overwridden in this class.
for eg:
interface InterfaceName{
function fun1();
function fun2(a,b);
}
class ClassName implements InterfaceName{
fuction fun1(){
function implementation.......
}
fuction fun2(a,b){
function implementation.......
}
}
Tuesday, July 14, 2009
Removing index.php from the url in codeigniter
I also tried to find out many the exact way to remove the index.php from the url but did not get much help. Then after lots of hits and try I made the .htacess that is working for me. So I wanted to share this with you all.
My framework is in the folder abc.
The .htaccess
RewriteEngine on
RewriteCond %{QUERY_STRING} ^(ACT=.*)$ [NC]
RewriteRule ^(.*)$ index.php?%1 [L]
RewriteCond $1 !^(images|_css|_js|scripts|cal|uploads|portal_member_image|index.php) [NC]
RewriteRule ^(.*) /abc/index.php?/$1 [L]
And when ever you make a call to a controller please specify the full url without the index.php like if I want to call a controller called hi controller and inside that a hello function then what i will have to write is.
redirect($this->config->item('baseurl').'hi/hello');
Hope this will of any help to someone.
Thanks
Jawed
Pagination in codeigniter
Let's now start with the pagination tutorial. This tutorial assumes that you have connected your CodeIgniter application to the database.
First, we need to create a table.
CREATE TABLE IF NOT EXISTS `articles` (
`id` int(11) NOT NULL auto_increment,
`title` varchar(50) NOT NULL,
`content` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
Next, we create our own Model for our articles table.
class Articles_model extends Model {
function Articles_model()
{
parent::Model();
}
function get_posts($limit = NULL, $offset = NULL)
{
$this->db->limit($limit, $offset);
return $this->db->get('posts');
}
function count_posts()
{
return $this->db->count_all_results('posts');
}
The method Articles_model()
is the constructor. In PHP 4, constructors are named after the class they are located in.
The method get_posts()
, retrieves the information from the database. Notice that it has parameters for limiting and the offset of returned rows.
The method count_posts()
, retrieves the total number of posts available in the table.
Next on our list is creating the controller function.
class Posts extends Controller {
function Posts()
{
parent::Controller();
}
function manage()
{
$this->load->model('posts_model');
$per_page = 10;
$total = $this->posts_model->count_posts();
$data['posts'] = $this->posts_model->get_posts($per_page, $this->uri->segment(3));
$base_url = site_url('posts/manage');
$config['base_url'] = $base_url;
$config['total_rows'] = $total;
$config['per_page'] = $per_page;
$config['uri_segment'] = '3';
$this->pagination->initialize($config);
$this->load->view('admin/posts/manage', $data);
}
Copy and paste and do not worry if you don't understand that chunk of code yet. We will get back to that later on.
Monday, July 13, 2009
Webservice in php
At the link below, there is a quick and good reference about web services in php
http://talks.php.net/show/oscon-webservices/
Saturday, July 11, 2009
download all php framework from here
you can download all php frameworks (popular) from this link.
http://www.phpframeworks.com/php-frameworks-download/
developing facebook application with cakephp
Here you can find something usefull for developing facebook application in cake php
http://facebook-developer.net/2007/10/18/building-your-first-facebook-application-with-cakephp/
Jquery plugings for codeigniter
At this link you can find many jquery plugins for code ignitor
http://malsup.com/jquery/form/
Nice cake php tutorials
At this link you can find nice cake php tutorials
http://cakebaker.42dh.com/tags/tutorial/
Making site in some other language like hebrew
While working on this mini-project I’ve realized that there is hardly any online tutorials on using the Hebrew font. Here’s my solution which is fairly simple and works effectively.
Step 1) Set the HTML page charset encoding to utf8:
meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8“
Step 2) set the ‘collation’ attribute for the fields which are to accept hebrew text to: utf8_bin
Step 3) within your php script, right before calling the mysql_query function to insert the data into your DB, use both the utf8_encode function along with addslashes. This will encode the data into utf8 friendly characters.
Step 4) when pulling the text from the DB onto the page, make sure to use the utf8_decode along with stripslashes in order to display the data on the page.
useful url rewriting examples using .htaccess
It is a simple redirection in which .php extension is hidden from the browser’s address bar and dynamic url (containing “?” character) is converted into a static URL.
RewriteEngine on
RewriteRule ^product-([0-9]+)\.html$ product.php?id=$1
2) Rewriting product.php?id=12 to product/ipod-nano/12.html
SEO expert always suggest to display the main keyword in the URL. In the following URL rewriting technique you can display the name of the product in URL.
RewriteEngine on
RewriteRule ^product/([a-zA-Z0-9_-]+)/([0-9]+)\.html
3) Rewriting yoursite.com/user.php?username=xyz to yoursite.com/xyz
Have you checked zorpia.com.If you type http://zorpia.com/roshanbh233 in browser you can see my profile over there. If you want to do the same kind of redirection i.e http://yoursite.com/xyz to http://yoursite.com/user.php?username=x
RewriteEngine On
RewriteRule ^([a-zA-Z0-9_-]+)$ user.php?username=$1
RewriteRule ^([a-zA-Z0-9_-]+)/$ user.php?username=$1
4) Redirecting the domain to a new subfolder of inside public_html.
Suppose the you’ve redeveloped your site and all the new development reside inside the “new” folder of inside root folder.Then the new development of the website can be accessed like “test.com/new”. Now moving these files to the root folder can be a hectic process so you can create the following code inside the .htaccess file and place it under the root folder of the website. In result, www.test.com point out to the files inside “new” folder.
RewriteEngine On
RewriteCond %{HTTP_HOST} ^test\.com$ [OR]
RewriteCond %{HTTP_HOST} ^www\.test\.com$
RewriteCond %{REQUEST_URI} !^/new/
RewriteRule (.*) /new/$1
Example of Custom URL rewritting
RewriteRule ^career-options/(.*)-([0-9]+)\.html$ careerdetails.php?carr_id=$2RewriteRule ^career-advice$ careeradvice.phpRewriteRule ^parent-career-help$ parent_profile.phpRewriteRule ^Forum/(.*)-([0-9]+)\.html$ forum_index.php?career_category_id=$2RewriteRule ^career-advice/career-counselling$ careercounselling.phpRewriteRule ^career-advice/interview-training$ interviewsuccess.phpRewriteRule ^career-advice/interview-questions-answers$ interview_questions.phpRewriteRule ^career-options$ career.phpRewriteRule ^community$ community.phpRewriteRule ^career--options/(.*)-([0-9]+)\.html$ careerdetails.php?carr_id=$2&addFirstChoice=1
PayPal Identity Token (PHP Script)
// parse the data $lines = explode("\n", $res); $keyarray = array(); if (strcmp ($lines[0], "SUCCESS") == 0) { for ($i=1; $iaddPaymentDetails($keyarray['txn_id'], 'Paypal', $keyarray['mc_gross'], $keyarray['option_name1'],$status);
header("location:thanks_payment.php"); } else if (strcmp ($lines[0], "FAIL") == 0) { header("location:error.php"); // log for manual investigation //header("location:thanks_payment.php"); }
}
fclose ($fp);?>
How do I generate a PayPal Identity Token
2. Click Profile at the top of the page.
3. On the right under Selling Preferences click on Website Payment Preferences.
4. Under Auto Return for Website Payments click "on"
5. After Return URL put http://www.mytalentplace.co.uk
6. Under Payment Data Transfer (Optional) click "on"
7. Scroll to the bottom of the page and click Save.
8. Copy the Identity Token (everything after the word "Token:" in the new window), and paste it into your My talent place PayPal Information.
Opening Cake THTML file with Dreaweaver CS4
C:\Program Files\Adobe\Adobe Dreamweaver CS4\configuration
Open file: Extensions.txt
edit line 16 and add THTML
Save and Close the File
Next, Open MMDocumentTypes.xml at C:\Program Files\Adobe\Adobe Dreamweaver CS4\configuration\DocumentTypes
Add THTML online 75 : winfileextension=”thtml,php,php3,php4,php5″ macfileextension=”thtml,php,php3,php4,php5″
Save, close and Restart Dreamweaver!
For more Info :- http://keithics.com/blog/article/opening-cake-thtml-file-with-dreaweaver-cs4/118/
php realex payment gateway code
$topay = '5';
$merchantid = "mytalentplace";//here grant crow`s realex merchent id should come
$secret = "wXcHmZ9yec";
$orderid= $timestamp.'-'.$_SESSION['ord_id'];
$amount =$_POST['amt']*100;
if($_REQUEST['currency']=="doller"){
$curr= "USD";
} elseif($_REQUEST['currency']=="euro"){
$curr= "EUR";
}else {
$curr= "GBP";
}
$tmp = "$timestamp.$merchantid.$orderid.$amount.$curr";
//$tmp = "$timestamp.$merchantid.$orderid";
$md5hash = sha1($tmp);
$tmp = "$md5hash.$secret";
$md5hash = sha1($tmp);
$up="UPDATE `mtp_user_payment` SET order_id='".$lid."' where user_payment_id='".$lid."'";
mysql_query($up);
?>
for live
for test
Wednesday, July 1, 2009
One more good blog
http://anuragtrivediphp.blogspot.com/
Thanks
Jawed
Help for php developers
I am making this blog keeping this mind that sometimes we search for codes and questions that are hard to find and we waste many time in it. So, I will put those kind of code and stuff, so that other can get help too. And I request to you all that you people too do the same.
Thanks
Jawed