Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

Saturday, October 30, 2021

Laravel @extends and @include and @section

 @include is just like a basic PHP include, it includes a "partial" view into your view.

@extends lets you "extend" a template, which defines its own sections etc. A template that you can extend will define its own sections using @yield, which you can then put your own stuff into in your view file.

Example:

template.blade.php

<html>
    <body>
        @yield('header')
        @yield('content')
        @yield('footer')
    </body>
</html>

view-one.blade.php

@extends('template')

@section('header')
    View one's header
@endsection

@section('content')
    View one's content
@endsection

@section('footer')
    View one's footer
@endsection

Which will result in:

<html>
    <body>
        View one's header
        View one's content
        View one's footer
    </body>
</html>

Now you could create another view which extends the same template, but provides its own sections.

Another benefit to using @extend is inheritance. You could provide a base template, and then another child template that extends that one which subsequently yields it's own sections. You can then extend that child template.

Wednesday, November 22, 2017

What is csrf and xss clean?

          CSRF :

Cross-site request forgeries are a type of malicious exploit whereby unauthorized commands are performed on behalf of an authenticated user.

Laravel automatically generates a CSRF "token" for each active user session managed by the application. This token is used to verify that the authenticated user is the one actually making the requests to the application

XSS clean :

the attack is basically a type of code injection attack which is made possible by incorrectly validating user data, which usually gets inserted into the page through a web form or using an altered hyperlink. The code injected can be any malicious client-side code, such as JavaScript, VBScript, HTML, CSS, Flash, and others. The code is used to save harmful data on the server or perform a malicious action within the user’s browser.

Unfortunately, cross-site scripting attacks occurs mostly, because developers are failing to deliver secure code. Every PHP programmer has the responsibility to understand how attacks can be carried out against their PHP scripts to exploit possible security vulnerabilities. Reading this article, you’ll find out more about cross-site scripting attacks and how to prevent them in your code.

Preventing Cross-Site Scripting Attacks

  •     Data Validation

  •     Data Sanitization

  •     Output Escaping

  • Htmlspecialchars :

    • The htmlspecialchars() function converts some predefined characters to HTML entities.

  • HTML entities

    • The htmlentities() function converts characters to HTML entities.

  • Strip_tags

    • The strip_tags() function strips a string from HTML, XML, and PHP tags.

    • Note: HTML comments are always stripped. This cannot be changed with the allow parameter.

    • Note: This function is binary-safe.

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

       

Trim()

The trim() function removes whitespace and other predefined characters from both sides of a string.


ltrim() - Removes whitespace or other predefined characters from the left side of a string

rtrim() - Removes whitespace or other predefined characters from the right side of a string

Monday, October 26, 2015

How to check if string has at least one letter, number and special character in php

Lowercase character, Uppercase character, Digit, Symbol
^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*(_|[^\w])).+$

A short explanation:

^ // the start of the string
(?=.*[a-z]) // use positive look ahead to see if at least one lower case letter exists
(?=.*[A-Z]) // use positive look ahead to see if at least one upper case letter exists
(?=.*\d) // use positive look ahead to see if at least one digit exists
(?=.*[_\W]) // use positive look ahead to see if at least one underscore or non-word character exists
.+ // gobble up the entire string
$ // the end of the string

Here is more explain of this type of password security in regex

Minimum 8 characters at least 1 Alphabet and 1 Number:
"^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$"
Minimum 8 characters at least 1 Alphabet, 1 Number and 1 Special Character:
"^(?=.*[A-Za-z])(?=.*\d)(?=.*[$@$!%*#?&])[A-Za-z\d$@$!%*#?&]{8,}$"
Minimum 8 characters at least 1 Uppercase Alphabet, 1 Lowercase Alphabet and 1 Number:
"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$"
Minimum 8 characters at least 1 Uppercase Alphabet, 1 Lowercase Alphabet, 1 Number and 1 Special Character:
"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&])[A-Za-z\d$@$!%*?&]{8,}"
Minimum 8 and Maximum 10 characters at least 1 Uppercase Alphabet, 1 Lowercase Alphabet, 1 Number and 1 Special Character:
"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&])[A-Za-z\d$@$!%*?&]{8,10}"
 
 
I hope this will help you  

Monday, October 19, 2015

Get country by mobile no

Here I am going to tell you how can you get country by mobile no
sometime you have the mobile no with country code


    mobile
   971525478965
   919844005522
   45712345678
 
I am going to through each number in the database and find the country code from
the mobile number display the country code and the country using php.

 
 
 
 If you  like then share 

Thursday, September 10, 2015

How to Getting start with regular expressions


Regular expressions are a very useful tool for developers. They allow to find, identify or replace text, words or any kind of characters. In this article, I have compiled 15+ extremely useful regular expressions that any web developer should have in his toolkit.

Getting started with regular expressions
For many beginners, regular expressions seems to be hard to learn and use. In fact, they’re far less hard than you may think. Before we dive deep inside regexp with useful and reusable codes, let’s quickly see the basics:
Regular expressions syntax
Regular Expression
Will match…
foo
The string “foo”
^foo
“foo” at the start of a string
foo$
“foo” at the end of a string
^foo$
“foo” when it is alone on a string
[abc]
a, b, or c
[a-z]
Any lowercase letter
[^A-Z]
Any character that is not a uppercase letter
(gif|jpg)
Matches either “gif” or “jpeg”
[a-z]+
One or more lowercase letters
[0-9.-]
Аny number, dot, or minus sign
^[a-zA-Z0-9_]{1,}$
Any word of at least one letter, number or _
([wx])([yz])
wy, wz, xy, or xz
[^A-Za-z0-9]
Any symbol (not a number or a letter)
([A-Z]{3}|[0-9]{4})
Matches three letters or four numbers

PHP regular expression functions
Function
Description
preg_match()
The preg_match() function searches string for pattern, returning true if pattern exists, and false otherwise.
preg_match_all()
The preg_match_all() function matches all occurrences of pattern in string.
preg_replace()
The preg_replace() function operates just like ereg_replace(), except that regular expressions can be used in the pattern and replacement input parameters.
preg_split()
The preg_split() function operates exactly like split(), except that regular expressions are accepted as input parameters for pattern.
preg_grep()
The preg_grep() function searches all elements of input_array, returning all elements matching the regexp pattern.
preg_ quote()
Quote regular expression characters

Validate domain name
Verify if a string is a valid domain name.


Friday, September 4, 2015

Language Constructs in PHP

PHP has a huge collection of built-in functions that you can call directly within your PHP files. While going through built-in functions, you might have faced the term language construct.

For an example you might have seen that echo() is not a function but a language construct. In addition to echo() following are some other language constructs.

1.print()
2.unset()
3.isset()
4.empty()
5.include()
6.require()
7.die()

Any computer language is made up of basic elements and these elements are known by their respective language parsers. For an example if is a basic element in PHP and PHP parser is aware of it.

So when a PHP file is going through PHP parser, if it sees an if then it knows that there should be a left parenthesis next to that. If not, PHP parser would throw an error. Here we can call if is a language construct because PHP parser knows what it is without further analyzing.

In a similar way we can think that PHP parser recognize and know what to do when it sees echo() or any other language construct. When PHP parser finds a built-in function, first it needs to check the language definitions and convert the function into set of known language constructs.
Language Constructs Are Relatively Faster

If you research on language constructs vs built-in functions, you might have seen that it says language constructs are relatively faster over built-in functions since they are basic elements of the language.

However you shouldn’t think about the difference in anything more than microseconds. And also final execution time depends on the parameters that are passed into language constructs or built-in functions.
Language Constructs Don’t Need Parenthesis

1.echo ('Today is a beautiful day');
2.echo 'Today is a beautiful day';
3.$today = 'Today is a beautiful day';
4.echo $today;
5.
6.die('You are not authorized to access this content');
7.die;

All above coding lines are correct and processed as expected. Note that echo() and die() both are language constructs and they can be used with or without parenthesis. However you can’t use built-in functions without parenthesis.
1.
count($namesArray); // This is correct assuming that $namesArray is defined.
2.
count $namesArray; // This is incorrect. It's identified as a syntax error.

Tuesday, August 18, 2015

Why shouldn't I use mysql_* functions in PHP ?




PHP offers three different APIs to connect to MySQL. There are the mysql, mysqli, and PDO extensions.
The mysql_* functions are very popular, but their use is not encouraged anymore. The documentation team is discussing the database security situation, and educating users to move away from the commonly used ext/mysql extension is part of this (check php.internals: deprecating ext/mysql).
And the later PHP developer team has taken the decision to generate E_DEPRECATED errors when users connect to MySQL, whether through mysql_connect(), mysql_pconnect() or the implicit connection functionality built into ext/mysql.
ext/mysql is now officially deprecated as of PHP 5.5!
See the Red Box?
When you go on any mysql_* function manual page, you see a red box, explaining it should not be used anymore.

Why


Moving away from ext/mysql is not only about security, but also about having access to all the features of the MySQL database.
ext/mysql was built for MySQL 3.23 and only got very few additions since then while mostly keeping compatibility with this old version which makes the code a bit harder to maintain. Missing features that is not supported by ext/mysql include:(from PHP manual)
Reason to not use mysql_* function
  • Not under active development
  • In deprecation process (so the intention is to remove it from a future version of PHP)
  • Lacks an OO interface
  • Doesn't support non-blocking, asynchronous queries
  • Doesn't support prepared statements or parametrized queries
  • Doesn't support stored procedures
  • Doesn't support multiple statements
  • Doesn't support transactions
  • Doesn't support all of the functionality in MySQL 5.1
Above point quoted from Quentin's answer
Lack of support for prepared statements is particularly important as they provide a clearer, less error prone method of escaping and quoting external data than manually escaping it with a separate function call.
See the comparison of SQL extensions

Suppressing deprecation warnings
While code is being converted to MySQLi/PDO, E_DEPRECATED errors can be suppressed by setting error_reporting in php.ini to exclude E_DEPRECATED:
 error_reporting = E_ALL ^ E_DEPRECATED
Note that this will also hide other deprecation warnings, which, however, may be for things other than MySQL.(from PHP manual)
The article PDO vs. MySQLi: Which Should You Use? by Dejan Marjanovic will help you to choose.
And a better way is PDO, and I am now writing a simple PDO tutorial.

A simple and short PDO tutorial


Q.First question in my mind was: what is PDO?

A. “PDO – PHP Data Objects – is a database access layer providing a uniform method of access to multiple databases.”


Connecting to MySQL

With mysql_* function or we can say it the old way (deprecated in PHP 5.5 and above)
<?php
    $link = mysql_connect('localhost', 'user', 'pass');
    mysql_select_db('testdb', $link);
    mysql_set_charset('UTF-8', $link);
With Pdo: All you need to do is create a new PDO object. The constructor accepts parameters for specifying the database source PDO's constructor mostly takes four parameters which are DSN (data source name) and optionally username, password.
Here I think you are familiar with all except DSN; this is new in PDO. A DSN is basically a string of options that tell PDO which driver to use, and connection details. For further reference, check PDO MYSQL DSN.
<?php
    $db = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8', 'username', 'password');
Note: you can also use charset=UTF-8, but sometimes it causes an error, so better to use utf8.
If there any connection error it will throw PDOException object it can be cached to handle Exception further.
Good read : Connections and Connection management ¶
You can also pass in several driver options as an array to the fourth parameter. I recommend passing the parameter which puts PDO into exception mode. Because some PDO drivers don't support native prepared statements, so PDO performs emulation of the prepare. It also lets you manually enable this emulation. To use the native server-side prepared statements, you should explicitly set it false
The other is to turn off prepare emulation which is enabled in the MySQL driver by default, but prepare emulation should be turned off to use PDO safely.
I will later explain why prepare emulation should be turned off To find reason please check this post .
It is only usable if you are using an old version of MySQL which I do not recommended.
Below I am showing how you can do it.
<?php
    $db = new PDO('mysql:host=localhost;dbname=testdb;charset=UTF-8', 
                  'username', 
                  'password',
                  array(PDO::ATTR_EMULATE_PREPARES => false,
                  PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
Can we set attributes after PDO construction?
Yes, we can also set some attributes after PDO construction with the setAttribute method:
<?php
    $db = new PDO('mysql:host=localhost;dbname=testdb;charset=UTF-8', 
                  'username', 
                  'password');
                  $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                  $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

Error Handling


Error handling is much easier in PDO than mysql_*.
A common practice when using mysql_* is:
<?php
    //Connected to MySQL
    $result = mysql_query("SELECT * FROM table", $link) or die(mysql_error($link));
OR die() is not a good way to handle the error since we can not handle the thing in die. It will just end the script abruptly and then echo the error to the screen which you usually do NOT want to show to your end users, and let bloody hackers discover your schema. Alternately, the return values of mysql_* functions can often be used in conjunction with mysql_error() to handle errors.
PDO offers a better solution: exceptions. Anything we do with PDO should be wrapped in a try-catch block. We can force PDO into one of three error modes by setting the error mode attribute. Three error handling modes are below.
  • PDO::ERRMODE_SILENT. It's just setting error codes and acts pretty much the same as mysql_* where you must check each result and then look at $db->errorInfo(); to get the error details.
  • PDO::ERRMODE_WARNING Raise E_WARNING. (Run-time warnings (non-fatal errors). Execution of the script is not halted.)
  • PDO::ERRMODE_EXCEPTION: Throw exceptions. It represents an error raised by PDO. You should not throw a PDOException from your own code. See Exceptions for more information about exceptions in PHP. It acts very much like or die(mysql_error());, when it isn't caught. But unlike or die(), the PDOException can be caught and handled gracefully if you choose to do so.
Good read
Like:
$stmt->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT );
$stmt->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );
$stmt->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
And you can wrap it in try-catch, like below:
<?php
try {
    //Connect as appropriate as above
    $db->query('hi'); //Invalid query!
} 
catch (PDOException $ex) {
    echo "An Error occured!"; //User friendly message/message you want to show to user
    some_logging_function($ex->getMessage());
}
You do not have to handle with try-catch right now. You can catch it at any time appropriate, but I strongly recommend you to use try-catch. Also it may make more sense to catch it at outside the function that calls the PDO stuff:
<?php
    function data_fun($db) {
       $stmt = $db->query("SELECT * FROM table");
       return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
 
    //Then later
    try {
       data_fun($db);
    }
    catch(PDOException $ex) {
       //Here you can handle error and show message/perform action you want.
    }
Also, you can handle by or die() or we can say like mysql_*, but it will be really varied. You can hide the dangerous error messages in production by turning `display_errors off' and just reading your error log.
Now, after reading all the things above, you are probably thinking: what the heck is that when I just want to start leaning simple SELECT, INSERT, UPDATE, or DELETE statements? Don't worry, here we go:

Selecting Data


So what you are doing in mysql_* is:
<?php
    $result = mysql_query('SELECT * from table') or die(mysql_error());
 
    $num_rows = mysql_num_rows($result);
 
    while($row = mysql_fetch_assoc($result)) {
        echo $row['field1'];
    }
Now in PDO, you can do this like:
<?php
    $stmt = $db->query('SELECT * FROM table');
 
    while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        echo $row['field1'];
    }
Or
<?php
    $stmt = $db->query('SELECT * FROM table');
    $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
 
    //Use $results
Note:: if you are using the method like below (query()), this method returns a PDOStatement object. So if you want to fetch the result, use it like above.
<?php
    foreach($db->query('SELECT * FROM table') as $row) {
        echo $row['field1'];
    }
In PDO Data, it is obtained via the ->fetch(), a method of your statement handle. Before calling fetch, the best approach would be telling PDO how you’d like the data to be fetched. In the below section I am explaining this.

Fetch Modes

Note the use of PDO::FETCH_ASSOC in the fetch() and fetchAll() code above. This tells PDO to return the rows as an associative array with the field names as keys. There are many other fetch modes too which I will explain one by one.
First of all, I explain how to select fetch mode:
 $stmt->fetch(PDO::FETCH_ASSOC)
In the above, I have been using fetch(). You can also use:
Now I come to fetch mode:
  • PDO::FETCH_ASSOC: returns an array indexed by column name as returned in your result set
  • PDO::FETCH_BOTH (default): returns an array indexed by both column name and 0-indexed column number as returned in your result set
There are even more choices! Read about them all in PDOStatement Fetch documentation..
Getting the Row Count
Instead of using mysql_num_rows to get the number of returned rows, you can get a PDOStatement and do rowCount();, like:
<?php
    $stmt = $db->query('SELECT * FROM table');
    $row_count = $stmt->rowCount();
    echo $row_count.' rows selected';
Getting the Last Inserted ID
<?php
    $result = $db->exec("INSERT INTO table(firstname, lastname) VAULES('John', 'Doe')");
    $insertId = $db->lastInsertId();

Insert and Update or Delete statements


What we are doing in mysql_* function is:
<?php
    $results = mysql_query("UPDATE table SET field='value'") or die(mysql_error());
    echo mysql_affected_rows($result);
And in pdo, this same thing can be done by:
<?php
    $affected_rows = $db->exec("UPDATE table SET field='value'");
    echo $affected_rows;
In the above query PDO::exec(execute an SQL statement and returns the number of affected rows)
(Insert and delete will be covered later.)
The above method is only useful when you are not using variable in query. But when you need to use a variable in a query, do not ever ever try like the above and there for prepared statement or parameterized statement is.

Prepared Statements

Q. What is a prepared statement and why do I need them?
A. A prepared statement is a precompiled SQL statement that can be executed multiple times by sending only the data to the server.
The typical workflow of using a prepared statement is as follows (quoted from Wikipedia three 3 point):
1.      Prepare: The statement template is created by the application and sent to the database management system (DBMS). Certain values are left unspecified, called parameters, placeholders or bind variables (labelled "?" below):
INSERT INTO PRODUCT (name, price) VALUES (?, ?)
2.      The DBMS parses, compiles, and performs query optimization on the statement template, and stores the result without executing it.
  1. Execute: At a later time, the application supplies (or binds) values for the parameters, and the DBMS executes the statement (possibly returning a result). The application may execute the statement as many times as it wants with different values. In this example, it might supply 'Bread' for the first parameter and '1.00' for the second parameter.
You can use a prepared statement by including placeholders in your SQL. There are basically three ones without placeholders (don't try this with variable its above one), one with unnamed placeholders, and one with named placeholders.
Q. So now, what are named placeholders and how do I use them?
A. Named placeholders. Use descriptive names preceded by a colon, instead of question marks. We don't care about position/order of value in name place holder:
 $stmt->bindParam(':bla', $bla);
bindParam(parameter,variable,data_type,length,driver_options)
You can also bind using an execute array as well:
<?php
    $stmt = $db->prepare("SELECT * FROM table WHERE id=:id AND name=:name");
    $stmt->execute(array(':name' => $name, ':id' => $id));
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
Another nice feature for OOP friends is that named placeholders have the ability to insert objects directly into your database, assuming the properties match the named fields. For example:
class person {
    public $name;
    public $add;
    function __construct($a,$b) {
        $this->name = $a;
        $this->add = $b;
    }
 
}
$demo = new person('john','29 bla district');
$stmt = $db->prepare("INSERT INTO table (name, add) value (:name, :add)");
$stmt->execute((array)$demo);
Q. So now, what are unnamed placeholders and how do I use them?
A. Let's have an example:
<?php
    $stmt = $db->prepare("INSERT INTO folks (name, add) values (?, ?)");
    $stmt->bindValue(1, $name, PDO::PARAM_STR);
    $stmt->bindValue(2, $add, PDO::PARAM_STR);
    $stmt->execute();
and
 $stmt = $db->prepare("INSERT INTO folks (name, add) values (?, ?)");
 $stmt->execute(array('john', '29 bla district'));
In the above, you can see those ? instead of a name like in a name place holder. Now in the first example, we assign variables to the various placeholders ($stmt->bindValue(1, $name, PDO::PARAM_STR);). Then, we assign values to those placeholders and execute the statement. In the second example, the first array element goes to the first ? and the second to the second ?.
NOTE: In unnamed placeholders we must take care of the proper order of the elements in the array that we are passing to the PDOStatement::execute() method.

SELECT,INSERT,UPDATE,DELETE prepaired queries

1 SELECT
<?php
    $stmt = $db->prepare("SELECT * FROM table WHERE id=:id AND name=:name");
    $stmt->execute(array(':name' => $name, ':id' => $id));
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
2 INSERT
$stmt = $db->prepare("INSERT INTO table(field1,field2) VALUES(:field1,:field2)");
$stmt->execute(array(':field1' => $field1, ':field2' => $field2));
$affected_rows = $stmt->rowCount();
3 DELETE
<?php
    $stmt = $db->prepare("DELETE FROM table WHERE id=:id");
    $stmt->bindValue(':id', $id, PDO::PARAM_STR);
    $stmt->execute();
    $affected_rows = $stmt->rowCount();
4 UPDATE
<?php
    $stmt = $db->prepare("UPDATE table SET name=? WHERE id=?");
    $stmt->execute(array($name, $id));
    $affected_rows = $stmt->rowCount();

NOTE:

However PDO/MySQLi are not completely safe.
Check some example.
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$pdo->query('SET NAMES GBK');
$stmt = $pdo->prepare("SELECT * FROM test WHERE name = ? LIMIT 1");
$stmt->execute(array(chr(0xbf) . chr(0x27) . " OR 1=1 /*"));

How to Host a Laravel Project on Hostinger’s hPanel: A Step-by-Step Guide

How to Host a Laravel Project on Hostinger’s hPanel: A Step-by-Step Guide If you're looking to host a Laravel project on Hostinger’s hPa...