SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse - javascript

I created an application with ionic with the help of this tutorial: http://masteringionic.com/blog/2016-12-15-using-php-and-mysql-with-ionic/ a school programm
But when i want to select all my client, i get this error :
SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse () at XMLHttp…, text
My PHP script :
<?php
// Define database connection parameters
$hn = 'localhost';
$un = 'root';
$pwd = '';
$db = 'equida';
$cs = 'utf8';
// Set up the PDO parameters
$dsn = "mysql:host=" . $hn . ";port=3306;dbname=" . $db . ";charset=" . $cs;
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
PDO::ATTR_EMULATE_PREPARES => false,
);
// Create a PDO instance (connect to the database)
$pdo = new PDO($dsn, $un, $pwd, $opt);
$data = array();
// Attempt to query database table and retrieve data
try {
$stmt = $pdo->query('SELECT * FROM client');
while($row = $stmt->fetch(PDO::FETCH_OBJ))
{
// Assign each row of data to associative array
$data[] = $row;
}
// Return data as JSON
echo json_encode($data);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
My javascript :
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { HttpClient } from '#angular/common/http';
#Component({
selector: 'page-lst-client',
templateUrl: 'lst-client.html'
})
export class LstClientPage {
/**
* #name items
* #type {Array}
* #public
* #description Used to store returned PHP data
*/
public items : Array<any> = [];
constructor(public navCtrl: NavController,
public http : HttpClient)
{
}
/*
* Triggered when template view is about to be entered
* Returns and parses the PHP data through the load() method
*
* #public
* #method ionViewWillEnter
* #return {None}
*/
ionViewWillEnter() : void
{
this.load();
}
/*
* Retrieve the JSON encoded data from the remote server
* Using Angular's Http class and an Observable - then
* assign this to the items array for rendering to the HTML template
*
* #public
* #method load
* #return {None}
*/
load() : void
{
this.http
.get('wequida/retrieve-client.php')
.subscribe((data : any) =>
{
console.dir(data);
this.items = data;
},
(error : any) =>
{
console.dir(error);
});
}
/*
* Allow navigation to the AddTechnologyPage for creating a new entry
*
* #public
* #method addEntry
* #return {None}
*/
addEntry() : void
{
this.navCtrl.push('AddClientPage');
}
/*
* Allow navigation to the AddTechnologyPage for amending an existing entry
* (We supply the actual record to be amended, as this method's parameter,
* to the AddTechnologyPage
*
* #public
* #method viewEntry
* #param param {any} Navigation data to send to the next page
* #return {None}
*/
viewEntry(param : any) : void
{
this.navCtrl.push('AddClientPage', param);
}
}

Your getting an HTML response from your PHP script.
You should include a json header in your PHP script.
header('Content-type: application/json');
The line
echo $e->getMessage();
will not output JSON. Your javascript does not accommodate sending errors.
In your PHP script you can use use:
echo json_encode(array('error' => false, 'data' => $data));
...
echo json_encode(array('error' => $e->getMessage(), 'data' => []));
Then in your javascript:
.subscribe((result: any) =>
{
if (result.error)
{
// error handling code
}
else
{
console.dir(result.data);
this.items = result.data;
}
},
If there is an error connecting to the database your script will output an HTML message with an 'Uncaught PDOException'. You can wrap that in try/catch as well.
To know what the problem is you should look at what your PHP script is outputting.
To do that
open the developers console [Option + ⌘ + J (on macOS), or Shift +
CTRL + J (on Windows/Linux)],
go to the 'Network' tab,
reload the page,
look for your php script and click on it,
open the 'Response' tab.
You will see the raw HTML or JSON response from the PHP script.
Edit - after reading comments:
If in the Response tab you see the full unparsed content of the PHP file then the web server you are using is not parsing PHP. You might be trying to do this without a sever by opening an HTML file with the javascript above through the file system using file:///C:/something/whatever.html
This will not work for obvious reasons.

Related

PhpBB Linked accounts extension in viewtopic_body

I was trying to expand the extension which offers to see linked accounts for each user on the forum. It works in memberlist_view page and I would like to have it inside viewtopic_body.
I have a difficulty with narrowing the linked accounts to particular post id and author.
The closest I got is to have linked accounts from each user within the topic.
/** * Assign functions defined in this class to event listeners in the core * * #return array */ static public function getSubscribedEvents(): array { return array( 'core.viewtopic_modify_post_row' => 'viewtopic_linked_accounts_list',
` /**
* Show list of linked accounts in every post.
*
* #param data $event The event object
*
* #return void
*/
public function viewtopic_linked_accounts_list(data $event): void
{
// $this->template->assign_var('U_CAN_VIEW_LINKED_ACCOUNTS', $this->auth->acl_get('u_view_other_users_linked_accounts'));
foreach ($this->linking_service->get_linked_accounts($event['row']['user_id']) as $account)
{
$this->template->assign_block_vars('linked_accounts', array(
'ID' => $account['user_id'],
'USERNAME' => get_username_string('full', $account['user_id'], $account['username'], $account['user_colour']),
));
}
}`

How to validate POST data in Laravel 5.4?

I am testing an API in Laravel 5.4. I am now in the part of storing a record via API. I am having some issues on how to use Request::input() or Input::get() to validate POST data.
LessonsController.php
<?php
namespace App\Http\Controllers;
use App\Http\Requests;
use App\Lesson;
use App\Acme\Transformers\LessonTransformer;
//use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use App\Http\Controllers\Controller;
class LessonsController extends ApiController
{
/**
* #var Acme\Transformers\LessonTransformer
*/
protected $lessonTransformer;
function __construct(LessonTransformer $lessonTransformer)
{
$this->lessonTransformer = $lessonTransformer;
// $this->middleware('sentry.auth')->only('post'); // basic level of protection for creating a lession
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
* If we are using basic authentication, we should be using SSL
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store()
{
if( ! Input::get('title') || ! Input::get('body')){
return $this->setStatusCode(422)->respondWithError('Parameters failed validation for a lesson.');
}
Lesson::create($request->all());
return $this->respondCreated('Lesson successfully created.');
}
/**
* Display the specified resource.
*
* #return \Illuminate\Http\Response
*/
public function show($id)
{
$lesson = Lesson::find($id);
if( ! $lesson) {
return $this->respondNotFound('Lesson does not exist');
}
return $this->respond([
'data' => $this->lessonTransformer->transform($lesson)
]);
}
}
When I test my code above with POSTMAN using POST request. I am prompted with "{"error":"Parameters failed validation for a lesson.","status_code":422}"
.
I receive an error when I try to add data or I don't add data.
Do you have any idea how to correct my store() code? Any help is appreciated.
To validate form data in Laravel simply use "Laravel Form Requests". This allows you to validate your form data in request using some predefined validation rules of Laravel and if you need you can also create you custom laravel validation logic.
According to Laravel docs:
Form requests are custom request classes that contain validation logic.
It will simplify your validation logic, make your code neat and let you handle complex validations.
Try this, might help
public function store(Request $request)
{
if( ! $request->has('title') || ! $request->has('body')){
return $this->setStatusCode(422)->respondWithError('Parameters failed validation for a lesson.');
}
Lesson::create($request->all());
return $this->respondCreated('Lesson successfully created.');
}
The problem with my code above is that it does not have the $request var in the store() method.
In my code be below, the Request class is now injected into store method.
public function store(Request $request)
{
if (! $request->input('title') or ! $request->input('body') )
{
return $this->respondUnprocessableEntity('Parameters failed validation for a lesson.');
}
Lesson::create($request->all());
return $this->respondCreated('Lesson successfully created.');
}
Note: In postman, select x-www-form-urlencoded in Body

how to add a user id to each file for downloading in laravel 5.2?

I have two tables a ''users'' and ''announcement'', which announcement table have 3 download file so I wanna add a function when a user download a file add user id to the download file?
Annoucements Table
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateAnnoucementsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('announcements', function (Blueprint $table) {
$table->increments('project_id')->unsigned();;
$table->integer('types_id')->unsigned();
$table->foreign('types_id')->references('id')->on('types')->onDelete('CASCADE')->onUpdate('CASCADE');
$table->string('project_name');
$table->string('extension');
$table->date('deadline');
$table->string('biddingdocuments');
$table->string('amendmentdocuments');
$table->string('noticestenders');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('announcements');
}
}
Users Table
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('username')->unique();
$table->string('email')->unique();
$table->string('securityq');
$table->string('securitya');
$table->string('name');
$table->string('fname');
$table->string('lname');
$table->string('gender');
$table->string('cname');
$table->integer('lnumber')->unique();
$table->string('province');
$table->string('city');
$table->string('pnumber');
$table->text('address');
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('users');
}
}
userAnnoucement controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use App\Http\Requests;
use App\Announcements;
class UserAnnoucment extends Controller
{
public function index(Request $request)
{
$announcements = Announcements::orderBy('project_id','DESC')->paginate(5);
return view('userAnnoucements.index',compact('announcements'))->with('i',
($request->input('page', 1) - 1) * 5);
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function count(){
$announcements = new Announcements;
$announcements->extension = Auth::user()->id;
$announcements->save();
return $announcements;
}
}
``
No problem if the site is not overly busy. Otherwise you can have conflicts if there a simultaneous download.
If there is little to no traffic, programmatically copy the download file to a temporary folder, prepend the UserID to the filename and then download from there, ie: 1024_file.pdf. If the user breaks the download or returns then the file is already there, although you may want to clear the file after each download to conserve disk space, and use the same download code each time.
On a busier service, create a folder for each user logs on (if one is not already available) and do your business in those folders.

Laravel inserting into 2 tables

i have 2 tables user and tn_user, table user is a table containing information to log in, i made it by tutorial from https://laravel.com/ so basically it was automatically created, while tn_user is a table that i make by myself
USER TABLE
in case u can't see the atribut are id, name, email, password that the important things, email and password in this table is used to logging in
TN_USER TABLE
the atribut are cn_id, cv_name, cv_email, cn_phone, cv_position, cv_address, cv_country, cv_username, cv_password, cv_privileges, those are the important thing
based on the form below i want to insert username and password into table user and the rest into table tn_user and how do i do that? im pretty new to laravel so not really quite understand how, usually i use CI
UserController.php
this is where the code i use to insert data
i use json response to parse the data and not quite sure how to insert data into 2 tables little help here
public function createOrEdit(){
//get current user
$currentUserId = Auth::user()->id;
$isUpdate = false;
$id = Input::get('id');
$user = new UserCompany;
if($id != ""){
$user = UserCompany::where('cn_id', '=', $id)->firstOrFail();
$user->cv_updated_by = $currentUserId;
$user->cv_updated_at = Carbon::now();
$isUpdate = true;
}else{
$user->cv_created_by = $currentUserId;
$user->cv_created_at = Carbon::now();
}
$user->cv_name = Input::get('name');
$user->cv_position = Input::get('position');
$user->cv_email = Input::get('email');
$user->cn_phone = Input::get('phone');
$user->cv_address = Input::get('address');
$user->cv_username = Input::get('username');
$user->cv_password = Input::get('password');
$user->cv_country = Input::get('country');
if($isUpdate){
UserCompany::where('cn_id','=',$id)->update(['cv_updated_by' => $user->cv_updated_by,
'cv_updated_at' => $user->cv_updated_at,
'cv_name' => $user->cv_name,
'cv_position' => $user->cv_position,
'cv_email' => $user->cv_email,
'cn_phone' => $user->cn_phone,
'cv_country' => $user->cv_country,
'cv_username' => $user->cv_username,
'cv_password' => $user->cv_password,
'cv_address' => $user->cv_address]);
}else{
$user->save();
}
$returnedData = UserCompany::all();
$response = array(
'content' => $returnedData,
'status' => 'success',
);
return Response::json($response);
}
UserCompany.php is my model but since im new im not really understand how to use relationship yet
<?php namespace Activity;
use Illuminate\Database\Eloquent\Model;
class UserCompany extends Model {
protected $table = 'tn_user';
public $timestamps = false;
protected $fillable = [
];
/*public function usercompany(){
return $this->belongsTo('Activity\user');
}*/
}
You should know that in the UserCompany class, by setting the fillable, It means you are setting table column which you want to alter, in this case tn_user table. So this means, by setting
protected $fillable = [];
It means, that you are making no table columns should undergo modification when you are using commands like;
$user_details->cv_name = Input::get('cv_name');
Okay, so the first thing that you should know is that when creating two tables i.e users and tn_users you should have a column which carries a value which relate the two tables, I suggest that you are to user id from the users table:
I have noticed that you have used cn_id to be a linker, but it is best if every table has its own incrementing id column and also in this case, its own link_id column
Let's say you are starting over:
Open the command prompt or Terminal and go to you laravel project folder directory and type: -$ php artisan make:model User -m and again -$ php artisan make:model UserDetail -m
What this will do is, create User and UserDetail, and adding the -m means its creating the migrations for the models associated which is create_users_table and create_user_details_table
From the create_users_table simply create the desired table columns as shown below:
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table){
$table->increments('id');
$table->integer('auth');
$table->string('username')->unique();
$table->string('email');
$table->string('password');
$table->boolean('online');
$table->string('lang', 2);
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
//
Schema::drop('users');
}
}
Now for the create_tn_users_table its kinda important, you should set which links with the users account so that suppose you delete the users, his credentials are also removed, but you can make it do otherwise if you want.
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateTnUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('tn_users', function (Blueprint $table) {
$table->increments('id');
$table->string('full_name');
$table->string('username')->unique();
$table->integer('link_user_id')
->references('id')->on('users'); // Relationship btn table tn_users and users
$table->string('phone');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('tn_users');
}
}
Now go the command prompt or terminal and type -$ php artisan migrate to have the tables created.
Again on the command prompt or terminal type -$ php artisan make:controller UserController --resource and have the controller made together with its resources.
On the create() function inside the UserController, add the Request in as a parameter.
The functions is to be reached upon the submission of the form that you have created
namespace App\Http\Controllers;
use App\User;
use App\TnUser;
use ...
class UserController extends Controller{
public function create(Request $request){
$tn_user = new TnUser();
$user = new User();
$user->username = $request['username'];
$user->password = bcrypt($request['username']);
...
$user->save();
$tn_user->full_name = ucword(strtolower($request['full_name'));
$tn_user->link_user_id = $user->id; // uses the previously save id
$tn_user->phone = trim($request['phone']);
$th_user->save();
}
}
I hope I have answered you questions. Here are some helpful links to learn.
https://laravel.com/docs/5.1/migrations#creating-columns
https://laravel.com/docs/5.1/requests
You Create 2 objects
$user = new User()
$user->username = INPUT::get('username');
$user->password = $password // Hashed
$user->save();
$user_detail = new UserCompany() // Your detail table modal.
$user_detail->cv_name = Input::get('cv_name');
//etc
$user_detail->save()

Work with php file outside public directory? I can access the file but receive error

I'm starting to get frustrated and cannot work with a php file that is outside my public folder. I am using fineuploader and this php mini framework https://github.com/panique/mini. I have the following file structure where “public” is my public directory.
application
--controller
----album.php
--libs
--model
public
--css
--img
--js
----application.js
I would like to use the php-file from a javascript in application.js. If I do like this and put s3demo in public/js folder everything works fine.
signature: {
endpoint: url + "/js/application/s3demo.php"
},
But I would like to have the s3demo.php in the application/libs folder instead of /js/application
I have using my controller with the following code
Javascript points to my controller instead of to the php-file
signature: {
endpoint: url + "/album/s3upload"
},
And my controller looks like this
public function s3upload() {
require APP . '/libs/s3demo.php';
}
When I run the code I get the following error message in the browser NET tab -> Response
Notice: Undefined index: _method in
/home/connecti/public_html/application/libs/s3demo.php on line 78
Warning: Cannot modify header information - headers already sent by
(output started at
/home/connecti/public_html/application/libs/s3demo.php:77) in
/home/connecti/public_html/application/libs/s3demo.php on line 103
Notice: Undefined index: headers in
/home/connecti/public_html/application/libs/s3demo.php on line 109
{"invalid":true}
My controller can access my s3admin.php (I have a index named “_method” in s3admin.php). But it feels like my php-file don’t know my javascript or something. What should I do to be able to runt s3demo.php from my libs folder? I don’t get any error if have have s3demo in the publicfolder and the fileupload works fine. If I have s3demo.php in my libs folder I get the error above and my file is not uploaded.
All javascript code
<script>
$(document).ready(function () {
$('#fineuploader-s3').fineUploaderS3({
request: {
// REQUIRED: We are using a custom domain
// for our S3 bucket, in this case. You can
// use any valid URL that points to your bucket.
endpoint: "upload.fineuploader.com",
// REQUIRED: The AWS public key for the client-side user
// we provisioned.
accessKey: "AKIAJB6BSMFWTAXC5M2Q"
},
template: "simple-previews-template",
// REQUIRED: Path to our local server where requests
// can be signed.
signature: {
endpoint: "/s3demo.php"
},
// OPTIONAL: An endopint for Fine Uploader to POST to
// after the file has been successfully uploaded.
// Server-side, we can declare this upload a failure
// if something is wrong with the file.
uploadSuccess: {
endpoint: "/s3demo.php?success"
},
// USUALLY REQUIRED: Blank file on the same domain
// as this page, for IE9 and older support.
iframeSupport: {
localBlankPagePath: "/server/success.html"
},
// optional feature
chunking: {
enabled: true
},
// optional feature
resume: {
enabled: true
},
// optional feature
deleteFile: {
enabled: true,
method: "POST",
endpoint: "/s3demo.php"
},
// optional feature
validation: {
itemLimit: 5,
sizeLimit: 15000000
},
thumbnails: {
placeholders: {
notAvailablePath: "assets/not_available-generic.png",
waitingPath: "assets/waiting-generic.png"
}
}
})
// Enable the "view" link in the UI that allows the file to be downloaded/viewed
.on('complete', function(event, id, name, response) {
var $fileEl = $(this).fineUploaderS3("getItemByFileId", id),
$viewBtn = $fileEl.find(".view-btn");
if (response.success) {
$viewBtn.show();
$viewBtn.attr("href", response.tempLink);
}
});
});
</script>
All php code in s3demo.php
<?php
/**
* PHP Server-Side Example for Fine Uploader S3.
* Maintained by Widen Enterprises.
*
*
* This example:
* - handles non-CORS environment
* - handles size validation and no size validation
* - handles delete file requests for both DELETE and POST methods
* - Performs basic inspections on the policy documents and REST headers before signing them
* - Ensures again the file size does not exceed the max (after file is in S3)
* - signs policy documents (simple uploads) and REST requests
* (chunked/multipart uploads)
*
* Requirements:
* - PHP 5.3 or newer
* - Amazon PHP SDK (only if utilizing the AWS SDK for deleting files or otherwise examining them)
*
* If you need to install the AWS SDK, see http://docs.aws.amazon.com/aws-sdk-php-2/guide/latest/installation.html.
*/
// You can remove these two lines if you are not using Fine Uploader's
// delete file feature
require 'aws/aws-autoloader.php';
use Aws\S3\S3Client;
// These assume you have the associated AWS keys stored in
// the associated system environment variables
$clientPrivateKey = $_SERVER['AWS_SECRET_KEY'];
// These two keys are only needed if the delete file feature is enabled
// or if you are, for example, confirming the file size in a successEndpoint
// handler via S3's SDK, as we are doing in this example.
$serverPublicKey = $_SERVER['PARAM1'];
$serverPrivateKey = $_SERVER['PARAM2'];
// The following variables are used when validating the policy document
// sent by the uploader.
$expectedBucketName = "upload.fineuploader.com";
// $expectedMaxSize is the value you set the sizeLimit property of the
// validation option. We assume it is `null` here. If you are performing
// validation, then change this to match the integer value you specified
// otherwise your policy document will be invalid.
// http://docs.fineuploader.com/branch/develop/api/options.html#validation-option
$expectedMaxSize = null;
$method = getRequestMethod();
// This second conditional will only ever evaluate to true if
// the delete file feature is enabled
if ($method == "DELETE") {
deleteObject();
}
// This is all you really need if not using the delete file feature
// and not working in a CORS environment
else if ($method == 'POST') {
// Assumes the successEndpoint has a parameter of "success" associated with it,
// to allow the server to differentiate between a successEndpoint request
// and other POST requests (all requests are sent to the same endpoint in this example).
// This condition is not needed if you don't require a callback on upload success.
if (isset($_REQUEST["success"])) {
verifyFileInS3();
}
else {
signRequest();
}
}
// This will retrieve the "intended" request method. Normally, this is the
// actual method of the request. Sometimes, though, the intended request method
// must be hidden in the parameters of the request. For example, when attempting to
// send a DELETE request in a cross-origin environment in IE9 or older, it is not
// possible to send a DELETE request. So, we send a POST with the intended method,
// DELETE, in a "_method" parameter.
function getRequestMethod() {
if ($_POST['_method'] != null) {
return $_POST['_method'];
}
return $_SERVER['REQUEST_METHOD'];
}
function getS3Client() {
global $serverPublicKey, $serverPrivateKey;
return S3Client::factory(array(
'key' => $serverPublicKey,
'secret' => $serverPrivateKey
));
}
// Only needed if the delete file feature is enabled
function deleteObject() {
getS3Client()->deleteObject(array(
'Bucket' => $_POST['bucket'],
'Key' => $_POST['key']
));
}
function signRequest() {
header('Content-Type: application/json');
$responseBody = file_get_contents('php://input');
$contentAsObject = json_decode($responseBody, true);
$jsonContent = json_encode($contentAsObject);
$headersStr = $contentAsObject["headers"];
if ($headersStr) {
signRestRequest($headersStr);
}
else {
signPolicy($jsonContent);
}
}
function signRestRequest($headersStr) {
if (isValidRestRequest($headersStr)) {
$response = array('signature' => sign($headersStr));
echo json_encode($response);
}
else {
echo json_encode(array("invalid" => true));
}
}
function isValidRestRequest($headersStr) {
global $expectedBucketName;
$pattern = "/\/$expectedBucketName\/.+$/";
preg_match($pattern, $headersStr, $matches);
return count($matches) > 0;
}
function signPolicy($policyStr) {
$policyObj = json_decode($policyStr, true);
if (isPolicyValid($policyObj)) {
$encodedPolicy = base64_encode($policyStr);
$response = array('policy' => $encodedPolicy, 'signature' => sign($encodedPolicy));
echo json_encode($response);
}
else {
echo json_encode(array("invalid" => true));
}
}
function isPolicyValid($policy) {
global $expectedMaxSize, $expectedBucketName;
$conditions = $policy["conditions"];
$bucket = null;
$parsedMaxSize = null;
for ($i = 0; $i < count($conditions); ++$i) {
$condition = $conditions[$i];
if (isset($condition["bucket"])) {
$bucket = $condition["bucket"];
}
else if (isset($condition[0]) && $condition[0] == "content-length-range") {
$parsedMaxSize = $condition[2];
}
}
return $bucket == $expectedBucketName && $parsedMaxSize == (string)$expectedMaxSize;
}
function sign($stringToSign) {
global $clientPrivateKey;
return base64_encode(hash_hmac(
'sha1',
$stringToSign,
$clientPrivateKey,
true
));
}
// This is not needed if you don't require a callback on upload success.
function verifyFileInS3() {
global $expectedMaxSize;
$bucket = $_POST["bucket"];
$key = $_POST["key"];
// If utilizing CORS, we return a 200 response with the error message in the body
// to ensure Fine Uploader can parse the error message in IE9 and IE8,
// since XDomainRequest is used on those browsers for CORS requests. XDomainRequest
// does not allow access to the response body for non-success responses.
if (getObjectSize($bucket, $key) > $expectedMaxSize) {
// You can safely uncomment this next line if you are not depending on CORS
header("HTTP/1.0 500 Internal Server Error");
deleteObject();
echo json_encode(array("error" => "File is too big!"));
}
else {
echo json_encode(array("tempLink" => getTempLink($bucket, $key)));
}
}
// Provide a time-bombed public link to the file.
function getTempLink($bucket, $key) {
$client = getS3Client();
$url = "{$bucket}/{$key}";
$request = $client->get($url);
return $client->createPresignedUrl($request, '+15 minutes');
}
function getObjectSize($bucket, $key) {
$objInfo = getS3Client()->headObject(array(
'Bucket' => $bucket,
'Key' => $key
));
return $objInfo['ContentLength'];
}
?>
You are getting a notice message and then the headers cannot be sent. Disable the notice messages with error_reporting(E_ALL ^ E_NOTICE) at the beginning of your script;

Categories