I was recently working on a project where I needed to integrate an external API using HTTP cURL requests. It was my first time doing this and I had a lot of problems figuring this out. I wrote this post so I can remember my cURL API calls for next time, and maybe it can help you as well.

The API calls and functions I’m using in this post are all working examples on PHP -v 5.6.

REST API calls with cURL, PHP and json

PHP cURL Basics

cURL stands for ‘Client URL Library’ and it allows you to connect and communicate with different types of servers with many different types of protocols (HTTP, https, FTP, proxy, cookies, …). More info about how cURL actually works can be found in the official PHP documentation. This article will provide more in-depth examples for integrating your applications.

I’ve received a lot of responses on ‘how does cURL actually work’ and I get the feeling that people don’t know what’s going on in a cURL call. Before we start with the article and our cURL setup, I’ve added a simple example of a plain cURL request. The request will return the API response as a string.

// create & initialize a curl session
$curl = curl_init();

// set our url with curl_setopt()
curl_setopt($curl, CURLOPT_URL, "api.example.com");

// return the transfer as a string, also with setopt()
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

// curl_exec() executes the started curl session
// $output contains the output string
$output = curl_exec($curl);

// close curl resource to free up system resources
// (deletes the variable made by curl_init)

Note that we stored our curl_exec() in a variable $output. This $output variable is still available in our program even after we closed it with curl_close(). So after we did our call and closed the connection, we can still access the result using our $output variable.

Now that we understand the basics, let’s try to put this into a function we can reuse within our application.

cURL setup

Implementing an external API into your project is probably going to take more than just one API call and from different pages in your project. This is why I’ve created a ‘simple’ PHP script that allows us to call this function, with a set of parameters, and a cURL request will be done.

Make sure to put this code into a file or place that can be accessed by your entire app or website. (I’ve updated this function so we’ll be able to define the headers when we’re making the call. I’ve added a section for custom headers at the bottom!)

function callAPI($method, $url, $data){
   $curl = curl_init();
   switch ($method){
      case "POST":
         curl_setopt($curl, CURLOPT_POST, 1);
         if ($data)
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
      case "PUT":
         curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
         if ($data)
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);			 					
         if ($data)
            $url = sprintf("%s?%s", $url, http_build_query($data));
   // OPTIONS:
   curl_setopt($curl, CURLOPT_URL, $url);
   curl_setopt($curl, CURLOPT_HTTPHEADER, array(
      'APIKEY: 111111111111111111111',
      'Content-Type: application/json',
   curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
   curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
   // EXECUTE:
   $result = curl_exec($curl);
   if(!$result){die("Connection Failure");}
   return $result;

This is a basic setup for doing a cURL call and I’m using a switch statement to check if the API call will be a POST, PUT, or something else (get or delete). I’ll go deeper into the switch case while we’re doing the specific requests.

I’m using if-statements inside the switch-case to see if we want to provide JSON data into our call or not. For the POST and PUT request the if-statement is not really necessary because we’re only using POST or PUT with data, but it’s an extra security to make sure our call function won’t break.

cURL GET request

The most simple API call is the GET call, so let’s start with that! Our callAPI function expects 3 parameters: $method, $url and $data. We need to give those parameters to all our API calls, so for a GET we can just set $data on false, because we are not passing any data with a GET call.

$get_data = callAPI('GET', 'https://api.example.com/get_url/'.$user['User']['customer_id'], false);
$response = json_decode($get_data, true);
$errors = $response['response']['errors'];
$data = $response['response']['data'][0];

$get_data already returns all the data we want from the API in a json string. I’m using $response to convert the json string back to a usable PHP array. You can skip those steps if you want, this is my personal preference. I’m also using the extra $errors and $data arrays to store the actual data and errors.

cURL POST request

Obviously, a POST request does require data. Make sure your json-data is correct, otherwise the request will keep returning errors. Although… If we receive errors from the API, that means our calls are working 😉

In my example I’m using the CakePHP syntax for setting up my json array, so don’t mind that.

$data_array =  array(
      "customer"        => $user['User']['customer_id'],
      "payment"         => array(
            "number"         => $this->request->data['account'],
            "routing"        => $this->request->data['routing'],
            "method"         => $this->request->data['method']
$make_call = callAPI('POST', 'https://api.example.com/post_url/', json_encode($data_array));
$response = json_decode($make_call, true);
$errors   = $response['response']['errors'];
$data     = $response['response']['data'][0];

Because we’re doing an API call with json data, I’m converting my PHP array to a json string with json_encode($data_array);. The response will come in as a json string again, so I’m using json_decode($make_call, true); to convert the json string back to a usable PHP array. Same as we did in our GET call, so you can skip these steps again if you don’t need them.

cURL PUT request

The PUT request is almost the same as the POST request. I had a hard time figuring out how to pass data into a PUT call. If we take a look at our callAPI() function, you see that I changed some things up between the PUT and the POST request. We can still use the same parameters in our callAPI() function as always.

$data_array =  array(
   "amount" => (string)($lease['amount'] / $tenant_count)
$update_plan = callAPI('PUT', 'https://api.example.com/put_url/'.$lease['plan_id'], json_encode($data_array));
$response = json_decode($update_plan, true);
$errors = $response['response']['errors'];
$data = $response['response']['data'][0];

cURL DELETE request

The delete request is very simple again. We can just hit the API url with the $id we want to remove and poof… it’s gone forever.

callAPI('DELETE', 'https://api.example.com/delete_url/' . $id, false);

What with flexible headers?

In the beginning we defined our callAPI function with preset headers. But what if we, for some reason, need to change the headers a bit for another call? We don’t want to write a whole new callAPI function just to edit some headers. Therefore, here’s an option on how to make the preset headers flexible:

function callAPI($method, $url, $data, $headers = false){
   $curl = curl_init();
   switch ($method){
   // OPTIONS:
   curl_setopt($curl, CURLOPT_URL, $url);
       curl_setopt($curl, CURLOPT_HTTPHEADER, array(
          'APIKEY: 111111111111111111111',
          'Content-Type: application/json',
       curl_setopt($curl, CURLOPT_HTTPHEADER, array(
          'APIKEY: 111111111111111111111',
          'Content-Type: application/json',
   curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
   curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
   // EXECUTE:

There are 2 differences here from our first function. 1: We’ve added an extra parameter in our function to define if we want to use a custom header or not. I put it to $headers = false to give it a default value. Now we’re not required to enter our headers with every call.

The second change is the if-statement when we’re setting the API headers. If we didn’t give in any headers when we make the call, it’s going to use our default headers instead of crashing. Now we’re ready to add custom headers with our call!

In this example, I’m using search parameters to search for specific data before I’ll pull in all the data with the API. To make the search, I obviously need to be able to add my search query into my callAPI headers. Here’s my example:

Creating custom headers before our call

$one_month_ago = date("Y-m-d", strtotime(date("Y-m-d", strtotime(date("Y-m-d"))) . "-1 month"));
$rent_header = 'Search: and[][created][greater]=' . $one_month_ago . '%and[][created][less]=' . date('Y-m-d') . '%';
//the actual call with custom search header
$make_call = callAPI('GET', 'https://api.example.com/get_url/', false, $rent_header);

This is just an example on how to add headers. My example is to get all rows where a rent was paid in the last 30 days. $one_month_ago is just a helper variable. The $rent_header is the actual header I want to add to my default headers. This needs to be a string!!

When you’ve set the header, you can just do a regular api call and add your new header at the end.

I didn’t need to use any other API call methods like patch or purge or anything like that. These you need to figure out yourself. If there’s some magic going on in this post I hope my examples can give you a better understanding.

I recently wrote a part 2 for this post, that will talk about generating an AUTH-key (utoken) before we make our calls. Make sure to check it out here as well!

sources: https://weichie.com/blog/curl-api-calls-with-php/


if  You’re concatenating the POST arguments in to a single string and then include it in an array but they should be individually presented; that can be done in as follows:

curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query(array(
 'code' => $code,
 'client_id' => $oauth2_client_id,
 'redirect_uri' => $oauth2_redirect,
 'grant_type' => 'authorization_code'

source: https://stackoverflow.com/questions/37496346/php-curl-grant-type-invalid-unsupported

Apache Fix

If your site is served by Apache, and you have access to Apache config files, there is a very simple way of preventing access to git files.

Open /etc/apache2/conf-enabled/security.conf for editing:

sudo nano /etc/apache2/conf-enabled/security.conf

You will see the following block:

# Forbid access to version control directories
# If you use version control systems in your document root, you should
# probably deny access to their directories. For example, for subversion:
#<DirectoryMatch "/\.svn">
# Require all denied

Amend this to:

# Forbid access to version control directories
# If you use version control systems in your document root, you should
# probably deny access to their directories. For example, for subversion:
<DirectoryMatch "/\.git">
Require all denied

Save (ctrl + o) and exit (ctrl + x) and restart apache:

sudo service apache2 restart

Now try accessing the .git/config file. You should see something like this:

You don't have permission to access /wp-content/themes/david/.git/config on this server.

If you DO NOT have access to Apache config files, add these lines to a .htaccess file in your project root:

# ==================================================================
# Prevent .git access
# ==================================================================

RedirectMatch 404 /\.git

source: https://davidegan.me/hide-git-repos-on-public-sites/

Download composer dengan menggunakan Curl lewat terminal, jalankan perintah dibawah ini:

curl -sS https://getcomposer.org/installer | php

kemudian jalankan perintah berikut ini untuk mengubah privileges file:

chmod a+x composer.phar

Tambahkan kode berikut ini di .bash_profile

alias composer='php /usr/local/bin/composer.phar'

Untuk mengetes, jalankan perintah composer maka akan muncul seperti berikut:

Hi guys! First of all, I just want to tell you that this is my first time writing a blog on Medium. Another thing is I am not an English speaker but I am Thai. Thus, if there are anything wrong grammatically and technically, please help me correct them! Alright, let’s begin!!!

If you are not struggling with Laravel or Laradock installation in offical website (https://laravel.com/) (http://laradock.io), you can skip this article.

For me, I was confusing when I first tried to install them. This is the reason why I am writing this article.

What is Laravel?

Simply, Laravel framework is a PHP framework for web application development that using MVC (Model-View-Controller) model.

Before using a wonderful Laravel, you NEED to set an environment for it. That is difficult and take a while to understand.

So, there are 3 options here as follow:

  1. Using Homestead
  2. Using Valet
  3. Using Laradock — > Highly recommended !!

Option 1: Using Homestead

Homestead is a virtual machine. Then, you will need VMWare or VirtualBox. It provides everything you need to fully develop web with Laravel.

I will not talk in details much in this option since it requires more storage than other options. You can look for more details Here

Option 2: Using Valet

Valet provides a light-weight local development environment that is fast. But it does not support everything. If you want only PHP and MySQL, it is your choice. Important thing is Valet is only for Mac user.

Option 3: Laradock

I am using this option. It is flexible and take advantages of Docker. Before using this option, you should study about Docker (Here). It will significantly help you in web development.

  1. Install Docker CE

download Docker Community Edition for Mac from Link. You need register in order use Docker.

2. Install Composer

download Composer from Link

3. Create Laravel project via composer

Open a terminal and get to the directory you want to locate. Then, type this command: “composer create-project –prefer-dist laravel/laravel blog “

4. Install Laradock

In terminal, type command: “git clone https://github.com/laradock/laradock.git

5. Edit your web server in Laradock folder

In terminal, type command: “cd laradock” and then “cp env-example .env”

At line 8, change to APP_CODE_PATH_HOST=../blog/

6. Run the environment

In terminal, type command: “docker-compose up -d nginx mysql”

7. Open your browser

Open your favorite browse and visit http://localhost/. It will display as picture follow:

That is it !

Now, you are ready to use powerful Laravel to develop.

Good luck !

Original Source from: https://medium.com/@thanatornboonnak/setting-laravel-environment-by-laradock-on-mac-c8d53cae52d7

Empat perintah utama yang termasuk dalam perintahData Manipulation Language (DML) yaitu SELECT, INSERT, UPDATE  dan DELETE. Ternyata ada beberapa perintah INSERT di MySQL yang jarang dipakai, yaitu:


Artikel lengkap yang membahas hal ini bisa ditinjau disini:

7 Variasi Perintah INSERT di MySQL yang Sering Terlupakan

FPDF is a PHP class which allows you to generate PDF files with purePHP, that is to say without using the PDFlib library.

For those who are already familiar with FPDF, this post will show you how to output your PDF file using FPDF. There are 4 methods that you can use according to your own needs:

    • Method 1: Saving the PDF to a file:
    • Method 1 (for server): Saving the PDF file to server (make sure you have 777 writing permissions for that folder!):
    • Method 2: Prompting user to choose where to save the PDF file:
    • Method 3: Automatically open PDF in your browser after being generated:
    • Method 4: Returning the PDF file content as a string:
$pdf->Output('', 'S');



source: https://phpexcel.codeplex.com/discussions/227620

If you want to modified date of files on linux, you can follow this steps:

You could cd to the folder containing the the files and:

touch -d '30 August 2013' *.php

Or if it has sub folders with php files – search through them recursively:

find /path/to/your/php/ -exec touch -d '30 August 2013' *.php {} \;

the folder ‘php’ in the command above would be included.


If you ONLY need to find/change EXACTLY files modified on 23 April 2013, you can use the -mtimeparameter in your find command.

  • -mtime +60 means you are looking for a file modified 60 days ago or more.
  • -mtime -60 means less than 60 days.
  • -mtime 60 If you skip + or - it means exactly 60 days.

So modifying the command above like this:

find /path/to/your/php/ -mtime 127 -exec touch -d '30 August 2013' *.php {} \;

Where 127 is the exact amount of days since 23 April (if my quick head calculation is correct). Else you can change the number to the correct amount of days, or use the + or - as described above if it doesn’t need to be ‘that’ exact.

You can read more about the find commands -mtime parameter here: http://www.cyberciti.biz/faq/howto-finding-files-by-date/


source: http://stackoverflow.com/questions/18522501/linux-change-modification-date-of-files

Sebenarnya sudah pingin nulis tentang framework ini sejak lama, tapi ya namanya pingin tapi ga ditulis ya ga ada tulisannya. Dari official websitenya si panada http://panadaframework.com, dia bilang kalau Panada adalah high performance PHP development framework namun tetap sederhana. Tidak hanya sederhana dalam pengertian cara penggunaanya, tetapi juga bagaimana core system-nya bekerja. Dari awal dikembangkan, Panada secara khusus ditujukan untuk membantu para PHP developer yang ingin mengembangkan aplikasi web berperforma tinggi (high performance web application). Namun demikian, prinsip kesederhanaan KISS atau Keep it Simple Son! selalu menjadi prinsip utama dalam setiap pengembangan. Panada adalah framework sederhana dan simpel untuk pembuatan website berbasiskan PHP 5.3 ke atas. Framework ini dikembangkan dengan tujuan membantu para pengembang website untuk bekerja lebih cepat, lebih mudah dan lebih alamiah dalam penulisan kode. Setiap komponen didesign untuk bisa saling memanfaatkan sumberdaya (resource) dari komponen-komponen lainnya secara otomatis. Hal ini memudahkan pengembang dalam memanfaatkan sumberdaya secara cepat dan efisien.

Read More →

Terdapat banyak faktor yang mengancam keamanan komunikasi data. Ancaman-ancaman tersebut menjadi masalah terutama dengan semakin meningkatnya komunikasi data yang bersifat rahasia. Secara garis besar, ancaman terhadap komunikasi data dapat dibagi menjadi 2 macam, yaitu :

  1. Ancaman aktif mencakup kecurangan dan kejahatan terhadap komunikasi data. Dari sekian banyak faktor-faktor yang dapat mengancam keamanan dari suatu data, maka berdasarkan tekniknya, faktor-faktor tersebut dapat dikelompokkan ke dalam empat jenis ancaman, yaitu:
    • Interruption, terjadi bila data yang dikirimkan dari A tidak sampai pada orang yang berhak (B). Interruption merupakan pola penyerangan terhadap sifat availability (ketersediaan data). Contohnya adalah merusak dan membuang data-data pada suatu sistem komputer, sehinggga menjadi tidak ada dan tidak berguna.
    • Interception, yaitu serangan ini terjadi jika pihak ketiga (C) berhasil mendapatkan akses informasi dari dalam sistem komunikasi. Contohnya, dengan menyadap data yang melalui jaringan  public (wiretapping) atau menyalin secara tidak sah  file atau program.  Interception mecangancam sifat kerahasiaan data.
    • Modification, pada serangan ini pihak ketiga berhasil merubah pesan yang dikirimkan. Modification merupakan pola penyerangan terhadap sifat integritas data.
    • Fabrication, merupakan ancaman terhadap integritas, yaitu orang yang tidak berhak yang meniru atau memalsukan suatu objek ke dalam sistem. Jadi, penyerang berhasil mengirimkan pesan menggunakan identitas orang lain
  2. Ancaman pasif mencakup kegagalan sistem, kesalahan manusia dan bencana alam.

Aspek keamanan komunikasi data terdiri dari:

  1. Authentication, memberi jaminan bahwa semua pelaku dalam komunikasi adalah otentik atau mereka yang dapat di-klaim
  2. Integrity, aspek yang menjamin bahwa data tidak dirubah tanpa ada ijin fihak yang berwenang (authorized), menjaga keakuratan dan keutuhan data serta metode prosesnya untuk menjamin aspek integrity ini.
  3. Privacy and Confidentiality, aspek yang menjamin kerahasiaan data atau informasi, memastikan bahwa informasi hanya dapat diakses oleh orang yang berwenang dan menjamin kerahasiaan data yang dikirim, diterima dan disimpan.
  4. Non-repudiation atau nir penyangkalan adalah usaha untuk mencegah terjadinya penyangkalan terhadap pengiriman/terciptanya suatu informasi oleh yang mengirimkan/membuat. Non-repudiation menyediakan metode untuk menjamin bahwa tidak terjadi kesalahan dalam melakukan klaim terhadap pihak yang melakukan transaksi
  5. Availibility, aspek yang menjamin bahwa data akan tersedia saat dibutuhkan, memastikan user yang berhak dapat menggunakan data dan perangkat terkait.


saya lupa sumber tulisan ini dari mana saja ya, maklum ini tugas 2 tahun yang lalu 😀

Tulisan ini saya comot dari blog salah satu pengajar saya, Pak Lukito Edi Nugroho di http://lukito.staff.ugm.ac.id/2013/03/01/strukturisasi-skripsi-tesis-atau-disertasi-dalam-satu-diagram/ Tulisan yang ringkas namun komplit pakai banget mengenai Skripsi – Thesis atau Disertasi, monggo dinikmati:

Menulis skripsi, tesis, atau disertasi bukan hanya sekedar menyusun kalimat untuk membangun konten dari bagian-bagian naskah ilmiah tersebut. Yang tidak kalah pentingnya adalah menjamin keruntutan antara satu bagian dengan bagian yang lain. Kelancaran “aliran” ide dan penjelasan inilah yang membuat naskah skripsi, tesis, dan disertasi menjadi enak dibaca.