Im using this code to make a zip from my folder:
<?php
// DIRECTORY WE WANT TO BACKUP
$pathBase = '../'; // Relate Path
// ZIP FILE NAMING ... This currently is equal to = sitename_www_YYYY_MM_DD_backup.zip
$zipPREFIX = "sitename_www";
$zipDATING = '_' . date('Y_m_d') . '_';
$zipPOSTFIX = "backup";
$zipEXTENSION = ".zip";
// SHOW PHP ERRORS... REMOVE/CHANGE FOR LIVE USE
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
// ############################################################################################################################
// NO CHANGES NEEDED FROM THIS POINT
// ############################################################################################################################
// SOME BASE VARIABLES WE MIGHT NEED
$iBaseLen = strlen($pathBase);
$iPreLen = strlen($zipPREFIX);
$iPostLen = strlen($zipPOSTFIX);
$sFileZip = $pathBase . $zipPREFIX . $zipDATING . $zipPOSTFIX . $zipEXTENSION;
$oFiles = array();
$oFiles_Error = array();
$oFiles_Previous = array();
// SIMPLE HEADER ;)
echo '<center><h2>PHP Example: ZipArchive - Mayhem</h2></center>';
// CHECK IF BACKUP ALREADY DONE
if (file_exists($sFileZip)) {
// IF BACKUP EXISTS... SHOW MESSAGE AND THATS IT
echo "<h3 style='margin-bottom:0px;'>Backup Already Exists</h3><div style='width:800px; border:1px solid #000;'>";
echo '<b>File Name: </b>',$sFileZip,'<br />';
echo '<b>File Size: </b>',$sFileZip,'<br />';
echo "</div>";
exit; // No point loading our function below ;)
} else {
// NO BACKUP FOR TODAY.. SO START IT AND SHOW SCRIPT SETTINGS
echo "<h3 style='margin-bottom:0px;'>Script Settings</h3><div style='width:800px; border:1px solid #000;'>";
echo '<b>Backup Directory: </b>',$pathBase,'<br /> ';
echo '<b>Backup Save File: </b>',$sFileZip,'<br />';
echo "</div>";
// CREATE ZIPPER AND LOOP DIRECTORY FOR SUB STUFF
$oZip = new ZipArchive;
$oZip->open($sFileZip, ZipArchive::CREATE | ZipArchive::OVERWRITE);
$oFilesWrk = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($pathBase),RecursiveIteratorIterator::LEAVES_ONLY);
foreach ($oFilesWrk as $oKey => $eFileWrk) {
// VARIOUS NAMING FORMATS OF THE CURRENT FILE / DIRECTORY.. RELATE & ABSOLUTE
$sFilePath = substr($eFileWrk->getPathname(),$iBaseLen, strlen($eFileWrk->getPathname())- $iBaseLen);
$sFileReal = $eFileWrk->getRealPath();
$sFile = $eFileWrk->getBasename();
// WINDOWS CORRECT SLASHES
$sMyFP = str_replace('\\', '/', $sFileReal);
if (file_exists($sMyFP)) { // CHECK IF THE FILE WE ARE LOOPING EXISTS
if ($sFile!="." && $sFile!="..") { // MAKE SURE NOT DIRECTORY / . || ..
// CHECK IF FILE HAS BACKUP NAME PREFIX/POSTFIX... If So, Dont Add It,, List It
if (substr($sFile,0, $iPreLen)!=$zipPREFIX && substr($sFile,-1, $iPostLen + 4)!= $zipPOSTFIX.$zipEXTENSION) {
$oFiles[] = $sMyFP; // LIST FILE AS DONE
$oZip->addFile($sMyFP, $sFilePath); // APPEND TO THE ZIP FILE
} else {
$oFiles_Previous[] = $sMyFP; // LIST PREVIOUS BACKUP
}
}
} else {
$oFiles_Error[] = $sMyFP; // LIST FILE THAT DOES NOT EXIST
}
}
$sZipStatus = $oZip->getStatusString(); // GET ZIP STATUS
$oZip->close(); // WARNING: Close Required to append files, dont delete any files before this.
// SHOW BACKUP STATUS / FILE INFO
echo "<h3 style='margin-bottom:0px;'>Backup Stats</h3><div style='width:800px; height:120px; border:1px solid #000;'>";
echo "<b>Zipper Status: </b>" . $sZipStatus . "<br />";
echo "<b>Finished Zip Script: </b>",$sFileZip,"<br />";
echo "<b>Zip Size: </b>",human_filesize($sFileZip),"<br />";
echo "</div>";
// SHOW ANY PREVIOUS BACKUP FILES
echo "<h3 style='margin-bottom:0px;'>Previous Backups Count(" . count($oFiles_Previous) . ")</h3><div style='overflow:auto; width:800px; height:120px; border:1px solid #000;'>";
foreach ($oFiles_Previous as $eFile) {
echo basename($eFile) . ", Size: " . human_filesize($eFile) . "<br />";
}
echo "</div>";
// SHOW ANY FILES THAT DID NOT EXIST??
if (count($oFiles_Error)>0) {
echo "<h3 style='margin-bottom:0px;'>Error Files, Count(" . count($oFiles_Error) . ")</h3><div style='overflow:auto; width:800px; height:120px; border:1px solid #000;'>";
foreach ($oFiles_Error as $eFile) {
echo $eFile . "<br />";
}
echo "</div>";
}
// SHOW ANY FILES THAT HAVE BEEN ADDED TO THE ZIP
echo "<h3 style='margin-bottom:0px;'>Added Files, Count(" . count($oFiles) . ")</h3><div style='overflow:auto; width:800px; height:120px; border:1px solid #000;'>";
foreach ($oFiles as $eFile) {
echo $eFile . "<br />";
}
echo "</div>";
}
// CONVERT FILENAME INTO A FILESIZE AS Bytes/Kilobytes/Megabytes,Giga,Tera,Peta
function human_filesize($sFile, $decimals = 2) {
$bytes = filesize($sFile);
$sz = 'BKMGTP';
$factor = floor((strlen($bytes) - 1) / 3);
return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . #$sz[$factor];
}
?>
Source
When this finishes it zip the folder but it lefts a slash on every file on root of the zip:
image
Then i have another script to unzip zip files.
$zip = new ZipArchive;
$res = $zip->open('file.zip');
if ($res === TRUE) {
$zip->extractTo('/myzips/extract_path/');
$zip->close();
echo 'woot!';
} else {
echo 'doh!';
}
Source
But when the files and directory start with \ it mess up with the unzip. and it doesnt unzip into the directories, every file go to root of the unziped folder. image
How can i remove \ on root of the zip file?
Related
I am having some trouble with a PHP script. I am trying to do two things:
Create an XML file in /usr/local/ezreplay/data/XML/ directory and add contents to it using inputs passed to it from a HTML form;
Upload a PCAP file which is included in the submitted HTML form.
Here is my PHP (apologies it is a little long but I believe all of it is relevant here):
<?php
// Check if the 'expirydate' input is set
if (isset($_POST['expirydate'])) {
// Convert the input string to a timestamp using 'strtotime'
$timestamp = strtotime($_POST['expirydate']);
// Format the timestamp as a 'mm/dd/yyyy' string using 'date'
$expirydate = date('m/d/Y', $timestamp);
}
// Check if all required POST variables are set
if ( isset($_POST['destinationip']) && isset($_POST['destinationport']) && isset($expirydate) && isset($_POST['multiplier']) && isset($_POST['pcap']) ) {
// Set the path for the XML file
$path = '/usr/local/ezreplay/data/XML/' . trim($_POST['destinationip']) . ':' . trim($_POST['destinationport']) . ':' . $expirydate . ':' . trim($_POST['multiplier']) . ':' . trim($_POST['pcap']) . '.xml';
// Initialize the contents of the XML file
$contents = "";
// Open the XML file in append mode
if ( $fh = fopen($path,"a+") ) {
// Add the opening 'config' tag to the XML file
$contents .= '<config>';
// If the 'destinationip' and 'destinationport' POST variables are not empty, add a 'destination' tag to the XML file
if ( trim( $_POST['destinationip'] ) != "" && trim( $_POST['destinationport'] ) != "" ) {
$contents .= "\n" . '<destination>' . $_POST['destinationip'] . ':' . $_POST['destinationport'] . '</destination>';
}
// If the 'multiplier' POST variable is not empty, add a 'multiplier' tag to the XML file
if ( trim( $_POST['multiplier'] ) != "" ) {
$contents .= "\n" . '<multiplier>' . $_POST['multiplier'] . '</multiplier>';
}
// If the 'pcap' POST variable is not empty, add a 'pcap' tag to the XML file
if ( trim( $_POST['pcap'] ) != "" ) {
$contents .= "\n" . '<pcap>/usr/local/ezreplay/data/PCAP/' . $_POST['pcap'] . '</pcap>';
// Add default tags to XML config file to ensure the pcap does not fail and loops continuously until expiration date hits
$contents .= "\n" . '<loop>0</loop>';
$contents .= "\n" . '<nofail>true</nofail>';
}
// Add the closing 'config' tag to the XML file
$contents .= "\n" . '</config>';
// Write the contents to the file
if ( fwrite( $fh, $contents ) ) {
// Success
} else {
echo "The XML config could not be created";
}
// Close the file
fclose($fh);
}
}
// Set the target directory and file name
$target_dir = "/usr/local/ezreplay/data/PCAP/";
$basename = basename($_FILES["pcap"]["name"]);
$target_file = $target_dir . $basename;
// Check if the file has a pcap extension
$allowedExtensions = array('pcap');
$basenameWithoutExt = null;
foreach ($allowedExtensions as $allowedExtension) {
if (preg_match('#\\.' . $allowedExtension . '$#',$basename)) {
$basenameWithoutExt = substr($basename,0,-1 - strlen($allowedExtension));
break;
}
}
// Accept only .pcap files
if (is_null($basenameWithoutExt)) {
echo "Sorry, only .pcap files are allowed. Please try creating your Packet Replay again using a .pcap file.";
exit;
}
// Check if the file already exists
if (file_exists($target_file)) {
echo "The Packet Replay could not be started, the PCAP is already running.";
exit;
}
// Try to upload the file
if (move_uploaded_file($_FILES["pcap"]["tmp_name"], $target_file)) {
// Success
} else {
echo "Sorry, there was an error uploading your file.";
exit;
}
// Start the Packet Replay
$command = '/usr/local/ezreplay/bin/startreplay.sh ' . $path;
system($command);
echo "The Packet Replay has been started.";
?>
Now the file upload is working and I can see the final echo message being returned in my browser however the XML file is never created. I have changed the directory ownership to the apache user and even chmod 777 to eliminate any permissions issues but it still doesn't create the file.
Any ideas why this is not working? The PHP and apache error logs don't show any issues and as I mentioned the script seems to be working to a degree as the file upload takes place perfectly.
Thanks!
I think the file is not being created due to "/" in the filename. As mentioned at Allowed characters in filename
I managed to fix this with the following edits.
<?php
// Set the target directory and file name
$target_dir = "/usr/local/ezreplay/data/PCAP/";
$basename = basename($_FILES["pcap"]["name"]);
$target_file = $target_dir . $basename;
// Check if the file has a pcap extension
$allowedExtensions = array('pcap');
$basenameWithoutExt = null;
foreach ($allowedExtensions as $allowedExtension) {
if (preg_match('#\\.' . $allowedExtension . '$#',$basename)) {
$basenameWithoutExt = substr($basename,0,-1 - strlen($allowedExtension));
break;
}
}
// Accept only .pcap files
if (is_null($basenameWithoutExt)) {
echo "Sorry, only .pcap files are allowed. Please try creating your Packet Replay again using a .pcap file.";
exit;
}
// Check if the file already exists
if (file_exists($target_file)) {
echo "The Packet Replay could not be started, the PCAP is already running.";
exit;
}
// Try to upload the file
if (move_uploaded_file($_FILES["pcap"]["tmp_name"], $target_file)) {
//Success
} else {
echo "Sorry, there was an error uploading your file.";
exit;
}
// Check if the 'expirydate' input is set
if (isset($_POST['expirydate'])) {
// Convert the input string to a timestamp using 'strtotime'
$timestamp = strtotime($_POST['expirydate']);
// Format the timestamp as a 'mm-dd-yyyy' string using 'date'
$expirydate = date('m-d-Y', $timestamp);
}
// Check if 'destinationip', 'destinationport', 'multiplier' and 'pcap' required POST variables are set
if (isset($_POST['destinationip']) && isset($_POST['destinationport']) && isset($_POST['multiplier'])) {
// Set the filename and path for the XML file
$file = '/usr/local/ezreplay/data/XML/' . trim($_POST['destinationip']) . ':' . trim($_POST['destinationport']) . ':' . trim($_POST['multiplier']) . ':' . $expirydate . ':' . $_FILES["pcap"]["name"] . '.xml';
// Initialize the contents of the XML file
$contents = "";
// Add the opening 'config' tag to the XML file
$contents .= '<config>';
// If the 'destinationip' and 'destinationport' POST variables are not empty, add a 'destination' tag to the XML file
if (trim($_POST['destinationip']) != "" && trim($_POST['destinationport']) != "") {
$contents .= "\n" . '<destination>' . $_POST['destinationip'] . ':' . $_POST['destinationport'] . '</destination>';
}
// If the 'multiplier' POST variable is not empty, add a 'multiplier' tag to the XML file
if (trim($_POST['multiplier']) != "") {
$contents .= "\n" . '<multiplier>' . $_POST['multiplier'] . '</multiplier>';
}
// If the 'pcap' POST variable is not empty, add a 'pcap' tag to the XML file
if (trim($_FILES["pcap"]["name"]) != "") {
$contents .= "\n" . '<pcap>/usr/local/ezreplay/data/PCAP/' . $_FILES["pcap"]["name"] . '</pcap>';
}
// Add default tags to XML config file to ensure the pcap does not fail and loops continuously until expiration date hits
$contents .= "\n" . '<loop>0</loop>';
$contents .= "\n" . '<nofail>true</nofail>';
// Add the closing 'config' tag to the XML file
$contents .= "\n" . '</config>';
// Write the contents to the file
if (file_put_contents($file, $contents)) {
// Success
} else {
echo "The XML config could not be created";
}
}
// Start the Packet Replay
$command = '/usr/local/ezreplay/bin/startreplay.sh ' . $path;
system($command);
echo "The Packet Replay has been started.";
?>
I m using this code to output content of files in a directory but I have two problems
first is that this directory contains sub-dir and this code doesn't output
files content in these sub-dir
Second problem
I want this code to output like
Filename:"name of the file"
Content :"content of the file"
so that I can parse this
$dir = new DirectoryIterator('./Chemistry');
foreach($dir as $file)
{
if(!$file->isDot() && $file->isFile() && strpos($file->getFilename(), '.md') !== false)
{
$content = file_get_contents($file->getPathname());
echo $content
}
}
?>
If I understand correct you want to output:
echo 'Filename: ' . $file->getFilename() . ' Content: ' . $content;
If this is not your intention I will require a more thorough explanation.
* edit *
For dir iteration use http://php.net/manual/en/function.scandir.php
From the top of my head it goes a little something like this (hit it)...
function loopDir($path) {
$allFilesAndFoldersInCurrentFolder = scandir($path);
foreach($allFilesAndFoldersInCurrentFolder as item) {
if(is_dir($item)) {
loopDir($path.'/'.$item);
}
else {
echo 'Filename: ' . $file->getFilename() . ' Content: ' . $content;
}
}
}
I want to be able to list all the directories, subdirectories and files in the "./" folder ie the project folder called fileSystem which contains this php file scanDir.php.
You can view the directory system I've got here:
At the minute it will only return the subdirectory folders/files in the root of the mkdir directory but not any folders inside that subdirectory.
How do I modify the code so that it demonstrates all the files, directories, subdirectories and their files and subdirectories within the fileSystem folder given that the php file being run is called scanDir.php and the code for that is provided below.
Here is the php code:
$path = "./";
if(is_dir($path))
{
$dir_handle = opendir($path);
//extra check to see if it's a directory handle.
//loop round one directory and read all it's content.
//readdir takes optional parameter of directory handle.
//if you only scan one single directory then no need to passs in argument.
//if you are then going to scan into sub-directories the argument needs
//to be passed into readdir.
while (($dir = readdir($dir_handle))!== false)
{
if(is_dir($dir))
{
echo "is dir: " . $dir . "<br>";
if($dir == "mkdir")
{
$sub_dir_handle = opendir($dir);
while(($sub_dir = readdir($sub_dir_handle))!== false)
{
echo "--> --> contents=$sub_dir <br>";
}
}
}
elseif(is_file($dir))
{
echo "is file: " . $dir . "<br>" ;
}
}
closedir($dir_handle); //will close the automatically open dir.
}
else {
echo "is not a directory";
}
Use scandir to see all stuff in the directory and is_file to check if the item is file or next directory, if it is directory, repeat the same thing over and over.
So, this is completely new code.
function listIt($path) {
$items = scandir($path);
foreach($items as $item) {
// Ignore the . and .. folders
if($item != "." AND $item != "..") {
if (is_file($path . $item)) {
// this is the file
echo "-> " . $item . "<br>";
} else {
// this is the directory
// do the list it again!
echo "---> " . $item;
echo "<div style='padding-left: 10px'>";
listIt($path . $item . "/");
echo "</div>";
}
}
}
}
echo "<div style='padding-left: 10px'>";
listIt("/");
echo "</div>";
You can see the live demo here in my webserver, btw, I will keep this link just for a second
When you see the "->" it's an file and "-->" is a directory
The pure code with no HTML:
function listIt($path) {
$items = scandir($path);
foreach($items as $item) {
// Ignore the . and .. folders
if($item != "." AND $item != "..") {
if (is_file($path . $item)) {
// this is the file
// Code for file
} else {
// this is the directory
// do the list it again!
// Code for directory
listIt($path . $item . "/");
}
}
}
}
listIt("/");
the demo can take a while to load, it's a lot of items.
There are some powerful builtin functions for PHP to find files and folders, personally I like the recursiveIterator family of classes.
$startfolder=$_SERVER['DOCUMENT_ROOT'];
$files=array();
foreach( new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $startfolder, RecursiveDirectoryIterator::KEY_AS_PATHNAME ), RecursiveIteratorIterator::CHILD_FIRST ) as $file => $info ) {
if( $info->isFile() && $info->isReadable() ){
$files[]=array('filename'=>$info->getFilename(),'path'=>realpath( $info->getPathname() ) );
}
}
echo '<pre>',print_r($files,true),'</pre>';
This is actually is an easy task
I want to display contents of all files located in specified folder.
I am passing directory name
echo "<a href='see.php?qname=". $_name ."'>" . $row["qname"] . "</a>";
on second page ,
I am iterating over the directory content
while($entryname = readdir($myDirectory))
{
if(is_dir($entryname))
{
continue;
}
if($entryname=="." || $entryname==".." )
{}
else
{
if(!is_dir($entryname))
{
$fileHandle=fopen($entryname, "r");
while (!feof($fileHandle) ) {
$line = fgets($fileHandle);
echo $line . "<br />";
}
.
.
.
but I am unable to read any file , I have changed their permissions as well.
I tried putting directory name statically which worked,
Can someone suggest what am I doing wrong?
$entryname will contain JUST the filename, with no path information. You have to manually rebuild the path yourself. e.g.
$dh = opendir('/path/you/want/to/read/');
while($file = readdir($dh)) {
$contents = file_get_contents('/path/you/want/to/read/' . $file);
^^^^^^^^^^^^^^^^^^^^^^^^^^---include path here
}
Without the explicit path in your "read the file code", you're trying to open and read a file in the script's current working directory, not the director you're reading the filenames from.
Much simpler:
foreach(glob("$myDirectory/*") as $file) {
foreach(file($file) as $line) {
echo $line . "<br />";
}
}
Even simpler:
foreach(glob("$myDirectory/*") as $file) {
echo nl2br(file_get_contents($file));
}
I have an image located on my site at:
www.blah.com/gallery/gallery/2244.jpg
If I type this URL directly I see the image.
Now, I have a small gallery where I want the image (and others) to show, but, using the following code it simply does not show:
$files = glob("/home/mysite/public_html/gallery/gallery/*.*");
for ($i=1; $i<count($files); $i++)
{
$num = $files[$i];
echo '<a class="fancybox-effects-a" rel="gallery" href="'.$num.'">';
echo '<img src="'.$num.'" class="gallery_img" alt=""></a>';
}
The image was uploaded without error like so (using http://www.verot.net/php_class_upload.htm):
if(isset($_FILES['image'])){
include('/home/mysite/php/lib/img_upload/class.upload.php');
// retrieve eventual CLI parameters
$cli = (isset($argc) && $argc > 1);
if ($cli) {
if (isset($argv[1])) $_GET['file'] = $argv[1];
if (isset($argv[2])) $_GET['dir'] = $argv[2];
if (isset($argv[3])) $_GET['pics'] = $argv[3];
}
// set variables
$dir_dest = (isset($_GET['dir']) ? $_GET['dir'] : 'test');
$dir_pics = (isset($_GET['pics']) ? $_GET['pics'] : $dir_dest);
if (!$cli) {
// ---------- IMAGE UPLOAD ----------
$handle = new Upload($_FILES['image']);
if ($handle->uploaded) {
$handle->image_resize = true;
$handle->image_ratio_x = true;
$handle->image_y = 500;
$handle->Process('/home/mysite/public_html/gallery/gallery/');
// we check if everything went OK
if ($handle->processed) {
// everything was fine !
$success .= 'Image uploaded to the gallery successfully!';
} else {
// one error occured
$error .= '<li>file not uploaded to the wanted location';
$error .= '<li>Error: ' . $handle->error . '';
}
// we now process the image a second time, with some other settings
/******************************/
// produce thumbnails
/*****************************/
$handle->image_resize = true;
$handle->image_ratio_x = true;
$handle->image_y = 120;
$handle->image_reflection_height = 50;
$handle->image_reflection_opacity = 90;
$handle->image_convert = 'png';
$handle->Process('/home/mysite/public_html/gallery/gallery/thumbs/');
// we check if everything went OK
if ($handle->processed) {
// everything was fine !
$success .= '<p>Thumbnail created successfully, see below...';
$success .= '<p><img src="/gallery/gallery/thumbs/' . $handle->file_dst_name . '" />';
} else {
// one error occured
$error .= 'file not uploaded to the wanted location';
$error .= ' Error: ' . $handle->error . '';
}
/******************************/
// END use this if you want to produce thumbnails
/*****************************/
// we delete the temporary files
$handle-> Clean();
} else {
// if we're here, the upload file failed for some reasons
// i.e. the server didn't receive the file
$error .= '<li>file not uploaded on the server';
$error .= '<li>Error: ' . $handle->error . '';
}
}
}
I cannot fathom this out at all!
It looks like you set the src to the images' absolute path. Try this:
foreach (glob('/home/mysite/public_html/gallery/gallery/*.jpg') as $file) {
$file = '/gallery/gallery/'.basename($file);
echo '<a class="fancybox-effects-a" rel="gallery" href="'.$file.'">';
echo '<img src="'.$file.'" class="gallery_img" alt=""></a>';
}