Saturday, 14 January 2017

PHP CURL POST & GET Examples – Submit Form using PHP CURL

PHP CURL POST & GET Examples – Submit Form using PHP CURL


In PHP CURL POST tutorial, I have explained how to send HTTP GET / POST requests with PHP CURL library.

Below are the examples covered in this article.
1) Send HTTP GET Request with CURL
2) Send HTTP POST Requests with CURL
3) Send Random User-Agent in the Requests
4) Handle redirects (HTTP 301,302)
5) Handle Errors.


Why we need PHP CURL ?

 
To send HTTP GET requests, simply we can use file_get_contents() method.
file_get_contents('http://gauravyadav94.blogspot.in/');

But sending POST request and handling errors are not easy with file_get_contents().

Sending HTTP requests is very simple with PHP CURL.You need to follow the four steps to send request.

 
step 1). Initialize CURL session    


$ch = curl_init();


step 2). Provide options for the CURL session   


curl_setopt($ch,CURLOPT_URL,"http://gauravyadav94.blogspot.in/");
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
//curl_setopt($ch,CURLOPT_HEADER, true); //if you want headers


CURLOPT_URL -> URL to fetch
CURLOPT_HEADER -> to include the header/not
CURLOPT_RETURNTRANSFER -> if it is set to true, data is returned as string instead of outputting it.

For full list of options, check this PHP Documentation.

step 3). Execute the CURL session  
$output=curl_exec($ch);


step 4). Close the session  
curl_close($ch);

Note: You can check whether CURL enabled/not with the following code.    
if(is_callable('curl_init')){
   echo "Enabled";
}
else
{
   echo "Not enabled";
}


1.PHP CURL GET Example

You can use the below code to send GET request.
   
function httpGet($url)
{
    $ch = curl_init(); 

    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
//  curl_setopt($ch,CURLOPT_HEADER, false);

    $output=curl_exec($ch);

    curl_close($ch);
    return $output;
}

echo httpGet("
http://gauravyadav94.blogspot.in/");


2.PHP CURL POST Example

PHP CURL POST & GET Examples
You can use the below code to submit form using PHP CURL.
   
function httpPost($url,$params)
{
  $postData = '';
   //create name value pairs seperated by &
   foreach($params as $k => $v)
   {
      $postData .= $k . '='.$v.'&';
   }
   $postData = rtrim($postData, '&');

    $ch = curl_init(); 

    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
    curl_setopt($ch,CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_POST, count($postData));
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);   

    $output=curl_exec($ch);

    curl_close($ch);
    return $output;

}

How to use the function:
   
$params = array(
   "name" => "Ravishanker Kusuma",
   "age" => "32",
   "location" => "India"
);


echo httpPost("http://
http://gauravyadav94.blogspot.in/examples/php/curl-examples/post.php",$params);


3.Send Random User-Agent in the Requests

You can use the below function to get Random User-Agent.  
function getRandomUserAgent()
{
    $userAgents=array(
        "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6",
        "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)",
        "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30)",
        "Opera/9.20 (Windows NT 6.0; U; en)",
        "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; en) Opera 8.50",
        "Mozilla/4.0 (compatible; MSIE 6.0; MSIE 5.5; Windows NT 5.1) Opera 7.02 [en]",
        "Mozilla/5.0 (Macintosh; U; PPC Mac OS X Mach-O; fr; rv:1.7) Gecko/20040624 Firefox/0.9",
        "Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en) AppleWebKit/48 (like Gecko) Safari/48"      
    );
    $random = rand(0,count($userAgents)-1);

    return $userAgents[$random];
}

Using CURLOPT_USERAGENT, you can set User-Agent string.
1  
curl_setopt($ch,CURLOPT_USERAGENT,getRandomUserAgent());


4.Handle redirects (HTTP 301,302)

To handle URL redirects, set CURLOPT_FOLLOWLOCATION to TRUE.Maximum number of redirects can be controlled using CURLOPT_MAXREDIRS.

curl_setopt($ch,CURLOPT_FOLLOWLOCATION,TRUE);
curl_setopt($ch,CURLOPT_MAXREDIRS,2);//only 2 redirects


5.How to handle CURL errors

we can use curl_errno(),curl_error() methods, to get the last errors for the current session.
curl_error($ch) -> returns error as string
curl_errno($ch) -> returns error number
You can use the below code to handle errors.  
function httpGetWithErros($url)
{
    $ch = curl_init(); 

    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);

    $output=curl_exec($ch);

    if($output === false)
    {
        echo "Error Number:".curl_errno($ch)."<br>";
        echo "Error String:".curl_error($ch);
    }
    curl_close($ch);
    return $output;
}

For the full list of errors, refer CURL errors

 

Wednesday, 4 January 2017

How They Hack Your Website

SQL Injection

SQL Injection involves entering SQL code into web forms, eg. login fields, or into the browser address field, to access and manipulate the database behind the site, system or application.When you enter text in the Username and Password fields of a login screen, the data you input is typically inserted into an SQL command. This command checks the data you've entered against the relevant table in the database. If your input matches table/row data, you're granted access (in the case of a login screen). If not, you're knocked back out.


The Simple SQL Injection Hack

In its simplest form, this is how the SQL Injection works. It's impossible to explain this without reverting to code for just a moment. Don't worry, it will all be over soon.

Suppose we enter the following string in a Username field:

' OR 1=1

double-dash-txt.png
The authorization SQL query that is run by the server, the command which must be satisfied to allow access, will be something along the lines of:

SELECT * FROM users WHERE username = ?USRTEXT '
AND password = ?PASSTEXT?

...where USRTEXT and PASSTEXT are what the user enters in the login fields of the web form.

So entering `OR 1=1 -- as your username, could result in the following actually being run:

SELECT * FROM users WHERE username = ?' OR 1=1 -- 'AND password = '?

Two things you need to know about this:
['] closes the [username] text field.

'

double-dash-txt.png
' is the SQL convention for Commenting code, and everything after Comment is ignored. So the actual routine now becomes:
SELECT * FROM users WHERE username = '' OR 1=1

1 is always equal to 1, last time I checked. So the authorization routine is now validated, and we are ushered in the front door to wreck havoc.

Tuesday, 3 January 2017

How do I get a YouTube video thumbnail from the YouTube API?

Each YouTube video has 4 generated images. They are predictably formatted as follows:

https://img.youtube.com/vi/<insert-youtube-video-id-here>/0.jpg
https://img.youtube.com/vi/<insert-youtube-video-id-here>/1.jpg
https://img.youtube.com/vi/<insert-youtube-video-id-here>/2.jpg
https://img.youtube.com/vi/<insert-youtube-video-id-here>/3.jpg
The first one in the list is a full size image and others are thumbnail images. The default thumbnail image (ie. one of 1.jpg, 2.jpg, 3.jpg) is:

https://img.youtube.com/vi/<insert-youtube-video-id-here>/default.jpg
For the high quality version of the thumbnail use a url similar to this:

https://img.youtube.com/vi/<insert-youtube-video-id-here>/hqdefault.jpg
There is also a medium quality version of the thumbnail, using a url similar to the HQ:

https://img.youtube.com/vi/<insert-youtube-video-id-here>/mqdefault.jpg
For the standard definition version of the thumbnail, use a url similar to this:

https://img.youtube.com/vi/<insert-youtube-video-id-here>/sddefault.jpg
For the maximum resolution version of the thumbnail use a url similar to this:

https://img.youtube.com/vi/<insert-youtube-video-id-here>/maxresdefault.jpg
All of the above urls are available over http too. Additionally, the slightly shorter hostname i3.ytimg.com works in place of img.youtube.com in the example urls above.