PHP Foreach and jQuery - php

I am working on a piece of code that I am wanting to "spice" up with jQuery but I can't think of a way to actually make it work. I am sure its simple, I just need a little advice to get me going.
I am wanting to create a piece of code that makes an Ajax request out to start a big loop that will download files and then upload them to an S3 bucket of mine. The place where I am stuck is I am wanting to send back a request back to the browser everytime a file is uploaded and output a string of text to the screen upon completion.
I don't have any of the frontend code working... just trying to get my head wrapped around the logic first... any ideas?
PHP Backend Code:
<?php
public function photos($city) {
if(isset($city))
$this->city_name = "{$city}";
// grab data array from Dropbox folder
$postcard_assets = $this->conn->getPostcardDirContent("{$this->city_name}", "Photos", TRUE);
$data = array();
foreach($postcard_assets['contents'] as $asset) {
//only grab contents in root folder... do not traverse into sub folders && make sure the folder is not empty
if(!$asset['is_dir'] && $asset['bytes'] > 0) {
// get information on file
$file = pathinfo($asset['path']);
// download file from Dropbox
$original_file = $this->conn->downloadFile(str_replace(" ", "%20", $asset['path']));
// create file name
$file_name = $this->cleanFileName($file['basename']);
// write photo to TMP_DIR ("/tmp/photos/") for manipulation
$fh = fopen(self::TMP_DIR . $file_name, 'w');
fwrite($fh, $original_file);
fclose($fh);
// Resize photo
$this->resize_photo($file_name);
// hash file name
$raw_file = sha1($file_name);
// create S3 hashed name
$s3_file_name = "1_{$raw_file}.{$file['extension']}";
// Upload manipulated file to S3
$this->s3->putObject($s3_file_name, file_get_contents(self::TMP_DIR . $file_name), $this->photo_s3_bucket, 'public-read');
// check to see if file exists in S3 bucket
$s3_check = $this->s3->getObjectInfo($s3_file_name, $this->photo_s3_bucket);
// if the file uploaded successully to S3, load into DB
if($s3_check['content-length'] > 0) {
$data['src'] = $s3_file_name;
$data['width'] = $this->width;
$data['height'] = $this->height;
Photo::create_postcard_photo($data, "{$this->city_name}");
// Now that the photo has been uploaded to S3 and saved in the DB, remove local file for cleanup
unlink(self::TMP_DIR . $file_name);
echo "{$file_name} uploaded to S3 and resized!<br />";
}
}
}
// after loop is complete, kill script or nasty PHP header warnings will appear
exit();
}
?>

The main problem is that with PHP, the output is buffered so it won't return a line at a time. You can try and force the flush but it's not always reliable.
You could add an entry to the DB for each file that is exchanged and create a seperate API to get the details of what has completed.
Generally, Jquery will wait till the request has finished before it allows you to manipulate data from a HTTP request.

Related

php getID3 returning the same info of an updated file?

I'm using the getID3 library to get the details of a remote video file. I'm trying to read a portion of the file to get the details of the file, however some videos don't have the full details at the start.
For these videos, I'm trying to download the full video, and then extract the relevant information. However, even after the video has downloaded completely, getID3->analyze($filename), returns the same erroneous file info.
But when I copy the video, and then run the function analyze($filename.'copied.mp4') on copied video, it returns the correct info even though the file contents are same. Perhaps getID3 isn't loading the video again, however, how can I fix this issue without copying the video.
Please find the code below.
if ($fp_remote = fopen($remotefilename, 'r')) {
echo 'conn opened';
$localtempfilename = tempnam('/home/xerox/abc', 'whateva').'.mp4';
if ($fp_local = fopen($localtempfilename, 'wb')) {
$count = 0;
$countExpiry = 8;
while ($buffer = fread($fp_remote, 8192)) {
$count++;
fwrite($fp_local, $buffer);
if ($count >= $countExpiry) {
fflush($fp_local);
$getID3 = new getID3;
$ThisFileInfo = $getID3->analyze($localtempfilename);
if ($ThisFileInfo["error"]){
print "problem encouterd";
$countExpiry += 1000;
} else {
break;}
}
}
fclose($fp_local);
$getID31 = new getID3;
copy ( $localtempfilename, $localtempfilename.'_copied.mp4' );
$ThisFileInfoz = $getID31->analyze($localtempfilename.'_copied.mp4');
// Delete temporary file
unlink($localtempfilename);
fclose($fp_remote);
var_dump($ThisFileInfoz);
}
}
A call to clearstatcache solved the problem for me,
since repeated calls to things like filesize will be cached by the
filesystem and getID3 won't read beyond end-of-file.
source: James Heinrich, developer of getID3.

Uploading files using php very slow in xampp

I am new for developing.I have opted for php to learn coding.So I might make mistake as I learn by myself, kindly clarify my doubts.
I have problem in uploading files using php to a folder.What I really do is, I upload a file and the file is saved in a folder and the name of the file alone inserted in the database. While uploading the file I do copy the file to another folder which will be used for the editing purpose so that the original file will not be disturbed.Here the problem I get is, the file is uploaded successfully as well as the name too inserted in database. But it take much time to get upload even the size of the file is small.It works good while I test using my local but when I come in real time this issue(slow uploading) I face. What the person incharge in uploading do is, uploading a file and opening a new browser and upload another file. When the new browser is opened the files get uploaded but in the previous browser it is still in process. The code I have written to copy the file to another folder is not executed as the new browser is opened to upload another set of files. I am using xamp cp v3.2.1.To minimize the execution time I have set the default Maximum execution time to 30. But unable to upload file fastly.
Below is my php coding:
<?php
// connect to the database
include('connect-db.php');
if (isset($_POST['submit']))
{
// get form data, making sure it is valid
$udate = mysql_real_escape_string(htmlspecialchars($_POST['udate']));
$file_array=($_FILES['file_array']['name']);
// check to make sure both fields are entered
if ($udate == '' || $file_array=='')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
// if either field is blank, display the form again
renderForm($udate, $file_array, $error);
}
else
{
$udate = mysql_real_escape_string(htmlspecialchars($_POST['udate']));
if(isset($_FILES['file_array']))
{
$name_arrray=$_FILES['file_array']['name'];
$tmp_name_arrray=$_FILES['file_array']['tmp_name'];
for($i=0;$i <count($tmp_name_arrray); $i++)
{
if(move_uploaded_file($tmp_name_arrray[$i],"test_uploads/".str_replace(' ','',$name_arrray[$i])))
{
// save the data to the database
$j=str_replace(' ','',$name_arrray[$i]);
echo $j;
$udate = mysql_real_escape_string(htmlspecialchars($_POST['udate']));
$provider = mysql_real_escape_string(htmlspecialchars($_POST['provider']));
$existfile=mysql_query("select ubatch_file from batches");
while($existing = mysql_fetch_array( $existfile)) {
if($j==$existing['ubatch_file'])
echo' <script>
function myFunction() {
alert("file already exists");
}
</script>';
}
mysql_query("INSERT IGNORE batches SET udate='$udate', ubatch_file='$j',provider='$provider',privilege='$_SESSION[PRIVILEGE]'")
or die(mysql_error());
echo $name_arrray[$i]."uploaded completed"."<br>";
$src = 'test_uploads';
$dst = 'copy_test_uploads';
$files = glob("test_uploads/*.*");
foreach($files as $file){
$file_to_go = str_replace($src,$dst,$file);
copy($file, $file_to_go);
/* echo "<script type=\"text/javascript\">
alert(\"CSV File has been successfully Uploaded.\");
window.location = \"uploadbatches1.php\"
</script>";*/
}
} else
{
echo "move_uploaded_file function failed for".$name_array[$i]."<br>";
}
}
}
// once saved, redirect back to the view page
header("Location:uploadbatches1.php");
}
}
?>
It takes much time because, each and everytime all the files are copied to the newfolder. This exceeds the execution time.Only copying the uploaded files makes uploading and copying files fast.

Downloading files from server

In my project I have a code for downloading images from a server. In php code I have:
if (is_dir($dir)){ //check if is directory
$files = scandir($dir); //list files
$i=-1;
$result = array();
foreach($files as $file){
$file = $dir.$file; //complete dir of file
if(is_file($file)){ //if it's a file
$i++;
$fileo = #fopen($file,"rb"); //open and write it on $result[$i]
if ($fileo) {
$result[$i] = "";
while(!feof($fileo)) {
$result[$i] .= fread($fileo, 1024*8);
flush();
if (connection_status()!=0) {
#fclose($fileo);
die();
}
}
$result[$i] = utf8_encode($result[$i]); //This prevents null returning on jsonencode
#fclose($fileo);
}
}
}
}else{
echo json_encode(array('Error'));
}
echo json_encode($result); //returns images as an array of strings, each one with all code of an image.
And in java I have an httpost method with asynctask. The problem of this is that I need to wait until all images are downloaded. I have thought that maybe I can download an image with a number and if the number is 0 for example recall to the server to download the next image but I think that maybe is a waste of time calling again the server and listing files again. Is there a better way so I can download image per image instead of all at the same time without calling N times to the sever?
I've had the same problem that you are having, and my solution was the next:
1º Download all data you need
2º Download to the computer the image web direction
3º Execute an asynctask per Image to download it and update your Activity while is needed
Maybe i'm not so exact and i would need some more details to give a better solution.

PHP upload image via AJAX/HTML 5 rename file

I am not real good at reading the code for uploading images via php/ajax so i am hoping a php guru can help me out. I am trying to take the image file name and if it has spaces in it then replace those spaces with an underscore "_"
The php code for uploading is this:
$file_name = ( isset($_REQUEST['ax-file-name']) && !empty($_REQUEST['ax-file-name']) )?$_REQUEST['ax-file-name']:'';
$currByte = isset($_REQUEST['ax-start-byte'])?$_REQUEST['ax-start-byte']:0;
if($is_ajax)//Ajax Upload, FormData Upload and FF3.6 php:/input upload
{
//we get the path only for the first chunk
$full_path = ($currByte==0) ? checkFileExits($file_name, $upload_path):$upload_path.$file_name;
//Just optional, avoid to write on exisiting file, but in theory filename should be unique from the checkFileExits function
$flag = ($currByte==0) ? 0:FILE_APPEND;
//formData post files just normal upload in $_FILES, older ajax upload post it in input
$post_bytes = isset($_FILES['Filedata'])? file_get_contents($_FILES['Filedata']['tmp_name']):file_get_contents('php://input');
//some rare times (on very very fast connection), file_put_contents will be unable to write on the file, so we try until it writes
while(#file_put_contents($full_path, $post_bytes, $flag) === false)
{
usleep(50);
}
//delete the temporany chunk
if(isset($_FILES['Filedata']))
{
#unlink($_FILES['Filedata']['tmp_name']);
}
//if it is not the last chunk just return success chunk upload
if($isLast!='true')
{
echo json_encode(array('name'=>basename($full_path), 'size'=>$full_size, 'status'=>1, 'info'=>'Chunk uploaded'));
}
}
else //Normal html and flash upload
{
$isLast = 'true';//we cannot upload by chunks here so assume it is the last single chunk
$full_path = checkFileExits($file_name, $upload_path);
$result = move_uploaded_file(str_replace(" ", "_",$_FILES['Filedata']['tmp_name']), $full_path);//make the upload
if(!$result) //if any error return the error
{
echo json_encode( array('name'=>basename($full_path), 'size'=>$full_size, 'status'=>-1, 'info'=>'File move error') );
return false;
}
}
I've already tried the following (with str_replace(" ", "_", $nameoffile):
$post_bytes = isset($_FILES['Filedata'])? file_get_contents(str_replace(" ", "_",$_FILES['Filedata']['tmp_name'])):file_get_contents('php://input');
That seems to do nothing to rename it. So where am i missing it at?
The problem in your code is , you are trying to rename the temporary name of image file not the actual name
move_uploaded_file(str_replace(" ", "_",$_FILES['Filedata']['tmp_name']), $full_path);//make the upload
So you have to remove the str_replace from temporary name and append this to actual name like this.
move_uploaded_file($_FILES['Filedata']['tmp_name'], str_replace(" ", "_",$full_path));//make the upload
Hope it clarifies your doubt.

Creating zip archive makes multiple files appended with unpredictable strings

I'm trying to make a PDf downloader where the user can select a couple files and then download a zip of what they selected. I had it working on my personal server, but on the production server I get an odd error. The zip file is generated, but it's appended with a string of numbers eg;
zipfile.zip.a08752, zipfile.zip.b08752
Weirder still, if I delete the string off the end and download the file it expands properly.
I read in this topic PHP Zip Archive sporadically creating multiple files that it's an issue with the file attempting to close multiple times, failing and the retrying.
Heres the code for my zip function, though I suspect it's something to do with the configuration of the
function buildZip($params){
/* Generate unique Id */
$downloadid = uniqid();
/* Pull in the order.xml */
if(!empty($_REQUEST['downloadlink'])){
if( $params->usexml == true){
$xml = #simplexml_load_file($params->pdfolder.'/order.xml');
$order = $xml->children();
}else{
$order = $params->files;
}
/* Create the new Zip */
$zip = new ZipArchive();
if ($zip->open($params->zipname.'version'.$downloadid.'.zip', ZIPARCHIVE::CREATE) !== TRUE) {
die ("Could not open archive");
}
/* Generate the download link to output further down the page */
global $downloadLink;
$downloadLink = $params->zipname.'version'.$downloadid.'.zip';
/* Make selected variable available to build the listSelection function */
global $selected;
$selected = array();
$i = 0;
foreach($order as $el){
if (isset($_POST[$i]) == true){
//generate list of selected PDF's
array_push($selected, $el->name);
//grab selected pdf's and zip them.
echo $zip->addFile($params->pdfolder.'/'.$el->link);
$zip->addFile($params->pdfolder.'/'.$el->link) or die ("ERROR: Could not add file: pdf'.$i.'.html");
}
$i++;
}
$zip->close();
}
}
<code>
For Clarity, I'm pulling in an XML list called order.xml to pull in the array of possible files.
Try trimming the weird string of numbers after zipping is done
I just ran into the same problem. This is happening because the zip file fails to get created. It's failing because your files are too large. To fix the problem, I had to create multiple smaller zip files. I hope this helps.

Categories