How to rename zipped filename? - php

So i have code to move from 1 dir to another dir file and make that file zipped.
That i need:
Rename zipped filename to second "-" symbol.
Example: i got zipped filename "SOMETEXT-de_dust2-20123323.dem.zip". I need that filename to be only "SOMETEXT.dem.zip"
So just remove all text until second -"-"
Any suggestion?
Thanks for helping me to understand code :)
My CODE:
<?php
//error_reporting(E_ALL);
//set_time_limit(0);
$path = "MIX1/cstrike";
$path2 = "/var/www/html/public/";
$to_dirs = array('/demos/');
$from_dirs = array('/demos/');
$filesizes = array();
//первый проход запоминаем размеры
foreach($from_dirs as $from_dir)
{
$demos_dir = opendir($path.$from_dir);
while (false!==($file=readdir($demos_dir)))
{
if ($file!='.'&&$file!='..'&&strpos($file,'.dem')!==false)
{
$fsize=filesize($path.$from_dir.$file);
if ($fsize<50000000)
{
$filesizes[$file]=$fsize;
}
else{
// echo "<br/>bad file:",$file, ", size = ", $fsize;
}
}
}
closedir($demos_dir);
}
//echo date("h:i:s");
sleep(3);
clearstatcache ();
//второй проход пермещаем
$i=0;
foreach($from_dirs as $from_dir)
{
$to_dir=$from_dirs[$i];
$demos_dir = opendir($path.$from_dir);
while (false!==($file=readdir($demos_dir)))
{
if ($file!='.'&&$file!='..'&&strpos($file,'.dem')!==false)
{
$fsize=0;
$fsize=filesize($path.$from_dir.$file);
if ($fsize<50000000)
{
if ($fsize==$filesizes[$file])
{
//echo "<br>ѕеремещаем файл ",$file," размер не изменилс¤; было ",$filesizes[$file]," стало, ".$fsize,";";
move_demo($file, $from_dir, $to_dir);
}
else
{
//echo "<br>","размер изменилс¤ у файла ", $file;
}
}
else
{
//echo "<br/>bad file:",$file, ", size = ", $fsize;
}
}
}
$i++;
closedir($demos_dir);
}
function move_demo($filename, $from_dir, $to_dir)
{
//echo $filename,"from ",$from_dir," to ",$to_dir,"<br>";
global $path, $path2;
if (file_exists($path2.$to_dir.$filename.".zip"))
unlink($path2.$to_dir.$filename.".zip");
echo "$path$from_dir$filename\n";
echo "$path2$to_dir$filename\n\n";
$data = file_get_contents($path.$from_dir.$filename);
$gzdata = gzencode($data, 9);
unset($data);
$fp = fopen($path2.$to_dir.$filename.".zip", "xb+");
//$fp = fopen($path.$to_dir.$filename.".zip")
fwrite($fp, $gzdata);
unset($gzdata);
fclose($fp);
unlink($path.$from_dir.$filename);
}
?>

Have a look at rename().
Here's a PoC:
function move_files($src, $dst)
{
$dh = opendir($src);
if (!$dh) {
return false;
}
// Combine the letters before the first dash/hyphen (-),
// and the letters after (and including) the first dot/period (.)
// after the first dash/hyphen (-).
$regex = '/^(.+?)-(?:.+?)(\..+?\.zip)$/';
$moved = 0;
$total = 0;
while (($filename = readdir($dh)) !== false) {
if (filetype("{$src}{$filename}") !== 'file') {
continue;
}
if (!preg_match($regex, $filename)) {
continue;
}
$total++;
$new_filename = preg_replace($regex, "$1$2", $filename);
$moved += (int)rename($src, "{$dst}{$new_filename}");
}
closedir($dh);
return [$moved, $total];
}
$srcDir = '/src/';
$dstDir = '/dst/';
$res = move_files($src, $dst);
if (!$res) {
// Error
}
list($moved, $total) = $res;
var_dump($moved, $total);

Related

creating a function for upload to save a specific path and check the limit of the folder

i have a function to upload a file(video,audio, images and documents) .. but i cant think of how to continue it.. I'm a beginner in programming by the way. and i want to upload a file and check the limit of the folder where i want to save the file if the folder reached the limit of 10 000 file inside, if it is true then it will create a new folder that has the same name but has a number in it (folder,folder 1 will be the next created) and save it to the folder created..
function uploads($filename,$tempname){
$errors= array();
$file_name = $filename;
$file_tmp = $tempname;
$audioPath = "./archivestorage/upload/media/audio/";
$videoPath = "./archivestorage/upload/media/video/";
$imagePath = "./archivestorage/upload/media/images/";
$documentPath = "./archivestorage/upload/document/";
$file = pathinfo($filename,PATHINFO_EXTENSION);
if(empty($errors)==true) {
if($file ==='jpg')
{
move_uploaded_file($file_tmp,$imagePath.$file_name);
echo "Success";
$return = $imagePath;
}
elseif($file ==='mp4')
{
move_uploaded_file($file_tmp,$videoPath.$file_name);
echo "Success";
$return = $imagePath;
}
elseif($file ==='mp3')
{
move_uploaded_file($file_tmp,$audioPath.$file_name);
echo "Success";
$return = $imagePath;
}
elseif($file ==='jpeg')
{
move_uploaded_file($file_tmp,$imagePath.$file_name);
echo "Success";
$return = $imagePath;
}
else if($file ==='docx')
{
move_uploaded_file($file_tmp,$documentPath.$file_name);
echo "Success";
$return = $imagePath;
}
elseif($file ==='png')
{
move_uploaded_file($file_tmp,$imagePath.$file_name);
echo "Success";
$return = $imagePath;
}
else{
print_r($errors);
}
}
i am giving you simple demonstration here.may be its not correct as per your need. remember class FilesystemIterator will work if your php version is above 5.3
if($file ==='jpg')
{
$folderChk = new FilesystemIterator($imagePath, FilesystemIterator::SKIP_DOTS)
if (iterator_count($folderChk)<10000) {
move_uploaded_file($file_tmp,$imagePath.$file_name);
echo "Success";
$return = $imagePath;
}
else{
$imagePath=$imagePath." 1 " ;
mkdir($imagePath, 0777, true);
move_uploaded_file($file_tmp,$imagePath.$file_name);
echo "Success";
$return = $imagePath;
}
}
if its not work you can use glob() try like that
if($file ==='jpg')
{ $filecount = 0;
$files = glob($imagePath . "*");
if ($files){
$filecount = count($files);
}
if ($filecount<10000) {
move_uploaded_file($file_tmp,$imagePath.$file_name);
echo "Success";
$return = $imagePath;
}
else{
$imagePath=$imagePath." 1 " ;
mkdir($imagePath, 0777, true);
move_uploaded_file($file_tmp,$imagePath.$file_name);
echo "Success";
$return = $imagePath;
}
}
if you want to create multiple folder you should try like this
$imagePath = "./archivestorage/upload/media/images/";
$folderCount = 0;
$folder = scandir($imagePath);//read directory
if ($folder){
$folderCount = count($folder)-2;//count dir
}
$file = pathinfo($filename,PATHINFO_EXTENSION);
if(empty($errors)==true) {
if($file ==='jpg')
{
$filecount = 0;
if (is_dir($imagePath)) {
$files = glob($imagePath . "*");
if($files){
$filecount = count($files);
}
if ($filecount<10000) {
move_uploaded_file($file_tmp,$imagePath.$file_name);
echo "Success";
$return = $imagePath;
}
else
{
for ($i = 1; $i <=$folderCount ; $i++) {
if(is_dir($imagePath." ".$i)) {
$imagePath=$imagePath." ".$i;
$files = glob($imagePath . "*");
if ($files){
$filecount = count($files);
}
if ($filecount<10000) {
move_uploaded_file($file_tmp,$imagePath.$file_name);
echo "Success";
$return = $imagePath;
exit();
}
}
else
{
$imagePath=$imagePath." "$i;
mkdir($imagePath, 0777, true);
move_uploaded_file($file_tmp,$imagePath.$file_name);
echo "Success";
$return = $imagePath;
exit();
}
}
}
}
}
}

Need to run twice in-order for it to fully work

$find = '.5010.';
$directory_with_files = './'.date('m-d-Y');
$dh = opendir($directory_with_files);
$files = array();
while (false !== ($filename = readdir($dh)))
{
if(in_array($filename, array('.', '..')) || is_dir($filename))
continue;
$files[] = $filename;}
foreach($files as $file){
//find only 5010 files
if(stripos($file, $find) !== false){
// open the 5010 file
$handle = fopen(date('m-d-Y').'/'.$file, "r");
$file_content = file_get_contents(date('m-d-Y').'/'.$file);
$handle2 = fopen(date('m-d-Y').'/'.$file, "r");
$file_content2 = file_get_contents(date('m-d-Y').'/'.$file);
if ($handle) {
$header = '';
$name = '';
$footer = '';
$payor_blocks = array();
// determine if file has more than one payor
$payor_count = substr_count($file_content, 'N1*PR*');
//if the file has more than one payor
if($payor_count > 1) {
//read the file line by line
$header_end = false;
$block_start = false;
$count = 1;
if($handle2){
$line_number = 0;
$line_stop= array();
while (($line1 = fgets($handle2)) !== false) {
$line_number++;
if(strpos($line1, 'CAS') !==false){
$line_stop[] = $line_number;}}
$footer_line = count($line_stop)-2;
$footer_line = $line_stop[$footer_line];
$line_number = 0; }
//look for occurances of CAS and what line each on is on
while (($line = fgets($handle)) !== false) {
$line_number++;
//look for the first payor block
if(strpos($line, 'N1*PR*') !== false || $block_start) {
$header_end = true; $block_start = true;
if(strpos($line, 'N1*PR*') !== false) {
$count++;
}
//see if the block finished
if($line_number == $footer_line) {
$block_start = false;
$payor_blocks[$count] .= $line;
$count++; }
$payor_blocks[$count] .= $line;}
else {
if($header_end) {
$footer .= $line."\n"; }
else {
$header .= $line."\n";}}
$refid = 'REF*2U*';
if(stripos($line, $refid) !== false)
{
$refnumber = str_replace(array($refid, '~'), array('', ''), $line);
$refnumber = trim($refnumber);
if($refnumber != '')
{
$refnumber = '_'.$refnumber.'_';
$filerenamed = str_replace($find, $refnumber,$file);
copy('./'.date('m-d-Y').'/'.$file, './'.date('m-d-Y').'/'. $filerenamed);
}
echo $refnumber . "\n";
}
}
//get payor blocks and create a file foreach payor
$new_files = array();
foreach($payor_blocks as $block) {
$filename = date('m-d-Y').'/'.$file . "_" . $count;
$count++;
$new_files[] = array(
'name' => $filename,
'content' => $header."\n".$block."\n".$footer
);
}
foreach($new_files as $new_file) {
$myfile = fopen($new_file['name'], "w");
fwrite($myfile, $new_file['content']);
fclose($myfile);
}
}
else{
while (($line = fgets($handle)) !== false)
{
$refid = 'REF*2U*';
if(stripos($line, $refid) !== false)
{
$refnumber = str_replace(array($refid, '~'), array('', ''), $line);
$refnumber = trim($refnumber);
if($refnumber != '')
{
$refnumber = '_'.$refnumber.'_';
$filerenamed = str_replace($find, $refnumber,$file);
copy('./'.date('m-d-Y').'/'.$file, './'.date('m-d-Y').'/'. $filerenamed);
}
echo $refnumber . "\n";
}
}
}
}
}
// DONE - close the file
fclose($handle);
}
foreach($files as $fiftyfile){
if(stripos($fiftyfile, $find) !== false){
$handle3 = fopen(date('m-d-Y').'/'.$fiftyfile, "r");
$file_content3 = file_get_contents(date('m-d-Y').'/'.$fiftyfile);
if ($handle3) {
if(unlink('./'.date('m-d-Y').'/'.$fiftyfile))
{
echo "file named $fiftyfile has been deleted successfully";
}
else
{
echo "file is not deleted";
}
}
}
}
I have a few files in my directory with filenames that contain "3256.5010.548674.23a" In this code it opens the file and searches if there is more than one "N1*PR*" and if there is to split them into separate files. Lastly to change ".5010." to the REF number which is something like "8743" . Then it deletes all the files with ".5010." And combines the rest in one document. It works fine however, when I first run it it splits and renames, but only deletes the first files not all the ".5010." (not the ones that were split), which then when I run it again after that, it deletes everything but renames the old ones, since it goes through the "else statement" that also does the renaming. How could I solve the issue with the delete?

Why base64_encode() return null

I have a 22M docx file and want to encode it using base64_encode() function in php. But It always returns NULL value after running this function. Is there any limit file size or condition for this function. My code:
$handle = fopen($fullpathfile, "rb");
$imagestr = base64_encode(fread($handle, filesize($fullpathfile)));
fclose($handle);
Try this code
$fh = fopen($fullpathfile, 'rb');
$cache = '';
$eof = false;
while (1) {
if (!$eof) {
if (!feof($fh)) {
$row = fgets($fh, 4096);
} else {
$row = '';
$eof = true;
}
}
if ($cache !== '')
$row = $cache.$row;
elseif ($eof)
break;
$b64 = base64_encode($row);
$put = '';
if (strlen($b64) < 76) {
if ($eof) {
$put = $b64."\n";
$cache = '';
} else {
$cache = $row;
}
} elseif (strlen($b64) > 76) {
do {
$put .= substr($b64, 0, 76)."\n";
$b64 = substr($b64, 76);
} while (strlen($b64) > 76);
$cache = base64_decode($b64);
} else {
if (!$eof && $b64{75} == '=') {
$cache = $row;
} else {
$put = $b64."\n";
$cache = '';
}
}
if ($put !== '') {
echo $put;
}
}
fclose($fh);

FTP_DELETE not working?

Hey guys I have my script here that is supposed to do some stuff then delete a file, unfortunetly my files never unlink. I"m wondering what the reason for this might be? Permissions was the only thing I could think of, or maybe the output buffer is messing up? I really don't know, but would appreciate some advice on how to handle it. Issue in question is that last IF() block.
public function remoteFtp() {
$enabled = Mage::getStoreConfig('cataloginventory/settings/use_ftp');
$remove = Mage::getStoreConfig('cataloginventory/settings/ftp_remove_file');
if ($enabled == 0) {
return true;
}
$base_path = Mage::getBaseDir('base');
$ftp_url = Mage::getStoreConfig('cataloginventory/settings/ftp_url');
$ftp_user = Mage::getStoreConfig('cataloginventory/settings/ftp_user');
$ftp_pass = Mage::getStoreConfig('cataloginventory/settings/ftp_password');
$ftp_remote_dir = Mage::getStoreConfig('cataloginventory/settings/ftp_remote_dir');
$ftp_filename_filter = Mage::getStoreConfig('cataloginventory/settings/ftp_remote_filename');
$ftp_file = $base_path . '/edi/working/working.edi';
$handle = fopen($ftp_file, 'w');
$conn_id = ftp_connect($ftp_url);
ftp_login($conn_id, $ftp_user, $ftp_pass) or die("unable to login");
if ($ftp_remote_dir) {
ftp_chdir($conn_id, $ftp_remote_dir);
}
//is there a file
$remote_list = ftp_nlist($conn_id, ".");
$exists = count($remote_list);
if ($exists > 0) {
$len = strlen($ftp_filename_filter) - 1;
foreach ($remote_list as $name) {
if (substr($ftp_filename_filter, 0, 1) == "*") {
if (substr($name, '-' . $len) == substr($ftp_filename_filter, '-' . $len)) {
$ftp_remote_name = $name;
}
}
if (substr($ftp_filename_filter, strlen($name) - 1) == "*") {
if (substr($ftp_filename_filter, 0, $len) == substr($name, 0, $len)) {
$ftp_remote_name = $name;
}
}
if ($ftp_filename_filter == $name) {
$ftp_remote_name = $name;
}
}
}
if (ftp_fget($conn_id, $handle, $ftp_remote_name, FTP_ASCII, 0)) {
echo "successfully written to $ftp_file <br />";
if ($remove == 1) {
ftp_delete($conn_id, $ftp_remote_name);
}
} else {
echo "There was a problem while downloading $ftp_remote_name to $ftp_file <br />";
}
ftp_close($conn_id);
}
The answer was that the system variable $remove = Mage::getStoreConfig('cataloginventory/settings/ftp_remove_file'); was set to BOOL(false)

How to modify this script to get only the mp4 file version from youtube knowing the youtube id?

How to mofify this to get only the url of the mp4 file version?
<?php
//$debug = true;
if(empty($debug))
$debug = false;
if(empty($_GET['id']))
die('no id');
if(!preg_match('/^[A-Z0-9-_]+$/i', $_GET['id']))
die('invalid character in id');
else
$id = $_GET['id'];
if(empty($_GET['type']))
$type = 'mp4';
else
if(!preg_match('/^[A-Z]+$/i', $_GET['type']))
die('invalid character in type');
else
$type = strtolower($_GET['type']);
$url = 'http://youtube.com/get_video_info?video_id=';
$key = 'url_encoded_fmt_stream_map';
$content = file_get_contents($url.$id);
parse_str($content, $result);
if($debug)
{
echo $url.$id.'<br/>';
echo $key.'<br/>';
echo $type.'<br/>';
echo '<pre>';
print_r($result);
echo '</pre>';
}
else
{
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="videofile.'.$type.'"');
}
$type = 'type=video/'.$type;
$files = explode(',url=', $result[$key]);
$files[0] = substr($files[0], 4);
for($i=0; $i<count($files); $i++)
{
$file = urldecode($files[$i]);
$found = strpos($file, $type) > -1;
if ($debug)
{
if ($found)
echo '[THIS]';
echo ''.$file.'<br/><br/>';
}
else
{
if ($found)
{
$file = explode('; codecs=', $file);
#readfile($file[0]);
break;
}
}
}
?>
Those 3 links are all the mp4 links with different ID tages (at the end).
Itags are different HD/Normal formats for the screen resolution, Google them up.
However, if you want to land now, keep this:
<?php
$debug = true;
if(empty($debug))
$debug = false;
if(empty($_GET['id']))
die('no id');
if(!preg_match('/^[A-Z0-9-_]+$/i', $_GET['id']))
die('invalid character in id');
else
$id = $_GET['id'];
if(empty($_GET['type']))
$type = 'mp4';
else
if(!preg_match('/^[A-Z]+$/i', $_GET['type']))
die('invalid character in type');
else
$type = strtolower($_GET['type']);
$url = 'http://youtube.com/get_video_info?video_id=';
$key = 'url_encoded_fmt_stream_map';
$content = file_get_contents($url.$id);
parse_str($content, $result);
/*if($debug)
{
echo $url.$id.'<br/>';
echo $key.'<br/>';
echo $type.'<br/>';
echo '<pre>';
print_r($result);
echo '</pre>';
}
else
{
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="videofile.'.$type.'"');
}
*/
$type = 'type=video/'.$type;
$files = explode(',url=', $result[$key]);
$files[0] = substr($files[0], 4);
for($i=0; $i<count($files); $i++)
{
$file = urldecode($files[$i]);
$found = strpos($file, $type) > -1;
$itag = strpos($file, "itag=18") > -1;
if ($found & $itag){
echo ''.$file.'<br/><br/>';
}
}
?>
<?php
$debug = true;
if(empty($debug))
$debug = false;
if(empty($_GET['id']))
die('no id');
if(!preg_match('/^[A-Z0-9-_]+$/i', $_GET['id']))
die('invalid character in id');
else
$id = $_GET['id'];
if(empty($_GET['type']))
$type = 'mp4';
else
if(!preg_match('/^[A-Z]+$/i', $_GET['type']))
die('invalid character in type');
else
$type = strtolower($_GET['type']);
$url = 'http://youtube.com/get_video_info?video_id=';
$key = 'url_encoded_fmt_stream_map';
$content = file_get_contents($url.$id);
parse_str($content, $result);
/*if($debug)
{
echo $url.$id.'<br/>';
echo $key.'<br/>';
echo $type.'<br/>';
echo '<pre>';
print_r($result);
echo '</pre>';
}
else
{
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="videofile.'.$type.'"');
}
*/
$type = 'type=video/'.$type;
$files = explode(',url=', $result[$key]);
$files[0] = substr($files[0], 4);
for($i=0; $i<count($files); $i++)
{
$file = urldecode($files[$i]);
$found = strpos($file, $type) > -1;
if ($found){
echo ''.$file.'<br/><br/>';
}
}
?>

Categories