I'm trying to create a XML file dynamically trough php, reading DIRS and FILES on a specific directory on my ftp.
So far so god, here's the code:
<?php
$path = ".";
$dir_handle = #opendir($path) or die("Unable to open $path");
function list_dir($dir_handle,$path)
{
while (false !== ($file = readdir($dir_handle))) {
$dir =$path.'/'.$file;
$link =$path.'/';
if(is_dir($dir) && $file != '.' && $file !='..' )
{
$handle = #opendir($dir) or die("unable to open file $file");
$xmlString .= '<' . $file . '>';
list_dir($handle, $dir);
$xmlString .= '</' . $file . '>';
}
elseif($file != '.' && $file !='..' && $file !='ftpteste.php')
{
$xmlString .= '<IMAGE>';
$xmlString .= '<PHOTO>' . $link . '' . $file . '</PHOTO>';
$xmlString .= '</IMAGE>';
}
}
closedir($dir_handle);
}
$xmlString ='<XML>';
list_dir($dir_handle,$path);
$xmlString .="</XML>";
$strXMLhead = '<?xml version="1.0" encoding="UTF-8" ?>';
$xmlString = $strXMLhead . "\n" . $xmlString;
$xmlLoc = "../../interiores/xml/content.xml";
$fileXML = fopen($xmlLoc, "w+") or die("Can't open XML file");
if(!fwrite($fileXML, pack("CCC",0xef,0xbb,0xbf)))
{
print "Error Saving File";
}
else
{
fwrite($fileXML, $xmlString);
print "XML file saved";
}
fclose($fileXML);
?>
The problem is that i'm getting no output on $XmlString running inside the function. If i use Print instead joining the strings it's fine, it does the job. But i need it to be in a variable in order to save to file.
Saving to file it's ok.
It should output something like:
<XML>
<$DIR NAME>
<IMAGE>
<PHOTO>$FILE_NAME</PHOTO>
</IMAGE>
</$DIR NAME>
</XML>
Can anyone help me with this?
thanks in advance,
artur
I think you should take a look at the DomDocument object. It provides an easy way to create a document with nodes (like an xml document). You will be able to avoid your problem with that.
Return the XML you're building from list_dir().
function list_dir($dir_handle,$path)
{
...
$xmlString .= list_dir($handle, $dir);
...
return $xmlString;
}
$xmlString = '<XML>' . list_dir($dir_handle,$path) . '</XML>';
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 have this code written in PHP, im using zend server on win 7 as localhost.
<?php
$dir = $_POST['link'];
// Create DOM from URL or file
require_once 'library/simple_html_dom.php';
$html = file_get_html($dir);
foreach($html->find('img') as $element){
$image = $element->src;
$imglink = $dir . $image;
$filename = $element->src;
$parsed_url = parse_url($filename, PHP_URL_PATH);
$basename = basename($filename).PHP_EOL;
$filenameOut = __DIR__ . "/images/" . $basename;
$pos = strpos($image, 'data:image');
if ($pos===false){
$parsing = parse_url($filename, PHP_URL_HOST);
if ($parsing != NULL){
file_put_contents($filenameOut, file_get_contents($image));
}
else{
file_put_contents($filenameOut, file_get_contents($imglink));
}
}
}
?>
And it gives me this error
file_put_contents(C:\Program Files (x86)\Zend\Apache2\htdocs/images/chrome-48.png ): failed to open stream: Invalid argument
Ive tried putting ways i've read from other questions from this site, but doesnt work.
I have this working fine in browser but air for ios need the full address.
<?php $path_to_image_dir = 'Games/game_images/'.$username;
$xml_string = "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?><data> <LoaderMax name=\"gallery\">";
if ( $handle = opendir( $path_to_image_dir ) ) {
$i = 1;
while (false !== ($file = readdir($handle))) {
if ( is_file($path_to_image_dir.'/'.$file) ) {
$xml_string .= "<ImageLoader url=\"" . $path_to_image_dir."/".$file . "\" />";
}
}
closedir($handle);
}
$xml_string .= "</LoaderMax></data>";
$ignore = array('.','..','cgi-bin','.DS_Store');
$file = fopen($username.'_imagesfile.xml','w');
fwrite($file, $xml_string);
fclose($file);
?>
this is the xml result:
<?xml version="1.0" encoding="iso-8859-1"?><data> <LoaderMax name="gallery"><ImageLoader url="Games/game_images/mrpeepers/1365535674.jpg" /><ImageLoader url="Games/game_images/mrpeepers/1365535527.jpg" /></LoaderMax></data>
works on ios if address is added by hand http://wwww.mysite.ccom/Games/game_images/mrpeeper/1365535674.jpg
Add $_SERVER['SERVER_NAME'] to your directory name like so:
$xml_string .= "<ImageLoader url=\"" . $_SERVER['SERVER_NAME'] . "/" . $path_to_image_dir."/".$file . "\" />";
http://php.net/manual/en/reserved.variables.server.php
I have a basic PHP script that displays the file contents of a directory. Here is the script:
<?php
$Dept = "deptTemplate";
if(isset($_REQUEST['dir'])) {
$current_dir = $_REQUEST['dir'];
} else {
$current_dir = 'docs';
}
if ($handle = opendir($current_dir)) {
while (false !== ($file_or_dir = readdir($handle))) {
if(in_array($file_or_dir, array('.', '..'))) continue;
$path = $current_dir.'/'.$file_or_dir;
if(is_file($path)) {
echo '`'.$file_or_dir.' - [Delete button/link]<br/>`';
} else {
echo '``'.$file_or_dir."\n`` - [Delete button/link]`<br/>`";
}
}
closedir($handle);
}
?>
I am trying to create a delete link/button that displays next to each file and when clicked, the corresponding file will be deleted. Would you know how to do this?
Use the built-in unlink($filepath) function.
Sure, you'd have to use unlink() and rmdir(), and you'd need a recursive directory removal function because rmdir() doesn't work on directories with files in them. You'd also want to make sure that the deletion script is really secure to stop people from just deleting everything.
Something like this for the recursive function:
function Remove_Dir($dir)
{
$error = array();
if(is_dir($dir))
{
$files = scandir($dir); //scandir() returns an array of all files/directories in the directory
foreach($files as $file)
{
$fullpath = $dir . "/" . $file;
if($file == '..' || $file == '.')
{
continue; //Skip if ".." or "."
}
elseif(is_dir($fullpath))
{
Remove_Dir($fullpath); //recursively remove nested directories if directory
}
elseif(is_file($fullpath))
{
unlink($fullpath); //Delete file otherwise
}
else
{
$error[] = 'Error on ' . $fullpath . '. Not Directory or File.' //Should be impossible error, because everything in a directory should be a file or directory, or . or .., and thus should be covered.
}
}
$files = scandir($dir); //Check directory again
if(count($files) > 2) //if $files contains more than . and ..
{
Remove_Dir($dir);
}
else
{
rmdir($dir); //Remove directory once all files/directories are removed from within it.
}
if(count($error) != 0)
{return $error;}
else
{return true;}
}
}
Then you just need to pass the file or directory to be deleted through GET or something to the script, probably require urlencode() or something for that, make sure that it's an authorized user with permissions to delete trying to delete the stuff, and unlink() if it's a file, and Remove_Dir() if it's a directory.
You should have to prepend the full path to the directory or file to the directory/file in the script before removing the directory/file.
Some things you'll want for security is firstly making sure that the deletion is taking place in the place it's supposed to, so someone can't do ?dir=/ or something and attempt to delete the entire filesystem from root, which can probably be circumvented by prepending the appropriate path onto the input with something like $dir = '/home/user/public_html/directories/' . $_GET['dir'];, of course then they can potentially delete everything in that path, which means that you need to make sure that the user is authorized to do so.
Need to keep periodic backups of files just in case.
Something like this? Not tested...
<?php
echo '`'.$file_or_dir.' - [Delete button/link]<br/>`';
?>
<?php
if ($_GET['del'] == 1 && isset($_GET['file_or_dir']){
unlink ("path/".$_GET['file_or_dir']);
}
?>
I've worked it out:
I added this delete link on the end of each listed file in the original script:
- < a href="delete.php?file='.$file_or_dir.'&dir=' . $dir . '"> Delete< /a>< br/>';
This link takes me to the download script page, which looked like this:
<?php
ob_start();
$file = $_GET["file"];
$getDir = $_GET["dir"];
$dir = 'docs/' . $getDir . '';
$isFile = ($dir == "") ? 'docs/' . $file . '' : '' . $dir . '/' . $file . '';
if (is_file($isFile)){
if ($dir == "")
unlink('docs/' . $file . '');
else
unlink('' . $dir . '/' . $file . '');
echo '' . $file . ' deleted';
echo ' from ' . $dir . '';
}
else{
rmdir('' . $dir . '/' . $file . '');
echo '' . $dir . '/' . $file . ' deleted';}
header("Location: indexer.php?p=" . $getDir . "");
ob_flush();
?>
It all works brilliantly now, thank you all for your help and suggestions :)