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

Thursday, 10 August 2017

PHP Interview Questions and Answer for 3 year experienced

PHP Interview Questions and Answer for 3 year experienced

Question: What is the difference between Unlink And Unset function In PHP?
unlink It is used to delete the file permanent.
Unset It is used to delete the variable.

Question: What are PHP Traits?
It is a mechanism that allows us to do code reusability the code and its similer as that of PHP class.
trait Goodmorning {

    public function goodmorning() {
        echo "Good Morning Viewer";


trait Welcome {

    public function welcome() {
        echo "Welcome Viewer";


class Message {

    use Welcome,

    public function sendMessage() {        
        echo $this->welcome();        
        echo $this->goodmorning();


$o = new Message;

Welcome Viewer
Good Morning Viewer 

Question: How to get URL Of The Current Webpage??
Client side, connect with  parameter

Question: What Is Autoloading Classes In PHP? and how it works?
With autoloaders, PHP allows the to load the class or interface before it fails with an error.
spl_autoload_register(function ($classname) {
    include  $classname . '.php';
$object  = new Class1();
$object2 = new Class2();

Question: What s The use of ini_set()?
PHP allows the user to modify its settings mentioned in php.ini using ini_set();
For Example
Display error on page
ini_set('display_errors', '1');

Set mysql connection timeout

Set maximum execution time

Set post max size

Set upload max file size

Question: Which PHP Extension Helps To Debug The Code?
The name of that Extension is Xdebug.
It uses the DBGp debugging protocol for debugging. It is highly configurable and adaptable to a variety of situations.

Question: How can we get the properties of browswer?

Question: How to get/set the session id?
Set the session Id

Get the session Id
echo session_id()

Question: What is Scrum?
Scrum is an Agile framework for completing complex projects.
Scrum originally was made for software development projects, but it works well for any complex and innovative scope of work.

Question: What are the ways to encrypt the data?
md5() – Calculate the md5 hash of a string.
sha1() – Calculate the sha1 hash of a string.
hash() – Generate a hash value.
crypt() – One-way string hashing.

Question: How to get cookie value?
$_COOKIE ["cookie_name"];

Question: What is use of header?
The header() function is used to send a raw HTTP header to a client. It must be called before sending the actual output.

Question: What is Type juggle in PHP?
Type Juggling means dealing with a variable type. In PHP a variables type is determined by the context in which it is used.
If an integer value assign to variable it become integer.
If an string value assign to variable it become string.
If an object assign to variable it become object.

Question: What will be output of following?
$x = true and false and true;

boolean false

Question: What will be output of following?
$text = 'Arun ';
$text[10] = 'Kumar';
echo $text;

Arun K

Question: What is use of header?
header() is used to redirect from one page to another: header("Location: index.php");
header() is used to send an HTTP status code: header("HTTP/1.0 this Not Found");

header() is used to send a raw HTTP header: header('Content-Type: application/json');

Tuesday, 6 September 2016

How to add Security in Website?

How to add Security in Website?

Server Signature invisible

Whatever technology you are using PHP, .Net, ASP etc you should not let to know other.

Hide the Server Signature.
Open php.ini file.
expose_php = on
expose_php = off

Add Following code in .htaccess
ServerSignature Off

XSS Protection header Enabled

Cross-site scripting (XSS) is a type of computer security vulnerability found in web applications. XSS enables attackers to inject client-side script into webpages.
We can add Protection layer to XSS attack by adding this on header.

Add Following code in .htaccess
Header set X-XSS-Protection "1; mode=block"

Content Security Policy (CSP)

It is an added layer of security that helps to detect and mitigate certain types of attacks, including Cross Site Scripting and data injection attacks.
This header is designed to specify how content interacts with your website.
Add Following code in .htaccess
Header set X-Content-Security-Policy "allow 'self';"


 This header prevents "mime" based attacks. Add Following code in .htaccess
Header set X-Content-Type-Options "nosniff"

Protection From libwww-perl

LWP is a Perl modules that give Perl programming easy access to sending requests to the website. We can protect our website from this

Add Following code in .htaccess
RewriteCond %{HTTP_USER_AGENT} libwww-perl.* 
RewriteRule .* ? [F,L]

Always Use Https over http

An extra security layer because of SSL (Encryption, Data Integrity, Authentication )


The X-Frame-Options HTTP response header can be used to indicate whether or not a browser should be allowed to render a page in a frame or iframe. Add Following code in .htaccess
Header set X-Frame-Options SAMEORIGIN

Tuesday, 21 June 2016

How to hide web server information from the headers?

How to hide web server information from the headers?

Question: What do you mean by server technology in header?
When an request is sent from client to server.
When an request is sent from one server to another server.
There are lot of information also sent back to client(receiver information).
For Example:
HTTP/1.1 200 OK
Date: Tue, 21 Jun 2016 05:24:34 GMT
Server: Apache/2.2.22 (Win32) PHP/5.4.3
X-Powered-By: PHP/5.4.3
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Transfer-Encoding: chunked
Content-Type: text/html

Question: What are benefits of hiding server info from header?
An attacker will not get to know which technology you are using in your application.

Question: How to hide the Server technology information from header?
Step 1:
Open php.ini file
expose_php = on

expose_php = Off

Step 2:
Add Following in your .htacess (root folder)
ServerSignature Off

Step 3 Setup the mod_security with Apache

Monday, 20 June 2016

How to enable the XSS Protection header?

How to enable the  XSS Protection header?

Question: How to enable the XSS Protection header?
Add Following code in your root's .htaccess file

# Set XSS Protection header
Header set X-XSS-Protection "1; mode=block"

Question: What is Cross-site scripting?
Cross-site scripting (XSS) is a type of computer security vulnerability which attack on the site by injection the code in webpage

Question: What benefits of XSS Protection header?
It will protect the your site from XSS Attack

Friday, 4 March 2016

AES Encryption and Decryption in PHP See example

AES Encryption and Decryption in PHP See example

Question: What is AES encryption?
Advanced Encryption Standard is a specification for the encryption of data established by the NIST (National Institute of Standards and Technology) in 2001.

Question: What are different key sizes availbles?
  1. 128 bits
  2. 192 bits
  3. 256 bits

Question: How AES encryption works?
AES comprises three block ciphers i.e AES-128, AES-192 and AES-256. Each cipher encrypts and decrypts data in blocks of 128 bits using cryptographic keys of 128-bits, 192-bits and 256-bits, respectively. Secret-key ciphers use the same key for encrypting and decrypting. In this encryption method works three times faster in software than DES.

Question: Write a Function to encrypt/decrypt?
function encrypt_string($string = '', $salt = '8638FD63E6CC16872ACDED6CE49E5A270ECDE1B3B938B590E547138BB7F120EA') {
    $key = pack('H*', $salt);    
    $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
    $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
    $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $string, MCRYPT_MODE_CBC, $iv);
    return base64_encode($iv . $ciphertext);

function decrypt_string($encodedText = '', $salt = '8638FD63E6CC16872ACDED6CE49E5A270ECDE1B3B938B590E547138BB7F120EA') {
    $key = pack('H*', $salt);
    $ciphertext_dec = base64_decode($encodedText);
    $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
    $iv_dec = substr($ciphertext_dec, 0, $iv_size);
    $ciphertext_dec = substr($ciphertext_dec, $iv_size);
    return mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $ciphertext_dec, MCRYPT_MODE_CBC, $iv_dec);
/** Encoded Decoded with 256 bits * */
$encodedText = encrypt_string('hello');
echo decrypt_string($encodedText);

Question: How to encrypt/decrypt a string using 192 bits?
/** Encoded Decoded with 192 bits * */
$encodedText  = encrypt_string('hello', '8638FD63E6CC16872ACDED6CE49E5A270ECDE1B3B938B590');
echo decrypt_string($encodedText , '8638FD63E6CC16872ACDED6CE49E5A270ECDE1B3B938B590');

Question: How to encrypt/decrypt a string using 128 bits?
/** Encoded Decoded with 128 bits * */
$encodedText  = encrypt_string('hello', '8638FD63E6CC16872ACDED6CE49E5A27');
echo decrypt_string($encodedText , '8638FD63E6CC16872ACDED6CE49E5A27');

Saturday, 9 January 2016

XMLRPC Wordpress Attack

How to protect your wordpress website from xmlrpc attack

Queston: What is XMLRPC?
XML-RPC is one of the protocols that use XML for messages between two server. It is used to "Remote Procedure Calls" using XML.

Queston: Question: What is JSON-RPC?
JSON-RPC is one of the protocols that use JSON for messages between two server.
It is used to "Remote Procedure Calls" using JSON.

Queston: What is xmlrpc in wordpress?
WordPress uses an XML-RPC interface.
XML-RPC protocol is used to post entries.

Question: How to protect your website from xmlrpc attack?
Add following code in bottom of .htaccess file in root folder.
<Files 'xmlrpc.php'>
Order Allow,Deny
deny from all

Question: How to stop abusing XML-RPC file?
Open functions.php file in your add theme and following code.
add_filter( 'xmlrpc_methods', function( $methods ) {
         unset( $methods[''] );
            return $methods;
      } ); 

Tuesday, 6 October 2015

How can I read request-headers in PHP

$headers = apache_request_headers();

Following are the Response of apache_request_headers()
How can I read request-headers in PHP?

Question: What is apache_request_headers()?
This function fetch all HTTP request headers.

Question: What format it return when success?
An associative array of all the HTTP headers in the current request.

Question: What happen when request failed?
It return FALSE when failed.

Question: Is it availble in all PHP Version?
No, It works only with >= PHP 5.4.

Question: How can I get header values less than 5.4 version
function getRequestHeadersCustomFunction() {
    $headers = array();
    foreach($_SERVER as $key => $value) {
        if (substr($key, 0, 5) <> 'HTTP_') {
        $headerKey = str_replace(' ', '-', ucwords(str_replace('_', ' ', strtolower(substr($key, 5)))));
        $headers[$headerKey] = $value;
    return $headers;

Thursday, 2 July 2015

How can I prevent SQL-injection in PHP?

How can I prevent SQL-injection in PHP?

Question: What is SQL Injection?
SQL injection is a code injection technique, which is used to attack on database driven applications. In this malicious SQL statements are inserted into an database query.

Question: How attackers attack on website with SQL Injection?
With use SQL Injection, attacker/hackers attack on web application's table/database.

For Example, Lets have a Web login-form where visitor enter the username and password to login in system.
Attacker use the special characters (i.e '"!@#$%^&*()_+)  in Web login-form, to attack the websites

What can attackers do with SQL Injection?
Below are couples of ways an attacker can harm our website.
  1. After submit the form, these special character mix the query and break the query, due to this an page will be crash. In this case attacker may able to see the queryies printed in browser(If debug mode is not off).
  2. They may use combination of special-characters due to which they may able to login in our system without having valid login.
  3. They may able to see list of users in our database
  4. They may delete record or table

How we can prevent with SQL Injection
We must filter data entered by user before saving in database OR using in SQL query.
If you are able to escaping the string, then you are able to prevent your website from SQL attack.

Following are few different ways to prevent SQL Injection in PHP, Use any of below:
Use a PHP Function For PHP 5.4
$safeData = mysql_real_escape_string($_POST["user-input"]);
mysql_query("INSERT INTO table (column) VALUES ('" . $safeData . "')");
//If you using PHP >5.5 Use MYSQL as mysql_real_escape_string is deprecated in PHP5.5

Use MySQLI (New version of MySQL)
$mysqli = new mysqli("server", "username", "password", "database_name");
$unsafeData = $_POST["user-input"];
$stmt = $mysqli->prepare("INSERT INTO table (column) VALUES (?)");
$stmt->bind_param("s", $unsafeData;

Use PDO to connect database
$stmt = $pdo->prepare('SELECT * FROM users WHERE name = :name');
$unsafeData = $_POST["user-input"];
$stmt->execute(array('name' => $unsafeData));

Friday, 22 May 2015

Shared Server Security Risk open_basedir disable_functions disable_classes

How to secure website on shared server

There are a variety of security issues that arise when using shared hosting solutions. There are three php.ini directives that remain important in a shared hosting

open_basedir : The open_basedir directive provides the ability to limit the files that PHP can open
to a specified directory tree. When PHP tries to open a file with, for example, fopen()
or include, it checks the the location of the file. If it exists within the directory tree
specified by open_basedir, then it will succeed; otherwise, it will fail to open the file.

disable_functions :  You can disable function like exec, passthru, shell_exec, system etc for security purpose.

disable_classes : You can disable class like DirectoryIterator, Directory for security purpose.

You may set the open_basedir directive in php.ini OR on a per-virtual-host basis in httpd.conf. In the following httpd.conf virtual host example, PHP scripts may only open files located in the /home/user/www and /usr/local/lib/php directories.

<VirtualHost *:80>
    DocumentRoot 'C:/wamp/www/zf1_11/public_html'
    ServerName zf11.localhost
    <Directory 'C:/wamp/www/zf1_11/public_html'>
        AllowOverride All
        Order allow,deny
        Allow from all

Tuesday, 14 April 2015

What is Best method for sanitizing user input with PHP?

What is  Best method for sanitizing user input with PHP

Sanitize user-input when using in Mysql Query.
You can use real_escape_string of mysqli.
For Example:
$mysqliObj = new mysqli("localhost", "root", "", "mydb");
$city = $mysqliObj->real_escape_string($_POST['city']);
if ($mysqli->query("INSERT into myCity (Name) VALUES ('$city')")) {
    printf("%d Row inserted.\n", $mysqli->affected_rows);

Sanitize user-input  while insert in database and displaying in Browser.
You can use htmlentities and html_entity_decode.
For Example:
echo htmlentities($data['description']);//at the time of insert in database 
echo html_entity_decode($data['description']); //at the time of display in browser from database

Sanitize user-input when using in Command Prompt.
You can use escapeshellarg.
For Example:
system('ls '.escapeshellarg($data['dir']));

Monday, 5 January 2015

Difference between Notice and warning and fatal error

Difference between Notice and warning and fatal error

  • A notice is an advisory message like "You probably shouldn't be doing what you're doing"
  • Execution of the script is not halted
  • Example
    echo $undefinedVariable;

  • A warning is a message like "You are doing something wrong and it is very likely to cause errors in the future, so please fix it." Execution of the script is not halted;
  • Example
    echo 1/0;

Fatal Error
  • Fatal run-time errors
  • Execution of the script is not halted
  • Example  
    require_once "notexistfile.php"

Thursday, 18 December 2014

How can I prevent SQL-injection in PHP [SOLVED]

How can I prevent SQL-injection in PHP [SOLVED]

Following are different 3 ways to prevent from SQL Injection.
1. Using PHP inbuilt Functions.
$name = mysql_real_escape_string($_POST["name"]);
mysql_query("INSERT INTO users VALUES($name)");

2. Use MySqli instead of MySQL. MySqli is far better than MySql because is object oriented MySql.
$stmt = $dbConnection->prepare('INSERT INTO users VALUES(?)');
$stmt->bind_param('s', $name);

3. Using PDO
$stmt = $conn->prepare("INSERT INTO users VALUES(:name)");
$stmt->bindValue(':name', $_POST["name"]);

Tuesday, 7 October 2014

PHP Register Globals

PHP Register Globals

register_globals is  PHP Setting, In which it registers the GET/POST array's elements as variables.

For example, If URL is /index.php?name=php-tutorial-php, when you echo $name; It will print the value i.e php-tutorial-php (if register_globals is ON). Same applicable to POST methods also.

When register_globals is ON you need not to extract the value of GET/POST explicitly, variable values are available with the element-Name.

Example with POST Data (if register_globals is ON)
If you post following data
    [name] => php-tutorial-php
    [description] => Web Technology Experts Notes
echo $name;//php-tutorial-php
echo $description;//Web Technology Experts Notes

For Example COOKIE Data(if register_globals is ON)
$_SESSION[value] = 123;
$value = 'This is session value';
echo $_SESSION[value]; //This is session value

When register_globals=on, anything passed via $_GET / $_POST / $_SESSION / $_COOKIE automatically appears to be global variable, this can might have security consequences. Due to this register_globals has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.

If you are using lower than php5.4 version, It's highly recommended you should set off the value of register_global.

Sunday, 8 June 2014

PHP Sessions and Cookie and Security

PHP Session
Session is Super global variable, that preserve certain data across multiple requests. A visitor accessing your web-site is assigned a unique id, the so-called session id. Its either stored in a cookie on the user side OR is propagated in the URL.

Why its is used
1. Get the Number of unique visitor
2. For Login functionality we need this.
3. It tell us whether user is registered OR not.

No external libraries are needed to build this extension.

Session is enabled in PHP by default. If you would not like to build your PHP with session support, you should specify the

Session configuration options
session.gc_divisor"100"PHP_INI_ALLAvailable since PHP 4.3.2.
session.cookie_secure""PHP_INI_ALLAvailable since PHP 4.0.4.
session.cookie_httponly""PHP_INI_ALLAvailable since PHP 5.2.0.
session.use_strict_mode"0"PHP_INI_ALLAvailable since PHP 5.5.2.
session.use_only_cookies"1"PHP_INI_ALLAvailable since PHP 4.3.0.
session.use_trans_sid"0"PHP_INI_ALLPHP_INI_ALL in PHP <= 4.2.3. PHP_INI_PERDIR in PHP < 5. Available since PHP 4.0.3.
session.bug_compat_42"1"PHP_INI_ALLAvailable since PHP 4.3.0. Removed in PHP 5.4.0.
session.bug_compat_warn"1"PHP_INI_ALLAvailable since PHP 4.3.0. Removed in PHP 5.4.0.
session.hash_function"0"PHP_INI_ALLAvailable since PHP 5.0.0.
session.hash_bits_per_character"4"PHP_INI_ALLAvailable since PHP 5.0.0.
url_rewriter.tags"a=href,area=href,frame=src,form=,fieldset="PHP_INI_ALLAvailable since PHP 4.0.4.
session.upload_progress.enabled"1"PHP_INI_PERDIRAvailable since PHP 5.4.0.
session.upload_progress.cleanup"1"PHP_INI_PERDIRAvailable since PHP 5.4.0.
session.upload_progress.prefix"upload_progress_"PHP_INI_PERDIRAvailable since PHP 5.4.0."PHP_SESSION_UPLOAD_PROGRESS"PHP_INI_PERDIRAvailable since PHP 5.4.0.
session.upload_progress.freq"1%"PHP_INI_PERDIRAvailable since PHP 5.4.0.
session.upload_progress.min_freq"1"PHP_INI_PERDIRAvailable since PHP 5.4.0.

How to set the Cookie?
bool setcookie ($name, $value);//set the cookie
bool setcookie ($name, $value,time()+3600); //set the cookie with expire 1 hour
bool setcookie ($name, $value, $expire = 0, $path, $domain, $secure = false, $httponly = false );//all parameter of set cookie
bool setrawcookie ($name, $value, $expire = 0, $path, $domain, $secure = false, $httponly = false );//Send a cookie without urlencoding the cookie value
Parameter of set_cookie function
name: The name of the cookie.
value: The value of the cookie. This value is stored on the clients computer; do not store sensitive information.
expire: The time the cookie expires. This is a Unix timestamp so is in number of seconds since the epoc. If set to 0, or omitted, the cookie will expire when the browser closes.
path: The path on the server in which the cookie will be available on. If set to '/', the cookie will be available within the entire domain.
domain: The domain that the cookie is available to.
secure: Indicates that the cookie should only be transmitted over a secure HTTPS connection from the client. 
httponly: When TRUE the cookie will be made accessible only through the HTTP protocol. 

How to get cookie?
echo $_COOKIE["cookieName"];

How to print all cookie?

How to delete a cookie?
setcookie ("cookieName", "", time() - 60);

How to set Array Cookie?
setcookie("cookieName[one]", "c_1");
setcookie("cookieName[three]", "c_2");
setcookie("cookieName[two]", "c_3");

How to get Array cookie?