Download file is getting corrupted - php

I have a code function in php
What it does:
it absorbs data from a table and converts the images(saved as blob) into files and put under a subfolder named "image" under a folder created dynamically based on version and date
ex: v3-20-12-2012
Then it creates a csv file and save it in the v3-20-12-2012 folder.
Then it creates a zip file for the folder v3-20-12-2012.
The problem is , the zip file getting saved in the project folder. I want it to be downloadable.
How can i achieve this.
Here's my code:
function create_csv($version,$ctg,$cnt,$nt,$api)
{
$folder = $version."-".date('d-m-Y')."-".time();
if(!file_exists('./'.$folder))
{
mkdir('./'.$folder);
mkdir('./'.$folder.'/image/');
}
$cnt_table = "aw_countries_".$version;
$ctg_table = "aw_categories_".$version;
$off_table = "aw_offers_".$version;
$sizeof_ctg = count($ctg);
$cond_ctg = " ( ";
for($c = 0; $c < $sizeof_ctg ; $c++)
{
$cond_ctg = $cond_ctg." $ctg_table.category = '".$ctg[$c]."' ";
if($c < intval($sizeof_ctg-1))
$cond_ctg = $cond_ctg." OR ";
else if($c == intval($sizeof_ctg-1))
$cond_ctg = $cond_ctg." ) ";
}
$sizeof_cnt = count($cnt);
$cond_cnt = " ( ";
for($cn = 0; $cn < $sizeof_cnt ; $cn++)
{
$cond_cnt = $cond_cnt." $cnt_table.country = '".$cnt[$cn]."' ";
if($cn < intval($sizeof_cnt-1))
$cond_cnt = $cond_cnt." OR ";
else if($cn == intval($sizeof_cnt-1))
$cond_cnt = $cond_cnt." ) ";
}
$sizeof_nt = count($nt);
$cond_nt = " ( ";
for($n = 0; $n < $sizeof_nt ; $n++)
{
$cond_nt = $cond_nt." $off_table.network_id = '".$nt[$n]."' ";
if($n < intval($sizeof_nt-1))
$cond_nt = $cond_nt." OR ";
else if($n == intval($sizeof_nt-1))
$cond_nt = $cond_nt." ) ";
}
$sizeof_api = count($api);
$cond_api = " ( ";
for($a = 0; $a < $sizeof_api ; $a++)
{
$cond_api = $cond_api." $off_table.api_key = '".$api[$a]."' ";
if($a < intval($sizeof_api-1))
$cond_api = $cond_api." OR ";
else if($a == intval($sizeof_api-1))
$cond_api = $cond_api." ) ";
}
$output = "";
$sql = "SELECT DISTINCT $off_table.id,$off_table.name
FROM $off_table,$cnt_table,$ctg_table
WHERE $off_table.id = $cnt_table.id
AND $off_table.id = $ctg_table.id
AND ".$cond_api."
AND ".$cond_nt."
AND ".$cond_cnt."
AND ".$cond_ctg;
$result = mysql_query($sql);
$columns_total = mysql_num_fields($result);
for ($i = 0; $i < $columns_total; $i++)
{
$heading = mysql_field_name($result, $i);
$output .= '"'.$heading.'",';
}
$output .= '"icon"';
$output .="\n";
while ($row = mysql_fetch_array($result))
{
for ($i = 0; $i < $columns_total; $i++)
{
$output .='"'.$row["$i"].'",';
}
$sql_icon = "SELECT $off_table.icon FROM $off_table WHERE id = '".$row['id']."'";
$result_icon = mysql_query($sql_icon);
while($row_icon = mysql_fetch_array($result_icon))
{
$image = $row_icon["icon"];
$id = $row["id"];
$icon = "./$folder/image/{$id}.jpg";
$icon_link = "$folder/image/{$id}.jpg";
file_put_contents($icon, $image);
}
$output .= '"'.$icon_link.'"';
$output .="\n";
}
$filename = "myFile.csv";
$fd = fopen ( "./$folder/$filename", "w");
fputs($fd, $output);
fclose($fd);
$source = $folder;
$destination = $folder.'.zip';
$flag = '';
if (!extension_loaded('zip') || !file_exists($source)) {
return false;
}
$zip = new ZipArchive();
if (!$zip->open($destination, ZIPARCHIVE::CREATE)) {
return false;
}
$source = str_replace('\\', '/', realpath($source));
if($flag)
{
$flag = basename($source) . '/';
}
if (is_dir($source) === true)
{
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);
foreach ($files as $file)
{
$file = str_replace('\\', '/', realpath($file));
if (is_dir($file) === true)
{
}
else if (is_file($file) === true)
{
$zip->addFromString(str_replace($source . '/', '', $flag.$file), file_get_contents($file));
}
}
}
else if (is_file($source) === true)
{
$zip->addFromString($flag.basename($source), file_get_contents($source));
}
$zip->close();
if (is_dir($folder))
{
$objects = scandir($folder);
foreach ($objects as $object)
{
if ($object != "." && $object != "..")
{
if (filetype($folder."/".$object) == "dir")
{
$object_inner = scandir($folder."/".$object);
foreach ($object_inner as $object_inner)
{
if ($object_inner != "." && $object_inner != "..")
{
unlink($folder."/".$object."/".$object_inner);
}
}
rmdir($folder."/".$object);
}
else
unlink($folder."/".$object);
}
}
reset($objects);
}
rmdir("./".$folder);
/*$zipfile = $folder.'.zip';
$file_name = basename($zipfile);
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=$file_name");
header("Content-Length: " . filesize($zipfile));
readfile($zipfile);
exit;*/
}
EDIT:
I have two instance of the file. One file gettng saved automaticaly at the project folder. The next one is getting forced to download. The one that is automatically saved has no prolem whle unzipping. But the one that is forcefully download, that having issue while unzipping.

You forgot to send the actual data at the end and it would be nice to also send the Content-Length header.
Example:
$filename = 'something.zip';
$filepath = './path/to/files/directory/';
header('Content-type: application/zip');
header('Content-Disposition: attachment; filename='.$filename);
header("Content-Length: ".filesize($filepath.$filename));
ob_end_flush();
readfile($filepath.$filename);
And as a side note, you may want to split that function because it does more than it should. As name states, it should just create_csv, but is also working with DB, creating a zip, sending the response, etc.
Update:
After your update I looked closely to your code and you have a few issues which might result in a corrupted download:
$source = str_replace('\\', '\\', realpath($source));
// more code ...
$file = realpath($file);
Those lines will result in full paths being used in archive, which you might not want. I recommend commenting those two lines so you store relative paths inside the archive.
After you add all your files to your archive, you don't close it and because the archive will have a temporary name which is different than its final one, your code used when sending headers will result in sending garbage data.
To fix that, you should close the .zip before sending the headers:
// more code ...
$zip->close();
header('Content-type: application/zip');

Related

How to rename zipped filename?

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);

PHP read lines not working on some computers but works on most

So im reading an CSV file and splitting it apart to get email,name,last name, however this outputs differently on different computers in my platform, let's say when I upload the same file it reads 38 lines and save them. However in 2 specific computers it reads only 1.
Before I was reading only TEMP file, but now im saving it to a directory and reading from there, however the problem is still here, I compared the file size and is the same even the content.
Is this a PHP bug ?
<?php
global $user;
if(isset($_POST['submit'])) {
if ($_FILES['file']['tmp_name']) {
$nome = $_POST['nome'];
$file = $_FILES['file']['tmp_name'];
$user->criarLista($nome, $file);
} else {
$user->mensagem(1, "Não existe nenhum ficheiro");
}
}
?>
public function criarLista($nome,$file){
// ADDED TO SAVE THE FILE IN THE SYSTEM AND READ FROM IT
if(file_exists("uploads/lista.txt")){ unlink("uploads/lista.txt"); }
move_uploaded_file($file, "uploads/lista.txt");
$file = file_get_contents("uploads/lista.txt");
$user = $this->user;
$get = $this->connect->query("SELECT * FROM users WHERE email = '$user'");
$fetch = $get->fetch_array(MYSQLI_ASSOC);
$user_id = $fetch['id'];
if($insert = $this->connect->prepare("INSERT INTO lista(user_id,nome) VALUES(?,?)")){
$insert->bind_param("is", $user_id,$nome);
$insert->execute();
$list_id = $insert->insert_id;
$file = preg_replace('#\\x1b[[][^A-Za-z]*[A-Za-z]#', '', $file);
$file = strip_tags($file);
$lines = file("uploads/lista.txt");
$emails = array();
$fnames = array();
$lnames = array();
$linha = 0;
foreach($lines as $line) {
if($linha == 0){
}else{
echo $Linha."</br>";
if (strpos($line, ',') !== false) {
$arr = explode(",", $line);
// Email \ FNAME | LAST
$emailx = trim($arr[0]);
$emailx = trim(preg_replace("/[\\n\\r]+/", "", $emailx));
array_push($emails,$emailx);
if(isset($arr[1])){
$fname = trim($arr[1]);
$fname = str_replace('"','',$fname);
array_push($fnames,$fname);
}
if(isset($arr[2])){
$lname = trim($arr[2]);
array_push($lnames,$lname);
}
}else{
array_push($emails,trim($line));
}
}
$linha++;
}
array_map('trim', $emails);
array_map('trim', $fnames);
array_map('trim', $lnames);
$emails = implode(",",$emails);
$fnames = implode(",",$fnames);
$lnames = implode(",",$lnames);
if($insert_list = $this->connect->prepare("INSERT INTO listas(lista_id,email,primeiro_nome,ultimo_nome) VALUES(?,?,?,?)")){
$insert_list->bind_param("isss", $list_id,$emails,$fnames,$lnames);
$insert_list->execute();
$this->mensagem(2,"Lista adicionada com sucesso");
}else{
echo
'
<div class="alert alert-danger">
Erro: '.$this->connect->error.'
</div>
';
}
}else{
echo
'
<div class="alert alert-danger">
Erro: '.$this->connect->error.'
</div>
';
}
}
FIXED this adding this on top of the function :
ini_set('auto_detect_line_endings',true);
I am not sure this is an 'answer' to what is going on, though it is what I had to do to fix an issue with a Mac user sending files.
What I found was that, every time he did an upload, it would send a .zip file, not just the file (like the PCs did). I did not have other Mac users to test against, so, again, I can't say this is exactly the issue you have, but I trust it will at least help in your search.
Note that I had to chop a lot of code out of this (where I was doing various other functions with the database, etc.), so this may not run directly, but I think I closed all the 'ifs' and such - or you can figure it out (if not, let me know and I'll go through it again).
Hope this helps!
$save_file = basename($_FILES["fileToUpload"]["name"]);
$zipfile='maps/'.$save_file; // location of a temp location (stops double uploads)
$alert_upload_file_exists = "Uploaded file exists!";
$alert_upload_successful = "UPLOAD SUCCESSFUL";
$action_failed_text = "Action FAILED";
if(file_exists($zipfile) && (empty($_GET['overwrite']) || $_GET['overwrite'] == 'false'))
die($alert_upload_file_exists);
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $zipfile))
{
// I found this mac to be sending a .zip file, not a standard one..... :(
$uploadOk = 0;
$mac_file = 0;
if($basename = basename($_FILES["fileToUpload"]["name"],".zip"))
{
$zip = new ZipArchive;
if($zip->open($zipfile) === true){
// echo "basename is $basename<BR>";
for($i = 0; $i < $zip->numFiles; $i++) {
$filename = $zip->getNameIndex($i);
$fileinfo = pathinfo($filename);
// look for the file we really want (in our case, any sort of img file)
if($fileinfo['basename'] == $basename . '.png' || $fileinfo['basename'] == $basename . '.jpg' || $fileinfo['basename'] == $basename . '.gif') {
$imgfile = $_GET['loc_data_id'].".".$fileinfo['extension'];
$files[]=$fileinfo['basename'];
// echo "file added to the list <BR>";
}
// echo "filename is $filename, basename is ->".$fileinfo['basename']."<- fileinfo = ";print_r($fileinfo);
// CHECK TO SEE IF THIS WAS THE 'WEIRD' MAC FILE
if($fileinfo['basename'] == "__MACOSX")
$mac_file = 1;
// echo "mac_file is $mac_file ";
}
if(($imglist = array_keys(array_flip(preg_grep('/^.*\.(jpg|jpeg|png|gif)$/i',$files))))
{
// echo "imglist = ";print_r($imglist);
// echo "files = ";print_r($files);
foreach($files as $key => $value)
{
if ($imglist[0]==$value) {$file = $imgfile;}
$upgrade += file_exists('maps/'.$file);
// echo "imgfile is $imgfile, file is $file upgrade is $upgrade and value is ".$basename."/".$value." ............";
// more 'FUNNY BUSINESS' to work the Mac file....
if($mac_file){
$extracted = $zip->extractTo('maps/',$basename."/".$value);
rename("maps/$basename/$value","maps/$file");
}
else {
$extracted = $zip->extractTo('maps/',$value);
rename("maps/$value","maps/$file");
}
}
// AND A BIT MORE.....
if($mac_file){
rmdir ("maps/$basename");
}
$zip->close();
$imgcount=0;$mapcount=0;$uploadOk=1;
$html = file_get_html('maps/'.$mapfile);
$imgck = strpos($html,'<img ');
if(($imgck===false) || $imgck<>0) {
$uploadOk += 2;
}
// echo "uploadOk is $uploadOk<br>";
if($uploadOk==1)
{
$mapname = pathinfo('maps/'.$mapfile);
// echo "mapfile is $mapfile, mapname = ";print_r($mapname);
}
}
else $uploadOk += 20;
}
}
if($uploadOk==1) echo basename($_FILES["fileToUpload"]["name"])." ".$alert_upload_successful;
else echo $action_failed_text . " ".$uploadOk;
// delete the original .zip file (and any that are in the 'maps/' folder)
array_map('unlink', glob("maps/*.zip"));
}
else
{
echo "Sorry, there was an error uploading your file.";
echo "temp name is " . $_FILES["fileToUpload"]["tmp_name"]. " save file is ". $save_file."<br>";
}

PHP - Loop through folders, open each docx file and replace string

I have a script that:
goes through each folder and subfolder of my "./sample/" directory
opens each .docx file
replaces a string such as "##PROPERTY##" with my $_POST['property'] variable
zips the folder content
launches a download
Now, running portions of the code individually, it does what is needed. However, when putting it all together, it dies while scanning the subfolders for docx files.
My folder structure is like this:
./sample/
/IT/it1.docx
/F&B/fb1.docx
/FO/fo1.docx
sample1.docx
The problem seems to occur during the is_dir($dir) part for the level 1 folders.
Any ideas what could cause this?
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
// form variables
$holidex = strtoupper($_POST['holidex']);
$property = $_POST['property'];
$brand = $_POST['brand'];
$division = $_POST['division'];
$language = $_POST['language'];
$date_issued = $_POST['date_issued'];
$approved_by = $_POST['approved_by'];
// script variables
//$dir = './Sample_SOP_-_'.$brand.'_('.$language.')'; //dir to scan like ./sample/
$dir = './sample/'; //dir to scan like ./sample/
$archive = date("Y-m-d H-i-s"); //UNIQUE name of zip file to create and download
$zipfile = "./".$holidex." - ".$archive.".zip"; //path to zip file download
$temp = "./temp/"; //directory to temp folder
// string replacements
$find = "##PROPERTY##"; // find and replace property information
$replace = $_POST['property'];
$find2 = "##BRAND##"; // find and replace brand information
$replace2 = $_POST['brand'];
$find3 = "##DATE##"; // find and replace effective date
$replace3 = $_POST['date_issued'];
$find4 = "##APPROVED_BY##"; // find and replace approved by
$replace4 = $_POST['approved_by'];
//read dir
$files = scandir($dir, 1);
//create new archive name
$zip_download = new ZipArchive();
$zip_download->open("$zipfile", ZipArchive::CREATE);
foreach($files as $file) {
//docx
$ext1 = ".docx";
$checkextension = explode($ext1, $file);
if (count($checkextension) > 1) {
$zip = new ZipArchive;
$zip->open("$file");
$word = $zip->getFromName('word/document.xml');
$word2 = str_replace($find, $replace, $word);
$word2 = str_replace($find2, $replace2, $word);
$word2 = str_replace($find3, $replace3, $word);
$word2 = str_replace($find4, $replace4, $word);
$zip->addFromString("word/document.xml", $word2);
$zip->close();
} else {
die("Error - There are no files the directory..");
}
//folders level 1
if (is_dir($file)) {
$sub = $file . '/';
$subfiles = scandir($sub, 1);
if ($subfiles > 1) {
if ($sub == "../" || $sub == "./") {
}
else {
foreach($subfiles as $subfile) {
//docx
$ext1 = ".docx";
$checkextensionsub = explode($ext1, $subfile);
$subsubfile = $sub . $subfile;
if (count($checkextensionsub) > 1) {
$zipsub = new ZipArchive;
$zipsub->open("$subsubfile");
$wordsub = $zipsub->getFromName('word/document.xml');
$word2sub = str_replace($find, $replace, $wordsub);
$word2sub = str_replace($find2, $replace2, $wordsub);
$word2sub = str_replace($find3, $replace3, $wordsub);
$word2sub = str_replace($find4, $replace4, $wordsub);
$zipsub->addFromString("word/document.xml", $word2sub);
$zipsub->close();
}
//folders level 2
$sub2 = $sub . $subfile;
if (is_dir($sub2)) {
$subfiles2 = scandir($sub2, 1);
if ($subfiles2 > 1) {
if ($sub2 == $sub.".." || $sub2 == $sub.".") {
}
else {
foreach($subfiles2 as $subfile2) {
//docx
$ext1 = ".docx";
$checkextensionsub2 = explode($ext1, $subfile2);
$subsubfile2 = $sub2 . '/' . $subfile2;
if (count($checkextensionsub2) > 1) {
$zipsub2 = new ZipArchive;
$zipsub2->open("$subsubfile2");
$wordsub2 = $zipsub2->getFromName('word/document.xml');
$word2sub2 = str_replace($find, $replace, $wordsub2);
$word2sub2 = str_replace($find2, $replace2, $wordsub2);
$word2sub2 = str_replace($find3, $replace3, $wordsub2);
$word2sub2 = str_replace($find4, $replace4, $wordsub2);
$zipsub2->addFromString("word/document.xml", $word2sub2);
$zipsub2->close();
}
//more directories when needed
//****replicate code here****
//add files to archive
$zip_download->addFile($subsubfile2, $subsubfile2);
}
}
}
}
//add files to archive
$zip_download->addFile($subsubfile, $subsubfile);
}
}
}
} else {
die ("Error - No files in the directory");
}
}
//add files to archive
$zip_download->addFile($file, $file);
}
$zip_download->close();
//download zip
if (file_exists($zipfile) && is_readable($zipfile)) {
header('Content-Type: application/octet-stream');
header('Content-Length: '.filesize($zipfile));
header('Content-Disposition: attachment; filename="'.basename($zipfile).'";');
header('Content-Transfer-Encoding: binary');
$file_download = # fopen($zipfile, 'rb');
if ($file_download) {
fpassthru($file_download);
exit;
}
echo ("ZIP generated successfully, download is starting...");
} else {
echo ("Error creating the ZIP archive!");
}
}
?>
I think it's because Scandir() will produce something like
`Array
(
...
[9] => .
[10] => ..`
at the end of the arrayand when you check those if they are folders maybe an error occurs and dies.

Glitches in code for deleting a folder after the zip is made

I have the code below.
It first create a dynamic folder with name like v3_12-02-2012-12873547839. Then it creates a subfolder called "image" and saves some jpeg images in the subfolder. Then it create a csv file and put it in "v3_12-02-2012-12873547839"
Then it creates a zip folder in the project folder with name "v3_12-02-2012-12873547839.zip"
function create_csv($version,$ctg,$cnt,$nt,$api)
{
$folder = $version."-".date('d-m-Y')."-".time();
if(!file_exists('./'.$folder))
{
mkdir('./'.$folder);
mkdir('./'.$folder.'/image/');
}
$cnt_table = "aw_countries_".$version;
$ctg_table = "aw_categories_".$version;
$off_table = "aw_offers_".$version;
$sizeof_ctg = count($ctg);
$cond_ctg = " ( ";
for($c = 0; $c < $sizeof_ctg ; $c++)
{
$cond_ctg = $cond_ctg." $ctg_table.category = '".$ctg[$c]."' ";
if($c < intval($sizeof_ctg-1))
$cond_ctg = $cond_ctg." OR ";
else if($c == intval($sizeof_ctg-1))
$cond_ctg = $cond_ctg." ) ";
}
$sizeof_cnt = count($cnt);
$cond_cnt = " ( ";
for($cn = 0; $cn < $sizeof_cnt ; $cn++)
{
$cond_cnt = $cond_cnt." $cnt_table.country = '".$cnt[$cn]."' ";
if($cn < intval($sizeof_cnt-1))
$cond_cnt = $cond_cnt." OR ";
else if($cn == intval($sizeof_cnt-1))
$cond_cnt = $cond_cnt." ) ";
}
$sizeof_nt = count($nt);
$cond_nt = " ( ";
for($n = 0; $n < $sizeof_nt ; $n++)
{
$cond_nt = $cond_nt." $off_table.network_id = '".$nt[$n]."' ";
if($n < intval($sizeof_nt-1))
$cond_nt = $cond_nt." OR ";
else if($n == intval($sizeof_nt-1))
$cond_nt = $cond_nt." ) ";
}
$sizeof_api = count($api);
$cond_api = " ( ";
for($a = 0; $a < $sizeof_api ; $a++)
{
$cond_api = $cond_api." $off_table.api_key = '".$api[$a]."' ";
if($a < intval($sizeof_api-1))
$cond_api = $cond_api." OR ";
else if($a == intval($sizeof_api-1))
$cond_api = $cond_api." ) ";
}
$output = "";
$sql = "SELECT DISTINCT $off_table.id,$off_table.name
FROM $off_table,$cnt_table,$ctg_table
WHERE $off_table.id = $cnt_table.id
AND $off_table.id = $ctg_table.id
AND ".$cond_api."
AND ".$cond_nt."
AND ".$cond_cnt."
AND ".$cond_ctg;
$result = mysql_query($sql);
$columns_total = mysql_num_fields($result);
for ($i = 0; $i < $columns_total; $i++)
{
$heading = mysql_field_name($result, $i);
$output .= '"'.$heading.'",';
}
$output .= '"icon"';
$output .="\n";
while ($row = mysql_fetch_array($result))
{
for ($i = 0; $i < $columns_total; $i++)
{
$output .='"'.$row["$i"].'",';
}
$sql_icon = "SELECT $off_table.icon FROM $off_table WHERE id = '".$row['id']."'";
$result_icon = mysql_query($sql_icon);
while($row_icon = mysql_fetch_array($result_icon))
{
$image = $row_icon["icon"];
$id = $row["id"];
$icon = "./$folder/image/{$id}.jpg";
$icon_link = "$folder/image/{$id}.jpg";
file_put_contents($icon, $image);
}
$output .= '"'.$icon_link.'"';
$output .="\n";
}
$filename = "myFile.csv";
$fd = fopen ( "./$folder/$filename", "w");
fputs($fd, $output);
fclose($fd);
$source = $folder;
$destination = $folder.'.zip';
$flag = '';
if (!extension_loaded('zip') || !file_exists($source)) {
return false;
}
$zip = new ZipArchive();
if (!$zip->open($destination, ZIPARCHIVE::CREATE)) {
return false;
}
$source = str_replace('\\', '/', $source);
if($flag)
{
$flag = basename($source) . '/';
}
if (is_dir($source) === true)
{
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);
foreach ($files as $file)
{
if (strpos($flag.$file,$source) !== false) { // this will add only the folder we want to add in zip
if (is_dir($file) === true)
{
}
else if (is_file($file) === true)
{
$zip->addFromString(str_replace($source . '/', '', $flag.$file), file_get_contents($file));
}
}
}
}
else if (is_file($source) === true)
{
$zip->addFromString($flag.basename($source), file_get_contents($source));
}
$zip->close();
if (is_dir($folder))
{
$objects = scandir($folder);
foreach ($objects as $object)
{
if ($object != "." && $object != "..")
{
if (filetype($folder."/".$object) == "dir")
{
$object_inner = scandir($folder."/".$object);
foreach ($object_inner as $object_inner)
{
if ($object_inner != "." && $object_inner != "..")
{
unlink($folder."/".$object."/".$object_inner);
}
}
rmdir($folder."/".$object);
}
else
unlink($folder."/".$object);
}
}
reset($objects);
}
rmdir("./".$folder);
}
Now the problem is, when I am trying to delete the folder, the folder somehow doesn't seem to delete, though I can recursively delete all its contents. Even though the folder becomes empty at the end, it doesn't get deleted.
Error I am getting:
Warning: rmdir(./v3-02-12-2014-1417512727): Permission denied in C:\xampp\htdocs\projecthas2offer\appwall_dev\frontend\ajax.php on line 265
Instances of ZipArchive and/or RecursiveIteratorIterator still live and might still have their hands on your directory, so free them using unset( $zip, $files );

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