Upload to Box Content API without user authentication

This post may not stay up long because it seems like a sneaky way of uploading files to Box without the Oauth2 prompting. But what the hay, why not.

Problem:

I wanted to be able to upload files to a “Shared” folder on Box that anyone could upload to using a web form. They should not be required to have a Box account and should not be prompted to login or authorize the app.

Solution:

You need to decide which account you want to store these files in and then that user will act as the proxy for everyone uploading files. You’ll authenticate once to get an access_token but after that a crontab will take care of refreshing the token every 15 minutes.

Setup a Box Developer account at https://developers.box.com/ and create an App to get a Client ID and Client Secret

boxAuth.php

    <?php 
	error_reporting(E_ALL);  
	ini_set("display_errors", 1);
	if(session_id() == '') {
	    session_start();
	}
	
        $client_id =  'ENTER_YOUR_CLIENT_ID'; 
	$client_secret =  'ENTER_YOUR_CLIENT_SECRET'; 
		
	// first step - enter username and password	
	if(empty($_GET["code"]) && empty($_GET["state"])) {

		$_SESSION["state"] = "security_token%3D".substr(uniqid(mt_rand(), true), 0, 20);
	
		$get_url = "https://app.box.com/api/oauth2/authorize?response_type=code&client_id={$client_id}&state=".$_SESSION["state"];
	
		$ch = curl_init(); 
		curl_setopt($ch, CURLOPT_URL, $get_url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
	
		$data = curl_exec($ch); 
		curl_close($ch);
		
		print_r($data);
		
	// second step - get access token from auth code
	} elseif(urlencode($_GET["state"]) == $_SESSION["state"]) {
		
		$_SESSION["code"] = $_GET["code"]; // this will last for 30 seconds - make it fast!
		
		$url = "https://app.box.com/api/oauth2/token";
		
		$fields = array(
					'grant_type' 	=>	'authorization_code',
					'code'		=>	$_SESSION["code"],
					'client_id'	=>	$client_id,
					'client_secret' =>	$client_secret
				  );
	
		try {       
	            $ch = curl_init();          
	            curl_setopt($ch, CURLOPT_URL, $url);
	            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
	                'Content-Type:multipart/form-data'
	            ));
	            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);          
	            curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
	            $response = curl_exec($ch);
	            curl_close($ch);
		    $responseArray = (array) json_decode($response);
		    file_put_contents("/PATH/TO/box_access_token", $responseArray["access_token"]);
		    file_put_contents("/PATH/TO/box_refresh_token", $responseArray["refresh_token"]);
		    header("Location: boxUpload.php");
	
	        } catch (Exception $e) {
	            $response = $e->getMessage();
	            die ("Issue authenticating: " . var_export($response, true));
	        }  
	}
?>

boxRefresh.php

    <?php 
	error_reporting(E_ALL);  
	ini_set("display_errors", 1);
	if(session_id() == '') {
	    session_start();
	}
	
        $client_id =  'ENTER_YOUR_CLIENT_ID'; 
	$client_secret =  'ENTER_YOUR_CLIENT_SECRET'; 
        $refresh_token = file_get_contents("/PATH/TO/box_refresh_token");	
		
	if(!empty($refresh_token)) {
		
		$url = "https://app.box.com/api/oauth2/token";
		
		$fields = array(
					'grant_type' 	=>	'refresh_token',
					'refresh_token'	=>	$refresh_token,
					'client_id'	=>	$client_id,
					'client_secret' =>	$client_secret
				  );
	
		try {       
	        	$ch = curl_init();          
	        	curl_setopt($ch,CURLOPT_URL, $url);
	        	curl_setopt($ch, CURLOPT_HTTPHEADER, array(
	         	   'Content-Type:multipart/form-data'
	       	 	));
	        	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);          
	        	curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
	        	$response = curl_exec($ch);
	        	curl_close($ch);
			$responseArray = (array) json_decode($response);
		 	file_put_contents("/PATH/TO/box_access_token", $responseArray["access_token"]);
		    	file_put_contents("/PATH/TO/box_refresh_token", $responseArray["refresh_token"]);
			print_r($responseArray);
	    } catch (Exception $e) {
	        	$response = $e->getMessage();
	        	die ("Issue refreshing token: " . var_export($response, true));
	    }   
	    
	}
    ?>

boxUpload.php

<?php 
	 //box caps at 15GB
	set_time_limit(600);
	ini_set("post_max_size", '15360M');
	ini_set("upload_max_filesize", '15360M');
        
	$folderID = 'REPLACE_WITH_THE_ID_OF_YOUR_FOLDER';
	$message = '';
	try {
		$access_token = file_get_contents("/PATH/TO/box_access_token");
	} catch(Exception $e) {
		$access_token = false;
	}
	
	if(empty($access_token)) {
		header("Location: boxAuth.php");
	}
	
	$url = "https://upload.box.com/api/2.0/files/content";

	if (isset($_POST['btnUpload']))
	{
	    $file_upload = $_FILES['file']['tmp_name'];
		$json  = json_encode(array('name' => $_FILES['file']['name'], 'parent' => array('id' => $folderID)));
		$fields = array('attributes' => $json,'file'=>new CurlFile($_FILES['file']['tmp_name'],$_FILES['file']['type'],$_FILES['file']['name']));
	
		try {       
	        $ch = curl_init();          
	        curl_setopt($ch,CURLOPT_URL, $url);
	        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
	            'Authorization: Bearer '.$access_token, 
	            'Content-Type:multipart/form-data'
	        ));
	        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);          
	        curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
	        $response = curl_exec($ch);
	        curl_close($ch);
	        $responseArray = (array) json_decode($response);
	        if(isset($responseArray["message"])) {
		        $message = $responseArray["message"] . ". ";
		    }
		    
		    if(isset($responseArray["total_count"])) {
			    $message = "'". $responseArray["entries"][0]->name . "' uploaded successfully! ";
		    }
		       
	
	    } catch (Exception $e) {
	        $response = $e->getMessage();    
	    }
	        
	}

?>
<div style="display: table; position: absolute; width:100%; height:100%;">
	<div style="display:table-cell; vertical-align: middle;">
		<div style="width:534px; margin: 0 auto; text-align: center; border: 1px solid #aaa; padding: 1em;">	
			<h1><?php echo $message; ?>Upload a file to your Box root folder</h1>
			<form action="boxUpload.php" method="post" name="frmUpload" enctype="multipart/form-data">
				 <label>Upload file to Box
		 		       <input name="file" type="file" id="file"/>
			   	 </label>
		    		<input name="btnUpload" type="submit" value="Upload" />
			</form>
		</div>
	</div>
</div>

crontab

*/15 * * * * php /PATH/TO/boxRefresh.php > /dev/null

Uploading files to Box Content API V2

This one gave me plenty of head-aches so I wanted to share the solution.

Problem:

I wanted to be able to upload a file to a web form and have it post to Box using the Box Content API.

Solution:

Create a Box Developer account at https://developers.box.com and create an app to get a Developer Token (this only lasts an hour before you have to get a new one from the app settings)

<?php
    // ENTER YOUR DEVELOPER TOKEN
    $token = "ekdfokeEdfdfkosdkoqwekof93kofsdfkosodSqd";

    $url = "https://upload.box.com/api/2.0/files/content";
    if (isset($_POST['btnUpload'])) {
        $file_upload = $_FILES['file']['tmp_name'];
        $json = json_encode(array(
                                'name' => $_FILES['file']['name'], 
                                'parent' => array('id' => 0)
                            ));
        $fields = array(
                      'attributes' => $json,
                      'file'=>new CurlFile($_FILES['file']['tmp_name'],$_FILES['file']['type'],$_FILES['file']['name'])
                  );

        try {
            $ch = curl_init();
            curl_setopt($ch,CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Authorization: Bearer '.$token, 
                'Content-Type:multipart/form-data'
            ));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
            $response = curl_exec($ch);
            curl_close($ch);
        } catch (Exception $e) {
            $response = $e->getMessage();
        }

        print_r($response);
    }

?>

<form method="post" name="frmUpload" enctype="multipart/form-data">
    <label>Upload file to Box
        <input name="file" type="file" id="file"/>
    </label>
    <input name="btnUpload" type="submit" value="Upload" />
</form>

Combining Javascript Files to Reduce HTTP Requests

I just wanted a very basic PHP script to combine all my JS files into one – no minification, just bring them together into one file.

<?php
// compress the file using GZIP
ob_start("ob_gzhandler"); 

// javascript content-type
header('Content-type: text/javascript');

// define the files you want to combine
$files = array('jquery.js', 'app.js', 'somePlugin.js');

// combine the files
foreach($files as $file) {
    // get the contents of this file
    $content .= file_get_contents($file) . '
'; //add a new line
}

// output the contents
echo $content;

?>

Resizing High Resolution (Hi-res) JPEG Images with PHP

I kept running into a problem when I uploaded high resolution (14MP) images and tried creating thumbnails with them. The issue turned out being the PHP script ran out of memory. So it was a simple increase to about a half gig (512MB) and the script ran perfectly. Here’s the code:

thumbnail.php?src=myImage.jpg&w=300

<?php
ini_set ( "memory_limit", "512M");
header('Content-Type:image/jpeg');
echo createThumb($_GET["src"],$_GET["w"]);


function createThumb( $path, $thumbWidth ) 
{
 
    $info = pathinfo($path);
    // continue only if this is a JPEG image
    if ( strtolower($info['extension']) == 'jpg' ) 
    {

      // load image and get image size
      $img = imagecreatefromjpeg( "{$path}" );
      $width = imagesx( $img );
      $height = imagesy( $img );

	 

      // calculate thumbnail size
      $new_width = $thumbWidth;
      $new_height = floor( $height * ( $thumbWidth / $width ) );

      // create a new temporary image
      $tmp_img = imagecreatetruecolor( $new_width, $new_height );

      // copy and resize old image into new image 
      imagecopyresized( $tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
	  $exif = exif_read_data($_GET["src"]);
	  $orientation = $exif["Orientation"]; //6 for portrait and 1 for landscape
	  if($orientation == 6 && $width > $height) {
	  	$tmp_img = imagerotate($tmp_img, 270, 0);
	  }
      return imagejpeg($tmp_img);
  
  }
}
?>