ZipArchive::getStreamIndex kills script - php

I decided to try out the latest PHP ZIP functions for extracting data and something odd has happened. This PHP script is to read data from packed files of a specific extension (gob or goo) and display them in an XML format for further use later.
$zip = new ZipArchive;
$zipres = $zip->open($zipfilename);
if($zipres === true)
{
for($i = 0; $i < $zip->numFiles; $i++)
{
echo "\t<entry id=\"".$i."\">".$zip->getNameIndex($i)."</entry>\n";
if(strripos($zip->getNameIndex($i),".gob") !== false || strripos($zip->getNameIndex($i),".goo") !== false)
{
$zipentry = $zip->getStreamIndex($i);
return;
if($zipentry)
{
$packagenames[] = $zip->getNameIndex($i);
$wholeGOB[] = stream_get_contents($zipentry);
fclose($zipentry);
}
else
echo "\t<error>Error reading entry ".$zip->getNameIndex($i)."</error>";
}
}
$zip->close();
}
else
echo "\t<error>Invalid ZIP file</error>\n\t<code>".$zipres."</code>\n";
Having the return; before getStreamIndex will print out the <entry>s, but as soon as I move the return; to after getStreamIndex I get a blank page (even in view-source). Am I doing something wrong, or has this function always been a bit off? And what alternative would you recommend?

Related

My PHP Script dont want to create a ZIP File

I tried to code a script, that put some data in a zip file. I think I have done all right, but he does not create the zip file.
I already tried a lot, but don´t find the issue.
<?php
$sql_abfrage_cloud = "SELECT * FROM dateien WHERE code = '$zugang' ORDER BY id";
$abfrage_cloud = $mysqli->query($sql_abfrage_cloud);
$verzeichnis = '/upload/';
$zip_name = date("dHis").'_fc.zip';
$anz_dateien = 0;
$error = 'fatal';
while($fetch = $abfrage_cloud->fetch_assoc()){
$anz_dateien = $anz_dateien + 1;
$zip_datei[$anz_dateien] = $fetch['path'];
}
$zip_arch = new ZipArchive;
$status = $zip_arch->open($zip_name, ZipArchive::CREATE);
if($status==true){
foreach($zip_datei as $datei){
$zip_arch->addFile($verzeichnis.$datei, $datei);
}
if(file_exists($zip_name)){
$error = 'false';
} else {
$error = 'true';
}
}
?>
I expected that $error would be 'false' but it´s 'true'.
You need to call $zip_arch->close() to save finish writing the file.
You should also use === when comparing the result of $zip_archive->open(), since the non-true results are numbers, and any non-zero number compares equal to true when type juggling is allowed.
$zip_arch = new ZipArchive;
$status = $zip_arch->open($zip_name, ZipArchive::CREATE);
if($status===true){
foreach($zip_datei as $datei){
$zip_arch->addFile($verzeichnis.$datei, $datei);
}
$zip_arch->close();
if(file_exists($zip_name)){
$error = 'false';
} else {
$error = 'true';
}
}

create GTT, insert csv, using PHP?

I have eight csv sheets, which where updated (every two hours) by an external service. I want to analyse these data - showing it in a php page for my boss....
I imagined, that it would be the easiest way to have the .csv in a GTT on my MsSQL Server. Maybe it is possible to create a GTT on ervery use (on commit preserve rows)? I still have no approach to make the csv to a normal format for insert syntax... is it even possible?
Or is there an other option? I try to catch some ideas for the solution...
Thank you!
EDIT
I have php code to read the .csv and put it into an array.
$csv_datei = "applicationData.csv";
$feler_trenner = ";";
$zeilen_trenner = "n";
if (#file_exists($csv_datei) == false) {
echo 'Die CSV Datei: '. $csv_datei.' gibt es nicht!';
}
else {
$datei_inhalt = #file_get_contents($csv_datei);
$zeilen = explode($zeilen_trenner, $datei_inhalt);
if (is_array($zeilen) == true) {
foreach($zeilen as $zeile) {
$felder = explode($feler_trenner, $zeile);
$i = 0;
if (is_array($felder) == true) {
foreach($felder as $felde) {
if ($felde != '') {
echo (($i != 0) ? ', ':'') . str_replace('"', '', $felde);
$i++;
}
}
}
echo '<br>';
}
}
}
source: PHP-space.info

Check if Two Videos are the Same using php

I have search many time but i did not find any solution so in this case i can not post any code. sorry for this.
I have faced a problem that how can i check that 2 or more video same like i have media folder and many video upload in this folder then when i upload new video then need to check that video already exit or not.
1. if i have video demo.mp4 then when i will try to upload same video then give error
2. if i change video name like demo.mp4 to demo1.mp4 then i will give same error cause video name different but video content same
3. if i upload video demo5.mp4 then show me no error
i already checked image compare using
include('compareImages.php');
$new_image_name = $uploadfile_temp;
$compareMachine = new compareImages($new_image_name);
$image1Hash = $compareMachine->getHasString();
$files = glob("uploads/*.*");
$check_image_duplicate = 0;
for ($i = 0; $i < count($files); $i++) {
$filename = $files[$i];
$image2Hash = $compareMachine->hasStringImage($filename);
$diff = $compareMachine->compareHash($image2Hash);
if($diff < 10){
$check_image_duplicate = 1;
//unlink($new_image_name);
break;
}
}
but i can not compare video. someone help me
Tested and works fine, code taken from :http://php.net/manual/en/function.md5-file.php#94494 not mine.
<?php
define('READ_LEN', 4096);
if(files_identical('demo.mp4', 'demo1.mp4'))
echo 'files identical';
else
echo 'files not identical';
// pass two file names
// returns TRUE if files are the same, FALSE otherwise
function files_identical($fn1, $fn2) {
if(filetype($fn1) !== filetype($fn2))
return FALSE;
if(filesize($fn1) !== filesize($fn2))
return FALSE;
if(!$fp1 = fopen($fn1, 'rb'))
return FALSE;
if(!$fp2 = fopen($fn2, 'rb')) {
fclose($fp1);
return FALSE;
}
$same = TRUE;
while (!feof($fp1) and !feof($fp2))
if(fread($fp1, READ_LEN) !== fread($fp2, READ_LEN)) {
$same = FALSE;
break;
}
if(feof($fp1) !== feof($fp2))
$same = FALSE;
fclose($fp1);
fclose($fp2);
return $same;
}
?>

Calculate Library Fine (PHP)

So, here is the question (https://www.hackerrank.com/challenges/library-fine) I am trying to solve. To solve this, I created a simple function calculateFine and set the conditions to calculate the fine. What's the problem, then? Well, when I run the code on my machine, everything seems fine, but hackerrank won't accept the code. I am new to PHP and concept of functions was a bit confusing for me, but I tried. Below is my code:
<?php
$_fp = fopen("php://stdin", "r");
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
$_a = explode(" ",fgets($_fp));
$_b = explode(" ",fgets($_fp));
// Initialising variable
$_fine = "";
// Calling Function
calculateFine($_a,$_b);
// Defining Function
function calculateFine($actualDate, $returnDate)
{
// Checking various conditions
if ($actualDate[0] <= $returnDate[0] && $actualDate[1] == $returnDate[1] && $actualDate[2] == $returnDate[2])
{
$_fine = 0;
echo $_fine;
}
elseif($actualDate[0] > $returnDate[0] && $actualDate[1] == $returnDate[1] && $actualDate[2] == $returnDate[2])
{
$_late = $actualDate[0] - $returnDate[0];
$_fine = 15*$_late;
echo $_fine;
}
elseif($actualDate[1] > $returnDate[1] && $actualDate[2] == $returnDate[2])
{
$_late = $actualDate[1] - $returnDate[1];
$_fine = 500*$_late;
echo $_fine;
}
elseif($actualDate[2] > $returnDate[2])
{
$_fine = 10000;
echo $_fine;
}
else
{
$_fine = 0;
echo $fine; // Updated (This is the undefined variable causing error )
}
}
?>
It seems there's a newline in $actualDate[2]. So if you trim it you'll get the right answer:
trim($actualDate[2])
But would be better to trim it here already:
$_a = explode(" ",trim(fgets($_fp)));
$_b = explode(" ",trim(fgets($_fp)));
I got it, sorry for the carelessness. The last echo is $fine instead of $_fine. That's why the condition was not matching with some of the test cases. Thankyou.

How to repeat a function in php for every element in an array without it timing out

I have a function that will take an id and with that find out other information in the database relating to it spread among 3 tables. It then compares this to a csv file which at most times is cpu intensive. Running this once with one id takes approx 8 to 10 sec at most but I have been asked to have it run automatically across a varing number of ids in the database. To do this I created an array of the ids that match the criteria in the database at any point and then run a 'while' statement to repeat the function for each element in the array but it gets as far as maybe 4 of them and I get the following error:
Server error!
The server encountered an internal error and was unable to complete
your request. Either the server is overloaded or there was an error in
a CGI script.
If you think this is a server error, please contact the webmaster.
Error 500
I'll admit that my code could be much much cleaner as I'm still learning as I go but the real bottle neck appears to be reading the csv which is a report which size changes each day. I have tried different combinations and the best result is (please don't chastise me for this as I know it is stupid but the other ways haven't works as of yet) to run the code as follows:
$eventArray = eventArray($venueId);
$totalEvents = count($eventArray);
for($i=0; $i<$totalEvents; $i++)
{
$eventId = $eventArray[$i];
echo $eventId;
echo $datename = getEventDetails($eventId, $zone);
// date of event
echo $eventDate = $datename['eventDate'];
// vs team
echo $eventName = $datename['eventName'];
$file_handle = fopen("data/rohm/sales/today.csv", "r");
while (!feof($file_handle) )
{
$line_of_text = fgetcsv($file_handle, 200);
include('finance_logic.php');
}
fclose($file_handle);
}
Yes, it is repeating the reading of the csv every time but I couldn't get it to function at all any other way so if this is the issue I would really appreciate some guidence on dealing with the csv better. Incase it is relevent the code it 'finance_logic.php' is listed below:
if($line_of_text[0] == "Event: $eventName ")
{
$f = 1;
$ticketTotalSet = "no";
$killSet = 'no';
// default totals zero
$totalHolds = 0;
$totalKills = 0;
$ticketSold = 0;
$ticketPrice = 0;
$totalCap = 0;
}
if($f == 1 && $line_of_text[0] == "$eventDate")
{
$f = 2;
}
if($f == 2 && $line_of_text[0] == "Holds")
{
$f = 3;
while($line_of_text[$col] !== "Face Value Amt")
{
$col++;
}
}
if($f == 3 && $line_of_text[0] !== "Face Value Amt")
{
if($f == 3 && $line_of_text[0] == "*: Kill")
{
$totalKills = $line_of_text[$col];
}
$holdsArray[] = $line_of_text[$col];
}
if($f == 3 && $line_of_text[0] == "--")
{
$f = 4;
}
if($f == 4 && $line_of_text[0] == "Capacity")
{
$totalCap = $line_of_text[$col];
$f = 5;
}
if($f == 5 && $line_of_text[0] == "Abbreviated Performance Totals")
{
$f = 6;
}
if($f == 6 && $line_of_text[0] == "$eventName")
{
// change when 1 ticket exists
$ticketTotalSet = "yes";
// set season tickets
include("financial/seasontickets/$orgShortName.php");
// all non season are single tickets
if(!isset($category))
{
$category = 'single';
}
$ticketName = $line_of_text[2];
$ticketSold = $line_of_text[3];
$ticketPrice = $line_of_text[4];
addTicketType($eventId, $ticketName, $category, $ticketSold, $ticketPrice);
unset($category);
}
if($f == 6 && $ticketTotalSet == "yes" && $line_of_text[0] !== "$eventName")
{
$totalHolds = (array_sum($holdsArray) - $totalKills);
// add cap, holds and kills
addKillsHoldsCap($eventId, $totalCap, $eventId, $totalHolds, $totalKills);
// reset everything
$f = 0;
$ticketTotalSet = "no";
echo "$eventName updated!";
}
Thanks in advance!
p.s. The reason the report is called each time is so that the 'eventName' and 'eventDate' are searched for with the 'finance_logic.php'. Obviously if this was set with all event names and dates already it would take one search of the report to find them all but I'm not sure how I could do this dynamically. Any suggestions would be welcome as I'm sure there is something out there that I just haven't learnt yet.
I have some heavy script i use with localhost sometimes and if i don't add anything they will just time out.
A simple solution is to limit the number of execution of your function, then reload the page, then restart where you stopped.

Categories