Stack of codes.
Please comment below your opinion. We will try to improve and bring more accurate contents for you.

Sunday, 31 December 2017

The 10 Most Common Mistakes PHP Developers Make

The 10 Most Common Mistakes PHP Developers Make::

PHP makes it relatively easy to build a web-based system, which is much of the reason for its popularity. But its ease of use notwithstanding, PHP has evolved into quite a sophisticated language with many frameworks, nuances, and subtleties that can bite developers, leading to hours of hair-pulling debugging. This article highlights ten of the more common mistakes that PHP developers need to beware of.

  1. Common Mistake #1: Leaving dangling array references after foreach loops::

Not sure how to use foreach loops in PHP?
Using references in foreach loops can be useful if you want to operate on each element in the array that you are iterating over.
 For example:$arr = array(1, 2, 3, 4); 
foreach ($arr as &$value)
 { $value = $value * 2; } 

// $arr is now array(2, 4, 6, 8)

The problem is that, if you’re not careful, this can also have some undesirable side effects and consequences. Specifically, in the above example, after the code is executed, $value will remain in scope and will hold a reference to the last element in the array. Subsequent operations involving $value could therefore unintentionally end up modifying the last element in the array.

The main thing to remember is that foreach does not create a scope. Thus, $value in the above example is a reference within the top scope of the script. On each iteration foreach sets the reference to point to the next element of $array. After the loop completes, therefore, $value still points to the last element of $arrayand remains in scope.

Here’s an example of the kind of evasive and confusing bugs that this can lead to:

$array = [1, 2, 3]; 
echo implode(',', $array), "\n"; 
 foreach ($array as &$value) {} 

// by reference 
echo implode(',', $array), "\n"; 

foreach ($array as $value) {} 

// by value (i.e., copy) 

echo implode(',', $array), "\n";

The above code will output the following:1,2,3 1,2,3 1,2,2

No, that’s not a typo. The last value on the last line is indeed a 2, not a 3.


After going through the first foreach loop,
 $array remains unchanged but, as explained above, 
$value is left as a dangling reference to the last element in $array (since that foreach loop accessed 

$value by reference).

As a result, when we go through the second foreach loop, “weird stuff” appears to happen. Specifically, since $value is now being accessed by value (i.e., by copy), foreach copies each sequential $array element into $value in each step of the loop. 
As a result, here’s what happens during each step of the second foreach loop:

Pass 1: Copies $array[0] (i.e., “1”) into $value (which is a reference to $array[2]), so $array[2] now equals 1. So $array now contains [1, 2, 1].

Pass 2: Copies $array[1] (i.e., “2”) into $value (which is a reference to $array[2]), so $array[2] now equals 2. So $array now contains [1, 2, 2].

Pass 3: Copies $array[2] (which now equals “2”) into $value (which is a reference to $array[2]), so $array[2] still equals 2. So $array now contains [1, 2, 2].

To still get the benefit of using references in foreach loops without running the risk of these kinds of problems, call unset() on the variable, immediately after the foreach loop, to remove the reference; e.g.:$arr = array(1, 2, 3, 4);

foreach ($arr as &$value) { $value = $value * 2; } 
// $value no longer references $arr[3]

Common Mistake #2: Misunderstanding isset() behavior

Despite its name,
  isset() not only returns false if an item does not exist, but also returns false for nullvalues.

This behavior is more problematic than it might appear at first and is a common source of problems.

Consider the following:$data = fetchRecordFromStorage($storage, $identifier); if (!isset($data['keyShouldBeSet']) { // do something here if 'keyShouldBeSet' is not set }

The author of this code presumably wanted to check if keyShouldBeSet was set in $data. But, as discussed, isset($data['keyShouldBeSet']) will also return false if $data['keyShouldBeSet'] was set, but was set to null. So the above logic is flawed.

Here’s another example:if ($_POST['active']) { $postData = extractSomething($_POST); } // ... if (!isset($postData)) { echo 'post not active'; }

The above code assumes that if $_POST['active'] returns true, then postData will necessarily be set, and therefore isset($postData) will return true. So conversely, the above code assumes that the only way that isset($postData) will return false is if $_POST['active'] returned false as well.


As explained, isset($postData) will also return false if $postData was set to null. It therefore is possible for isset($postData) to return false even if $_POST['active'] returned true. So again, the above logic is flawed.

And by the way, as a side point, if the intent in the above code really was to again check if $_POST['active']returned true, relying on isset() for this was a poor coding decision in any case. Instead, it would have been better to just recheck 

$_POST['active']; i.e.:if ($_POST['active']) 
 $postData = extractSomething($_POST); 

 // ... if ($_POST['active']) { echo 'post not active'; } 

For cases, though, where it is important to check if a variable was really set (i.e., to distinguish between a variable that wasn’t set and a variable that was set to null), the array_key_exists() method is a much more robust solution.

For example, we could rewrite the first of the above two examples as follows:$data = fetchRecordFromStorage($storage, $identifier); if (! array_key_exists('keyShouldBeSet', $data)) { // do this if 'keyShouldBeSet' isn't set }

Moreover, by combining array_key_exists() with get_defined_vars(), we can reliably check whether a variable within the current scope has been set or not:if (array_key_exists('varShouldBeSet', get_defined_vars())) { // variable $varShouldBeSet exists in current scope }

Common Mistake #3: Confusion about returning by reference vs. by value

Consider this code snippet:class Config { private $values = []; public function getValues() { return $this->values; } } $config = new Config(); $config->getValues()['test'] = 'test'; echo $config->getValues()['test'];

If you run the above code, you’ll get the following:PHP Notice: Undefined index: test in /path/to/my/script.php on line 21

What’s wrong?

The issue is that the above code confuses returning arrays by reference with returning arrays by value. Unless you explicitly tell PHP to return an array by reference (i.e., by using&), PHP will by default return the the array “by value”. This means that a copy of the array will be returned and therefore the called function and the caller will not be accessing the same instance of the array.

So the above call to getValues() returns a copy of the $values array rather than a reference to it. With that in mind, let’s revisit the two key lines from the above the example:// getValues() returns a COPY of the $values array, so this adds a 'test' element // to a COPY of the $values array, but not to the $values array itself. $config->getValues()['test'] = 'test'; // getValues() again returns ANOTHER COPY of the $values array, and THIS copy doesn't // contain a 'test' element (which is why we get the "undefined index" message). echo $config->getValues()['test'];

One possible fix would be to save the first copy of the $values array returned by getValues() and then operate on that copy subsequently; e.g.:$vals = $config->getValues(); $vals['test'] = 'test'; echo $vals['test'];

That code will work fine (i.e., it will output test without generating any “undefined index” message), but depending on what you’re trying to accomplish, this approach may or may not be adequate. In particular, the above code will not modify the original $values array. So if you do want your modifications (such as adding a ‘test’ element) to affect the original array, you would instead need to modify the getValues() function to return a reference to the $values array itself. This is done by adding a & before the function name, thereby indicating that it should return a reference; i.e.:class Config { private $values = []; // return a REFERENCE to the actual $values array public function &getValues() { return $this->values; } } $config = new Config(); $config->getValues()['test'] = 'test'; echo $config->getValues()['test'];

The output of this will be test, as expected.

But to make things more confusing, consider instead the following code snippet:class Config { private $values; // using ArrayObject rather than array public function __construct() { $this->values = new ArrayObject(); } public function getValues() { return $this->values; } } $config = new Config(); $config->getValues()['test'] = 'test'; echo $config->getValues()['test'];

If you guessed that this would result in the same “undefined index” error as our earlier array example, you were wrong. In fact, this code will work just fine. The reason is that, unlike arrays, PHP always passes objects by reference. (ArrayObject is an SPL object, which fully mimics arrays usage, but works as an object.)

As these examples demonstrate, it is not always entirely obvious in PHP whether you are dealing with a copy or a reference. It is therefore essential to understand these default behaviors (i.e., variables and arrays are passed by value; objects are passed by reference) and also to carefully check the API documentation for the function you are calling to see if it is returning a value, a copy of an array, a reference to an array, or a reference to an object.

All that said, it is important to note that the practice of returning a reference to an array or an ArrayObject is generally something that should be avoided, as it provides the caller with the ability to modify the instance’s private data. This “flies in the face” of encapsulation. Instead, it’s better to use old style “getters” and “setters”, e.g.:class Config { private $values = []; public function setValue($key, $value) { $this->values[$key] = $value; } public function getValue($key) { return $this->values[$key]; } } $config = new Config(); $config->setValue('testKey', 'testValue'); echo $config->getValue('testKey'); // echos 'testValue'

This approach gives the caller the ability to set or get any value in the array without providing public access to the otherwise-private $values array itself.

Common Mistake #4: Performing queries in a loop::

It’s not uncommon to come across something like this if your PHP is not working:$models = []; foreach ($inputValues as $inputValue) { $models[] = $valueRepository->findByValue($inputValue); }

While there may be absolutely nothing wrong here, but if you follow the logic in the code, you may find that the innocent looking call above to $valueRepository->findByValue() ultimately results in a query of some sort, such as:$result = $connection->query("SELECT `x`,`y` FROM `values` WHERE `value`=" . $inputValue);

As a result, each iteration of the above loop would result in a separate query to the database. So if, for example, you supplied an array of 1,000 values to the loop, it would generate 1,000 separate queries to the resource! If such a script is called in multiple threads, it could potentially bring the system to a grinding halt.

It’s therefore crucial to recognize when queries are being made by your code and, whenever possible, gather the values and then run one query to fetch all the results.

One example of a fairly common place to encounter querying being done inefficiently (i.e., in a loop) is when a form is posted with a list of values (IDs, for example). Then, to retrieve the full record data for each of the IDs, the code will loop through the array and do a separate SQL query for each ID. This will often look something like this:$data = []; foreach ($ids as $id) { $result = $connection->query("SELECT `x`, `y` FROM `values` WHERE `id` = " . $id); $data[] = $result->fetch_row(); }

But the same thing can be accomplished much more efficiently in a single SQL query as follows:$data = []; if (count($ids)) { $result = $connection->query("SELECT `x`, `y` FROM `values` WHERE `id` IN (" . implode(',', $ids)); while ($row = $result->fetch_row()) { $data[] = $row; } }

It’s therefore crucial to recognize when queries are being made, either directly or indirectly, by your code. Whenever possible, gather the values and then run one query to fetch all the results. Yet caution must be exercised there as well, which leads us to our next common PHP mistake…
Common Mistake #5: Memory usage headfakes and inefficiencies

While fetching many records at once is definitely more efficient than running a single query for each row to fetch, such an approach can potentially lead to an “out of memory” condition in libmysqlclient when using PHP’s mysql extension.

To demonstrate, let’s take a look at a test box with limited resources (512MB RAM), MySQL, and php-cli.

We’ll bootstrap a database table like this:// connect to mysql $connection = new mysqli('localhost', 'username', 'password', 'database'); // create table of 400 columns $query = 'CREATE TABLE `test`(`id` INT NOT NULL PRIMARY KEY AUTO_INCREMENT'; for ($col = 0; $col < 400; $col++) { $query .= ", `col$col` CHAR(10) NOT NULL"; } $query .= ');'; $connection->query($query); // write 2 million rows for ($row = 0; $row < 2000000; $row++) { $query = "INSERT INTO `test` VALUES ($row"; for ($col = 0; $col < 400; $col++) { $query .= ', ' . mt_rand(1000000000, 9999999999); } $query .= ')'; $connection->query($query); }

OK, now let’s check resources usage:// connect to mysql $connection = new mysqli('localhost', 'username', 'password', 'database'); echo "Before: " . memory_get_peak_usage() . "\n"; $res = $connection->query('SELECT `x`,`y` FROM `test` LIMIT 1'); echo "Limit 1: " . memory_get_peak_usage() . "\n"; $res = $connection->query('SELECT `x`,`y` FROM `test` LIMIT 10000'); echo "Limit 10000: " . memory_get_peak_usage() . "\n";

Output:Before: 224704 Limit 1: 224704 Limit 10000: 224704

Cool. Looks like the query is safely managed internally in terms of resources.

Just to be sure, though, let’s boost the limit one more time and set it to 100,000. Uh-oh. When we do that, we get:PHP Warning: mysqli::query(): (HY000/2013): Lost connection to MySQL server during query in /root/test.php on line 11

What happened?

The issue here is the way PHP’s mysql module works. It’s really just a proxy for libmysqlclient, which does the dirty work. When a portion of data is selected, it goes directly into memory. Since this memory is not managed by PHP’s manager, memory_get_peak_usage() won’t show any increase in resources utilization as we up the limit in our query. This leads to problems like the one demonstrated above where we’re tricked into complacency thinking that our memory management is fine. But in reality, our memory management is seriously flawed and we can experience problems like the one shown above.

You can at least avoid the above headfake (although it won’t itself improve your memory utilization) by instead using the mysqlnd module. mysqlnd is compiled as a native PHP extension and it does use PHP’s memory manager.

Therefore, if we run the above test using mysqlnd rather than mysql, we get a much more realistic picture of our memory utilization:Before: 232048 Limit 1: 324952 Limit 10000: 32572912

And it’s even worse than that, by the way. According to PHP documentation, mysql uses twice as many resources as mysqlnd to store data, so the original script using mysql really used even more memory than shown here (roughly twice as much).

To avoid such problems, consider limiting the size of your queries and using a loop with small number of iterations; e.g.:$totalNumberToFetch = 10000; $portionSize = 100; for ($i = 0; $i <= ceil($totalNumberToFetch / $portionSize); $i++) { $limitFrom = $portionSize * $i; $res = $connection->query( "SELECT `x`,`y` FROM `test` LIMIT $limitFrom, $portionSize"); }

When we consider both this PHP mistake and mistake #4 above, we realize that there is a healthy balance that your code ideally needs to achieve between, on the one hand, having your queries being too granular and repetitive, vs. having each of your individual queries be too large. As is true with most things in life, balance is needed; either extreme is not good and can cause problems with PHP not working properly.
Common Mistake #6: Ignoring Unicode/UTF-8 issues

In some sense, this is really more of an issue in PHP itself than something you would run into while debugging PHP, but it has never been adequately addressed. PHP 6’s core was to be made Unicode-aware, but that was put on hold when development of PHP 6 was suspended back in 2010.

But that by no means absolves the developer from properly handing UTF-8 and avoiding the erroneous assumption that all strings will necessarily be “plain old ASCII”. Code that fails to properly handle non-ASCII strings is notorious for introducing gnarly heisenbugs into your code. Even simple strlen($_POST['name'])calls could cause problems if someone with a last name like “Schrödinger” tried to sign up into your system.

Here’s a small checklist to avoid such problems in your code:
If you don’t know much about Unicode and UTF-8, you should at least learn the basics. There’s a great primer here.
Be sure to always use the mb_* functions instead of the old string functions (make sure the “multibyte” extension is included in your PHP build).
Make sure your database and tables are set to use Unicode (many builds of MySQL still use latin1 by default).
Remember that json_encode() converts non-ASCII symbols (e.g., “Schrödinger” becomes “Schr\u00f6dinger”) but serialize() does not.
Make sure your PHP code files are also UTF-8 encoded to avoid collisions when concatenating strings with hardcoded or configured string constants.

A particularly valuable resource in this regard is the UTF-8 Primer for PHP and MySQL post by Francisco Claria on this blog.

Like what you're reading?
Get the latest updates first.

No spam. Just great engineering posts.

Common Mistake #7: Assuming $_POST will always contain your POST data::

Despite its name, the $_POST array won’t always contain your POST data and can be easily found empty. To understand this, let’s take a look at an example. Assume we make a server request with a jQuery.ajax() call as follows:// js $.ajax({ url: '', method: 'post', data: JSON.stringify({a: 'a', b: 'b'}), contentType: 'application/json' });

(Incidentally, note the contentType: 'application/json' here. We send data as JSON, which is quite popular for APIs. It’s the default, for example, for posting in the AngularJS $http service.)

On the server side of our example, we simply dump the $_POST array:// php var_dump($_POST);

Surprisingly, the result will be:array(0) { }

Why? What happened to our JSON string {a: 'a', b: 'b'}?

The answer is that PHP only parses a POST payload automatically when it has a content type of application/x-www-form-urlencoded or multipart/form-data. The reasons for this are historical — these two content types were essentially the only ones used years ago when PHP’s $_POST was implemented. So with any other content type (even those that are quite popular today, like application/json), PHP doesn’t automatically load the POST payload.

Since $_POST is a superglobal, if we override it once (preferably early in our script), the modified value (i.e., including the POST payload) will then be referenceable throughout our code. This is important since $_POSTis commonly used by PHP frameworks and almost all custom scripts to extract and transform request data.

So, for example, when processing a POST payload with a content type of application/json, we need to manually parse the request contents (i.e., decode the JSON data) and override the $_POST variable, as follows:// php $_POST = json_decode(file_get_contents('php://input'), true);

Then when we dump the $_POST array, we see that it correctly includes the POST payload; e.g.:array(2) { ["a"]=> string(1) "a" ["b"]=> string(1) "b" }

Common Mistake #8: Thinking that PHP supports a character data type

Look at this sample piece of code and try guessing what it will print:for ($c = 'a'; $c <= 'z'; $c++) { echo $c . "\n"; }

If you answered ‘a’ through ‘z’, you may be surprised to know that you were wrong.

Yes, it will print ‘a’ through ‘z’, but then it will also print ‘aa’ through ‘yz’. Let’s see why.

In PHP there’s no char datatype; only string is available. With that in mind, incrementing the string z in PHP yields aa:php> $c = 'z'; echo ++$c . "\n"; aa

Yet to further confuse matters, aa is lexicographically less than z:php> var_export((boolean)('aa' < 'z')) . "\n"; true

That’s why the sample code presented above prints the letters a through z, but then also prints aathrough yz. It stops when it reachs za, which is the first value it encounters that it “greater than” z:php> var_export((boolean)('za' < 'z')) . "\n"; false

That being the case, here’s one way to properly loop through the values ‘a’ through ‘z’ in PHP:for ($i = ord('a'); $i <= ord('z'); $i++) { echo chr($i) . "\n"; }

Or alternatively:$letters = range('a', 'z'); for ($i = 0; $i < count($letters); $i++) { echo $letters[$i] . "\n"; }

Common Mistake #9: Ignoring coding standards::

Although ignoring coding standards doesn’t directly lead to needing to debug PHP code, it is still probably one of the most important things to discuss here.

Ignoring coding standards can cause a whole slew of problems on a project. At best, it results in code that is inconsistent (since every developer is “doing their own thing”). But at worst, it produces PHP code that does not work or can be difficult (sometimes almost impossible) to navigate, making it extremely difficult to debug, enhance, maintain. And that means reduced productivity for your team, including lots of wasted (or at least unnecessary) effort.

Fortunately for PHP developers, there is the PHP Standards Recommendation (PSR), comprised of the following five standards:
PSR-0: Autoloading Standard
PSR-1: Basic Coding Standard
PSR-2: Coding Style Guide
PSR-3: Logger Interface
PSR-4: Autoloader

PSR was originally created based on inputs from maintainers of the most recognized platforms on the market. Zend, Drupal, Symfony, Joomla and others contributed to these standards, and are now following them. Even PEAR, which attempted to be a standard for years before that, participates in PSR now.

In some sense, it almost doesn’t matter what your coding standard is, as long as you agree on a standard and stick to it, but following the PSR is generally a good idea unless you have some compelling reason on your project to do otherwise. More and more teams and projects are conforming with the PSR. Tt’s definitely recognized at this point as “the” standard by the majority of PHP developers, so using it will help ensure that new developers are familiar and comfortable with your coding standard when they join your team.
Common Mistake #10: Misusing empty()

Some PHP developers like using empty() for boolean checks for just about everything. There are case, though, where this can lead to confusion.

First, let’s come back to arrays and ArrayObject instances (which mimic arrays). Given their similarity, it’s easy to assume that arrays and ArrayObject instances will behave identically. This proves, however, to be a dangerous assumption. For example, in PHP 5.0:// PHP 5.0 or later: $array = []; var_dump(empty($array)); // outputs bool(true) $array = new ArrayObject(); var_dump(empty($array)); // outputs bool(false) // why don't these both produce the same output?

And to make matters even worse, the results would have been different prior to PHP 5.0:// Prior to PHP 5.0: $array = []; var_dump(empty($array)); // outputs bool(false) $array = new ArrayObject(); var_dump(empty($array)); // outputs bool(false)

This approach is unfortunately quite popular. For example, this is the way Zend\Db\TableGateway of Zend Framework 2 returns data when calling current() on TableGateway::select() result as the doc suggests. Developer can easily become victim of this mistake with such data.

To avoid these issues, the better approach to checking for empty array structures is to use count():// Note that this work in ALL versions of PHP (both pre and post 5.0): $array = []; var_dump(count($array)); // outputs int(0) $array = new ArrayObject(); var_dump(count($array)); // outputs int(0)

And incidentally, since PHP casts 0 to false, count() can also be used within if () conditions to check for empty arrays. It’s also worth noting that, in PHP, count() is constant complexity (O(1) operation) on arrays, which makes it even clearer that it’s the right choice.

Another example when empty() can be dangerous is when combining it with the magic class function __get(). Let’s define two classes and have a test property in both.

First let’s define a Regular class that includes test as a normal property:class Regular { public $test = 'value'; }

Then let’s define a Magic class that uses the magic __get() operator to access its test property:class Magic { private $values = ['test' => 'value']; public function __get($key) { if (isset($this->values[$key])) { return $this->values[$key]; } } }

OK, now let’s see what happens when we attempt to access the test property of each of these classes:$regular = new Regular(); var_dump($regular->test); // outputs string(4) "value" $magic = new Magic(); var_dump($magic->test); // outputs string(4) "value"

Fine so far.

But now let’s see what happens when we call empty() on each of these:var_dump(empty($regular->test)); // outputs bool(false) var_dump(empty($magic->test)); // outputs bool(true)

Ugh. So if we rely on empty(), we can be misled into believing that the test property of $magic is empty, whereas in reality it is set to 'value'.

Unfortunately, if a class uses the magic __get() function to retrieve a property’s value, there’s no foolproof way to check if that property value is empty or not. Outside of the class’ scope, you can really only check if a null value will be returned, and that doesn’t necessarily mean that the corresponding key is not set, since it actually could have been set to null.

In contrast, if we attempt to reference a non-existent property of a Regular class instance, we will get a notice similar to the following:Notice: Undefined property: Regular::$nonExistantTest in /path/to/test.php on line 10 Call Stack: 0.0012 234704 1. {main}() /path/to/test.php:0

So the main point here is that the empty() method should be used with care as it can lend itself to confusing – or even potentially misleading – results, if one is not careful.


PHP’s ease of use can lull developers into a false sense of comfort, leaving themselves vulnerable to lengthy PHP debugging due to some of the nuances and idiosyncrasies of the language. This can result in PHP not working and problems such as those described herein.

The PHP language has evolved significantly over the course of its 20 year history. Familiarizing oneself with its subtleties is a worthwhile endeavor, as it will help ensure that the software you produce is more scalable, robust, and maintainable.

Friday, 29 December 2017

php - MySQL error when inserting data containing apostrophes

php - MySQL error when inserting data containing apostrophes::


A Database Error Occurred
Error Number: 1064

You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 's lynn'' at line 8

select c.* from os_state where c.code = 'GB' and = 'king's lynn'


$val = mysql_real_escape_string(trim($val));

Sub string in Php

Sub string in Php:

   $str  = "ghsdgdsgadsgdhg djahdjhajdh hdsjahdjahd hjkhdsajhd
          ahdjsahdjahsdjahsdjashd jkdsajdahdjsahjhdsajh djash 
         djashdjhs hjdsahjdhasdh hjdsahdhsajdhjas jhdsjahdahdhs 
         jhdsjahdjahdjsa jhdsjahdjah djhsadjhadha hsjdha shdajsh 

   $ddd  =  sub_string($str);

   function sub_string($str = '', $length = 150) {
        if (!$str) {
            return FALSE;

        if (strlen($str) > $length)
            return substr($str, 0, $length) . '...';
            return $str;

Wednesday, 27 December 2017

Showing Cannot modify header information in php

Showing Cannot modify header information in php::

A PHP Error was encountered
Severity: Warning

Message: Cannot modify header information - headers already sent by (output started at C:\xampp\htdocs\...)

Filename: libraries/Session.php

Line Number: 675


Add at the start of the page or function:


Constructor and Destructor in Php

Constructor and Destructor in Php::

class my_class {
  public $error_reporting = false;

  function __construct($error_reporting = false) {
    $this->error_reporting = $error_reporting;

  function __destruct() {
    if($this->error_reporting === true) $this->show_report();


Monday, 25 December 2017

Here is a step-by-step guide to buy bitcoin in India

Here is a step-by-step guide to buy bitcoin in India

Bitcoin has became one of the most popular cryptocurrencies around the world and has a growing number of applications every day. In case you are also looking to find out how to buy and sell bitcoin currency in India, here's a step-by-step guide for you:

Create an account
Next, you can create your account by registering on the selected bitcoin service provider. This will give you a secure place to store your bitcoin, and easy payment methods to convert your local currency into or out of bitcoin.

Start buy/ sell order
Once you initiate buy bitcoin, it will take you to the exchange and the rate at which you can buy the bitcoin. At present, the value of bitcoin has been pushed to very high levels, so you will probably be able to buy only a fraction of a bitcoin. You can sell your bitcoin in the same manner.


Friday, 22 December 2017

Constants in Php

Constants in Php::

A constant is an identifier (name) for a simple value. As the name suggests, that value cannot change during the execution of the script (except for magic constants, which aren't actually constants). A constant is case-sensitive by default. By convention, constant identifiers are always uppercase.

The name of a constant follows the same rules as any label in PHP. A valid constant name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thusly: [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*

Example #1 Valid and invalid constant names

// Valid constant names
define("FOO", "something");
define("FOO2", "something else");
define("FOO_BAR", "something more");

// Invalid constant names
define("2FOO", "something");

// This is valid, but should be avoided:
// PHP may one day provide a magical constant
// that will break your script
define("__FOO__", "something");

- Stack Of Codes

Thursday, 21 December 2017

Check if image exists in folder or not currupted in php

Check if image exists in folder or not currupted in php::

$full_path = Full Image path; (Like: ../dd/tmp.jpg)


    //Image Not Available or Not Exists

    //Image File Exists 

  //Check if image not damaged.
    $ext = strtolower(pathinfo($full_path, PATHINFO_EXTENSION));
    if ($ext === 'jpg') { $ext = 'jpeg'; }
    $function = 'imagecreatefrom' . $ext;

    if (function_exists($function) && @$function($full_path) === FALSE) 
//Image Is Corrupted or Damaged.
// Image is Ok

Wednesday, 20 December 2017

Htaccess changes required in php

Htaccess changes required in php::

RewriteEngine on
Rewritebase /
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond $1 !^/(index\.php|assets/|humans\.txt)
RewriteRule ^(.*)$ index.php?/$1 [L]

# BEGIN cPanel-generated php ini directives, do not edit
# Manual editing of this file may result in unexpected behavior.
# To make changes to this file, use the cPanel MultiPHP INI Editor (Home >> Software >> MultiPHP INI Editor)
# For more information, read our documentation (
<IfModule php5_module>
   php_flag asp_tags Off
   php_flag display_errors On
   php_value max_execution_time 3000
   php_value max_input_time 6000
   php_value max_input_vars 1000
   php_value memory_limit 1024M
   php_value session.gc_maxlifetime 1440
   php_value session.save_path "/var/cpanel/php/sessions/ea-php56"
   php_value upload_max_filesize 1024M
# END cPanel-generated php ini directives, do not edit

<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access 1 year"
ExpiresByType image/jpeg "access 1 year"
ExpiresByType image/gif "access 1 year"
ExpiresByType image/png "access 1 year"
ExpiresByType text/css "access 1 month"
ExpiresByType text/html "access 1 month"
ExpiresByType application/pdf "access 1 month"
ExpiresByType text/x-javascript "access 1 month"
ExpiresByType application/x-shockwave-flash "access 1 month"
ExpiresByType image/x-icon "access 1 year"
ExpiresDefault "access 1 month"


Tuesday, 19 December 2017

Scraping Data from Website in php

Scraping Data from Website in php::

There is PHP Simple HTML DOM Parser. It's fast, easy and super flexible.
It basically sticks an entire HTML page in an object then you can access any element from that object.

Document Link :

Like:: get all links on the main Google page:

// Create DOM from URL or file
$html = file_get_html('');

// Find all images 
foreach($html->find('img') as $element) 
       echo $element->src . '<br>';

// Find all links 
foreach($html->find('a') as $element) 
       echo $element->href . '<br>';

we can use this library PHPPowertools/DOM-Query.
Document Link:

It uses customized version of Masterminds/html5-php under the hood parsing an HTML5 string into a DomDocument and symfony/DomCrawler for conversion of CSS selectors to XPath selectors.
It always uses the same DomDocument, even when passing one object to another, to ensure decent performance.

namespace PowerTools;

// Get file content
$pagecontent = file_get_contents( '' );

// Define your DOMCrawler based on file string
$H = new DOM_Query( $pagecontent );

// Define your DOMCrawler based on an existing DOM_Query instance
$H = new DOM_Query( $H->select('body') );

// Passing a string (CSS selector)
$s = $H->select( '' );

// Passing an element object (DOM Element)
$s = $H->select( $documentBody );

// Passing a DOM Query object
$s = $H->select( $H->select('p + p') );

// Select the body tag
$body = $H->select('body');

// Combine different classes as one selector to get all site blocks
$siteblocks = $body->select('.site-header, .masthead, .site-body, .site-footer');

// Nest your methods just like you would with jQuery
$siteblocks->select('button')->add('span')->addClass('icon icon-printer');

// Use a lambda function to set the text of all site blocks
$siteblocks->text(function( $i, $val) {
    return $i . " - " . $val->attr('class');

// Append the following HTML to all site blocks
$siteblocks->append('<div class="site-center"></div>');

// Use a descendant selector to select the site's footer
$sitefooter = $body->select('.site-footer > .site-center');

// Set some attributes for the site's footer
$sitefooter->attr(array('id' => 'aweeesome', 'data-val' => 'see'));

// Use a lambda function to set the attributes of all site blocks
$siteblocks->attr('data-val', function( $i, $val) {
    return $i . " - " . $val->attr('class') . " - photo by Kelly Clark";

// Select the parent of the site's footer
$sitefooterparent = $sitefooter->parent();

// Remove the class of all i-tags within the site's footer's parent

// Wrap the site's footer within two nex selectors
$sitefooter->wrap('<section><div class="footer-wrapper"></div></section>');

Two submit buttons in one form

Two submit buttons in one form::

Multiple Submit Buttons in a form-

We can use more than one submit button in a single form.
We can give each input a different value and keep the same name or different name:

#Same name Like::
<input type="submit" name="action" value="Update" />
<input type="submit" name="action" value="Delete" />

PHP Code:
if ($_POST['action'] == 'Update') {
    //action for update here
} else if ($_POST['action'] == 'Delete') {
    //action for delete
} else {
    //invalid action!

#Diffent Name like::

<input type="submit" name="update_button" value="Update" />
<input type="submit" name="delete_button" value="Delete" />

PHP Code:

if (isset($_POST['update_button'])) {
    //update action
} else if (isset($_POST['delete_button'])) {
    //delete action
} else {
    //no button pressed


update all row in codeigniter

update all row in codeigniter::


Generates an update string based on the data you supply, and runs the query. You can either pass an array or an object to the function. Here is an example using an array:

$data = array(
      'title' => 'My title' ,
      'name' => 'My Name 2' ,
      'date' => 'My date 2'
      'title' => 'Another title' ,
      'name' => 'Another Name 2' ,
      'date' => 'Another date 2'

$this->db->update_batch('mytable', $data, 'title');

// Produces:
// UPDATE `mytable` SET `name` = CASE
// WHEN `title` = 'My title' THEN 'My Name 2'
// WHEN `title` = 'Another title' THEN 'Another Name 2'
// ELSE `name` END,
// `date` = CASE
// WHEN `title` = 'My title' THEN 'My date 2'
// WHEN `title` = 'Another title' THEN 'Another date 2'
// ELSE `date` END
// WHERE `title` IN ('My title','Another title')

The first parameter will contain the table name, the second is an associative array of values, the third parameter is the where key.

Monday, 18 December 2017

Select / Deselect all checkboxes using jQuery

Select / Deselect all checkboxes using jQuery::

The HTML Structure is following type::

<td><input type="checkbox" id="checkbx_selectall" /> Select all</td>
<input type="checkbox" class="__chckbx_select" value="1"/>Item 1</td>
<input type="checkbox" class="__chckbx_select" value="2"/>Item 2</td>
<input type="checkbox" class="__chckbx_select" value="3"/>Item 3</td>
<td><input type="checkbox" class="__chckbx_select" value="4"/>Item 4</td>

<script src="">
<script type="text/javascript">
$("#checkbx_selectall").on('change', function() {

    if($('.__chckbx_select:checked').length ==           $('.__chckbx_select').length){


How to get the user browser information in Codeigniter

How to get the user browser information in Codeigniter::

//For Ip Address::
$ip_address = $this->input->ip_address();

//For User Agent / Browser::
if ($this->agent->is_browser())
    $agent = $this->agent->browser().' '.$this->agent->version();

}elseif ($this->agent->is_robot()){
   $agent = $this->agent->robot();

}elseif ($this->agent->is_mobile()){
$agent = $this->agent->mobile();

$agent = 'Unidentified User Agent';

//For Using platform::
$platform = $this->agent->platform();

//For Full Agent String::
$full_user_agent_string = $_SERVER['HTTP_USER_AGENT'];


$full_user_agent_string = $this->agent->agent_string();;

Saturday, 16 December 2017

Date formats in php

Date formats in php


The following characters are recognized in the 
format parameter string
Example returned values
Day of the month, 2 digits with leading zeros
01 to 31
A textual representation of a day, three letters
Mon through Sun
Day of the month without leading zeros
1 to 31
(lowercase 'L')
A full textual representation of the day of the week
Sunday through Saturday
ISO-8601 numeric representation of the day of the week (added in PHP 5.1.0)
1 (for Monday) through 7 (for Sunday)
English ordinal suffix for the day of the month, 2 characters
stndrd or th. Works well with j
Numeric representation of the day of the week
0 (for Sunday) through 6 (for Saturday)
The day of the year (starting from 0)
0 through 365
ISO-8601 week number of year, weeks starting on Monday
Example: 42 (the 42nd week in the year)
A full textual representation of a month, such as January or March
January through December
Numeric representation of a month, with leading zeros
01 through 12
A short textual representation of a month, three letters
Jan through Dec
Numeric representation of a month, without leading zeros
1 through 12
Number of days in the given month
28 through 31
Whether it's a leap year
1 if it is a leap year, 0otherwise.
ISO-8601 week-numbering year. This has the same value as Y, except that if the ISO week number (W) belongs to the previous or next year, that year is used instead. (added in PHP 5.1.0)
Examples: 1999or 2003
A full numeric representation of a year, 4 digits
Examples: 1999or 2003
A two digit representation of a year
Examples: 99 or 03
Lowercase Ante meridiem and Post meridiem
am or pm
Uppercase Ante meridiem and Post meridiem
AM or PM
Swatch Internet time
000 through 999
12-hour format of an hour without leading zeros
1 through 12
24-hour format of an hour without leading zeros
0 through 23
12-hour format of an hour with leading zeros
01 through 12
24-hour format of an hour with leading zeros
00 through 23
Minutes with leading zeros
00 to 59
Seconds, with leading zeros
00 through 59
Microseconds (added in PHP 5.2.2).
Note that date() will always generate000000 since it takes an integer parameter, whereas DateTime::format()does support microseconds if DateTime was created with microseconds.
Example: 654321
Milliseconds (added in PHP 7.0.0). Same note applies as for u.
Example: 654
Timezone identifier (added in PHP 5.1.0)
Examples: UTCGMTAtlantic/Azores
I (capital i)
Whether or not the date is in daylight saving time
1 if Daylight Saving Time, 0otherwise.
Difference to Greenwich time (GMT) in hours
Example: +0200
Difference to Greenwich time (GMT) with colon between hours and minutes (added in PHP 5.1.3)
Example: +02:00
Timezone abbreviation
Examples: ESTMDT ...
Timezone offset in seconds. The offset for timezones west of UTC is always negative, and for those east of UTC is always positive.
-43200 through 50400
Full Date/Time
ISO 8601 date (added in PHP 5)
» RFC 2822 formatted date
Example: Thu, 21 Dec 2000 16:01:07 +0200
Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)
See also time()

Popular Posts

Stack Of Codes, stackofcodes, Stack your codes here, Open your coding for all, Php coding, Codeigniter, blogger, Stack of codes Developers, Php Framework,, best coding site, Stack the codes, place the code in stack, Stack of codes is the largest, most trusted online community for developers to learn and share their programming knowledge and build their carrers.


PHP CodeIgniter SQL Facebook HTML Connect mysqli Constructor Destructor Stack Of Codes Update SQL codeignitre delete files from folder Aadhaar Agent Align center image Alternative Control Structure Back Slash Browser Browser version CSS Calculate Date Difference in php Cannot modify header information Check image exists CodeIgniter get_where CodeIgniter-HMVC-3.1.6 Codeigniter 3.1.7 Connect and select database Constants Constructor and Destructor Convert stdClass object to array in PHP Copy Image from URL Date Calculator]php Date Difference Disable Window Update Documents exists Enable Window Update File exists Gas Linking with Aadhaar Get TinyMCE to use full image url instead of relative one Get all files from folder How to delete a file in php Image Corrupted Image Exists in php Ip address Jquery Checkbox check all Make slug in Javascript or Jquery Multiple Submit Buttons in a form Mysqli connect Only variable references should be returned by reference Open and Close html ul tag and close the ul on evry third block Phar Php Version For Codeigniter 3.0 Platform Read All files in Directory Reduce the image file size using PHP Rename Table Robots.txt Generator Robots.txt Generator - SEO Tools - SEObook Scraping Data Scraping Data From Website Scrollbar Design Select Checkbox Server Requirements For Codeigniter 3.1.6 Simple Carousel demo Slug Sub string in Php Substring TinyMCE URL Conversion Example TinyMCE settings to get image path correct UAC Warning in windows pro Unique Check Unique Check in Codeigniter Virtual hosts WSDL cache Win 8.1 with UAC Warning XAMPP to send mail from localhost Xampp apache - XAMPP installation best frameworks best javascript frameworks check if contains http:// in php clean url clear cache codeigniter $this->db->like is case sensitive data containing apostrophes deselect Checkbox all duplicate field entry escape_str every third block ul tag will close facebook Share facebook server foreach etc front Slash get_where in codeigniter hash_hmac headers already sent how to make robot.txt file for my website? htaccess http:// or https:// iS mobile if-else iv size for all mobile / tablet display javascript json_decode in array php looking for a job make url with hyphen media queries. mysql_real_escape_string mysqli real escapr string server down slug in Javascript some function of xamp is possible disabled sql - How to split a single column values to multiple column values tinymce image path showing as ../../ unlink File url contains http:// or https:// while window update