Friday, 20 May 2016

Laravel: How to update composer in laravel through command

How to update composer in laravel through command

sudo /usr/local/bin/composer self-update

Monday, 16 May 2016

Laravel 5 - Remove public from URL

For Laravel 5:

Follow steps below to remove "public" word from URL,

1) Rename the server.php in the your Laravel root folder to index.php

2) Copy .htaccess file from /public directory to your Laravel root folder.

3) Changing .htaccess file as follows for statics:


RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R=301]

RewriteCond %{REQUEST_URI} !(\.css|\.js|\.png|\.jpg|\.gif|robots\.txt)$ [NC]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !^/public/
RewriteRule ^(css|js|images)/(.*)$ public/$1/$2 [L,NC]
 


If there are any other static files needed just add the extension to the previous declared list

And now its done!!!

 

Tuesday, 29 March 2016

Laravel - Introduction and features

Laravel:

Laravel is a free, open-source PHP web framework created by Taylor Otwell.

Latest version of Laravel as of now is Laravel 5.1, released in June 2015.

Laravel is intended for the development with model–view–controller (MVC) architectural pattern.

In laravel, some of the features are a modular packaging system with a dedicated dependency manager, different ways for accessing relational databases, utilities that aid in application deployment and maintenance.

As of March 2015, Laravel is regarded as one of the most popular PHP frameworks, together with Symfony2, Nette, CodeIgniter, Yii2 and other frameworks.

The source code of Laravel is hosted on GitHub and licensed under the terms of MIT License.



Features of Laravel,

Bundles: provide a modular packaging system

Eloquent ORM (object-relational mapping): advanced PHP implementation of the active record pattern, providing at the same time internal methods for enforcing constraints on the relationships between database objects.

Query builder: provides a more direct database access alternative to the Eloquent ORM.

Application logic: integral part of developed applications, implemented either by using controllers or as part of the route declarations.

Reverse routing: defines a relationship between the links and routes, making it possible for later changes to routes to be automatically propagated into relevant links.

Class auto loading: provides automated loading of PHP classes without the need for manual maintenance of inclusion paths.

Blade templating engine: combines one or more templates with a data model to produce resulting views, doing that by transpiling the templates into cached PHP code for improved performance.

Unit testing is provided as an integral part of Laravel

Automatic pagination simplifies the task of implementing pagination

Monday, 21 March 2016

LOAD DATA INFILE statement in MySQL

Your script stops while fetch data from txt/csv file? Here is a MySQL feature to make this task faster. "LOAD DATA INFILE" statement::

The LOAD DATA INFILE statement reads rows from a text/CSV file into a table at a very high speed.

To write data from a table to a file, use SELECT ... INTO OUTFILE. To read the file back into a table, use LOAD DATA INFILE. The syntax of the FIELDS and LINES clauses is the same for both statements. Both clauses are optional, but FIELDS must precede LINES if both are specified.

SYNTAX to fetch data from CSV file:

$FILE_PATH = "test.csv";
$TABLE_NAME = "tablename";
$TABLE_FIELDS = "name,address";

'LOAD DATA LOCAL INFILE "$file_path"
            INTO TABLE "$table_name"
        FIELDS TERMINATED BY ","
        OPTIONALLY ENCLOSED BY "\"
        LINES TERMINATED BY "\n"
($TABLE_FIELDS)';

In the above example, your CSV file must contains 2 fields name and address and line terminated by "\n".

For more reference
http://dev.mysql.com/doc/refman/5.7/en/load-data.html

Friday, 18 March 2016

PHP strings: Difference between single and double quoted strings.

PHP strings can be specified in four ways.

1) Single quoted strings:

 
- This type of strings will display things completely "as is."
- Variables and escape sequences will not be interpreted. The exception is that to display a literal single quote, you can escape it with a back slash \', and to display a back slash, you can escape it with another backslash \\
- So yes, even single quoted strings are parsed.

2) Double quote strings:
- This type of strings will display a host of escaped characters (including some regexes), and variables in the strings will be evaluated.
- An important point here is that you can use curly braces to isolate the name of the variable.
- For example let's say we have the variable $abc and we want to echo "The $abc are", That will look for the variable $abc.
  To get around this use echo "The {$abc} is" You can put the brace before or after the dollar sign.

Let us discuss an example for this,

$abc="test";
echo "test$abc"; // output = testtest

echo "test$abcaa"; // output = test


As $ is in Double quote, system will try to find remaining string as a variable. Like in first example $abc = "test"; and we request for "test@abc" so it will result as testtest. In second example system will try to find $abcaa variable and its not declared so it will consider as an empty string and result as test only.

So if we need to write test$abc as a string we need to use,


$abc="test";
echo 'test$abc'; // output = test$abc
echo 'test$abcaa'; // output = test$abcaa


Note: Single quotes being faster than double quotes in many situations.

3) Heredoc:
- String syntax works like double quoted strings.
- It starts with <<<. After this operator, an identifier is provided, then a newline.
- The string itself follows, and then the same identifier again to close the quotation. You don't need to escape quotes in this syntax.

<?php
var_dump(array(<<<EOD
foobar!
EOD
)); exit;
?>


4) Nowdoc:

- PHP 5.3.0+
- String syntax works essentially like single quoted strings.
- The difference is that not even single quotes or backslashes have to be escaped. A nowdoc is identified with the same <<< sequence used for heredocs, but the identifier which follows is enclosed in single quotes, e.g. <<<'EOT'. No parsing is done in nowdoc.


<?php
class foo {
    public $bar = <<<'EOT'
bar
EOT;
}
?>

Visit http://php.net/manual/en/language.types.string.php for more information..

Wednesday, 16 March 2016

Difference between OR and || in PHP

Difference between OR and || in PHP

Based on behavior OR and || are same,

$a = 1;
$b = 1;

if($a==$b || $a=='5') {
   echo "here";
}  // OUTPUT: here


if($a==$b || $a=='5') {
   echo "here";
}  // OUTPUT: here



//////////////////////////////////////////////////

BUT, "OR" operator have lower precedence than ||

Because 'OR' have lower priority than '=' but '||' have higher priority. Same thing apply to "and" and && operator.

Let's check difference,

<?php
$bool = true && false;
var_dump($bool); // false, that's expected

$bool = true and false;
var_dump($bool); // true, ouch!
?>

Please refer below link for more detail,
http://php.net/manual/en/language.operators.precedence.php

So use only ("||" , "&&") operator instead of ("or","and") operator.

Enjoy your coding!!!

Difference between == (equality or Double Equals) and === (identity or Triple Equals) in PHP

Difference between == (equality or Double Equals) and === (identity or Triple Equals) in PHP

== compares the values of variables for equality, type casting as necessary. 


=== checks and returns true only if the two variables are of the same type AND have the same value.


Examples:
a === a // returns true
a == a  // returns true

1 === "1" // returns false because 1 is an integer, "1" is a string
1 == "1"  // returns true because "1" gets casted to an integer, which is 1


"abc" == "abc" // returns true
"abc" === "abc" // returns true because both operands are strings and have the same value


For the security reasons, it is better to use identity operator whenever possible because it compares variable type also.

Enjoy your coding!!!

Monday, 14 March 2016

Register Globals (register_globals) in PHP

Register Globals (register_globals)

Secure you application by disabling register_globals variable,

register_globals
was meant to help rapid application development. 


Any URL which includes a query string,the register_globals statement allows us to access the value of variable with $variable instead of $_GET['variable'] automatically.

This might be useful for us, but all variables in the code now have this property, and we can now easily get into PHP applications that do not protect against this unintended consequence.

If you have added below code into your login page,

if(!empty($_POST['user_name']) && $_POST['user_name'] == 'abc' && !empty( $_POST['password'] ) && $_POST['password'] == "abc123")
{
    $valid = true;
}
if($valid==true) { $show_user_pages = 1; }

If the application is running with register_globals ON, a user could just place valid=1 into a query string, and would then have access to whatever the script is running.


So it is better to running application with register_globals OFF.

We cannot disable register_globals from the script side, but we can use an .htaccess files or change php.ini file to do this.

Disabling with php.iniregister_globals = Off


Disabling with .htaccess
php_flag register_globals 0


Enjoy with secure php script with register_globals Off !!

Friday, 11 March 2016

Spaceship operator (<=>) in PHP7

Spaceship operator (<=>) + PHP7

PHP7 introduce the Spaceship (<=>) operator.

This <=> operator will offer combined comparison
Return 0 if values on either side are equal
Return 1 if value on the left is greater
Return -1 if the value on the right is greater



<=> operator will be similar to in older PHP versions of below syntax,
($a < $b) ? -1 : (($a > $b) ? 1 : 0);

Now in PHP 7, it will be like,
$a <=> $b;


The rules used by the combined comparison operator are same as the currently used comparison operators by PHP with <, <=, ==, >= and >.

PERL or RUBY programming background programmers are already familiar with this new operator proposed for PHP7.

It returns,
0 if $a == $b
-1 if $a < $b
1 if $a > $b

Comparing Integers,

echo 2 <=> 2; //ouputs 0
echo 2 <=> 3; //outputs -1
echo 3 <=> 2; //outputs 1


String Comparison
echo "a" <=> "a"; // 0
echo "a" <=> "b"; //-1
echo "b" <=> "a"; //1

It can be used for sorting.



Thursday, 10 March 2016

HTML5 - Difference between HTML and HTML5.



HTML5 is a markup language used for structuring and presenting content on website. HTML 5 is an updated version of HTML. It's much similar to HTML. But difference is HTML 5 contains much better support for media such as audio, video etc.

1. Simple Syntax


The simple doctype declaration is one of the many novelties in HTML5. Now you need to write only: <!doctype html>. The syntax of HTML5 is compatible with HTML4 and XHTML1, but not with SGML.


2. HTML5 is in Progress

HTML5 hasn’t been standardized like HTML4. You don’t have to worry about updating pages built using HTML4.
Elements and attributes are added and modified several times. Of course, this is dependent how much we depend on rich elements.

Build with HTML4, play with HTML5.


3. New Elements


<header> and <footer> are specifically marked for such. Because of this, it is unnecessary to identify these two elements with a <div> tag.
<section> and <article> allows you to mark specific areas of your layout as such, and should have a positive effect on on your SEO in the end.
<menu> can be used for your main menu, but it can also be used for toolbars and context menus.
<figure> element is another way to arrange text and images.
<audio> and <video> elements to use/run audio and video files on the html page
<canvas>
New <form> and <forminput> elements are added


4. No more use of some of the Elements

<b> and <font> are added in CSS itself
No more <frame>, <center>, <big> elements


Conclusion

HTML5 actually strives to be something very different.  It aims to be more of an application development platform,  which includes not only depends on text and images, but also playing video and audio, storing data in the application, and real-time networking protocols for exchanging data as it happens etc..

Enjoy your website with updated markup language HTML5!!!!

Wednesday, 9 March 2016

Redirect https to http through htaccess

Add below code in you htaccess file for redirect https to http

RewriteCond %{HTTPS} =on
RewriteRule ^(.*)$ http://www.yourdomain.com/$1 [R=301,L]

Tuesday, 8 March 2016

Set iframe height dynamically through Javascript / jQuery

Add an event listener in the parent document (the page where you called iframe)

<script type='text/javascript'>
window.addEventListener('message', function(e) {
    var data = e.data[1];
    var eventName = e.data[0];
    if(eventName=='setHeight') { document.getElementById('iframeID').height = data; }
}, false);
</script>


Write below function into your iframe,

This function will fetch document height and called parent page function to set height dynamic.
<script type='text/javascript'>
function setSize() {
  var height = document.body.scrollHeight;
  window.parent.postMessage(["setHeight", height], "*");
}


Call this function inside iframe through onload event
$( window ).load(function() {
  setSize();
});
    OR
<body onLoad="setSize();">
</script>

Friday, 31 July 2015

How to install node js? How to run a Node js on windows?


What is Node js?
A lot of the confusion for newcomers to Node is misunderstanding exactly what it is. The description on nodejs.org definitely doesn't help more.

An important thing to realize is that Nodejs is not a webserver. By itself it doesn't do anything. And It doesn't work like Apache. There is no config file where you point it to you HTML files. If you want it to be a HTTP server, you have to write an HTTP server (with the help of its built-in libraries). Node.js is just another way to execute code on your computer. It is very simply a JavaScript runtime.

Installing Node
Node.js is very easy to install. If you're using Windows or Mac, installers are available on the download page.
https://nodejs.org/#download

I've Installed Node, now what?

It's so easy. Here are the exact steps I just took to run the "Hello World" example found at http://nodejs.org/. This is a quick and non understable example. For a permanent installation you'd want to store the executable in a more reasonable place than the root directory and update your PATH to include its location.

Download the Windows executable here: http://nodejs.org/#download
Copy the file to C:\
Create C:\hello.js
Paste in the following content:
   var http = require('http');

var server = http.createServer(function(req, res) {
  res.writeHead(200);
  res.end('Hello This is my first node script. Thanks - Arpan Thakrar');
});
server.listen(8080);

console.log('Hey This is my first nodejs script. Thanks - Arpan Thakrar');


Save the file. And Go to the
Start -> Run... -> cmd
c:
C:>node hello.js

Output -:
Hey This is my first nodejs script. Thanks - Arpan Thakrar

Note-:
This is a basic of nodejs. This is not a full-featured HTTP server. It can't serve any HTML file or images. In fact, no matter what you request, it will return 'Hey This is my first nodejs script. Thanks - Arpan Thakrar'. However, you can run this and hit http://localhost:8080 in your browser and you'll see the text.

Hey This is my first nodejs script. Thanks - Arpan Thakrar

You might notice something a little different now. Your Node.js application no longer exits. This is because you created a server and your Node.js application will continue to run and respond to requests until you kill it yourself.

If you want this to be a full-featured web server, then you have to do that work. We will learn that in next post :)NJOY!!

That's it. This was done on Windows.

Wednesday, 17 June 2015

How to increase import size in phpmyadmin in WAMP:-


how to increase maximum execution time in php, 
How to increase maximum execution time in php, 
How to change maximum execution time in phpmyadmin, 
phpmyadmin max execution time, phpmyadmin import file size, 
phpmyadmin import file size increase, 
Increase the import file size in phpmyadmin wamp, 
Phpmyadmin increase import file size

Solution 1):-
Please follow below settings in C:\wamp\bin\apache\apache2.2.8\bin\php.ini

Find:
post_max_size = 8M
max_execution_time = 30
upload_max_filesize = 2M
memory_limit = 8M
max_input_time = 60

Change to:
post_max_size = 750M
max_execution_time = 5000
upload_max_filesize = 750M
memory_limit = 1000M
max_input_time = 5000

Then restart your wamp to take effect

Solution 2):-
Add this to an htaccess file:
<IfModule mod_php5.c>
php_value post_max_size 200M
php_value max_execution_time 259200
php_value upload_max_filesize 200M
php_value memory_limit 300M
php_value max_input_time 259200
</IfModule>

Solution 3:-
If you don't have access of your php.ini or dont use htaccess file, you can use ini_set in your php file:
For example - ini_set('max_execution_time', 5000);

You can also refer http://forum.wampserver.com/read.php?2,45000 for more informaion

Saturday, 13 June 2015

Non secure to Secure AJAX call in PHP with Maintaining Session Variables

Want to Non secure to Secure AJAX call in PHP and maintain session?


What is .htaccess file?
".htaccess is a configuration file for use on web servers running the Apache Web Server software.

When a .htaccess file is placed in a directory which is in turn 'loaded via the Apache Web Server', then the .htaccess file is detected and executed by the Apache Web Server software.

These .htaccess files can be used to alter the configuration of the Apache Web Server software to enable/disable additional functionality and features that the Apache Web Server software has to offer."

------------------------------------------------

Write below code in .htaccess file.


SetEnvIf Origin "http(s)?://(www\.)?(yourdomainname.com)$" AccessControlAllowOrigin=$0
Header set Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin

Header set Access-Control-Allow-Credentials true

-------------------------------------------------------------

In your jQuery AJAX call add below code,

xhrFields : { withCredentials : true }

Example,

$.ajax({ 
 type: 'POST',
url: http://www.yourdominname.com?test.php
data:  $('#formname').serialize(),
xhrFields : { withCredentials : true },
success: function(msg) 
}
});

Thursday, 31 October 2013

Opencart view file path

Add this line into system/engine/controller.php just after the $this->output = ob_get_contents(); on (or about) line 65.

CODE: SELECT ALL
           if( strpos( $_SERVER[ 'SCRIPT_FILENAME' ], '/admin/' ) === false )
              $this->output = '<div style="margin:2px;border: 1px red solid;display:inline-block;"><div style="float:left;color:white;background-color:red;">' . $this->template . '</div><div>' . $this->output . '</div></div>';

opencart Template Path Guide

Thursday, 27 June 2013

Send email from localhost/WAMP Server using sendmail


The new WAMP Server’s PHP and stand-alone PHP v5.3+, are now NOT available with some of the extensions required to implement the previous solution [PHPMailer] (there is a workaround to install the missing extension(s), described in the linked article). So an alternate and much less efficient (slower, but negligible low-speed for development platform (WAMP/localhost)) solution can be implemented, as below:

Solution:
This solution requires sendmail.exe (a Command Line Interface (CLI) executable which accepts email from PHP, connects to an SMTP server and sends email). You will not require to use it by command, don’t bother about it :-) Download the sendmail.zip and follow these steps:
  • Create a folder named “sendmail” in “C:\wamp\”.
  • Extract these 4 files in “sendmail” folder: “sendmail.exe”, “libeay32.dll”, “ssleay32.dll” and “sendmail.ini”.
  • Open the “sendmail.ini” file and configure it as following
    • smtp_server=smtp.gmail.com
    • smtp_port=465
    • smtp_ssl=ssl
    • default_domain=localhost
    • error_logfile=error.log
    • debug_logfile=debug.log
    • auth_username=[your_gmail_account_username]@gmail.com
    • auth_password=[your_gmail_account_password]
    • pop3_server=
    • pop3_username=
    • pop3_password=
    • force_sender=
    • force_recipient=
    • hostname=localhost
    You do not need to specify any value for these properties: pop3_server, pop3_username, pop3_password, force_sender, force_recipient. The error_logfile and debug_logfile settings should be kept blank if you have already sent successful email(s) otherwise size of this file will keep increasing. Enable these log file settings if you don’t get able to send email using sendmail.
  • Enable IMAP Access in your GMail’s Settings -> Forwarding and POP/IMAP -> IMAP Access:
  • Enable “ssl_module” module in Apache server:
  • Enable “php_openssl” and “php_sockets” extensions for PHP compiler:
  • Open php.ini from “C:\wamp\bin\apache\Apache2.2.17\bin” and configure it as following (The php.ini at “C:\wamp\bin\php\php5.3.x” would not work) (You just need to configure the last line in the following code, prefix semicolon (;) against other lines):
    [mail function]
    ; For Win32 only.
    ; http://php.net/smtp
    ;SMTP =
    ; http://php.net/smtp-port
    ;smtp_port = 25
    
    ; For Win32 only.
    ; http://php.net/sendmail-from
    ;sendmail_from = you@domain.com
    ; For Unix only.  You may supply arguments as well (default: "sendmail -t -i").
    ; http://php.net/sendmail-path
    sendmail_path = "C:\wamp\sendmail\sendmail.exe -t -i"
  • Restart WAMP Server.
  • Create a PHP file and write the following code in it:
    <?php
    $to       = 'recipient@yahoo.com';
    $subject  = 'Testing sendmail.exe';
    $message  = 'Hi, you just received an email using sendmail!';
    $headers  = 'From: sender@gmail.com' . "\r\n" .
                'Reply-To: sender@gmail.com' . "\r\n" .
                'MIME-Version: 1.0' . "\r\n" .
                'Content-type: text/html; charset=iso-8859-1' . "\r\n" .
                'X-Mailer: PHP/' . phpversion();
    if(mail($to, $subject, $message, $headers))
        echo "Email sent";
    else
        echo "Email sending failed";
    ?>
  • Make appropriate changes in $to and $headers variables to set recipient, sender and reply-to address. Save it as “send-mail.php”. (You can save it anywhere or inside any sub-folder in “C:\wamp\www”.)
  • Open this file in browser, it MUST work now :-)

Monday, 21 May 2012

Ship

http://code.google.com/p/php-parcel-tracker/source/browse/carriers/usps.class.php?r=ecd3a1e9dfed7a2555b39178bf6bfd197040933e


http://forum.opencart.com/viewtopic.php?f=119&t=35867


http://lamp-dev.com/usps-web-tools-guide/205


http://bytes.com/topic/php/answers/905483-usps-tracking-api

Thursday, 9 February 2012