PHP script doesn't end - php

So I got my script doing this:
I got a list of filenames (images), I loop through the array and load the images from Amazon S3 to my local storage. We are talking about 35k pictures which takes more than 3 hours.
After I downloaded all the images I want to make a redirect via header Location. But the script won't execute that. It's like it's stopping after the loop.
When I have a very small list of images to load it will work with no issues.
The apache error log doesn't show any errors. There is no php process running on the server after that. But the request is still running in the browser.
Ini settings are as followed:
ini_set( 'max_execution_time', 60 * 30 );
ini_set( 'memory_limit', '4096M' );
Foreach loop lookes like this:
foreach( $arrImages as $file ) {
$strPath = $strBasePath . DIRECTORY_SEPARATOR . $file['name'];
// check directory
$pos = strrpos( $strPath, DIRECTORY_SEPARATOR );
$dir = substr( $strPath, 0, $pos );
if( !is_dir( $dir ) ) {
exec( "mkdir -p " . $dir );
exec( "chmod -R 777 " . $strBasePath . DIRECTORY_SEPARATOR );
}
// check if file or path
if( !is_dir( $strPath ) ) {
// build filename
$lastSeparatorPos = strrpos( $strPath, DIRECTORY_SEPARATOR );
$filename = explode( '.', substr( $strPath, $lastSeparatorPos + 1, strlen( $strPath ) - 1 ) );
$clearedFilename = explode( '_', $filename[0] );
if( !in_array( $clearedFilename[0], $arrOrdernumbers ) && strpos( $dir, 'groups' ) == false && strpos( $dir, 'background' ) == false ) {
$intCountNotImported++;
}
else {
$handle = fopen( $strPath, 'wb' );
if( $handle == false ) {
\ImportLogger::log( $strPath . ' - Bild konnte nicht uebertragen werden' );
}
else {
// get File/Folder
$objImage = \S3::getObject( C_S3_BUCKET, $file['name'] );
fwrite( $handle, $objImage->body );
$intAmount++;
// Log every 100 Files
if( $intAmount % 100 == 0 ) {
\ImportLogger::log( $intAmount . ' Bilder uebertragen' );
}
}
fclose( $strPath );
}
}
}
\Debugger::sendEmail( 'xx#xxxx.de', 'Fetchimages', $intAmount . ' - Images loaded' ); // This E-Mail I still get
// Redirect is not happening
$strUrl = '/string/configurator2/compressimages';
header( 'Location: ' . $strUrl );
exit;
Any ideas what could cause this?
Thanks for your help!

Related

WordPress plugin development : How to upload a file to the default "uploads" directory?

I'm trying to upload files to the default "wp-content/uploads" directory. Have tried almost all the available tags, still not working.
Few of the codes I tried:
$filename = $_FILES["uploadfile"]["name"];
$tempname = $_FILES["uploadfile"]["tmp_name"];
$folder= 'wp_upload_dir()'. $filename; //This code is uploading the file to the "wp-admin" directory
if(move_uploaded_file($tempname, $folder)){$response}
$uploaddir = 'uploads/'; $uploadfile = $uploaddir . $filename;`
if(move_uploaded_file($tempname, $uploadfile))
`
I've coded to save the image in uploads folder for one of my website. please check if this code helps
//taking image in $name_icon
$name_icon = $_POST['myfile'];
// WordPress environment
require( dirname(__FILE__) . '/../../../wp-load.php' );
$wordpress_upload_dir = wp_upload_dir();
$i = 1; // number of tries when the file with the same name is already exists
$profilepicture = $_FILES['myfile'];
$new_file_path = $wordpress_upload_dir['path'] . '/' . $profilepicture['name'];
$new_file_mime = mime_content_type( $profilepicture['tmp_name'] );
if( empty( $profilepicture ) )
die();
if( $profilepicture['error'] )
die( $profilepicture['error'] );
if( $profilepicture['size'] > wp_max_upload_size() )
die( 'It is too large than expected.' );
if( !in_array( $new_file_mime, get_allowed_mime_types() ) )
die( 'WordPress doesn\'t allow this type of uploads.' );
while( file_exists( $new_file_path ) ) {
$i++;
$new_file_path = $wordpress_upload_dir['path'] . '/' . $i . '_' . $profilepicture['name'];
}
// looks like everything is OK
if( move_uploaded_file( $profilepicture['tmp_name'], $new_file_path ) ) {
$upload_id = wp_insert_attachment( array(
'guid' => $new_file_path,
'post_mime_type' => $new_file_mime,
'post_title' => preg_replace( '/\.[^.]+$/', '', $profilepicture['name'] ),
'post_content' => '',
'post_status' => 'inherit'
), $new_file_path );
// wp_generate_attachment_metadata() won't work if you do not include this file
require_once( ABSPATH . 'wp-admin/includes/image.php' );
// Generate and save the attachment metas into the database
wp_update_attachment_metadata( $upload_id, wp_generate_attachment_metadata( $upload_id, $new_file_path ) );
Tested & works

PHP file not copying correctly => file empty

I'm currently trying to copy a file from location A to B in PHP. The file get's copied but it has 0 Bytes. I'm so confused why this file is empty after this process. This is my code:
if ( ! file_exists( $file_dir . $file_category ) ) {
if ( ! mkdir( $file_dir . $file_category, 0777, true ) && ! is_dir( $file_dir . $file_category ) ) {
throw new \RuntimeException( sprintf( 'Directory "%s" was not created', $file_dir . $file_category ) );
}
$data = '<html><body bgcolor="#FFFFFF"></body></html>';
$file = fopen( $file_dir . $file_category . '/index.html', 'wb' );
fwrite( $file, $data );
fclose( $file );
$data = 'deny from all';
$file = fopen( $file_dir . $file_category . '/.htaccess', 'wb' );
fwrite( $file, $data );
fclose( $file );
}
copy( $output_dir . $filename, $file_dir . $file_category . '/' . $filename . '.pdf' );
Any help would be awesome.
is it just me or do you have switched the source and the destination file in your copy line:
copy( $output_dir . $filename, $file_dir . $file_category . '/' . $filename . '.pdf' );
PHP docs says that the parameters is like this:
copy ( string $source , string $dest [, resource $context ] ) : bool
but you first parameter uses "$output_dir" (might just be your variable name)
If this is not the case it would be helpful to know where you get "$filename" from since you are not validating it anywhere in your code, only "$file_category". Are you sure that your source file actually exists and has content?

Error http uploading images on Wordpress

I'm working with Imagick and I don't know what happens because when I upload an file "png" or "jpg" It returns:
Error HTTP
but when I upload an file "jpge" it works perfectly.
This is the code on functions.php:
add_filter( 'wp_generate_attachment_metadata', 'generate_watermarked_image' );
function watermark_image( $filename, $upload_dir ) {
$original_image_path = trailingslashit( $upload_dir['path'] ) . $filename;
$image_resource = new Imagick( $original_image_path );
$watermark_resource = new Imagick( get_stylesheet_directory() . '/images/logo.png' );
$image_resource->compositeImage( $watermark_resource, Imagick::COMPOSITE_DEFAULT, 0, 0 );
return save_watermarked_image( $image_resource, $original_image_path );
}
function save_watermarked_image( $image_resource, $original_image_path ) {
$image_data = pathinfo( $original_image_path );
$new_filename = $image_data['filename'] . '-watermarked.' . $image_data['extension'];
$watermarked_image_path = str_replace($image_data['basename'], $new_filename, $original_image_path);
if ( ! $image_resource->writeImage( $watermarked_image_path ) )
return $image_data['basename'];
unlink( $original_image_path ); // Because that file isn't referred to anymore
return $new_filename;
}
I'm sorry for my english.

PHP: Copy entire contents of a directory

Sorry for new post! I'm not yet trusted to comment on others posts.
I'm having trouble copying folders and this is where I started:
Copy entire contents of a directory
Function
function recurse_copy($src,$dst) {
$dir = opendir($src);
#mkdir($dst);
while(false !== ( $file = readdir($dir)) ) {
if (( $file != '.' ) && ( $file != '..' )) {
if ( is_dir($src . '/' . $file) ) {
recurse_copy($src . '/' . $file,$dst . '/' . $file);
}
else {
copy($src . '/' . $file,$dst . '/' . $file);
}
}
}
closedir($dir);
}
My input
$src = "http://$_SERVER[HTTP_HOST]/_template/function/";
$dst = "http://$_SERVER[HTTP_HOST]/city/department/function/";
recurse_copy($src, $dst);
I've also tried this
$src = "$_SERVER[DOCUMENT_ROOT]/_template/function/"; // And so on...
The function is executed but nothing is being copied.
Any ideas on what might be wrong?
SOLVED
Working solution
Along with
$src = "$_SERVER[DOCUMENT_ROOT]/_template/function/";
$dst = "$_SERVER[DOCUMENT_ROOT]/city/department/function/";
recurse_copy($src, $dst);
It's not tested but I think the issue might be that the target directory is not necessarily being created before attempting to copy files to it. The piece of code that creates the target directory would require a folder path rather than a full filepath - hence using dirname( $dst )
if( !defined('DS') ) define( 'DS', DIRECTORY_SEPARATOR );
function recurse_copy( $src, $dst ) {
$dir = opendir( $src );
#mkdir( dirname( $dst ) );
while( false !== ( $file = readdir( $dir ) ) ) {
if( $file != '.' && $file != '..' ) {
if( is_dir( $src . DS . $file ) ) {
recurse_copy( $src . DS . $file, $dst . DS . $file );
} else {
copy( $src . DS . $file, $dst . DS . $file );
}
}
}
closedir( $dir );
}
Use local paths
$src= "_template/function/";
$dst= "city/department/function/";
recurse_copy($src, $dst);
copy works locally on your server. You're trying to copy using HTTP scheme, it's not working that way.

Download random files as zip

I posted my code a few days back and I am now at this point with it. I have acquired the random files however, when they zip it becomes a zip.cpgz file after unzipping. I am sure that this has something to do with the way I used array in my loop but I am not quite sure of how to fix this.
<?php
//./uploads
$dir = "./uploads";
$nfiles = glob($dir.'*.{aiff}', GLOB_BRACE);
$n=1;
while ($n<=10){
$n ++;
$arr[$n] = rand(2, sizeof($nfiles)-1);
print($arr[$n]);
print(" ");
}
$zip = new ZipArchive();
$zip_name = "zipfile.zip";
if($zip->open($zip_name, ZIPARCHIVE::CREATE)!==TRUE){
$error .= "* Sorry ZIP creation failed at this time";
}
foreach($arr as $file){
$path = "./uploads".$file;
$zip->addFromString(basename($path), file_get_contents($path));
}
$zip->close();
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zip_name);
readfile('zipfile.zip');
?>
Also if you are kinda lost here is my website I am trying to implement it on. (click the download button)
Recently helped another user get something similar to work ( without the random selection ) and you might find the following useful. This does search a directory for a particular file extension and then randomly select 10 files which get zipped and sent. Change the $sourcedir and $ext to suit - hope it helps.
/* From David Walsh's site - modified */
function create_zip( $files = array(), $destination = '', $overwrite = false ) {
if( file_exists( $destination) && !$overwrite ) { return false; }
$valid_files = array();
if( is_array( $files ) ) {
foreach( $files as $file ) if( file_exists( $file ) ) $valid_files[] = $file;
}
if( count( $valid_files ) ) {
$zip = new ZipArchive();
if( $zip->open( $destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE ) !== true) return false;
foreach( $valid_files as $file ) $zip->addFile( $file, pathinfo( $file, PATHINFO_FILENAME ) );
$zip->close();
return file_exists( $destination );
}
return false;
}
/* Simple function to send a file */
function sendfile( $filename=NULL, $filepath=NULL ){
if( file_exists( $filepath ) ){
if( !is_file( $filepath ) or connection_status()!=0 ) return FALSE;
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Pragma: no-cache");
header("Expires: ".gmdate("D, d M Y H:i:s", mktime( date("H")+2, date("i"), date("s"), date("m"), date("d"), date("Y")))." GMT");
header("Content-Type: application/octet-stream");
header("Content-Length: ".(string)( filesize( $filepath ) ) );
header("Content-Disposition: inline; filename={$filename}");
header("Content-Transfer-Encoding: binary\n");
if( $file = #fopen( $filepath, 'rb' ) ) {
while( !#feof( $file ) and ( connection_status()==0 ) ) {
print( fread( $file, 1024*8 ) );
flush();
}
#fclose( $file );
}
return( ( connection_status()==0 ) and !connection_aborted() );
}
}
/* Select a random entry from the array */
function pick( $arr ){
return $arr[ rand( 0, count( $arr )-1 ) ];
}
/* The directory to which the zip file will be written before sending */
$target=__DIR__.'\zipfile.zip';
/* The directory you wish to scan for files or create an array in some other manner */
$sourcedir = 'C:\Temp\temp_uploads';
/* File extension to scan for */
$ext='txt';
/* Placeholder to store files*/
$output=array();
/* Scan the dir, or as mentioned, create an array of files some other way */
$files=glob( realpath( $sourcedir ) . DIRECTORY_SEPARATOR . '*.'.$ext );
/* Pick 10 random files from all possible files */
do{
$rnd=pick( $files );
$output[ $rnd ] = $rnd;
}while( count( $output ) < 10 );
/* streamline array */
$output=array_values($output);
if( $target ) {
/* Zip the contents */
$result=create_zip( $output, $target, true );
/* Send the file - zipped! */
if( $result ) {
$res=call_user_func( 'sendfile', 'zipfile.zip', $target );
if( $res ) unlink( $target );
}
}
You sure it doens't work? I've donwloaded your zip file and extracted it and I got UploadsX files. So I don't get a zip.cpgz file.

Categories