I'm running 2 simple function:
<?php
$zipUrl = "path_of_original.zip"
$zipFilename = "local_path_and_name_of.zip"
$unzipPath = "destination_of_unzipped_files"
upload_archive ($zipUrl, $zipFilename);
unzip_archive ($zipFilename, $unzipPath);
?>
the 1st, upload a .zip archive on server
function upload_archive ($zipUrl, $zipFilename){
define('BUFSIZ', 4095);
$rfile = fopen($zipUrl, 'r');
$lfile = fopen($zipFilename, 'w');
while(!feof($rfile))
fwrite($lfile, fread($rfile, BUFSIZ), BUFSIZ);
fclose($rfile);
fclose($lfile);}
the 2nd, unzip the archive
function unzip_archive ($zipFilename, $unzipPath){
$zip = new ZipArchive;
$res = $zip->open($zipFilename);
if ($res === TRUE) {
$zip->extractTo($unzipPath);
$zip->close();
echo 'success!';
} else {
echo 'error!';
}
}
when these 2 functions are executed separately everything's fine, but when executed in sequence I can't appreciate the output of the second function (unzip).
I think the problem is that the .zip file is still locked in write by the first function.
any Suggestions?
Angelo.
Related
I'm beginner in html and php. I trying to create a script that will open the directory, display all text files, open each of them for editing and save the changes to a file (all the script operation will be transferred to the html form). Unfortunately, after opening the directory and viewing the files, I have trouble reading their contents. Could someone tell me what I doing wrong ?
Thank for help
<?php
$path = "books/";
$books = opendir($path);
while (($book = readdir($books)) !== false)
{
echo $book;
foreach (glob("*.txt") as $readfile)
{
$readFile = fopen($book, "r") or die("Permission error");
echo fread($readFile, filesize($book));
fclose($readFile);
}
}
closedir();
?>
Server response:
...Atlas_chmur.txtDiuna.txt
I used the loop so that only .txt files were opened. Currently I have this:
<?php
$path = "books/";
$books = opendir($path);
while (($book = readdir($books)) !== false)
{
echo $book;
$readFile = fopen($book, "r") or die("Permission error");
echo fread($readFile, filesize($book));
fclose($readFile);
}
closedir();
?>
Now I'm getting an error when trying to read the files.
Server response:
. Warning: fopen (.): Failed to open stream: Permission denied in C: \ xampp \ htdocs \ BooksEditorForm \ index.php on line 9 Permission error
Try this code
$path = "blog/";
$books = opendir($path);
while (($book = readdir($books)) !== false)
{
if( substr($book, -4) === ".txt" )
{
$filePath = $path.$book;
$readFile = fopen($filePath, "r") or die("Permission error");
echo fread($readFile, filesize($filePath));
fclose($readFile);
}
}
closedir();
Let me explain it...
First, occasions where you need loop inside a loop are quite rare so if your code has them, analyze it because there's a big possibility that problem can be solved differently and more efficient.
Code: value of $book is string that contains filename so simple use of substr() function to check last 4 characters will tell us is it of "*.txt" format.
Other thing that is changed is filepath; $book contains it's name but your script is looking for a file from its own perspective so file path should be containing folder + filename.
And there's no need for closing PHP tags at the end unless you have something else following it that is not PHP (like HTML).
I have used the below code. It's working well.try this code
$files = scandir('books/');
if(count($files) > 0) {
foreach ($files as $key => $value) {
echo '<pre>'; print_r($value); echo '</pre>';
// to read files data
$readFileVar = fopen ($value, "r");
while ($filedata = fgets($readFileVar)) {
print_r($filedata);
}
}
}
I have a file.php inside a .zip archive. In this example my file has 10 lines of code in it. How do i count those lines using php?(i can count them for files outside that .zip but i can't figure out how to count those lines for files inside that zip :().
Thank you! :D
Try getting a file handler using getStream(); method that's already built in PHP ZipArchive class. Your code will look something like this:
$lines = 0;
$z = new ZipArchive();
if ($z->open('path/to/your/archive.zip')) { //make sure you edit this
$fp = $z->getStream('file.php'); //and this according to your file names and path/s
if(!$fp) exit("Couldn't find your file.");
while (!feof($fp)) {
$line = fgets($fp);
$lines++;
}
fclose($fp);
echo $lines; //Total lines counter
}
A possible answer can be extract the contents of zip file count out the lines (you already know) remove the files.
$zip = new ZipArchive;
$res = $zip->open('file.zip');
if ($res === TRUE) {
$zip->extractTo('/path/');
$zip->close();
// read lines then delete extracted files using unlink()
} else {
echo 'ERROR!';
}
I've tryed some ways to automatically unzip files with php but all of them failed:
1st variant
<?php
function unzip($file){
$zip=zip_open(realpath(".")."/".$file);
if(!$zip) {return("Unable to proccess file '{$file}'");}
$e='';
while($zip_entry=zip_read($zip)) {
$zdir=dirname(zip_entry_name($zip_entry));
$zname=zip_entry_name($zip_entry);
if(!zip_entry_open($zip,$zip_entry,"r")) {$e.="Unable to proccess file '{$zname}'"; continue; }
if(!is_dir($zdir)) mkdirr($zdir,0777);
#print "{$zdir} | {$zname} \n";
$zip_fs=zip_entry_filesize($zip_entry);
if(empty($zip_fs)) continue;
$zz=zip_entry_read($zip_entry,$zip_fs);
$z=fopen($zname,"w");
fwrite($z,$zz);
fclose($z);
zip_entry_close($zip_entry);
}
zip_close($zip);
return $e;
}
$file = 'file_name.zip';
echo unzip($file);
2nd variant
<?php
$zip = zip_open("my_linkedin_groups_scrape_my_run_1_2015.zip");
if ($zip) {
while ($zip_entry = zip_read($zip)) {
$fp = fopen("./".zip_entry_name($zip_entry), "w");
if (zip_entry_open($zip, $zip_entry, "r")) {
$buf = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
fwrite($fp,"$buf");
zip_entry_close($zip_entry);
fclose($fp);
}
}
zip_close($zip);
}
?>
3rd variant
<?php
// assuming file.zip is in the same directory as the executing script.
$file = 'file.zip';
// get the absolute path to $file
$path = pathinfo(realpath($file), PATHINFO_DIRNAME);
$zip = new ZipArchive;
$res = $zip->open($file);
if ($res === TRUE) {
// extract it to the path we determined above
$zip->extractTo($path);
$zip->close();
echo "WOOT! $file extracted to $path";
} else {
echo "Doh! I couldn't open $file";
}
?>
for the 3rd case output is Doh! I couldn't open file.zip
What's wrong? Am I something missing?
I
Seems like a problem with write/read rights.
Change the rights for testing purposes on to 0777
I would go with 3rd variant. Try using absolute path to zip file and dump $res in the error message. It will say exactly whats wrong, just compare it with specific error codes http://php.net/manual/en/ziparchive.open.php.
I'm working on what seems to be a simple php reading and writing to a txt file. I'm able to read the file but not write. I've tried variations of the following but to no avail. I'm trying to read the txt file that will have a 0 or a 1 in it and switch it. But for some reason I can only read. How can I make this code write to the file? Note I do have write permissions to the txt file.
Thx
Rich
<?php
$status = readfile("0.txt");
echo $status;
$file_handle = fopen("../light_switches/0.txt", "w");
if($status = 1){
$file_contents = "0";
fwrite($file_handle, $file_contents);
}
else if($status = 0){
$file_contents = "1";
fwrite($file_handle, $file_contents);
}
fclose($file_handle);
?>
readfile returns the number of bytes read from the file, but not the file content.
You could use file_get_contents to get the file content, and use file_put_contents to write:
$path = "../light_switches/0.txt";
file_put_contents($path, file_get_contents($path) === '0' ? '1' : '0');
Use file_put_contents(). It is the same as calling fopen(), fwrite(), and fclose(). Use the flag FILE_APPEND
file_put_contents($filepath, $content, FILE_APPEND);
PHP Documentation
EDIT
I have reworked this code. If all you are doing is trying to switch the 0 and 1 of the txt file, this code is working. Simply just replace the file path with yours.
<?php
$file_path = '0.txt';
if (!file_exists($file_path)) {
echo 'File does not exist';
exit;
}
$currentContent = file_get_contents($file_path);
echo $currentContent;
if ($currentContent == '0') {
$newContent = '1';
}
elseif ($currentContent == '1') {
$newContent = '0';
}
else {
//Start the file fresh if it found extra lines for example
$newContent = '0';
}
file_put_contents($file_path, $newContent);
?>
I am using a fairly straight-forward script to open and parse several xml files that are gzipped. I also need to do the same basic operation with a ZIP file. It seems like it should be simple, but I haven't been able to find what looked like equivalent code anywhere.
Here is the simple version of what I am already doing:
$import_file = "source.gz";
$sfp = gzopen($import_file, "rb"); ///// OPEN GZIPPED data
while ($string = gzread($sfp, 4096)) { //Loop through the data
/// Parse Output And Do Stuff with $string
}
gzclose($sfp);
What would do the same thing for a zipped file?
If you have PHP 5 >= 5.2.0, PECL zip >= 1.5.0 then you may use the ZipArchive libraries:
$zip = new ZipArchive;
if ($zip->open('source.zip') === TRUE)
{
for($i = 0; $i < $zip->numFiles; $i++)
{
$fp = $zip->getStream($zip->getNameIndex($i));
if(!$fp) exit("failed\n");
while (!feof($fp)) {
$contents = fread($fp, 8192);
// do some stuff
}
fclose($fp);
}
}
else
{
echo 'Error reading zip-archive!';
}
There is a smart way to do it with ZipArchive. You can use a for loop with ZipArchive::statIndex() to get all the information you need. You can access the files by their index (ZipArchive::getFromIndex()) or name (ZipArchive::getFromName()).
For example:
function processZip(string $zipFile): bool
{
$zip = new ZipArchive();
if ($zip->open($zipFile) !== true) {
echo '<p>Can\'t open zip archive!</p>';
return false;
}
// As long as statIndex() does not return false keep iterating
for ($idx = 0; $zipFile = $zip->statIndex($idx); $idx++) {
$directory = \dirname($zipFile['name']);
if (!\is_dir($zipFile['name'])) {
// file contents
$contents = $zip->getFromIndex($idx);
}
}
$zip->close();
}