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')
));
}
}
?>
Related
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');
I'm studying Prestashop's development. And I trying to create a "third part" side application with react.js (React Native for more precision) and catch Json data in the prestashop's webservice. But I want to let the "customer" make login with his own account and only his account. With CRUD also.
in advance; Very thank you for your patience and attention.
Best Regards.
Michel Diz
Prestashop backoffice login give no access to webservices. Webservices must be enabled and a key generated. So, I recommend you that change your "login" way. Customers accounts are not related with webservices and webservices are only used to access stored data un Prestashop (more like Backoffice than Frontoffice).
What exactly do you need to do?
I hope it helps you.
I don't know if you're still searching for a solution but there is a way actually.
DO MAKE SURE IT IS A SECURE LOGIN.
Since you're giving access to all prestashop data do make sure the login is very secure. I've been able to recreate it with PHP I think that with some additions you're able to recreate it the way you want it. See it as a guideline.
To create a login system by using the prestashop webservice you'll need three things
Access through webservice to the customers table
The COOKIE_KEY, defined in app/config -> parameters.php:: 'cookie_key' => '12321test';
Some expierence with PHP
The first thing is to get the customers table from the webservice.
// code placeholder
require_once('./../PSWebServiceLibrary.php');
/**
* get information from PrestaShop
*/
$webService = new PrestaShopWebservice($url, $key, $debug);
$COOKIE_KEY = 'CookieKey';
$email = $_REQUEST['email'];
$password = $_REQUEST['password'];
$optUser = array(
'resource' => 'customers',
'filter[email]' => '[' . $email . ']',
'display' => '[id,email,lastname,firstname,passwd]'
);
$resultUser = ($webService->get($optUser));
$json = json_encode($resultUser);
The second and most important thing is to Check the user input
// code placeholder
foreach ($resultUser->customers->customer as $info) {
// Prestashop uses the cookie_key in combination with a salt key. To check the password use the php function: password_verify();
$salt = substr($info->passwd, strrpos($info->passwd, ':') + 1, 2);
$ZCpassword = md5($COOKIE_KEY . $password) . ':' . $salt;
// Check if password comparison is true or false
if (password_verify($password, $info->passwd) == true) {
session_start();
$response = array();
$response['status'] = 'succes';
$response['message'] = "You did it!";
setcookie("userId", $info->id);
header('Content-type: application/json');
echo json_encode($response);
} else {
$response = array();
$response['status'] = 'error';
$response['message'] = 'Wrong password';
header('Content-type: application/json');
echo json_encode($response);
}
}
This is how to reproduce the issue to a working example.
Hope this helps!
For those who are still searching for this answer,
<?
if (isset($_GET["email"]) && isset($_GET["password"]) )
{
$email = $_GET["email"];
$password = $_GET["password"];
$COOKIE_KEY = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
$jsonurl = "https://XXXXXXXXXXXXXXXXXXXX#example.com/api/customers?filter[email]=".$email."&display=[passwd]&output_format=JSON";
$json = file_get_contents($jsonurl);
$json_a = json_decode($json, true);
$loopone = $json_a['customers'];
$looptwo = $loopone[0];
$loopthree = $looptwo['passwd'];
$ZCpassword = md5($COOKIE_KEY . $password);
if (strcmp($loopthree, $ZCpassword) == 0) {
echo "sucess";
} else {
echo "fail";
}
}
else
{
echo "Send something with url dude";
}
?>
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).
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.
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