Saturday, 29 September 2018

I’ve searched a lot on Google how to do certain git actions, and this actually motivated me to write this post. This may not be so useful for a person who is a PRO in git, but I tried to list out all the git commands which will definitely benefit a newbie.





Here are the list of git commands which is going to get covered in this Post:


Clone
Stash Changes
List stashes
Apply stash
List branches
Create Branch
Commit
Push
Pull
Checkout Branch
Config
Ignore Filemode changes


Git Clone:
git clone [url]


Git clone with custom directory name:
git clone [url] [directory name]


Git Clone with password:
git clone https://username:password@xyz.com/abc/repository.git


Stash Changes:
git stash save
git stash save [stash name] 
This command stash changes with name

List all stashes:
git stash list


Apply a stash:
git stash pop
git stash apply


List branches:
git branch
Note:  The one which is highlighted is the current branch


Create Branch:
git branch [branch name]


Commit:
git commit -m “[ commit message]”


Push changes:
git push origin [branch name]


Pull changes:
git pull origin [branch name]


Checkout branch:
git fetch && git checkout [branch name]


Config:
git config –global user.name [name]
git config –global user.email [email address]


This command sets the author name and email address to be used with your commits.


Ignore File mode changes:
git config core.fileMode false

If you need or know some more essential git commands, mention it in comments. I am always open to learning. 

Useful Git Commands for developer

Friday, 6 October 2017

Having a complete list of your site is incredibly important in the current search landscape. You need not use a tool to get all the links of your site. Use the following PHP code to get all the links

<?php
$html = file_get_contents('http://www.kayalspot.blogspot.in');
$dom = new DOMDocument();
@$dom->loadHTML($html);
// grab all the links on the page
$xpath = new DOMXPath($dom);
$hrefs = $xpath->evaluate("/html/body//a");
for ($i = 0; $i < $hrefs->length; $i++) {
 $href = $hrefs->item($i);
 $url = $href->getAttribute('href');
 echo $url.'<br />';
}

How to get all links from a site

It is common to upload the images dynamically to the websites. But when we upload the large file size image on the website, it consumes a lot of time while loading. So the developer should write the code to reduce the image file size while uploading the image dynamically to the website. Using PHP, you can easily reduce the file size of those uploaded images during  time of upload. Of course, when reducing the file size we sacrifice the image quality.

seo-image-optimization

Code to reduce file size for the image:
<?php 
 function compress($source, $destination, $quality) {

  $info = getimagesize($source);

  if ($info['mime'] == 'image/jpeg') 
   $image = imagecreatefromjpeg($source);

  elseif ($info['mime'] == 'image/gif') 
   $image = imagecreatefromgif($source);

  elseif ($info['mime'] == 'image/png') 
   $image = imagecreatefrompng($source);

  imagejpeg($image, $destination, $quality);

  return $destination;
 }

 $source_img = 'source.jpg';
 $destination_img = 'destination .jpg';

 $d = compress($source_img, $destination_img, 90);
 ?>
$d = compress($source_img, $destination_img, 90);
This is just a php function that passes the source image ( i.e., $source_img ), destination image ( $destination_img ) and quality for the image that will take to compress ( i.e., 90 ).
$info = getimagesize($source);
The getimagesize() function is used to find the size of any given image file and return the dimensions along with the file type.
Example:
$info = getimagesize($source);
print_r($info);
Output:
Array ( [0] => 1280 [1] => 768 [2] => 2 [3] => width="1280" height="768" [bits] => 8 [channels] => 3 [mime] => image/jpeg )
$image = imagecreatefromjpeg($source);
$image = imagecreatefromgif($source);
$image = imagecreatefrompng($source);
All the above functions are used to create a new image from the given file or URL. These functions are used to return an image identifier representing the image obtained from the given file name.
imagejpeg($image, $destination, $quality);
imagejpeg() function is used to create a JPEG file from the given image.
Syntax: imagejpeg ( $source_image, $destination_image, $quality )
Quality ($quality): quality is optional, and ranges from 0 (worst quality, smaller file) to 100 (best quality, biggest file). The default range is 75.
Note:
The GD library is used for dynamic image creation. From PHP we use with the GD library to create GIF, PNG or JPG. This is very important to run all the image creation function in PHP. If your server doesn’t support the GD library then all the above functionality related to the image creation will not work.
Complete code to reduce the image file size:
<?php
 $name = ''; $type = ''; $size = ''; $error = '';
 function compress_image($source_url, $destination_url, $quality) {

  $info = getimagesize($source_url);

      if ($info['mime'] == 'image/jpeg')
           $image = imagecreatefromjpeg($source_url);

      elseif ($info['mime'] == 'image/gif')
           $image = imagecreatefromgif($source_url);

     elseif ($info['mime'] == 'image/png')
           $image = imagecreatefrompng($source_url);

      imagejpeg($image, $destination_url, $quality);
  return $destination_url;
 }

 if ($_POST) {

      if ($_FILES["file"]["error"] > 0) {
           $error = $_FILES["file"]["error"];
      } 
      else if (($_FILES["file"]["type"] == "image/gif") || 
   ($_FILES["file"]["type"] == "image/jpeg") || 
   ($_FILES["file"]["type"] == "image/png") || 
   ($_FILES["file"]["type"] == "image/pjpeg")) {

           $url = 'destination .jpg';

           $filename = compress_image($_FILES["file"]["tmp_name"], $url, 80);
           $buffer = file_get_contents($url);

           /* Force download dialog... */
           header("Content-Type: application/force-download");
           header("Content-Type: application/octet-stream");
           header("Content-Type: application/download");

   /* Don't allow caching... */
           header("Cache-Control: must-revalidate, post-check=0, pre-check=0");

           /* Set data type, size and filename */
           header("Content-Type: application/octet-stream");
           header("Content-Transfer-Encoding: binary");
           header("Content-Length: " . strlen($buffer));
           header("Content-Disposition: attachment; filename=$url");

           /* Send our file... */
           echo $buffer;
      }else {
           $error = "Uploaded image should be jpg or gif or png";
      }
 }
?>
<html>
     <head>
          <title>Php code compress the image</title>
     </head>
     <body>

  <div class="message">
                     <?php
                      if($_POST){
                          if ($error) {
                              ?>
                              <label class="error"><?php echo $error; ?></label>
                        <?php
                              }
                         }
                     ?>
                 </div>
  <fieldset class="well">
                  <legend>Upload Image:</legend>                
   <form action="" name="myform" id="myform" method="post" enctype="multipart/form-data">
    <ul>
                <li>
      <label>Upload:</label>
                                   <input type="file" name="file" id="file"/>
     </li>
     <li>
      <input type="submit" name="submit" id="submit" class="submit btn-success"/>
     </li>
    </ul>
   </form>
  </fieldset>
 </body>
</html>
I hope the above-mentioned PHP code could be beneficial in reducing the image file size while uploading it to save your precious time. I believe the topic discussed here is quite useful to everyone who reads it!
Source: https://www.apptha.com/blog/how-to-reduce-image-file-size-while-uploading-using-php-code/

How to optimize images for SEO - PHP


Contents


  1. Code Structure
    1. Spaces
    2. Ternary Operator
    3. String Literals
    4. Assignment Expressions
    5. C borrowings
    6. Alternative syntax for control structures
  2. Naming
    1. Functions
    2. Variables
  3. Pitfalls
    1. empty()
    2. isset()
    3. Boolean conversion
    4. Equality operators
  4. Comments and Documentation
  5. Visibility
    1. Global Objects
    2. Static methods and properties
    3. Classes
  6. Error handling

coding standards php

Code structure

Spaces

Put spaces on either side of binary operators,
eg) $a = $b + $c;
Put spaces next to parentheses on the inside, except where the parentheses are empty. Do not put a space following a function name.
Examples:
$a = getFoo( $b );
$c = getBar();
Put spaces in brackets when declaring an array, except where the array is empty. Do not put spaces in brackets when accessing array elements.
Examples:
$a = [ 'foo', 'bar' ];
$c = $a[0];
$x = [];
Control structures such as if, while, for, foreach, and switch, as well as the catch keyword, should be followed by a space:
Example:
if ( isFoo() ) {
$a = 'foo';
}
When type casting, do not use a space within or after the cast operator:
Example: (int)$foo;


In comments there should be one space between the # or // character and the comment.
// Proper inline comment
/***** Do not comment like this ***/

Ternary operator

The ternary operator can be used profitably if the expressions are very short and obvious:


$value = isset( $this->variable[key] ) ? $this->variable[key] : false;
But if you're considering a multi-line expression with a ternary operator, please consider using an if () block instead. Remember, disk space is cheap, code readability is everything, "if" is English and ?: is not.

String literals

For simple string literals, single quotes are slightly faster for PHP to parse than double quotes. Also for people using US/UK qwerty keyboards, they are easier to type, since it avoids the need to press shift. For these reasons, single quotes are preferred in cases where they are equivalent to double quotes.


However, do not be afraid of using PHP's double-quoted string interpolation feature: $elementId = "myextension-$index"; This has slightly better performance characteristics than the equivalent using the concatenation (dot) operator, and it looks nicer too.

Assignment expressions

Using assignment as an expression is surprising to the reader and looks like an error. Do not write code like this:


if ( $a = foo() ) {
   bar();
}
Space is cheap, and you're a fast typist, so instead use:


$a = foo();
if ( $a ) {
   bar();
}
Using assignment in a while() clause used to be legitimate, for iteration:


$res = $dbr->query( 'SELECT * FROM some_table' );
while ( $row = $dbr->fetchObject( $res ) ) {
   showRow( $row );
}
This is unnecessary in new code; instead use:


$res = $dbr->query( 'SELECT * FROM some_table' );
foreach ( $res as $row ) {
   showRow( $row );
}

C borrowings

The PHP language was designed by people who love C and wanted to bring souvenirs from that language into PHP. But PHP has some important differences from C.


In C, constants are implemented as preprocessor macros and are fast. In PHP, they are implemented by doing a runtime hashtable lookup for the constant name, and are slower than just using a string literal. In most places where you would use an enum or enum-like set of macros in C, you can use string literals in PHP.


PHP has three special literals for which upper-/lower-/mixed-case is insignificant in the language (since PHP 5.1.3), but for which our convention is always lowercase : true, false and null.


Use elseif not else if. They have subtly different meanings:


// This:
if ( $foo == 'bar' ) {
echo 'Hello world';
} else if ( $foo == 'Bar' ) {
echo 'Hello world';
} else if ( $baz == $foo ) {
echo 'Hello baz';
} else {
echo 'Eh?';
}


// Is actually equivalent to:
if ( $foo == 'bar' ) {
echo 'Hello world';
} else {
if ( $foo == 'Bar' ) {
echo 'Hello world';
} else {
if ( $baz == $foo ) {
echo 'Hello baz';
} else {
  echo 'Eh?';
}
}
}
And the latter has poorer performance.

Alternative syntax for control structures

PHP offers an alternative syntax for control structures using colons and keywords such as "endif", "endwhile", etc.:


if ( $foo == $bar ):
   echo "<div>Hello world</div>";
endif;
This syntax should be avoided, as it prevents many text editors from automatically matching and folding braces. Standard syntax should be used instead:


if ( $foo == $bar ) {
   echo "<div>Hello world</div>";
}

Naming

Use lowerCamelCase when naming functions or variables. For example:


private function doSomething( $userPrefs, $editSummary )
Use UpperCamelCase when naming classes: class ImportantClass. Use uppercase with underscores for global and class constants: DB_MASTER, Revision::REV_DELETED_TEXT. Other variables are usually lowercase or lowerCamelCase; avoid using underscores in variable names.


There are also some prefixes used in different places:

Functions

sf (sample functions) – top-level functions, e.g.
function sfFuncname() { ... }
ef (extension functions) = global functions in extensions, although "in most cases modern style puts hook functions as static methods on a class, leaving few or no raw top-level functions to be so named." (-- brion in Manual_talk:Coding_conventions#ef_prefix_9510)
Verb phrases are preferred: use getReturnText() instead of returnText().

Variables

$gv – global variables, e.g. $gvVersion, $gvTitle. Always use this for new globals, so that it's easy to spot missing "global $gvFoo" declarations. In extensions, the extension name should be used as a namespace delimiter. For example, $gvAbuseFilterConditionLimit, not $gvConditionLimit.
Global declarations should be at the beginning of a function so dependencies can be determined without having to read the whole function.
It is common to work with an instance of the Database class; we have a naming convention for these which helps keep track of the nature of the server to which we are connected. In development environments there is usually no difference between the two types, which can conceal subtle errors.

Pitfalls

empty()

The empty() function should only be used when you want to suppress errors. Otherwise just use ! (boolean conversion).


empty( $var ) essentially does !isset( $var ) || !$var.
Common use case: Optional boolean configuration options that default to false. $this->enableFoo = !empty( $options['foo'] );
Beware of boolean conversion pitfalls.
It suppresses errors about undefined properties and variables. If only intending to test for undefined, use !isset(). If only intending to test for "empty" values (e.g. false, zero, empty array, etc.), use !.

isset()

Do not use isset() to test for null. Using isset() in this situation could introduce errors by hiding misspelled variable names. Instead, use $var === null.

Boolean conversion

if ( !$var ) {
...
}
Study the rules for conversion to boolean. Be careful when converting strings to boolean.
Do not use it to test if a string is empty, because PHP considers '0' and similar expressions to be falsy. Use === '' instead.

Equality operators

Be careful with double-equals comparison operators. Triple-equals (===) is generally more intuitive and should be preferred unless you have a reason to use double-equals (==).


'foo' == 0 is true (!)
'000' == '0' is true (!)
'000' === '0' is false
To check if two scalars that are supposed to be numeric are equal, use ==, e.g. 5 == "5" is true.
To check if two variables are both of type 'string' and are the same sequence of characters, use ===, e.g. "1.e6" === "1.0e6" is false.
To check if two scalars that should be treated as strings are equal as strings, use strcmp(), e.g. strcmp(13,"13") is 0.

Comments and documentation

It is essential that your code be well documented so that other developers and bug fixers can easily navigate the logic of your code. New classes, methods, and member variables should include comments providing brief descriptions of their functionality (unless it is obvious), even if private. In addition, all new methods should document their parameters and return values.

Visibility

Make methods public/protected/private (think what makes sense). Don't just make everything public!

Global objects

Main page: Manual:RequestContext.php
Do not access the PHP superglobals $_GET, $_POST, etc, directly; use $request->get*( 'param' ) instead; there are various functions depending on what type of value you want. You can get a WebRequest from the nearest RequestContext, or if absolutely necessary $wgRequest. Equally, do not access $_SERVER directly; use $request->getIP() if you want to get the IP address of the current user.

Static methods and properties

Static methods and properties are useful for programmers because they act like globals without polluting the global namespace. However, they make subclassing and reuse more difficult for other developers. Generally, you should avoid introducing static functions and properties when you can, especially if the sole purpose is to just save typing.


For example, lots of developers would prefer to write something like:


Foo::bar();
This is because it is shorter and takes less keystrokes. However, by doing this you've made the Foo class much harder to subclass and reuse. Instead of introducing a static method, you could just type:


$f = new Foo();
$f->bar();
Remember, shorter does not always mean better, and you should take the time to design your classes in a way that makes them easy to reuse.

Classes

Encapsulate your code in an object-oriented class, or add functionality to existing classes; do not add new global functions or variables. Try to be mindful of the distinction between 'backend' classes, which represent entities in the database (eg User, Block, Revision, etc), and 'frontend' classes, which represent pages or interfaces visible to the user (SpecialPage, Article, ChangesList, etc. Even if your code is not obviously object-oriented, you can put it in a static class (eg IP or Html).


As a holdover from PHP 4's lack of private class members and methods, older code will be marked with comments such as /** @private */ to indicate the intention; respect this as if it were enforced by the interpreter.


Mark new code with proper visibility modifiers, including public if appropriate, but do not add visibility to existing code without first checking, testing and refactoring as required. It's generally a good idea to avoid visibility changes unless you're making changes to the function which would break old uses of it anyway.

Error handling

Don't suppress errors with PHP's @ operator, for any reason ever. It's broken when E_STRICT is enabled and it causes an unlogged, unexplained error if there is a fatal, which is hard to support.


The proper method of handling errors is to actually handle the errors. For example, if you are thinking of using an error suppression operator to suppress an invalid array index warning, you should instead perform an isset() check on the array index before trying to access it. When possible, always prevent PHP errors rather than catching and handling them afterward. It makes the code more understandable and avoids dealing with slow error suppression methods.

PHP Coding Standards

 
KayalSpot © 2015 - Designed by Templateism.com