jQuery File Upload with Wistia API - javascript

I've got an demo page with jQuery File Upload that is currently allowing upload of video files to the web hosting through PHP.
Code:
<?
// A list of permitted file extensions
$allowed = array('mov', 'mp4', 'avi');
if(isset($_FILES['upl']) && $_FILES['upl']['error'] == 0){
$extension = pathinfo($_FILES['upl']['name'], PATHINFO_EXTENSION);
if(!in_array(strtolower($extension), $allowed)){
echo '{"status":"error"}';
exit;
}
if(move_uploaded_file($_FILES['upl']['tmp_name'], 'uploads/'.$_FILES['upl']['name'])){
echo '{"status":"success"}';
exit;
}
}
echo '{"status":"error"}';
exit;
?>
I need this demo to be fully working to upload video files to my Wistia gallery through their API instead of upload directory.
Working snippet for upload.php to Wistia API with video url:
<?
$data = array(
'api_password' => '[password]',
'project_id' => '[project_id]',
'url' => '[video_url]'
);
$wistia = curl_init('https://upload.wistia.com');
curl_setopt_array($wistia, array(
CURLOPT_POST => TRUE,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_POSTFIELDS => http_build_query($data)
));
// Send the request
$wistia_request = curl_exec($wistia);
?>
However changing these values and using it in my form doesn't work:
$data = array(
'api_password' => '[password]',
'project_id' => '[project_id]',
'file' => '#' . $_FILES['upl']['name']
);
As you can see I need guidance and help. Any hints are much appreciated.
Here's some docs for this project:
http://wistia.com/doc/upload-api
https://github.com/blueimp/jQuery-File-Upload

Solved!
$data = [
'file' => "#{$_FILES['upl']['tmp_name']};filename={$_FILES['upl']['name']};type={$_FILES['upl']['type']}"
]

If you are going to upload the file directly there is no reason to move the uploaded file. You could probably just use the tmp-file directly.
$data= [
'file' => '#' . $_FILES['upl']['tmp_name']
]
The next problem is that you are now doing 2 video uploads. 1 from the users computer to your server and then one from your server to Wistia.
So instead of letting the user wait for 2 uploads you should move the second one into a background task.

Related

Proper way to download multiple files from s3 on fly in zip?

I want to download multiple files from amazon s3 in zip file while click on single download button.
I want to achieve this using php or JavaScript.
I went over many solutions such as: Use recursive in aws cli,
Zipstream on fly, but I didn't get any proper solution.
Do you have any idea for another, more efficient solution?
<?php
$urls = [
'http://django-dev.s3.amazonaws.com/static/img/sample-store.jpg',
'http://ds-assets.s3.amazonaws.com/baobao/feature/2020/video/movie_sample.mp4',
'http://ds-assets.s3.amazonaws.com/briefing/mailmagazine/2019/0701/sample_g.jpg',
];
$mh = curl_multi_init();
$resources = [];
foreach ($urls as $key => $url) {
$resources[$key]['fp'] = fopen(sys_get_temp_dir() . '/file' . $key, 'w+'); // file pointer
$resources[$key]['ch'] = curl_init($url); // curl handle
curl_setopt($resources[$key]['ch'], CURLOPT_FILE, $resources[$key]['fp']);
curl_setopt($resources[$key]['ch'], CURLOPT_FOLLOWLOCATION, true);
curl_multi_add_handle($mh, $resources[$key]['ch']);
}
$running = null;
do {
curl_multi_exec($mh, $running);
} while ($running);
$zip = new ZipArchive();
$zip->open(sys_get_temp_dir() . '/files.zip', ZIPARCHIVE::CREATE);
foreach ($resources as $key => $resource) {
curl_multi_remove_handle($mh, $resource['ch']);
curl_close($resource['ch']);
fclose($resource['fp']);
$zip->addFile(sys_get_temp_dir() . '/file' . $key, '/file' . $key);
}
curl_multi_close($mh);
$zip->close();
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename=files.zip');
header('Pragma: no-cache');
readfile(sys_get_temp_dir() . '/files.zip');

Lost variable i script

I have some problem with a variable in my script I need to "send" the variable through some different files
The variable comes from the link:
index.php?email=emailname#emailname.com
The script is a file upload script. It's using 3 files in the process, please here:
/public_html/upload/index.php
/public_html/upload/content/index.php
/public_html/upload/content/UploadHandler.php
/public_html/upload/index.php is that runs the script and where the variable is received from the link:
index.php?email=emailname#emailname.com
The file code of /public_html/upload/index.php looks like:
<?php
// change the name below for the folder you want
$dir = "content/".$_GET["email"];
$file_to_write = 'test.txt';
$content_to_write = "The content";
if( is_dir($dir) === false )
{
mkdir($dir);
}
$file = fopen($dir . '/' . $file_to_write,"w");
// a different way to write content into
// fwrite($file,"Hello World.");
fwrite($file, $content_to_write);
// closes the file
fclose($file);
// this will show the created file from the created folder on screen
include $dir . '/' . $file_to_write;
$_SESSION['tmem']= $_GET["email"];
?>
I know that $_GET["email"] works since I can the code: <?=$_GET["email"]?> on the index.php file to see if it receive the variable.
The code:
$_SESSION['tmem']= $_GET["email"];
should forward the variable to the next file:
/public_html/upload/content/index.php
that looks like this:
session_start();
$dir = "content/" . $_GET["email"];
error_reporting(E_ALL | E_STRICT);
require('UploadHandler.php');
$upload_handler = new UploadHandler( array ('upload_url' =>$dir) );
And that code should forward the variable to the codes of the script where the upload patch is. Codes on the file: /public_html/upload/content/UploadHandler.php looks like:
'script_url' => $this->get_full_url().'/'.$this->basename($this->get_server_var('SCRIPT_NAME')),
'upload_dir' => dirname($this->get_server_var('SCRIPT_FILENAME')).'/'.$_GET['email'].'/',
'upload_url' => $this->get_full_url().'/'.$_GET['email'].'/',
'input_stream' => 'php://input',
'user_dirs' => false,
'mkdir_mode' => 0755,
'param_name' => 'files',
Can somebody see where in the process I lose the variable?
I think, in this part of code:
session_start();
$dir = "content/" . $_GET["email"];
you try to get your "email" from URI instead of getting it from session (tmem).

Jquery and Swfupload causing whole website to slow down drastically

I have been working on a website for a while and I recently encountered a problem that I can't seem to figure out. I am a relatively new web developer so help would be greatly appreciated.
I am using swfupload to handle audio uploads to my website. I am aware that swfupload has the power to handle multiple file uploads at once through a queue. However, when I queue up a long list of audio files, the uploading would begin to get slow and slower with each file...The php code used to handle the uploading is given below. Even though the code references a lot of other helper functions, I will do my best to explain what I am trying to do...
Essentially with all the fluff aside such as user authorization checks..etc, the code creates a temporary "track" which is stored in my database. Tracks are stored under a certain album(I refer to albums as releases) and once a temporary track is created under that certain album, I can then upload an audio file under that database entry. I use getID3 to parse the media file and then update the track information in the database by whatever I can pull from the audio.
This code works fine but if I select over (queue up) 15ish tracks to upload, the tracks after the 15th one becomes slow and by the 50th track...uploading will take over 10 minutes for just 1 file. I know there can be a lot of issues causing this but I was just wondering if anyone had a hint on where this issue might be?
Thanks a lot!
<?php
private function saveBatchAudio($artist) {
Utils::checkFileUpload();
if ($this->isEditable($artist['artist_id'])) {
require_once "Db/DbTracks.php";
require_once "Db/DbReleases.php";
$trackList = DbTracks::getTracksByReleaseHash($_POST['ReleaseHash'], 0, 100);
$trackListOrder = count($trackList);
$row = array(
'track_name' => Utils::escape($_POST['Name']),
'artist_id' => $artist['artist_id'],
'release_hash' => Utils::escape($_POST['ReleaseHash']),
'track_order' => $trackListOrder+1,
'user_id' => $_SESSION['user']['user_id'],
'track_upload_user_ip' => Utils::getIpAddress()
);
$id = DbTracks::newTrack($row);
$this->log($artist, "User [{$_SESSION['user']['user_name']}] has created track:" . var_export($row, true));
}
else {
echo json_encode(array(
'message' => Utils::getMessage('e001')
));
}
require_once "Db/DbTracks.php";
$track = DbTracks::getTrackById($id);
if (!empty($track)) {
$f = __FFM_ARCHIVE__ . $track['release_hash'] . '/' . $track['track_filename'];
if (!empty($track['track_filename']) && file_exists($f)) {
unlink($f);
}
include_once "formatting.php";
$filename = wp_unique_filename(__FFM_ARCHIVE__ . $track['release_hash'], $_FILES['Filedata']['name']);
$path = __FFM_ARCHIVE__ . $track['release_hash'] . '/' . $filename;
if (!is_dir(dirname($path))) {
wp_mkdir_p(dirname($path));
}
move_uploaded_file($_FILES["Filedata"]["tmp_name"], $path);
require_once(dirname(__FILE__) . '/../../getid3/getid3.php');
$getID3 = new getID3;
$getID3->setOption(array('encoding' => 'UTF-8'));
$info = $getID3->analyze($path);
getid3_lib::CopyTagsToComments($info);
$data = array(
'track_name' => isset($info['tags']['id3v2']['title']['0']) ? $info['tags']['id3v2']['title']['0'] : $filename,
'track_label' => isset($info['tags']['id3v2']['album']['0']) ? $info['tags']['id3v2']['album']['0'] : Utils::escape($_POST['Label']),
'track_year' => isset($info['tags']['id3v2']['year']['0']) ? $info['tags']['id3v2']['year']['0'] : Utils::escape($_POST['Year']),
'track_filename' => $filename,
'track_size' => filesize($path),
'track_length' => isset($info['playtime_seconds']) ? $info['playtime_seconds'] : 0,
'track_bitrate' => isset($info['audio']['bitrate']) ? $info['audio']['bitrate'] : 0,
);
DbTracks::updateTrackById($track['track_id'], $data);
$this->zipFolder(__FFM_ARCHIVE__ . $track['release_hash'], $track['release_hash']);
$this->log($artist, "User [{$_SESSION['user']['user_name']}] has uploaded track");
echo json_encode(array(
'mp3' => $mp3 = __FFM_ARCHIVE_FRONT__ . $track['release_hash'] . '/' . $filename
));
} else {
echo json_encode(array(
'message' => Utils::getMessage('e002')
));
}
}
?>

Facebook App Issue - Can not obtain Permissions , Keeps on refreshing

I found this Love Calculator app online , It is open source and free to use, I setted it up on my test server, I added all the app Id's and secrets and did all the setting but I am getting this permissions issue when I or Someone else try to use it , There are 3 Important files in this script,
Config.php (i setted it up , it has only 4 fields for the app id,secret,canvas url,app domain)
Index.php
Facebook.php (this is the sdk I figure)
Config.php is loaded in Index.php with the following code
include_once ('lib/facebook.php'); // Facebook client library
include_once ('config.php'); // Config file
// Constants are located in config.php file
$facebook = new Facebook(
array(
'appId' => FACEBOOK_APP_ID,
'secret' => FACEBOOK_SECRET_KEY,
'cookie' => true,
'domain' => FACEBOOK_DOMAIN
)
);
Now , When I tried to figure out the problem , I found this code in index.php for obtaining permissions
$session = $facebook->getSession();
if (!$session) {
$url = $facebook->getLoginUrl(array(
'canvas' => 1,
'fbconnect' => 0,
'scope' => 'publish_stream'
));
echo "<script type='text/javascript'>top.location.href = '$url';</script>";
} else {
try {
$uid = $facebook->getUser();
$me = $facebook->api('/me');
$updated = date("l, F j, Y", strtotime($me['updated_time']));
} catch (FacebookApiException $e) {
echo "<script type='text/javascript'>top.location.href = '$url';</script>";
exit;
}
}
The canvas app url is https://apps.facebook.com/fb-love-calculator-f
The domain url is https://apps.mjobz.com/love/
You are using and out dated version of facebook sdk, Facebook sdk has updated a couple of times after this one

Validating a downloading file

I have some files in server that users can download it but user must be logged in to download those files so files are in format of rar or zip. is there any way to validate that use is already logged before downloading files in php ?
<?php
session_start();
if (isset($_COOKIE['username']) AND isset($_COOKIE['hash']) {
if (isset($_SESSION['url']) {
Header("Location:".$_SESSION['url']);
}
}
?>
yeah below is approach to use
step1:prevent zip file direct access
order allow,deny
deny from all
step2:
<?php
function output_file($file, $name, $mime_type='')
{
if(!is_readable($file)) die('File not found or inaccessible!');
$size = filesize($file);
$name = rawurldecode($name);
$known_mime_types=array(
"htm" => "text/html",
"exe" => "application/octet-stream",
"zip" => "application/zip",
"doc" => "application/msword",
"jpg" => "image/jpg",
"php" => "text/plain",
"xls" => "application/vnd.ms-excel",
"ppt" => "application/vnd.ms-powerpoint",
"gif" => "image/gif",
"pdf" => "application/pdf",
"txt" => "text/plain",
"html"=> "text/html",
"png" => "image/png",
"jpeg"=> "image/jpg"
);
if($mime_type==''){
$file_extension = strtolower(substr(strrchr($file,"."),1));
if(array_key_exists($file_extension, $known_mime_types)){
$mime_type=$known_mime_types[$file_extension];
} else {
$mime_type="application/force-download";
};
};
//turn off output buffering to decrease cpu usage
#ob_end_clean();
// required for IE, otherwise Content-Disposition may be ignored
if(ini_get('zlib.output_compression'))
ini_set('zlib.output_compression', 'Off');
header('Content-Type: ' . $mime_type);
header('Content-Disposition: attachment; filename="'.$name.'"');
header("Content-Transfer-Encoding: binary");
header('Accept-Ranges: bytes');
// multipart-download and download resuming support
if(isset($_SERVER['HTTP_RANGE']))
{
list($a, $range) = explode("=",$_SERVER['HTTP_RANGE'],2);
list($range) = explode(",",$range,2);
list($range, $range_end) = explode("-", $range);
$range=intval($range);
if(!$range_end) {
$range_end=$size-1;
} else {
$range_end=intval($range_end);
}
$new_length = $range_end-$range+1;
header("HTTP/1.1 206 Partial Content");
header("Content-Length: $new_length");
header("Content-Range: bytes $range-$range_end/$size");
} else {
$new_length=$size;
header("Content-Length: ".$size);
}
/* Will output the file itself */
$chunksize = 1*(1024*1024); //you may want to change this
$bytes_send = 0;
if ($file = fopen($file, 'r'))
{
if(isset($_SERVER['HTTP_RANGE']))
fseek($file, $range);
while(!feof($file) &&
(!connection_aborted()) &&
($bytes_send<$new_length)
)
{
$buffer = fread($file, $chunksize);
echo($buffer);
flush();
$bytes_send += strlen($buffer);
}
fclose($file);
} else
//If no permissiion
die('Error - can not open file.');
//die
die();
}
//Set the time out
set_time_limit(0);
//path to the file
$file_path='files/'.$_REQUEST['filename'];
//Call the download function with file path,file name and file type
if($_SESSION['userloggedin']){
output_file($file_path, ''.$_REQUEST['filename'].'', 'text/plain');
}else{
echo "login";
}
?>
You can do this like any other content you are serving. A php file does not have to return a text/html document. It can serve any data, including images, pdf's or executables. You just have to serve it with the right headers.
<?php
if(isset($_COOKIE['username']) && isset($_COOKIE['hash'])
{
//The user is logged in... we have no clue if the user is allowed to download the file
header( "Content-Type: image/jpeg" );
header( "Cache-Control: private, max-age=0, no-cache" );
file_get_contents( "images/image.jpg" );
exit();
} else {
header('HTTP/1.0 403 Forbidden');
exit();
}
The cache-control header is here to prevent servers between the client and your server from caching this request. ISP's sometimes do this to serve common files faster. The content-type header should be set to the correct mime-type based on what file you are serving. You can find a list of common mime types on wikipedia.
IMPORTANT
This answer uses 'file_get_contents(...)'. You should always make sure that the url that is passed to this function is sane. This means: It should point to an existing file, and it should only point to a file you actually want to serve. If someone passes '../../../.htaccess' you don't want to accidentally spill the contents of that file to the user!

Categories

Resources