DevSael Blog. C, CPP, C++, PHP, .NET Programming BLOG! advanced, MySQL, MongoDB, RDBMS.

Recent Posts



Q. PHP Session variable value is not transfering?

So, you are having trouble with php session variables! Well, Let see how can it being solved! If you didn't read about PHP Session variables then have a look on the manual!

Well let see what is happening...

PHP file: <test1.php>

<?PHP
session_start();

header("Access-Control-Allow-Origin: *"); 
header("Content-Type: application/json; charset=UTF-8");

//some code to determine $approvedToSet
$approvedToSet = true;
if(isset($approvedToSet))
{
$_SESSION["userName"] = 'MyName'; 
echo " Session variable is set." .$_SESSION["userName"];
} 
else { 
echo "User name is not set";} 

?>

PHP file: <test2.php>

<?PHP
echo $_SESSION["userName"];

ERROR:

Notice: Undefined index: userName in /var/www/xyz on line 30


[Solution:]

Correct Your file and ensure session_start(); function is on the top of your page.

PHP file: <test2.php>

<?PHP
session_start()
echo $_SESSION["userName"]; ?>

  1. Stop your apache2 or http server and start it again!
  2. Ensure session.save_path has been set.
  3. Must be Make sure session_start(); is called before any sessions are being called. So a safe bet would be to put it at the beginning of your page, immediately after the opening <?php tag before anything else. Also ensure there are no whitespaces/tabs before the opening <?phptag.
  4. After the header redirect, end the current script using exit(); (Others have also suggestedsession_write_close(); and session_regenerate_id(true), you can try those as well, but I'd use exit();).
  5. Make sure cookies are enabled in the browser you are using to test it on.
  6. Ensure register_globals is off, you can check this on the php.ini file and also using phpinfo(). Refer to this as to how to turn it off.
  7. Make sure you didn't delete or empty the session.
  8. Make sure the key in your $_SESSION superglobal array is not overwritten anywhere.
  9. Make sure you redirect to the same domain. So redirecting from a www.yourdomain.com to yourdomain.com doesn't carry the session forward.
  10. Make sure your file extension is .php (it happens!).
  11. If you use a connection script, dont forget to use start_session(); at the connection too, had some trouble before noticing that issue.
iu

[SOLVED] PHP Session variable value doesn't retrieved to another page

By Game Changer → Friday, May 5, 2017


Hi guys!
Let's have a clear conception about {int} {float} and {double} Do you know? Precision is the main difference. First, I am gonna show you some practical example!

C Difference between float and double

A float has 23 bits of precision; 8 bits of exponent, and 1 sign bit. A double has 52. bits of precision; 11 bits of exponent, and 1 sign bit.

float x = 3.141592653589793238;
double z = 3.141592653589793238;
printf("x=%f\n", x);
printf("z=%f\n", z);
printf("x=%20.18f\n", x);
printf("z=%20.18f\n", z);

Gives you the output

x=3.141593
z=3.141593
x=3.141592741012573242
z=3.141592653589793116

.Net difference between int, float and double

When Float ~7 digits (then 32 b),  Double ~15-16 digits (then 64 b) and Decimal ~28-29 digits takes 128 bit!

float flt = 1F/3;
double dbl = 1D/3;
decimal dcm = 1M/3;
Console.WriteLine("float: {0} double: {1} decimal: {2}", flt, dbl, dcm);
Result :

float: 0.3333333
double: 0.333333333333333
decimal: 0.3333333333333333333333333333

You have seen, Decimals much higher precision and are usually used within financial applications that require a high degree of accuracy.
Okay, Prob is decimals are much slower (up to 20X times in some tests) than a double/float.

Decimals and Floats/Doubles cannot be compared without a cast whereas Floats and Doubles can. Decimals also allow the encoding or trailing zeros.



Java difference between int, float and double:

One Asked: Can you explain what makes this difference between float and double?

Sure. Imagine you had two decimal types, one with five significant digits, and one with ten.

What value would you use to represent pi for each of those types? In both cases you'd be trying to get as close to a number which you couldn't represent exactly - but you wouldn't end up with the same value, would you?

It's the same for float and double - both are binary floating point types, but double has more precision than float.

12 {int}
12.345678 {float}
12.345678910111213 {double}

float is represented in 32 bits, with 1 sign bit, 8 bits of exponent, and 23 bits of the significant (or what follows from a scientific-notation number: 2.33728*1012; 33728 is the significand).
double is represented in 64 bits, with 1 sign bit, 11 bits of exponent, and 52 bits of significand.
By default, Java uses double to represent its floating-point numerals (so a literal 3.14 is typed double). It's also the data type that will give you a much larger number range, so I would strongly encourage its use over float.

Javascript:

12 {int}
12.345678 {float}
12.345678910111213 {double}

Actually All numbers in JavaScript are doubles: that is, they are stored as 64-bit IEEE-754 doubles.

That is, the goal is not to get a "double": the goal is to get the string reprsentation of a number formatted as "YYY.XX". For that, consider Number.toFixed, for instance:

(100).toFixed(2)
The result is the string (not a "double"!) "100.00". The parenthesis are required to avoid a grammar ambiguity in this case (it could also have been written as 100.0.toFixed or 100..toFixed), but would not be required if 100 was in a variable.

Happy coding!!


Tags:

Difference between decimal, float and double in programming

By Game Changer → Tuesday, April 25, 2017
PHP Mongodb Indexing:
It is not so hard to make index in Bigdata database such like MongoDB. Take look following bellow.

<?php

$c = new MongoCollection($db, 'foo');

// Create an index on 'A' ascending
$AscIndex = array('A' => 1);
$c->createIndex($AscIndex);

// Create an index on 'A' descending
$DscIndex = array('A' => -1);
$c->createIndex($DscIndex);

// Create a unique index on 'a_row_index'
$a_row_index = array('a_row_index' => 1), array('unique' => true);
$cIndex -> createIndex($a_row_index);

// create a compound index on 'XY' ascending and 'YX' descending
$XyYx = array('XY' => 1, 'YX' => -1);
$cIndex -> createIndex($XyYx);

?>

MongoDB indexing in PHP

By Game Changer → Thursday, February 25, 2016

PHP isset() equiv JavaScript isset() funciton:

Often I am get asked from junior developers that, Is there any isset() function in Javascript? Ha ha ha. I ignore them, but let them try to create a custom function to do this job.
Ok no more words...Let get it...
/**
 * 
 * @returns {Boolean}
 * Original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
 * Improved by: FremyCompany
 * Improved by: Onno Marsman
 * Improved by: Rafał Kukawski
 * Example-1: isset( undefined, true);
 * Returns: false
 * Example 2: isset( 'Kevin van Zonneveld' );
 * Returns: true
 */
function isset ()
{

  var a = arguments,
    l = a.length,
    i = 0,
    undef;

  if (l === 0)
  {
    throw new Error('Empty isset');
  }

  while (i !== l)
  {
    if (a[i] === undef || a[i] === null)
    {
      return false;
    }
    i++;
  }
  return true;
}
But........
The problem is this will raise an exception when calling isset(abc.def.ghi) in case if abc.defis undefined. However by combining this solution with the one that accepts a variable name in a form of a string, it will be identical to the PHP version

You can use this function as PHP isset() given to use.

var a;

a = {
    b: {
        c: 'e'
    }
};

function isset (obj, path) {
    var stone;

    path = path || '';

    if (path.indexOf('[') !== -1) {
        throw new Error('Unsupported object path notation.');
    }

    
    path = path.split('.');
    
    do {
        if (obj === undefined) {
            return false;
        }

        stone = path.shift();
        
        if (!obj.hasOwnProperty(stone)) {
            return false;
        }
        
        obj = obj[stone];
        
    } while (path.length);

    return true;
}

console.log(
    isset(a, 'b') == true,
    isset(a, 'b.c') == true,
    isset(a, 'b.c.d') == false,
    isset(a, 'b.c.d.e') == false,
    isset(a, 'b.c.d.e.f') == false
);

Another Way to do isset() function using javascript.

if(typeof(data.length) != 'undefined')
    {
       // do something
    }

    if(empty(data))
    {
        // do something
    }

   if(typeof(data) == 'undefined' || data === null)
   {
     //do something
   }

JavaScript isset() equivalent PHP isset()

By Game Changer → Thursday, December 17, 2015


From the terminal:
Hristo$ sudo /usr/local/mysql/support-files/mysql.server start
Starting MySQL
.....................................................................
ERROR! Manager of pid-file quit without updating file.
so I checked the status:
Hristo$ sudo /usr/local/mysql/support-files/mysql.server status
Password:
/usr/local/mysql/support-files/mysql.server: line 418: pidof: command not found
 ERROR! MySQL is not running
Again tried this?
Hristo$ /usr/local/mysql/bin/mysql -u root -p
Enter password: 
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)

mysql.err:
100706 11:38:36 mysqld_safe Starting mysqld daemon with databases from /usr/local/mysql/data
100706 11:38:36 [Warning] '--log' is deprecated and will be removed in a future release. Please use ''--general_log'/'--general_log_file'' instead.
100706 11:38:36 [Warning] '--log_slow_queries' is deprecated and will be removed in a future release. Please use ''--slow_query_log'/'--slow_query_log_file'' instead.
100706 11:38:36 [Warning] Setting lower_case_table_names=2 because file system for /usr/local/mysql/data/ is case insensitive
100706 11:38:36 [Note] Plugin 'FEDERATED' is disabled.
100706 11:38:36  InnoDB: Started; log sequence number 0 69987
100706 11:38:36 [ERROR] Can't start server : Bind on unix socket: Permission denied
100706 11:38:36 [ERROR] Do you already have another mysqld server running on socket: /var/mysql/mysql.sock ?
100706 11:38:36 [ERROR] Aborting

100706 11:38:36  InnoDB: Starting shutdown...
100706 11:38:41  InnoDB: Shutdown completed; log sequence number 0 69987
100706 11:38:41 [Note] /usr/local/mysql/bin/mysqld: Shutdown complete


Solution:

Configure correctly your my.cnf file.
[mysqld]
#
# * Basic Settings
#

user        = mysql
pid-file    = /var/run/mysqld/mysqld.pid
socket      = /var/run/mysqld/mysqld.sock
port        = 3306
basedir     = /usr
datadir     = /var/lib/mysql
tmpdir      = /tmp
skip-external-locking

#
# Instead of skip-networking the default is now to listen only on
# localhost which is more compatible and is not less secure.
bind-address        = 127.0.0.1

[Solved] MySQL Error on Snow Leopard

By Game Changer → Friday, December 11, 2015
PHP scripts to send the e-mail messages for contact form via SMTP. Already found several articles and PHPMailer tutorials? but a lot of them didn’t worked for you?

Why GMail for sending mail messages?

Obviously! it’s FREE! Sure most website owners can use their own SMTP server for sending email messages from their website, but it makes sense even than to use GMail for sending mail. The chance is big that your websites IP address is on a blacklist if your site is on hosted by a shared web hosting provider. If not or you host your site on your own server, there is always a risk that your IP address get blacklisted. Because of some limitations, the SMTP server from Google is a good choice applications with less than 500 recipients a day, check this information from the Google help pages.

Requirements

You need for this PHPMailer code example a PHP5 enabled web host (I did tests only on Linux), the port 465 need to be open and of course you need a GMail or Google Apps account.

Trouble sending e-mails with your “normal” GMail account? If you own a domain name, you can register for a Google Apps account or check below the tutorial update about an alternative SMTP service!

PHPMailer tutorial for GMail and Google Apps

Check that your web hosting provider has opened the port 465 (TCP out), if not ask him to open that port
Include the PHPMailer class file: require_once('phpmailer/class.phpmailer.php');
Create those two constant variables to store your GMail login and password. Use the login for your Google Apps mail account if you have one.
define('GUSER', 'you@gmail.com'); // GMail username
define('GPWD', 'password'); // GMail password
Use the following function to send the e-mail messages (add the function in one of your included files):
function smtpmailer($to, $from, $from_name, $subject, $body) { 
 global $error;
 $mail = new PHPMailer();  // create a new object
 $mail->IsSMTP(); // enable SMTP
 $mail->SMTPDebug = 0;  // debugging: 1 = errors and messages, 2 = messages only
 $mail->SMTPAuth = true;  // authentication enabled
 $mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for GMail
 $mail->Host = 'smtp.gmail.com';
 $mail->Port = 465; 
 $mail->Username = GUSER;  
 $mail->Password = GPWD;           
 $mail->SetFrom($from, $from_name);
 $mail->Subject = $subject;
 $mail->Body = $body;
 $mail->AddAddress($to);
 if(!$mail->Send()) {
  $error = 'Mail error: '.$mail->ErrorInfo; 
  return false;
 } else {
  $error = 'Message sent!';
  return true;
 }
}
Most of the settings inside the function are required by GMail. While searching for PHPmailer tutorials I found articles with different settings for the port and security. My advice is to use the settings from this tutorial. Call the function within your code:
smtpmailer('to@mail.com', 'from@mail.com', 'yourName', 'test mail message', 'Hello World!');
Use this more “advanced” usage inside your application:
if (smtpmailer('to@mail.com', 'from@mail.com', 'yourName', 'test mail message', 'Hello World!')) {
 // do something
}
if (!empty($error)) echo $error;
Advanced setup with fall-back SMTP server Because of the e-mail message limit it might be useful to use a secondary SMTP server if the GMail option is unable to send the message. For this functionality you need to replace the part with the SMTP settings. First create login/server variables for the second SMTP server:
define('SMTPUSER', 'you@yoursmtp.com'); // sec. smtp username
define('SMTPPWD', 'password'); // sec. password
define('SMTPSERVER', 'smtp.yoursmtp.com'); // sec. smtp server
Next we need to create an if/else statement using the variables for the second server (replace).
function smtpmailer($to, $from, $from_name, $subject, $body, $is_gmail = true) { 
 global $error;
 $mail = new PHPMailer();
 $mail->IsSMTP();
 $mail->SMTPAuth = true; 
 if ($is_gmail) {
  $mail->SMTPSecure = 'ssl'; 
  $mail->Host = 'smtp.gmail.com';
  $mail->Port = 465;  
  $mail->Username = GUSER;  
  $mail->Password = GPWD;   
 } else {
  $mail->Host = SMTPSERVER;
  $mail->Username = SMTPUSER;  
  $mail->Password = SMTPPWD;
 }        
 $mail->SetFrom($from, $from_name);
 $mail->Subject = $subject;
 $mail->Body = $body;
 $mail->AddAddress($to);
 if(!$mail->Send()) {
  $error = 'Mail error: '.$mail->ErrorInfo;
  return false;
 } else {
  $error = 'Message sent!';
  return true;
 }
}
And next use the modified PHPMailer function as followed:
$msg = 'Hello World';
$subj = 'test mail message';
$to = 'to@mail.com';
$from = 'from@mail.com';
$name = 'yourName';
 
if (smtpmailer($to, $from, $name, $subj, $msg)) {
 echo 'Yippie, message send via Gmail';
} else {
 if (!smtpmailer($to, $from, $name, $subj, $msg, false)) {
  if (!empty($error)) echo $error;
 } else {
  echo 'Yep, the message is send (after doing some hard work)';
 }
}
Both examples are very simple and demonstrate only how-to send e-mail messages using PHPmailer with the SMTP server provided by GMail. Of course you can extend the code to handle HTML messages and attachments etc. If you have any issues with these examples, just let me know. UPDATE: Alternate SMTP service Since this tutorial was published, I got several messages that the free GMail account doesn’t allow you to send a lot of e-mail messages from your own websites. Your can use this PHPmailer example code for any other SMTP server or service. I suggest to use ElasticEmail, a premium e-mail service provider in the cloud. Signup for a free account which is good for the first 25.000 mail messages and 10.000 contacts every month. If you use the tutorial code with ElasticEmail you need to replace this part of code
 if ($is_gmail) {
  $mail->SMTPSecure = 'ssl'; 
  $mail->Host = 'smtp.gmail.com';
  $mail->Port = 465;  
  $mail->Username = GUSER;  
  $mail->Password = GPWD;   
 } else {
  $mail->Host = SMTPSERVER;
  $mail->Username = SMTPUSER;  
  $mail->Password = SMTPPWD;
 } 
with this code
 $mail->Host = 'smtp.elasticemail.com';
 $mail->Port = 2525; 
 $mail->Username = 'your username';
 $mail->Password = 'your password';
Optional: Remove the “$is_gmail” attribute from the function.
Tags:

Sending e-mails using SMTP with PHPMailer and GMail

By Game Changer →

Date and time manipulation is an unavoidable part of programming; there will inevitably be a part of a project that requires a date to be modified. While, on the surface, echoing a date in the future brings a small bit of accomplishment, it can be quickly eradicated when one is tasked with manipulating that date.
Without being aware of the arsenal of tools PHP provides you with regards to working with dates, you might find yourself writing kludges that convert strings into timestamps for various comparisons.
Today we’re going to dissect the PHP DateInterval class, a power tool for dealing with dates in a web app.
But before learning about the DateInterval object, one needs to first understand what an interval is.

What is an Interval?

Simply put, an interval is a duration of time.
When we converse about the topic of duration, we wouldn’t say, "Honey, I’ll be home on Dec 3rd, 2015 15:19pm".
Instead, we would simplify and say "I’ll be home in 5 minutes". Although this is ideal when conversing with another person, this is not so great as a data construct.
So how do we define "in 5 minutes" for a web app?
Fortunately, there’s an ISO for that.
ISO 8601 is the international standard that defines how to use, store, and transfer date, time, and duration information.
The specific string to define durations is an easy-to-remember pattern:
PYMDTHMS
  • P: period
  • Y: years
  • M: months
  • D: days
  • T: time
  • H: hours
  • M: minutes
  • S: seconds
Except for P, each designator is optional.
Immediately preceding each designator is the quantity of time you want to store.
Below is a table showing samples of different date and time ranges:
StringEquivalent to…
P1Y1 year
P1M1 month
P1D1 day
P30D30 days
PT1H1 hour
PT5M5 minutes
PT35S35 seconds
P1Y6M29DT4H34M23S1 year, 6 months, 29 days, 4 hours, 34 minutes, 23 seconds

Creating a DateInterval Object

Now that we understand what an interval is — it’s simply a duration of time — and that ISO 8601 defines our duration’s format, we can start playing around with the PHP DateInterval class.
Let’s define a predictable duration, create a DateInterval object, and output the result to the screen.
We’ll start with "1 year, 2 months, 3 days, 4 hours, 5 minutes, 6 seconds".
$Duration = new DateInterval( "P1Y2M3DT4H5M6S" );
print_r( $Duration );
Result:
DateInterval Object
(
[y] => 1
[m] => 2
[d] => 3
[h] => 4
[i] => 5
[s] => 6
...
)
You will notice that the constructor for the DateInterval class has parsed your duration and stored the individual values in its own properties. $Duration->ymatches the 1Y from the duration string you passed in.
Let’s try another more practical duration: 1 month. You’ll notice that any undefined durations are automatically defaulted to 0.
$Duration = new DateInterval( "P1M" );
print_r( $Duration );
Result:
DateInterval Object
(
[y] => 0
[m] => 1
[d] => 0
[h] => 0
[i] => 0
[s] => 0
...
)
So now we know what’s happening, but what do we really have? What’s so great and tangible about this?
The real benefit to what we have here is that the $Duration object itself represents a duration of time. We don’t need to know a source or destination date; $Duration is simply 1 month.
Note: It’s important to note that creating a DateInterval with 13 months (P13M) will not roll over and provide you with "1 year 1 month".
That makes sense because we don’t have a source or destination date. Imagine the case of 61 days:
  • On October 1, it’s 2 months
  • On December 1, it’s only 1 month and 30 days
  • On February 1, it’s 2 months and 2 days (or only 2 months and 1 day on leap years)

Manipulating Dates with Durations

Durations tame the manipulation of PHP DateTime objects.
The PHP DateTime class has three methods that work with a DateIntervalobject:
  • add
  • sub
  • diff
Both add and sub will modify a DateTime object by a DateInterval, while diffwill compare two DateTime objects and return a DateInterval.
$Now = new DateTime();
echo $Now->format('Y-m-d'); // 2014-06-12

$Duration = new DateInterval('P1M'); // 1 month
$Now->add( $Duration );
echo $Now->format('Y-m-d'); // 2014-07-12

$Duration = new DateInterval('P2M'); // 2 months
$Now->sub( $Duration );
echo $Now->format('Y-m-d'); // 2014-05-12
In the above example you can see how date manipulation becomes much easier and more predictable by using DateInterval objects to modify DateTime objects.
The diff method is just as easy to use, but provides an extra piece of information:total days. This is important because when using the DateTime object to find a difference, we have a source and destination date, and therefore we can reduce the units of time into larger denominations. However, having the total number of days in between is a valuable piece of information.
$Year = new DateInterval('P1Y');
echo $Year->days; // 0

$Date1 = new DateTime();
$Date2 = new DateTime();
$Date2->add( $Year );

$Difference = $Date1->diff( $Date2 );
echo $Difference->days; // 365

Reading Durations and Extracting Intervals

There are inevitably going to be times where you want to extract portions of the stored interval (much the same as you would a date).
The DateInterval class has a handy format method. PHP docs has a table for the format method that is a useful reference.
You use the format method like this:
$Duration = new DateInterval('P345D');
echo $Duration->format('I am %d days'); // I am 345 days
Note: It’s important to note, for those familiar with the strftime method, that the recognized characters are completely different. For example, theDateInterval::format method interprets %a as total days while strftimeinterprets it as a textual representation of the day (i.e. "Sun").
Oddly enough, DateInterval doesn’t natively have a way to extract the entire interval spec without the zero values. This leaves you with two options:
  1. Extract it with 0 elements, which is perfectly acceptable
  2. Extend the DateInterval class
The second option, extending the DateInterval class, brings upon it’s own difficulties that we won’t touch on here today.
To extract the interval spec with the 0 elements intact, you can use the same format method like so:
$Duration = new DateInterval('P345D');
echo $Duration->format('P%yY%mM%dDT%hH%iM%sS'); // P0Y0M345DT0H0M0S
If you want to confirm the above, simply create a new DateInterval with the result of the first:
$interval_spec = 'P345D';
$Duration1 = new DateInterval( $interval_spec );
echo $Duration1->format('%d'); // 345

$interval_spec = $Duration1->format('P%yY%mM%dDT%hH%iM%sS'); // P0Y0M345DT0H0M0S
$Duration2 = new DateInterval( $interval_spec );
echo $Duration2->format('%d'); // 345
You should now have a grasp on using the PHP DateInterval class, and it’s capabilities.
Hopefully you’re able to apply this current and future web app projects.

PHP DateInterval Class

By Game Changer →