How to use PHP curl GET and POST with JSON web services


Here are two PHP scripts I just wrote that use curl and curl_setopt. The first example makes a GET request, and the second example makes a POST request, and passes JSON data to the web service it accesses.

A PHP curl GET request

This first one makes an HTTP GET request and prints the data that is returned by the URL that it hits:

<?php

# An HTTP GET request example

$url = 'http://localhost:8080/stocks';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
curl_close($ch);
echo $data;

?>

A PHP curl POST request, with JSON data

This next one makes an HTTP POST request. The way it works is that it sits in the middle of (a) a Sencha ExtJS client and (b) another web service at the URL shown. The Sencha client gives this script the data in a simple POST format, and this script converts that data to JSON, passes it to the URL shown, and returns whatever information that service returns directly to the Sencha client:

<?php

# An HTTP POST request example

# a pass-thru script to call my Play server-side code.
# currently needed in my dev environment because Apache and Play run on
# different ports. (i need to do something like a reverse-proxy from
# Apache to Play.)

# the POST data we receive from Sencha (which is not JSON)
$id = $_POST['id'];
$symbol = $_POST['symbol'];
$companyName = $_POST['companyName'];

# data needs to be POSTed to the Play url as JSON.
# (some code from http://www.lornajane.net/posts/2011/posting-json-data-with-php-curl)
$data = array("id" => "$id", "symbol" => "$symbol", "companyName" => "$companyName");
$data_string = json_encode($data);

$ch = curl_init('http://localhost:8080/stocks/add');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Content-Length: ' . strlen($data_string))
);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);

//execute post
$result = curl_exec($ch);

//close connection
curl_close($ch);

echo $result;

?>

In summary, if you needed some PHP curl examples, including how to set curl options with curl_setopt, I hope these examples have been helpful.

Advertisements

Running PHP applications in Tomcat 6


This guide shows how to install and run PHP applications like Moodle, mediaWiki, Joomla as Tomcat 6 web applications. And how to install PHP 5.x for all existing web applications.

Download and install Java, Tomcat and PHP

Install a PHP web application into Tomcat

  1. Copy the PHP web application JavaBridgeTemplate.war or the demo JavaBridge.war to the Tomcat webapps directory.
  2. Wait two seconds until Tomcat has loaded the web application.
  3. Browse to http://127.0.0.1:8080/JavaBridgeTemplate621 and http://127.0.0.1:8080/JavaBridgeTemplate621/test.php to see the PHP info page.
  4. Rename the file file:webapps/JavaBridgeTemplate621 directory, for example to file:webapps/Moodle, and download and install your PHP application to this directory.
  5. Browse to the name of your web application, for example http://127.0.0.1:8080/Moodle, to run it from your internet browser.

PHP support for all existing

Tomcat web applications

If you want to enable PHP for all of your web applications, move the Java libraries from the local web application folder to the Tomcat library folder and edit the Tomcat web configuration as follows:

  1. Stop Tomcat.
  2. Move the libraries JavaBridge.jar, php-servlet.jar and php-script.jar from the webapps/JavaBridgeTemplate621/WEB-INF/lib directory over to the tomcat lib directory.
  3. Edit the Tomcat conf/web.xml. Add the following 9 lines marked with a +:


    <web-app xmlns=... >

    + <listener><listener-class>php.java.servlet.ContextLoaderListener</listener-class></listener>
    + <servlet><servlet-name>PhpJavaServlet</servlet-name><servlet-class>php.java.servlet.PhpJavaServlet</servlet-class>
    + </servlet>
    + <servlet><servlet-name>PhpCGIServlet</servlet-name><servlet-class>php.java.servlet.fastcgi.FastCGIServlet</servlet-class>
    + <init-param><param-name>prefer_system_php_exec</param-name><param-value>On</param-value></init-param>
    + <init-param><param-name>php_include_java</param-name><param-value>Off</param-value></init-param>
    + </servlet>
    + <servlet-mapping><servlet-name>PhpJavaServlet</servlet-name><url-pattern>*.phpjavabridge</url-pattern> </servlet-mapping>
    + <servlet-mapping><servlet-name>PhpCGIServlet</servlet-name><url-pattern>*.php</url-pattern></servlet-mapping>

    </web-app>

  4. Start Tomcat again. Now you can add PHP scripts to tomcat.
  5. Add a PHP test file

    <?php require_once("java/Java.inc");
    echo java("java.lang.System")->getProperties(); ?>

    to some web context, for example “examples”, and browse to http://yourHost.com:8080/examples/test.php.

  6. Check the process list using the Unix/Linux or Windows task manager. There should be 5 php-cgi FastCGI executables waiting for requests from Java.
  7. Please see our FAQ for more information how to set up a load balancer or how to create a distributable PHP/Java web application.

Human Readable File Size with PHP


Here’s a nice and simple function to get a human readable file size in PHP


<?php
function human_filesize($bytes, $decimals = 2) {
$size = array('B','kB','MB','GB','TB','PB','EB','ZB','YB');
$factor = floor((strlen($bytes) - 1) / 3);
return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . @$size[$factor];
}

for example:

<?php
echo human_filesize(filesize('example.zip'));

may echo 42.64MB.

Encryption and Decryption for Java/Android and PHP


Use case

While working on an android app that retrieves it’s data from a PHP-API I needed to build a both-sided en- and decryption layer to secure the requests and responses properly.

I decided to use an AES encryption with IvParameterSpec, SecretKeySpec and “AES/CBC/PKCS5Padding” on Java side, and mcrypt_module “rijndael-128″ on PHP side.

Implementations
PHP


class ApiCrypter
{
private $iv = 'fdsfds85435nfdfs'; #Same as in JAVA
private $key = '89432hjfsd891787'; #Same as in JAVA

public function __construct() {
}

public function encrypt($str) {
$str = $this->pkcs5_pad($str);
$iv = $this->iv;
$td = mcrypt_module_open('rijndael-128', '', 'cbc', $iv);
mcrypt_generic_init($td, $this->key, $iv);
$encrypted = mcrypt_generic($td, $str);
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
return bin2hex($encrypted);
}

public function decrypt($code) {
$code = $this->hex2bin($code);
$iv = $this->iv;
$td = mcrypt_module_open('rijndael-128', '', 'cbc', $iv);
mcrypt_generic_init($td, $this->key, $iv);
$decrypted = mdecrypt_generic($td, $code);
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
$ut = utf8_encode(trim($decrypted));
return $this->pkcs5_unpad($ut);
}

protected function hex2bin($hexdata) {
$bindata = '';
for ($i = 0; $i strlen($text)) {
return false;
}
if (strspn($text, chr($pad), strlen($text) - $pad) != $pad) {
return false;
}
return substr($text, 0, -1 * $pad);
}
}

$str = "abc";

$ApiCrypter = new ApiCrypter();

$encrypted = $ApiCrypter -> encrypt($str);

echo "Encryption : " . $encrypted;

$decrypted = $ApiCrypter -> decrypt($encrypted);

echo "Decryption :" . $decrypted;

Encryption
Java


package cipher;

import java.net.URLDecoder;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class ApiCrypter {

private String iv = "fdsfds85435nfdfs";
private String secretkey = "89432hjfsd891787";
private IvParameterSpec ivspec;
private SecretKeySpec keyspec;
private Cipher cipher;

public ApiCrypter()
{
ivspec = new IvParameterSpec(iv.getBytes());
keyspec = new SecretKeySpec(secretkey.getBytes(), "AES");

try {
cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
}
}

public byte[] encrypt(String text) throws Exception
{
if(text == null || text.length() == 0) {
throw new Exception("Empty string");
}
byte[] encrypted = null;
try {
cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
encrypted = cipher.doFinal(text.getBytes("UTF-8"));
}
catch (Exception e) {
throw new Exception("[encrypt] " + e.getMessage());
}
return encrypted;
}

public byte[] decrypt(String code) throws Exception
{
if(code == null || code.length() == 0) {
throw new Exception("Empty string");
}
byte[] decrypted = null;
try {
cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);
decrypted = cipher.doFinal(hexToBytes(code));
}
catch (Exception e) {
throw new Exception("[decrypt] " + e.getMessage());
}
return decrypted;
}

public static String bytesToHex(byte[] data)
{
if (data==null) {
return null;
}
int len = data.length;
String str = "";
for (int i=0; i<len; i++) {
if ((data[i]&0xFF)<16) {
str = str + "0" + java.lang.Integer.toHexString(data[i]&0xFF);
}
else {
str = str + java.lang.Integer.toHexString(data[i]&0xFF);
}
}
return str;
}

public static byte[] hexToBytes(String str) {
if (str==null) {
return null;
}
else if (str.length() < 2) {
return null;
}
else {
int len = str.length() / 2;
byte[] buffer = new byte[len];
for (int i=0; i<len; i++) {
buffer[i] = (byte) Integer.parseInt(str.substring(i*2,i*2+2),16);
}
return buffer;
}
}

public static void main(String args[]) throws Exception
{
ApiCrypter obj = new ApiCrypter();
byte[] str = obj.encrypt("abc");
String encryptedRequest = obj.bytesToHex(str);
System.out.println(encryptedRequest);
String res = new String( obj.decrypt( encryptedRequest ), "UTF-8" );
res = URLDecoder.decode(res,"UTF-8");
System.out.println(res);
}
}

Script for uploading ZIP file and unzip it on the server using PHP


 

<?php
/* Simple script to upload a zip file to the webserver and have it unzipped
  Saves tons of time, think only of uploading WordPress to the server
  I have modified the script a little to make it more convenient
  Modified by: Prabhu (22.08.2014)
 */

function rmdir_recursive($dir) {
    foreach (scandir($dir) as $file) {
        if ('.' === $file || '..' === $file)
            continue;
        if (is_dir("$dir/$file"))
            rmdir_recursive("$dir/$file");
        else
            unlink("$dir/$file");
    }
    rmdir($dir);
}

if (!empty($_FILES["zip_file"]["name"])){
    $filename = $_FILES["zip_file"]["name"];
    $source = $_FILES["zip_file"]["tmp_name"];
    $type = $_FILES["zip_file"]["type"];

    $name = explode(".", $filename);
    $accepted_types = array('application/zip', 'application/x-zip-compressed', 'multipart/x-zip', 'application/x-compressed');
    foreach ($accepted_types as $mime_type) {
        if ($mime_type == $type) {
            $okay = true;
            break;
        }
    }

    $continue = strtolower($name[1]) == 'zip' ? true : false;
    if (!$continue) {
        $message = "The file you are trying to upload is not a .zip file. Please try again.";
    }

    /* PHP current path */
    $path = dirname(__FILE__) . '/';  // absolute path to the directory where zipper.php is in
    $filenoext = basename($filename, '.zip');  // absolute path to the directory where zipper.php is in (lowercase)
    $filenoext = basename($filenoext, '.ZIP');  // absolute path to the directory where zipper.php is in (when uppercase)

    $targetdir = $path . $filenoext; // target directory
    $targetzip = $path . $filename; // target zip file

    /* create directory if not exists', otherwise overwrite */
    /* target directory is same as filename without extension */

    if (is_dir($targetdir))
        rmdir_recursive($targetdir);
    mkdir($targetdir, 0777);

    /* here it is really happening */

    if (move_uploaded_file($source, $targetzip)) {
        $zip = new ZipArchive();
        $x = $zip->open($targetzip);  // open the zip file to extract
        if ($x === true) {
            $zip->extractTo($targetdir); // place in the directory with same name  
            $zip->close();

            unlink($targetzip);
        }
        $message = "Your .zip file was uploaded and unpacked.";
    } else {
        $message = "There was a problem with the upload. Please try again.";
    }
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title>Unzip a zip file to the webserver</title>
    </head>

    <body>
<?php if (!empty($message)){ echo "<p>$message</p>"; }?>
        <form enctype="multipart/form-data" method="post" action="">
            <label>Choose a zip file to upload: <input type="file" name="zip_file" /></label>
            <br />
            <input type="submit" name="submit" value="Upload" />
        </form>
    </body>
</html>