i have zip archive and after extract him i need to check if moduleConfig.xml exist inside zip archive. How i can do that.
I try this
$zip = new ZipArchive();
if($zip->open('test.zip') === TRUE )
{
if(file_exists($zip->getFromName('moduleConfig.xml')))
{
echo "Config exists";
// Do somthing
}
}
else {
echo 'Failed code:'. $res;
}
It should be like this:
$zip = new ZipArchive();
if($zip->open('test.zip') === TRUE )
{
if ($zip->locateName('moduleConfig.xml') !== false)
{
echo "Config exists";
}
}
else {
echo 'Failed code:'. $res;
}
try:
if ($zip->locateName('moduleConfig.xml') !== false)
{
echo "Config exists";
}
You can do this by using getFromName
$zip = new ZipArchive();
if($zip->open('test.zip') === TRUE )
{
if($zip->getFromName('moduleConfig.xml') != false)
{
echo "Config exists";
// Do somthing
}
}
else {
echo 'Failed code:'. $res;
}
Related
I am working on a Laravel project, the code saves the image inside a folder created with the title coming from a post. The problem is that while adding post it does not gives a warning saying filename too long but while deleting the post it says filename too long in demo.php/uploads/filename.php.
Is it really because of long folder name or something else?
The following code is called for deleting the folder while deleting a post.
function rmdir_recursive($dir) {
if (is_array($dir) || is_object($dir))
{
foreach(scandir($dir) as $file) {
if ('.' === $file || '..' === $file) continue;
if (is_dir("$dir/$file")) rmdir_recursive("$dir/$file");
else unlink("$dir/$file");
}
}
if (is_string($dir)) {
rmdir($dir);
}
}
Following the function to add post:
function create()
{
if($_SERVER['REQUEST_METHOD']=="POST")
{
$pid = rand(1000,9000);
$title = $_POST['title'];
$descpt = $_POST['description'];
$push = isset($_POST['send_push']) ? $_POST['send_push'] : "";
$feature_image = array();
$fy = $_POST['fy'];
if(empty($title) || empty($descpt) || empty($fy))
{
array_push($this->errors, MEND_FIELD_ERROR);
return;
}
if(!empty($_FILES['feature_image']['name'][0]))
{
$image = $_FILES['feature_image'];
$allowed_ext = array('jpeg','jpg','png','pdf','docx');
$allowed_size = 20000000;
foreach($image['name'] as $pos=>$image_name)
{
$dir = "./cdn/uploads/notice/".$title;
$tmp = $image['tmp_name'][$pos];
$img_size = $image['size'][$pos];
$img_error = $image['error'][$pos];
$img_ext = explode('.', $image_name);
$img_name = $img_ext[0];
$img_ext = strtolower(end($img_ext));
if(in_array($img_ext, $allowed_ext))
{
if($img_size <= $allowed_size)
{
if(!file_exists($dir))
{
mkdir($dir);
}
$image_new_name = $img_name.'$$'.uniqid('', true).'.'.$img_ext;
$upload_destination = $dir.'/'.$image_new_name;
if(move_uploaded_file($tmp, $upload_destination))
{
array_push($feature_image, $image_new_name);
}
else
{
array_push($this->errors, $img_error);
return;
}
}
}
else
{
array_push($this->errors, $img_ext.' is not an allowed file extension.');
return;
}
}
}
$s_feature_image = json_encode($feature_image, JSON_UNESCAPED_UNICODE);
$statement = $this->db->prepare("INSERT INTO `notice` (`pid`,`title`,`descpt`,`date`,`photo`,`fy`)
VALUES (?,?,?,?,?,?)");
if($statement->execute([$pid,$title,$descpt,DAT, $s_feature_image, $fy]))
{
if($push == "checked")
{
$descpt = strip_tags($descpt);
$tek = array("message"=>$descpt,"title"=>$title);
$tokens = $this->getTokens();
$this->push_notification($tokens,$tek);
}
ExitThis::send_to(URL.'notice?id='.$pid);
}
else
{
array_push($this->errors, DATABASE_ERROR);
return;
}
}
}
Note: The title will be Nepali character.
I don't know this was right but deleting folder if that is not string help me. I did following changes in my code:
function rmdir_recursive($dir) {
if (is_array($dir) || is_object($dir))
{
foreach(scandir($dir) as $file) {
if ('.' === $file || '..' === $file) continue;
if (is_dir("$dir/$file")) rmdir_recursive("$dir/$file");
else unlink("$dir/$file");
}
}
if(!is_string($dir)){
rmdir($dir);
}
}
Only the elseif (isset($foo['read'])) on line 37 is working, the if and first elseif work, when I try to call the second elseif, it returns the first elseif statements output. I have even swapped the two elseif statements and it still only returned the first elseif statement output when calling the second elseif statement.
<?php
$nh = "true";
$foo = file_get_contents("php://input");
//$stuff = json_decode($foo, true);
function savetxt($sttext)
{
$filename = 'test.txt';
$somecontent = $sttext;
if (is_writable($filename)) {
if (!$handle = fopen($filename, 'a')) {
echo "Cannot open file ($filename)";
exit;
}
if (fwrite($handle, $somecontent) === FALSE) {
echo "Cannot write to file ($filename)";
exit;
}
echo "Success, wrote ($somecontent) to file ($filename)";
fclose($handle);
}
else {
echo "The file $filename is not writable";
}
}
if (strpos($foo, 'write:') !== false) {
echo 'Attempting to write!';
$stext = substr($foo, 6);
savetxt($stext);
}
elseif ($foo == "read"){
echo file_get_contents( "test.txt" );
}
elseif ($foo == "test){
echo 'Working!';
}
else {
echo 'Didn't get test.';
}
?>
try this(you must replace else if with elseif)
else if ($foo && $foo=='read')
and
else if ($foo && $foo=='test')
and at end
else if (!$foo || $foo=='')
I'm having an issue with a PHP print statement that repeats the output continuously for about 40 or 50 times, then stops. I thought it was supposed to print only one line. I'm still somewhat new to PHP, so I don't understand what I'm doing wrong. The code in question is located at the bottom of the snippet.
Thanks in advance.....
<?php
$query = $_POST['query'];
find_files('.');
function find_files($seed) {
if(! is_dir($seed)) return false;
$files = array();
$dirs = array($seed);
while(NULL !== ($dir = array_pop($dirs))) {
if($dh = opendir($dir)) {
while( false !== ($file = readdir($dh))) {
if($file == '.' || $file == '..') continue;
$path = $dir . '/' . $file;
if(is_dir($path)) {
$dirs[] = $path;
} else {
if(preg_match('/^.*\.(php[\d]?|js|txt)$/i', $path)) {
check_files($path);
}
}
}
closedir($dh);
}
}
}
function check_files($this_file) {
$query = $_POST['query'];
$str_to_find = $query;
if ((isset($str_to_find)) && (empty($str_to_find))) {
print '<p>Your search produced no results</p>';
} else {
if(!($content = file_get_contents($this_file))) {
echo("<p>Could not check $this_file</p>\n");
} else {
if(stristr($content, $str_to_find)) {
echo("<p>$this_file -> contains $str_to_find</p>\n");
}
}
unset($content);
}
}
?>
'Your search produced no results' will be printed out once for every file that your loop sees. You should do the check before you call find_files():
if (!isset($str_to_find) || empty($str_to_find)) {
print '<p>Your search produced no results</p>';
} else {
find_files('.');
}
You can then remove that bit of code from check_files().
You have the print statement inside of the check_files() function, which is being called from inside your while... loop. So, yes, it's going to be executed each time that loop executes and the conditions match.
By !== you maybe meant !=?
I'm writing a code in PHP which deletes a file if it's more than a day old.
but i t does not do so, and append line after it :(
$fileName = 'news/'.$_COOKIE['sign'];
if (isset($_COOKIE['sign']))
{
if ((file_exists($fileName)) && (date("d",filemtime($fileName))==date("d")))
{
$data = file_get_contents($fileName);
if ($data == '')
{
$data = 'Temporary network problem !';
unlink($fileName);
}
echo $data;
}
else
echo 'Fetch and put new news';
$fileName = 'news/'.$_COOKIE['sign'];
if (isset($_COOKIE['sign'])) {
if ((file_exists($fileName)) && (date("d", filemtime($fileName)) == date("d"))) {
$data = file_get_contents($fileName);
if ($data == '') {
$data = 'Temporary network problem !';
unlink($fileName);
}
echo $data;
}
elseif(file_exists($fileName)) { //if not above, then delete it!
unlink($fileName);
}
else {
echo 'Fetch and put new news';
}
}
I am currently trying to create a content uploading system and although there are error being made from the page when I check the appropriate folder for the contents it is empty
$chapterZip = new ZipArchive();
if ($chapterZip->open($_FILES['chapterUpload']['name']))
{
for($i = 0; $i < $chapterZip->numFiles; $i++)
{
$pictureName = $chapterZip->getNameIndex($i);
$fileOpened = $chapterZip->getStream($pictureName);
if(!$fileOpened) exit("failed\n");
while (!feof($fileOpened)) {
$contents = fread($fileOpened, 8192);
// do some stuff
if(copy($contents,"Manga/".$_POST['mangaName']."/".$_POST['chapterName']."/".$pictureName.""))
{
if(chmod("Manga/".$_POST['mangaName']."/".$_POST['chapterName']."/".$pictureName."", 0664))
{
$errmsg0.= "File successfully copied<br/>";
}
else
{
$errmsg0.= "Error: failed to chmod file<br/>";
}
}
else
{
$errmsg0.= "Error: failed to copy file<br/>";
}
}
fclose($fileOpened);
}
}
Any help with this problem would be much appreciated
I looked into it further and found a fairly simple method to extract file with on the PHP online manual
$zip = new ZipArchive;
$res = $zip->open('test.zip');
if ($res === TRUE) {
echo 'ok';
$zip->extractTo('test');
$zip->close();
} else {
echo 'failed, code:' . $res;
}
I don't know if this helps you, but I wrote this script yesterday after some info I found searching for zipping recursively.
function zip($source, $destination)
{
if (file_exists($source) === true)
{
$zip = new ZipArchive();
if ($zip->open($destination, ZIPARCHIVE::CREATE) === true)
{
$source = realpath($source);
if (is_dir($source) === true)
{
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);
foreach ($files as $file)
{
$file = realpath($file);
if (is_dir($file) === true)
{
$zip->addEmptyDir(str_replace($source . '/', '', $file . '/'));
}
else if (is_file($file) === true)
{
$zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
}
}
}
else if (is_file($source) === true)
{
$zip->addFromString(basename($source), file_get_contents($source));
}
}
return $zip->close();
}
}
Found it on some website I can't remember where. Adapted it a slight bit.
Usage: zip('mydir/', 'myZipFile.zip');
Br,
Paul Peelen