Showing posts with label php problem solutions. Show all posts
Showing posts with label php problem solutions. Show all posts

Friday 19 February 2016

How to detect Mobile Device in PHP? - Simplest way

How to detect Mobile Device in PHP - Simplest way

Question: What does this script do?
It simply detect the request and tells request comes from mobile browser (Mobile devices) OR Web Devices (Desktop, Laptop, Ipad).


Question: What are Server Requirements for this script?
PHP Must be installed.


Question: Why we do need this script?
Sometime we need to give the different response on the behalf of devices.
For Example:
We give 20 records for web browser.
We give 10 records for Mobile browser.


Question: Where we do need this script? Give Example?
We need this script where we change the response on the behalf of devices browser.
For Example:
  1. Different number of record in web and in mobile.
  2. In Responsive website, we hide the extra information which is not displayed in mobile devices. In this case we should also not fetch these details from the server.
  3. Display the different sizes of images on the behalf of device.
  4. If website is not compatiable to mobile devices, Give a good message to users.



Question: How to detect the mobile devices?
$useragent=$_SERVER['HTTP_USER_AGENT'];
$isMobile=0;
if(preg_match('/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i',$useragent)||preg_match('/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i',substr($useragent,0,4))){
    $isMobile=1;
}

if($isMobile){
    /** Script For Mobile **/

    /** Script For Mobile **/
}else{
    /** Script For Web**/

    /** Script For Web**/
}



Wednesday 10 February 2016

How to Create Thumbnail Images of uploaded image using PHP

How to Create Thumbnail Images of uploaded image using PHP

This tutorial will describe how to create thumbnail images on the fly using PHP while uploading a image. With uploaded of single image you can create different thumbnail with different size of same Image. Here you will Learn how to process a images and create their thumbnails.

System Requirements:
  1. Work for PHP only.
  2. GD library must be installed which you can check with phpinfo() with version of >=GD 2.0.1
  3. Uploading image size should be less than 2MB but if you want to increase then increase the value of "upload_max_filesize", "post_max_size" from php.ini

Code Snippets
   function resize($width, $height, $imageName,$extension) {
        if(empty($width) || empty($height) || empty($imageName) || empty($extension)){
            die('Required parameter is missing');
        }
        $docRoot = getenv("DOCUMENT_ROOT");
        
        /* Get original image x y */
        $tmpNM = $_FILES['files']['tmp_name'];
        
        list($w, $h) = getimagesize($_FILES['files']['tmp_name']);
        /* calculate new image size with ratio */
        $ratio = max($width / $w, $height / $h);
        $h = ceil($height / $ratio);
        $x = ($w - $width / $ratio) / 2;
        $w = ceil($width / $ratio);
        /* new file name */
        $path = $docRoot . '/images/thumb/' . $imageName;

        /* read binary data from image file */
        $imgString = file_get_contents($_FILES['files']['tmp_name']);
        /* create image from string */
        $image = imagecreatefromstring($imgString);
        $tmp = imagecreatetruecolor($width, $height);
        imagecopyresampled($tmp, $image, 0, 0, $x, 0, $width, $height, $w, $h);
        $fileTypes = array('jpg', 'jpeg', 'jpe', 'png', 'bmp', 'gif'); // File extensions
        /* Save image */
        switch ($extension) {
            case 'jpg':
            case 'jpeg':
            case 'jpe':
                imagejpeg($tmp, $path, 100);
                break;
            case 'png':
                imagepng($tmp, $path,0);
                break;
            case 'gif':
                imagegif($tmp, $path, 100);
                break;
            case 'bmp':
                imagewbmp($tmp, $path);
                break;
            default:
                exit;
                break;
        }
        return $path;
        /* cleanup memory */
        imagedestroy($image);
        imagedestroy($tmp);
    }
This function is able to create multiple thumbnail with different sizes of uploaded images.

How to  create thumbnail of 50pxX50px image?
    
    $w='50'; //New image width
    $h='50'; //New image height
    $imageName=$w.'_'.$h.'_'.$_FILES['files']['name']; //Uploaded file Name
    $imageExtensionArray = explode(".", $_FILES['files']['name']);
    $extension=$imageExtensionArray[1];
    $this->resize($w, $h,  "{$imageName}",$extension);

How to create thumbnail of 100pxX100px image?
$w='100'; //New image width
$h='100'; //New image height
$imageName=$w.'_'.$h.'_'.$_FILES['files']['name']; //Uploaded file Name
$imageExtensionArray = explode(".", $_FILES['files']['name']);
$extension=$imageExtensionArray[1];
$this->resize($w, $h,  "{$imageName}",$extension);

Saturday 16 January 2016

Advanced PHP Interview Questions and Answers

Advanced PHP Interview Questions and Answers


Question: What is PEAR in php?
PEAR means PHP Extension and Application Repository.
PEAR is a framework and distribution system for reusable PHP components. PEAR can be installed by bringing an automated wizard.
Following are main purpose of PEAR
A structured opensource library .
Distribution and package maintenance.
The PHP Foundation Classes (PFC)
The PHP Extension Community Library (PECL)


Question: How can we repair a MySQL table?
We can repair the MySQL with following 3 queries. Each have its own feature.
REPAIR TABLE tablename
REPAIR TABLE tablename QUICK
REPAIR TABLE tablename EXTENDED


Question: What Is a Persistent Cookie?
A persistent cookie is a cookie which is stored in a cookie file permanently on the browser.
A persistent cookie can be used for tracking long-term information.
Persistent cookies are less secure.


Question: How to create persistent cookie in php?
Cookies will only persistent for as long as you have set them.
setcookie( "cookieName", 'cookieValue', strtotime( '+1 year' ) ); //set for 1 year


Question: What is meant by urlencode and urldecode?
urlencode() returns the URL encoded version of the given string.
It convert special characters into % signs followed by two hex digits.

urldecode() returns the Decodes any %## encoding in the given string. Plus symbols ('+') are decoded to a space character.



Question: How To Get the Uploaded File Information in PHP Global variables?
We are all data in $_FILES variable and are following
$_FILES[$fieldName]['name'] - The Original file name on the browser system.
$_FILES[$fieldName]['type'] – The file type determined by the browser.
$_FILES[$fieldName]['size'] – The Number of bytes of the file content.
$_FILES[$fieldName]['tmp_name'] – The temporary filename of the file in which the uploaded file was stored on the server.
$_FILES[$fieldName]['error'] – The error code associated with this file upload.


Question: How can I execute a PHP script using command line?
php c:/wamp/www/myfile.php


Question: Are objects passed by value OR by reference?
Everything is passed by value.


Question: How do you call a constructor of a parent class from child class?
parent::constructor();


Question: Can we use include ("abc.php") two or more times?
Yes, we can include mutiple times.


Question: What is the difference between the functions unlink and unset?
unlink() deletes the given file from the file system.
unset() makes a variable undefined from memory


Question: What are the different functions in sorting an array?
Sort()
arsort()
asort()
ksort()
natsort()
natcasesort()
rsort()
usort()
array_multisort()
uksort().

Question: How can we get the browser properties using PHP?
$_SERVER['HTTP_USER_AGENT']


Question: How can I configure PHP to show error at runtime?
error_reporting(E_ALL) 



Question: How do I turn off PHP Notices?
Add following code in top of php script.
error_reporting(0);


Question: What is T_PAAMAYIM_NEKUDOTAYIM?
T_PAAMAYIM_NEKUDOTAYIM the scope resolution operator (double colon)
::


Qustion: What is output of following program?
function doSomething( &$arg )
{
    $return = $arg;
    $arg += 1;
    return $return;
}

$a = 3;
$b = doSomething( $a );

echo $a;
echo '\n';
echo $b;


Question: How to protect your website from SQL injection attack?
use mysql_real_escape_string() function.


Question: How to protect your website from CSRF (Cross-Site Request Forgery) attack?
Add a token on every important request to secure important operations


Question: How to protech your website from XSS (Cross-Site Scripting) attack?
use php function htmlentities()


Question: what is the list of sensible functions?
exec(), passthru(), system(), popen(), eval(), preg_replace() 


Question: What is output of following?
$a = 012;
echo $a / 4;



Monday 5 October 2015

How to import csv file to database through phpmyadmin

How to import csv file to database through phpmyadmin

To import csv file in database though phpmyadmin, Follow the following steps.
  1. You must have valid CSV File. EXCEL file will not work.
  2. you must have a table in database
  3. Number of Colums in CSV file must be equal to Number of column in table
  4. Now login to phpmyamdin.
  5. Make sure you server allow to upload the heavy files (If CSV is heavy).
    You can update the php.ini file as following(If you CSV is less than 700MB).
    upload_max_filesize = 700M
    post_max_size = 800M
    
    If your CSV is more than 700MB, then increase the above values in php.ini
  6. If you are uploading heavy files, you might need to increase the max_execution_time. (Means loading time to upload )
    max_execution_time = 300000
    
  7. Go to database and then go to table listing.
  8. Click on Import link at top page
  9. Next, Follow the steps in next.


  10. If you are getting any problem, Please comment below.. We will help you.


Wednesday 2 September 2015

How to export mysql query results to csv?

How to export mysql query results to csv?

To Learn OR understand the exporting mysql results in CSV.
Lets have below simple example.


  1. Step 1: Create a employee table
    CREATE TABLE IF NOT EXISTS `employee` (
      `id` int(11) unsigned NOT NULL,
      `first_name` varchar(100) DEFAULT NULL,
      `last_name` varchar(100) DEFAULT NULL,
      `gender` enum('m','f') DEFAULT NULL,
      `status` enum('0','1') NOT NULL COMMENT '0-Inactive, 1-Active',
      `address` varchar(255) DEFAULT NULL,
      `created_at` datetime DEFAULT NULL,
      `modified_at` datetime DEFAULT NULL
    ) ENGINE=InnoDB AUTO_INCREMENT=6;

  2. Add The records in employee table
    INSERT INTO `employee` (`id`, `first_name`, `last_name`, `gender`, `status`, `address`, `created_at`, `modified_at`) VALUES
    (1, 'Sunil', 'Malhotra', 'm', '1', '3020 new town, chandigarh', '2015-09-02 12:38:00', '2015-09-02 12:38:00'),
    (2, 'Anil ', 'Yadav', 'm', '1', '3020 new town, chandigarh', '2015-09-02 12:38:00', '2015-09-02 12:38:00'),
    (3, 'Aman ', 'Verma', 'm', '1', '3020 new town, chandigarh', '2015-09-02 12:38:00', '2015-09-02 12:38:00'),
    (4, 'Ram ', 'Singh', 'm', '1', '3020 new town, chandigarh', '2015-09-02 12:38:00', '2015-09-02 12:38:00'),
    (5, 'Arun', 'Kumar', 'm', '1', '3020 new town, chandigarh', '2015-09-02 12:38:00', '2015-09-02 12:38:00');
    

  3. Create a folder where you are going to export the csv file.
  4. Execute the Mysql Query.
    SELECT id,first_name,last_name,gender, STATUS, address FROM employee
    INTO OUTFILE 'E:/wamp/www/export/employee3.csv' FIELDS TERMINATED BY ',' ENCLOSED BY '"'
    LINES TERMINATED BY '\n';

Tuesday 1 September 2015

MySql replace NULL values with empty string without effecting Rowset

MySql replace NULL values with empty string without effecting Rowset

Question: What is NULL Value in MySQL?
NULL values means don't have any value. It is neither empty NOR it have any value.


Question: Give an Example which is give NULL Values in Query?
NULL values means don't have any value. It is neither empty NOR it have any values.
SELECT u.id, u.first_name,u.last_name,b.address1 FROM `users` as u LEFT JOIN billings as b on b.user_id=u.id order by u.id desc limit 5;
See Screenshot below:
Give an Example which is give NULL Values in Query



Question: How we can replace the null value with empty string?
We can use mysql IFNULL function to replace the null values with empty string. See Example:
SELECT IFNULL(null,"") as value 



Question: Give an Example to replace the NULL with empty string in mysql query?
We can use mysql IFNULL function to replace the null values with empty string. See Example:
SELECT u.id, u.first_name,u.last_name,IFNULL(b.address1,"") AS address1 FROM `users` as u LEFT JOIN billings as b on b.user_id=u.id  order by u.id desc limit 5; 

See Screenhot below:
Give an Example to replace the NULL with empty string in mysql query





Saturday 11 July 2015

How to fix Headers already sent error in PHP?


How to fix Headers already sent error in PHP?
We are here to fix below error in PHP
Warning: Cannot modify header information - headers already sent by (output started at E:\wamp\www\testp\public_html\ram.php:2) in E:\wamp\www\testp\public_html\ram.php on line 4

Question: Why this Error comes? This error comes when sending header after the output.
OR
using "header" function after the output.


Question: Give an example when this error comes?
echo "arun";
header("Location: next.php");



Question: How to fix this error?
When you are using header function to send header, make sure you have not any output before. In another words, header function must be called first in any script(if applicable). you can not send header after the output. For Example: below will work
header("Location: next.php");
echo "arun";



Question: Is there any another way to fix this error?
Yes, you need to set the output_buffering "on" (By default it is off)


Question: How to set output_buffering on in PHP?
ini_set('output_buffering','On');


Question: How to set output_buffering on in php.ini?
output_buffering = Off
replace with
output_buffering = On


Question: How to set output_buffering on in htaccess?
open you .htacces file and add following code.

  php_value output_buffering On


Monday 25 May 2015

How can I upload file asynchronously in php?

How can I upload file asynchronously in php?

Following are simple 4 Steps to upload file asynchronously  in PHP.

Step #1
Add jQuery javascript file in your page - Need for Ajax call.


<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>


Step #2
Add Following Html, where you want to show the button to upload the file.






Step #3:
Add following javascript code which is responsible for uploading the file.
URL: /folder/upload-file.php
Description: Here you need to write the send the request to server.
$( document ).ready(function() {
    $(':button').click(function(){
        var formData = new FormData($('form')[0]);
        $.ajax({
            url: '/folder/upload-file.php', //Location of upload file 
            type: 'POST',
            xhr: function() {  // Custom XMLHttpRequest
                var myXhr = $.ajaxSettings.xhr();
                return myXhr;
            },

            beforeSend: function(data){},
            success: function(data){},
            error: function(data){},        
            data: formData,        
            cache: false,
            contentType: false,
            processData: false
        });
    });
});


Step #4
Add Following code in "/folder/upload-file.php" which will upload the file in Server.
$targetFile="/path/to/upload/file";//Location of srver
if (move_uploaded_file($_FILES["file"]["tmp_name"], $targetFile)) {
        echo "success";
    } else {
        echo "failure";
    }





Wednesday 22 April 2015

Twitter login failed leads to Page not found

I have integration Twitter Sign and Its working fine. :)
Problem: When any user sign in with wrong credentials, It redirect to "Sorry, that page doesn’t exist!"
I am assuming, It should remain on same page, so that user can retry!.

Please see screenshot below:


I am Expecting, It must on same page if some one add wrong credentials. So that user can retry.

Solution:

See First login screenshot.
You are using Below URL for authentication
https://api.twitter.com/oauth/authenticate?oauth_token=XXXXXXXXXXXXXXXXXXXXXXXX

Authentication URL Must be start with https://twitter.com/xxx like below
https://twitter.com/oauth/authenticate?oauth_token=XXXXXXXXXXXXXXXXXXXXXXXX