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

Friday 7 November 2014

Enabling the openssl in Wamp-Xampp

Enabling the openssl in Wamp-Xampp

If you have any of following issue, then you are on right page.

  • How to enable SSL
  • Enabling the openssl in WampServer/xampp
  • How to enable openssl support in XAMPP
  • Unable to Connect to ssl
  • Fatal error: Uncaught exception Zend_Http_Client_Adapter_Exception


Solution: enable the extension php_openssl from PHP Extension

Option 1 (If using Wamp-Server)

Enabling the openssl in Wamp










and Restart your wamp Server


Option 2 (Direct change in php.ini File)
You can do direct change
Just comment your php_openssl.dll in your php.ini file.
Search
;extension=php_openssl.dll
Replace with
extension=php_openssl.dll
Here we have just removed the semicolon.



Tuesday 23 September 2014

Zend Cache Tutorial - Zend Framework 1.12

Zend Cache Tutorial - Zend Framework 1.12

Zend_Cache provides a flexible approach toward caching data, including support for tagging, manipulating, iterating, and removing data.

Question: What is Zend Cache?
It is Inbuilt component of zend framework which is used to speed up the application by using the caching concept.


Question: Why we use Zend Cache?
We use Zend cache for different purpose are following
  • Increase the website Performance.
  • Reduce the load on database.
  • Reduce the load of api, if using in application.
  • To get the result faster.


What is the use of  Zend Cache?
We can speedup our application as well as can reduce the burdon on database and API.
Zend_Cache use the file system to store the cache. We have option in zend cache to use the other caching component like Memcached, Sqlite, ibmemcached,Apc,Xcache and ZendPlatform etc. In this tutorial we will understand the zend_cache with file system.


How to Setup Zend Cache?
Step1: Add Following function Bootstrap
    public function _initCache() {
        $cache = Zend_Cache::factory(
                        'Core', 'File', array(
                    'lifetime' => 3600 * 24 * 7, /*caching time is 7 days*/                            
                    'automatic_serialization' => true
                        ), array('cache_dir' => APPLICATION_PATH . '/cache' /* This is caching folder where caching data will be stored and it must be writable by apache **/
                    )
        );
       
        Zend_Registry::set('Cache', $cache); /* set the cache object in zend_registery so that you can globally access*/
    }
Step2: cache folder must be writeable by PHP
Step3: Now, Just use the zend cache
        /* get the cache object */
        $cache = Zend_Registry::get('Cache');
        /* create a unique cache key */
        $cacheKey = "mydata";
        $result = array();
        if (empty($cacheKey) || ($result = $cache->load($cacheKey)) == false) {
            /*
            Here Process the and store the data in $result variable
            */            
            $cache->save($result, $cacheKey);
        }





What is Tagging in Zend Cache?
Tags are a way to categorize cache records. You can add two OR more type of records in single tag. You can create unlimited tags and also can add unlimited records in single tag.


How to used Tagging in Zend Cache.
        /* get the cache object */
        $cache = Zend_Registry::get('Cache');
        /* create a unique cache key */
        $cacheKey = "mydata";
        $result = array();
        if (empty($cacheKey) || ($result = $cache->load($cacheKey)) == false) {
            /*
            Here Process the and store the data in $result variable
            */            
            $cache->save($result, $cacheKey , array('Tags'));
        }


Can we add multiple Tags for 1 Record?
Yes, We can do.
$cache->save($result, $cacheKey , array('Tag1','Tag2','Tag3')); 


How can we clean one cache?
$cache->remove('idToRemove');


How to clean all records?
$cache->clean(Zend_Cache::CLEANING_MODE_ALL);


How to clean outdated records?
$cache->clean(Zend_Cache::CLEANING_MODE_OLD);


How to clean all records of one/more tags?
$cache->clean(
    Zend_Cache::CLEANING_MODE_MATCHING_TAG,
    array('Tag1', 'Tag2')
);

Thursday 24 July 2014

Important PHP Interview Questions and Answers - jQuery, SQL Modes, Client Programs and Reset

How to get jQuery nth Element
//include jQuery file
<script type="text/javascript" src="jquery.js"></script>
<script>
function go_to(id_number){     
     var obj=jQuery('div.mydiv ul li:nth-child('+id_number+') a');      
     alert(obj.html()) 
}
go_to(3);
</script>

jQuery Multiple File Upload Plugin
http://www.fyneworks.com/jquery/multiple-file-upload/#tab-Overview


jQuery Paging
Here you can table Sorting, Searching and Paging in Easy Way
http://www.datatables.net/examples/


Paypal return error : malformed

Hi,
I am using payapl gateway for payment in my project.
It is working fine for sandbox(test account) but no working for paypal (original paypal detail on client server);
It return following errror from paypal
  Array
    (
        [Error] => Array
            (
                [Number] =>  malformed
            )

    )



Solution: When you are sending amount in api call, sent amount with 2 digit decimal places. For Example 100.02 OR 22.32 


How to Download Openinviter?
You want to implement openInviter and your project is in Wordpress, Joomla, Drupal, Social engine, phpBB, Dolphin, Symfony & webmail. then Its maximum 2-5 min work. Just download the plugin/component & install in your application it will start working.


If your project is in some other CMS or Core PHP, then you need to download the files.
Include the file & call the appropriate function. It will start working...
http://openinviter.com/download.php


What is PHP?
PHP is language that enable web-developer to create the dynamic web pages with the use of HTML/CSS/JavaScript.


What is Full Form of PHP?
Full Form of PHP is Personal Home Page but now it stand for PHP: Hypertext Preprocessor


Who is Father of PHP?
Rasmus Lerdorf


When php was invented?
PHP was created by Rasmus Lerdorf in 1995


What is Rest
REpresentational Sate Transfer.
It is set of architectural rules by which you design a web service that focus on transfer of data from one server to another ignorance of operating system and language.
It was introduced in 2000.


What is Invoking Client Programs?
MySQL client programs can be invoked from the command line. For example from a Windows console prompt OR a Unix shell prompt.
For Example
shell> mysql -h localhost -p -u myname


What are Server SQL modes?
It define what SQL syntax, MySQL should support and what kind of data validation checks it should perform.
It easier to use MySQL in different environments.


How many server SQL modes?
The MySQL server can operate in different SQL modes, and can apply these modes differently for different clients.


Thanks for reading our page
http://www.web-technology-experts-notes.in/2014/07/important-php-interview-questions-and-Answers.html

Thursday 5 June 2014

PHP DataStructures

Data structure is a way of storing and organizing data in a computer so that it can be used efficiently. It provide a efficient way to manage large amounts of data efficiently, such as large databases and Internet indexing services.


SPL provides a following set of standard datastructures.
SplDoublyLinkedList: The SplDoublyLinkedList class provides the main functionalities of a doubly linked list.

SplStack
The SplStack class provides the main functionalities of a stack implemented using a doubly linked list.

SplQueue
The SplQueue class provides the main functionalities of a queue implemented using a doubly linked list.
See Example
echo "Create Object of SplQueue:";
$obj = new SplQueue();

echo "
Check for Queue, is it Empty:";
if($obj->isEmpty())
{
    $obj->enqueue("Simple");
    $obj->enqueue("Example");
    $obj->enqueue("Of");
    $obj->enqueue("PHP");
}
echo "
View queue:";
print_r($obj);
if(! $obj->offsetExists(4))
{
    $obj->enqueue(10);
}
print_r($obj);
echo "
"; echo " Get the value of the offset at 3 "; if($obj->offsetGet(3)) { echo $obj->offsetGet(3); echo " Resetting the value of a node:"; $obj->offsetSet(4,6); }
SplHeap The SplHeap class provides the main functionalities of a Heap. Heaps are crucial in several efficient graph algorithms such as Dijkstra's algorithm, and in the sorting algorithm heapsort.

SplMaxHeap The SplMaxHeap class provides the main functionalities of a heap, keeping the maximum on the top.

SplMinHeap The SplMinHeap class provides the main functionalities of a heap, keeping the minimum on the top.


SplPriorityQueue The SplPriorityQueue class provides the main functionalists of an functionalists of an prioritized queue, implemented using a max heap.

SplFixedArray The SplFixedArray class provides the main functionalities of array. The main differences between a SplFixedArray and a normal PHP array is that the SplFixedArray is of fixed length and allows only integers within the range as indexes. The advantage is that it allows a faster array implementation. See Example Below
$array = new SplFixedArray(5);
$array[1] = 2;
$array[4] = "foo";
var_dump($array[0]); // NULL
var_dump($array[1]); // int(2)

var_dump($array["5"]); // Fatal error: Uncaught exception 'RuntimeException' with message 'Index invalid or out of range'

SplObjectStorage The SplObjectStorage class provides a map from objects to data or, by ignoring data, an object set. This dual purpose can be useful in many cases involving the need to uniquely identify objects. 

Monday 19 May 2014

PHP Check Mime Type of File - Return Information About A File

PHP Check Mime Type of File - Return Information About A File

Now a days, we are uploading files like Profile images, Video files OR excel files in our web application. 
With uploading these files there are chances some user upload the .exe file (Virus) by renaming the .exe into .jpg, which can damage website.

You might have added the extension check from javaScript as well as PHP. But this is not enough from security end because someone can upload the file after changing the extension of file( ".exe" to ".png"). In this case your security check will be failed.

What to do.
Answer is  check the Mime of file before get uploaded in your web server.

How to do this
"fileinfo" is extension which must be enabled in your php.ini. (for existence you can check  in phpinfo)
If this extension is not enabled ask your server admin, he will do this for you OR you can also do this your self (http://php.net/manual/en/fileinfo.installation.php).


After installing the fileinfo extension, use following code to get the mime type of file before get uploaded in web server.
if (function_exists("finfo_file")) {
    $finfo = finfo_open(FILEINFO_MIME_TYPE);    

    //file which you want to check the mime of the file
    $file = $_SERVER['DOCUMENT_ROOT'] . '/images/feedback.png';    //file which is going to get uploaded in web server
    try {
        $type = finfo_file($finfo,$file);        
        echo "File Type: ".$type;
    } catch (Exception $e) {
        echo $e->getMessage();
    }
} else {
    echo "'finfo_file' is Not installed";
}


When you execute above code, if will get the mime-type of file. This is directly checking the mime type of already uploaded file.
You can use $type = finfo_file($finfo,$file); for checking the file type, before using move_uploaded_file function.

Wednesday 5 March 2014

Zend Database Query - Zend Profiler Example - Code Snippets

Zend Profiler: It is used to display the queries executed by zend indirectly with MySql. It will show all the queries like insert, update, delete etc.

Zend Profiler is very important just because it show the queries but It can help you to improve the performance of your website.

See How you can use the Zend Profiler.
  1. With zend profiler you will get to know what type of queries are running in your application and which is making slow your website.
  2. Zend Profiler also also how much time each query is taking to execute.
  3. you can get to know, what are un-necessary queries are running
  4. What queries are running multiple times
  5. For future you can store these queries for further use.


 See below Example, How to use zend Profiler

//create class
class Application_Model_Test extends Zend_Db_Table_Abstract {
    protected $_name = 'tests';
    protected $_primary = 'id';

    //create function
    function insertData($data) {
        /** enable the zend profiler **/
        $this->getAdapter()->getProfiler()->setEnabled(true);
        $profiler = $this->getAdapter()->getProfiler();
        /** enable the zend profiler **/

        //save data
        $this->insert($data);

        /** to list the mysql queries * */
        foreach ($profiler->getQueryProfiles() as $query) {
            $sqlQuery = $query->getQuery();
            $params = $query->getQueryParams();
            echo $sqlQuery = str_replace(array('?'), $params, $sqlQuery);
            echo '';            
        }
        
        /** to list the mysql queries * */
    }
}




5 Best Related Posts are Following:1. Web service - current time zone for a city- Free API
2. Zend Gdata Youtube API - Search Video - View Video Detail
3. Download the video from Amazon Simple Storage Service S3
4. How to set Cron in Zend Framework
5. Zend Cache Tutorial - Zend Framework 1.12 

Wednesday 26 February 2014

Export to CSV File - PHP

Export to CSV File - PHP

CSV is a simple file format that is widely used by IT Professional, business, and all who are familar with computer. Those who use computer in day to day life, they know how to use CSV/Excel. Among its most common uses is to move tabular data between programs that naturally operate on a more efficient or complete proprietary format. This file is easily readable even in mobile with use of some basic apps.

In Web Technology fileld,  number of times we have the send Stats, Logs and detail to our client in Form of CSV files.  Event may times we got the Text in form of excel/CSV Fle.

Now, Export the PHP data into CSV is very simple. Just  you need to do few simple steps.
  1. Save into into PHP multidimensional array
  2. Set the header
  3. Now, render the rows and then render EOL (First Row)
  4. Now, render the rows and then render EOL (Second Row)
  5. Now, render the rows and then render EOL  (Third Row and so on)
 Here EOL is End of Line.

Code Snippet
$lists = array(
    array(
        'Web', 'Technology', 'Experts', 'Notes',
    ),
    array(
        'Web1', 'Technology1', 'Experts1', 'Notes1',
    ),
    array(
        'Web2', 'Technology2', 'Experts2', 'Notes2'
    ),
    array(
        'Web3', 'Technology3', 'Experts3', 'Notes3',
    ),
    array(
        'Web4', 'Technology4', 'Experts4', 'Notes4',
    ),
    array(
        'Web5', 'Technology6', 'Experts5', 'Notes5',
    )
);

header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=csv.csv");
header("Pragma: no-cache");
header("Expires: 0");

//header
echo  "Title1, Title2,Title3, Title4 \n";

foreach ($lists as $list) {
    echo implode(',', $list);
    echo PHP_EOL;
}

Saturday 22 February 2014

htaccess code snippets example

htaccess code snippets example

.htaccess file is used for configuration on File Level/Directory Level and its supported by all webserver. Today all types of websites use htaccess technology.



Following are Benefits of .htaccess
  • Mange Error Pages for Better SEO
  • Set PHP Config variable
  • Set Environment variable
  • Password protection for File/Directory
  • Allow/Deny visitors by IP Address
  • Detect OS (like Mobile/Laptop/Ios/Android)
  • Redirection pages 
  • Optimize Performance of website
  • Improve Site Security


Following are Few Example of .htaccess

Redirect Home page to Another Website
Redirect / http://php-tutorial-php.blogspot.in/


Redirect Home page to Another another Directory(i.e newdir)
Redirect / /newdir


Redirect about.html to Another another Directory(i.e /pages/about)
Redirect /about.html /pages/about


Redirect old file to New Path
Redirect /oldfile.html /newfile.html


Set PHP Environment
SetEnv APPLICATION_ENV development


Set max_filesize in php
php_value upload_max_filesize 32M


Set off error in PHP
php_flag display_errors off
php_flag display_startup_errors off


Dedect mobile/laptop and redirect to mobile site
RewriteCond %{HTTP_USER_AGENT} android|avantgo|blackberry|blazer|compal|elaine|fennec|hiptop|ipad|ipod|iemobile|ip(hone|od)|iris|kindle|lge\ |maemo|midp|mmp|opera\ m(ob|in)i|palm(\ os)?|phone|p(ixi|re)\/|plucker|pocket|psp|symbian|treo|up\.(browser|link)|vodafone|wap|windows\ (ce|phone)|xda|xiino [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^(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)|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)|hp(\ i|ip)|hs\-c|ht(c(\-|\ |_|a|g|p|s|t)|tp)|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|e\-|e\/|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(di|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|xda(\-|2|g)|yas\-|your|zeto|zte\-) [NC]
RewriteRule ^$ http://mobile.domain.com/ [R,L]


Block IP Address
order allow,deny
deny from xxx.xxx.xxx.xxx #specify a specific address
deny from xxx.xxx.xxx.xxx/30 #specify a subnet range
deny from xxx.xxx.* #specify an IP address wildcard
allow from all


Allow IP Address
order allow,deny
allow from xxx.xxx.xxx.xxx #specify a specific address
allow from xxx.xxx.xxx.xxx/30 #specify a subnet range
allow from xxx.xxx.* #specify an IP address wildcard
allow from all


Redirect to 400.html, If 400 error comes
ErrorDocument 400 /errorpages/400.html


Redirect to 403.html, If 403 error comes
ErrorDocument 403 /errorpages/403.html


Redirect to 404.html, If 404 error comes
ErrorDocument 404 /errorpages/404.html


Redirect to 500.html, If 500 error comes
ErrorDocument 500 /errorpages/500.html


Disable Directory Listing
Options ExecCGI Includes IncludesNOEXEC SymLinksIfOwnerMatch -Indexes


Enable Directory Listing
 Options All +Indexes


Password Protection
AuthName "Authentication Section"
AuthType Basic
AuthUserFile /home/username/.htpasswds #Here your password will be stored
#htpasswds file format username:password
Require valid-user


Password Protection but Google can Crawl
AuthName "Under Development"
AuthUserFile /home/website/.htpasswd
AuthType basic
Require valid-user
Order deny,allow
Deny from all
Allow from xxx.xxx.xxx.xxx w3.org htmlhelp.com googlebot.com
Satisfy Any


Set Timezone of the Server
SetEnv TZ America/Indianapolis


301 Redirect Old File
Redirect 301 /old/file.html http://php-tutorial-php.blogspot.in/2013/12/curl-example.html


301 Redirect Entire Directory
Redirect 301 /old/ /new/



301 redirect https to http
RewriteEngine On
RewriteCond %{HTTPS} on
RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]


301 redirect https to http://www
RewriteEngine On
RewriteCond %{HTTPS} on
RewriteRule (.*) http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]


301 redirect non www to www with htaccess
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]


Set Caching for javascript/image/css
ExpiresActive On
ExpiresByType application/javascript "now plus 3 day"
ExpiresByType application/x-javascript "now plus 3 day"
ExpiresByType image/jpg "now plus 1 week"
ExpiresByType image/jpeg "now plus 1 week"
ExpiresByType image/png "now plus 1 week"
ExpiresByType image/pjpeg "now plus 1 week"
ExpiresByType image/gif "now plus 1 week"
ExpiresByType text/css "now plus 3 day"


Error Codes - Defination
301 - Permanent movement(redirection)
302 - Temporary movement(redirection)
400 - Bad request
401 - Authorization Required
403 - Forbidden
404 - Page Not Found
500 - Internal Server Error


Saturday 14 December 2013

CURL Example

CURL
CURL is a library and command-line tool for transferring data using various protocols like HTTP, FTP, SCP, PUT, POST, POP3 & SMTP etc. It also used for scrapping the data from websites. We can scrap get the text as well as images with use of CURL.


It have two products libcurl and cURL.

cURL: Its command line tool for transferring information.
Libcurl: It is a free client-side URL transfer library.


CURL COMMAND-LINE EXAMPLE

Curl Example with "GET" Method (By Default GET)
curl http://www.web-technology-experts-notes.in/p/sitemap.html

Curl Example with "POST" Method
curl --request POST http://www.web-technology-experts-notes.in/p/sitemap.html

Curl Example with "PUT" Method
curl --request PUT http://www.web-technology-experts-notes.in/p/sitemap.html

Curl Example with "DELETE" Method
curl --request DELETE http://www.web-technology-experts-notes.in/p/sitemap.html

Curl Example with "POST" Method and pass data (Data: username, password & logintype)
curl --request POST http://www.web-technology-experts-notes.in/p/sitemap.html
--data 'username=user&password=****&logintype=normal' 

Curl Example with "POST" Method and pass data(data in text file)
curl --request POST http://www.web-technology-experts-notes.in/p/sitemap.html --data @datafile.txt

Curl Example with "POST" Method, pass data and pass header
curl --request POST http://www.web-technology-experts-notes.in/p/sitemap.html --data @datafile.txt --header 'sessionid:9874563211235884' 

Curl Example with "POST" Method, pass data and pass header (Get Header in response) --include
curl --request POST http://www.web-technology-experts-notes.in/p/sitemap.html --data @datafile.txt --header 'sessionid:9874563211235884' --include

CURL LIBCURL EXAMPLE

Mostly to get data from an REST API, we use following method in php
echo file_get_contents('http://www.web-technology-experts-notes.in/p/sitemap.html');
But if, "allow_url_fopen" is disable in php.ini file due to security reason then above will not work. You need to use below code
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.google.co.in");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
$output = curl_exec($ch);
curl_close($ch);
echo $output;die;


CURL Example with Post Method with parameter
$url = "http://localhost/test/index2";
$post_data = array(
            "foo" => "bar",
            "foo1" => "testdata"
);
try {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
    $output = curl_exec($ch);
    curl_close($ch);
} catch (Exception $e) {
    echo $e->getMessage();die;
}

File Upload with CURL in PHP
 $file_name_with_full_path = realpath('uploadFile.zip');        
        $url = "http://localhost/test/index2";
        $post_data = array(
            "foo" => "bar",
            "upload" => "@".$file_name_with_full_path
        );
        try {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
            $output = curl_exec($ch);
            curl_close($ch);
        } catch (Exception $e) {
            echo $e->getMessage();
            die;
        }
        
Transfer the File through FTP
curl_setopt_array($ch, array(
    CURLOPT_URL => 'ftp://ftp.example.com/test.txt',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_USERPWD => 'username:password'
));
 
$output = curl_exec($ch);

Set Header and Json data in Curl
$url='http://www.web-technology-experts-notes.in/';
$jsonData='{"name":"arun","email":"arun@gmail.com"}';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  'X-API-Token: ' . X_API_TOKEN,
  'Content-Type: application/json',
  "HTTP_X_FORWARDED_FOR: xxx.xxx.x.xx"
));

curl_setopt($ch, CURLOPT_INTERFACE, "xxx.xxx.x.xx");
echo curl_exec($ch);
curl_close($ch);
Following are some Options which can be set be set in "curl_setopt" function


CURLOPT_REFERER - Set the Http Refer

CURLOPT_USERAGENT - Set the UserAgent

CURLOPT_HEADER - Include the header in response or not

CURLOPT_RETURNTRANSFER - Print the output or not

CURLOPT_URL - Set the URL (Uniform Resource Locator)

CURLOPT_POST - set 0 or 1 for post method

CURLOPT_POSTFIELDS - set the data which you want to post

CURLOPT_FOLLOWLOCATION - if set true, cURL will follow redirects

CURLOPT_CONNECTTIMEOUT -Total seconds to spend attempting to connect

CURLOPT_TIMEOUT - Total Seconds to allow cURL to execute






Zend Curl Example

$config = array(
    'adapter' => 'Zend_Http_Client_Adapter_Curl',
    'ssltransport' => 'tls',
    'strict' => false,
    'persistent' => true,
);
$url = 'http://www.example.com';
$client = new Zend_Http_Client($url, $config);
$postArray = array('name'=>'Georage','age'=>33);
$client->setParameterPost($postArray);
/** set Headers **/
$client->setHeaders(array(
    'Host: www.example.com',
    'User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0',
    'Accept: text/javascript, application/javascript, */*',
    'Accept-Language: en-gb,en;q=0.5',
    'Accept-Encoding: gzip, deflate',
    'Content-Type: application/x-www-form-urlencoded; charset=UTF-8',
    'X-Requested-With: XMLHttpRequest',
    'Referer: http://example.com'
));

/** set cookie **/
$client->setCookie('__utma', '174057141.1507422797.1392357517.1392698281.1392702703.3');
$client->setCookie('__utmz', '174057141.1392357517.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)');
$client->setCookie('__atuvc', '58');
$client->setCookie('PHPSESSID', '0a12ket5d8d7otlo6uh66p658a5');
$response = $client->request('POST');

$data= $response->getBody();
echo $data; 

Zend CURL Ignore SSL_VERIFYPEER
$url='www.example.com';
$config = array(
    'adapter' => 'Zend_Http_Client_Adapter_Curl',
    'curloptions' => array(
        CURLOPT_FOLLOWLOCATION => TRUE,
        CURLOPT_SSL_VERIFYPEER => FALSE
    ),
);
 $client = new Zend_Http_Client($url, $config);
 $response = $client->request('GET');

Set CURL'S Timeout in Milli-seconds
 $ch = curl_init();
          //set the curl for crawl
          curl_setopt($ch, CURLOPT_URL, "http://www.web-technology-experts-notes.in/2014/03/captcha-code-example.html");
          //include the header in the output
          curl_setopt($ch, CURLOPT_HEADER, 0);
          //The number of seconds to wait while trying to connect. Use 0 to wait indefinitely.
          curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 0);
          //The maximum number of milliseconds to allow cURL functions to execute.
          curl_setopt($ch, CURLOPT_TIMEOUT_MS, 4000); //timeout in seconds
          $output = curl_exec($ch);
          curl_close($ch); 

Set Zend CURL'S Timeout in Milli-seconds
$config = array(
            'adapter' => 'Zend_Http_Client_Adapter_Curl',
            'curloptions' => array(
                CURLOPT_FOLLOWLOCATION => FALSE,
                CURLOPT_HEADER => false,
                //The number of seconds to wait while trying to connect. Use 0 to wait indefinitely.
                CURLOPT_TIMEOUT_MS => 3000,
                //The maximum number of milliseconds to allow cURL functions to execute.
                CURLOPT_CONNECTTIMEOUT_MS => 3000
            )
        );
        $url = "http://www.web-technology-experts-notes.in/2014/03/captcha-code-example.html";
        $client = new Zend_Http_Client($url, $config);
        $response = $client->request('GET');
        $output = $response->getBody();



Question: How to Set the username/password in CURL?
curl -X POST -u "USERNAME":"PASSWORD" --header "Content-Type: audio/flac" --header "Transfer-Encoding: chunked"  "https://stream.watsonplatform.net/speech-to-text/api/v1/recognize" 



Question: How to pass binary data(file) in CURL ?
curl -X POST -u "USERNAME":"PASSWORD" --header "Content-Type: audio/flac" --header "Transfer-Encoding: chunked" --data-binary @audio.flac "https://stream.watsonplatform.net/speech-to-text/api/v1/recognize" 



Question: How to store linux command output in file?
curl -X POST -u "USERNAME":"PASSWORD" --header "Content-Type: audio/flac" --header "Transfer-Encoding: chunked" --data-binary @audio.flac "https://stream.watsonplatform.net/speech-to-text/api/v1/recognize" > output1.txt