when I was using a Mac and MAMP the command worked fine but after moving the source code on Windows 10 and XAMPP now the following script doesn't delete the file but only move a copy of the file inside a folder (exported_files) and renaming the new file.
<?php
session_start();
error_reporting(0);
if (isset($_POST['ok']) && ($_POST['ok'] == 1))
{
//$arrayRicevuto = implode(" ",$arrayRicevuto);
if (!isset($_SESSION['countRows']) && empty($_SESSION['countRows']))
{
$_SESSION['countRows'] = $_POST['countRows'];
}
$data = date("dmY");
$filename = "EstrazioneParziale_del_" . $data;
$estensione = ".csv";
$fileOpen = fopen($filename.$estensione, "a") or die("Impossibile aprire il file");
foreach ($_POST['arrayFiltrato'] as $fields) {
fputcsv($fileOpen, $fields);
}
fclose($fileOpen);
$_SESSION['countRows']--;
if ($_SESSION['countRows'] == 0)
{
$finalData = date("h-i-s");
$directory="exported_files/";
copy($filename.$estensione, $directory.$_SESSION['email']."_".$filename.$finalData.$estensione);
unlink('$filename.$estensione');
unset($_SESSION['countRows']);
echo $directory.$_SESSION['email']."_".$filename.$finalData.$estensione;
}
} else {
echo "Errore! ";
}
?>
Can somebody give me a suggestion?
Many thanks in advance! :)
First problem: Don't use single quotes around variables as it will take the variable as a literal string instead of returning you its value. For example:
<?php
$test = "hello";
echo '$test'; // This will print $test
echo "$test"; // This will print hello
?>
In unlink();, you don't have to use quotes at all when using a variable.
Sometimes the system is unable to find the location of the file you're trying to delete with unlink(). In those cases, you can use realpath(); as it will return the absolute path towards the file you're trying to delete:
unlink(realpath($filename.$estensione));
Related
In short: I am uploading to /var/tmp multiple excel files, then convert them into .csv(2 different converters for .xls and .xlsx). The resulting file, result.csv should be inserted into database. It all worked until we decided to allow to upload multiple files simultaneously(adding multiple attribute to html input tag). Problem: data not inserted into table
<?php
// database connection goes here;
include 'convertt2a.php';
if (isset($_POST["submit"])) {
$updir = "/var/tmp/result.xlsx";
$n= count($_FILES['rawexcel']['name']);
for ($i=0; $i<$n; $i++) {
$upfile = $updir.basename($_FILES['rawexcel']['name'][$i]);
$ext = pathinfo ($_FILES['rawexcel']['name'][$i], PATHINFO_EXTENSION);
if(is_uploaded_file ($_FILES ["rawexcel"]["tmp_name"][$i]))
{
move_uploaded_file ($_FILES["rawexcel"]["tmp_name"][$i], $updir);
if ($ext == 'xlsx' ) { exec("/usr/local/bin/cnvt /var/tmp/result.xlsx /var/tmp/result.csv "); } else
if ($ext == 'xls' ) { exec("/usr/local/bin/xls2csv -x /var/tmp/result.xls* -b WINDOWS-1251 -c /var/tmp/result.csv -a UTF-8"); }
echo "File successfully uploaded and converted to .csv ";
}
else {
echo "error uploading file ".$upfile;}
if (isset($_POST['provider'])) {
//select action to perform on case of different providers
if ($_POST['provider']=='tele2altel'){echo t2a("tele2");}
}
echo "cycle ".$i."ended here; </br>";
}}
else {echo "not isset post method";}
?>
t2a function:
function t2a ($string){
//opening .csv file, inserting into table in SAMPLEBANK TELE2ALTEL
$row =0;
if (($handle = fopen("/var/tmp/result.csv", "r"))!==FALSE){
while (($data = fgetcsv($handle, 1000, ","))!==FALSE) {
$row ++;
//we got data in $data[$i] array
if ($row==4) {$idb=$data[2];}
if ($row >6) {
$da=$data[0]; $imei = $data[1]; $ab=$data[2];$ty = NULL;
$du=$data[6]; $op = $data[3];$dir =$data[5];
$num= strlen($dir);
if ($num>=28) {$ty= $dir; $dir=NULL;}
if ($ab!==''){
$sql= "INSERT INTO tele2altel(Abonent,Opponent, Type, Data, Duration, idBase, IMEI,direction)
values ('$ab','$op','$ty','$da','$du', '$idb','$imei','$dir')";
$res = mysqli_query($conn, $sql);}
}}
fclose($handle);
} else {echo "unable to read file";}
$s = "Successfully inserted into DB";
return $s;
}
My output:
File successfully uploaded and converted to .csv
cycle i ended here;
Successfully inserted into DB, i times(number of files to be uploaded)
I have checked seapartely .csv files, they are being converted correctly. Thus, the error is in t2a function. I will appreciate any help.
Include the another file in it.
<?php include('yourfilename'); ?>
I think the line below is opening the wrong file...
fopen("/var/tmp/result.xlsx", "r")
Should be
fopen("/var/tmp/result.csv", "r")
The thing that was needed for this code to work was clarification of type of return for function:
function t2a ($string):string {}
solved the problem.
I have not much experience with php but i try to devise a simple way to convert old uncompactible php opening tag to 5.5 accepted version.
convert all <? opening tags to <?php
My application had more than 2000 php script and modules. I written this little peice of code to be able to call a recursive function to find and replace, using a regular expression all old tags to correct new ones. Theres seem to be a problem with my extension checking logic ( which seek to match only.php files).
Can someone point me out what i do wrong ? Or Is there a better solution to convert old php files to correct standard for php 5.5?
This is my little replacer.php file:
#!/usr/bin/php
<?php
function getItAll($dir) {
$di = new RecursiveDirectoryIterator($dir);
$i=0;
$fileNb = array();
foreach (new RecursiveIteratorIterator($di) as $filename => $file) {
$fileNb[$i] = $filename;
$i++;
Here i try to catch the file extension of the current browsed directory
$path_parts = pathinfo($fileNb[$i]);
$ext = $path_parts['extension'];
if($ext == '.php'){
$file = file_get_contents($fileNb[$i], true);
$pattern = '(?=[<]+[?][^<"?"phpa-zA-Z0-9+-.,!##$%^&<*`?~();:\/\|>"_\\{\]\\[}])\D\W/g';
$replacement = "<?php";
echo preg_replace($pattern, $replacement, $file);
echo "\n Replaced in: ($fileNb[$i]";
}
}
}
echo "\n";
echo "Replacing in $argv[1] directory \n";
getItAll($argv[1])
?>
Thank you very much in advance !
A way that uses the tokenizer:
#!/usr/bin/php -d short_open_tag=On
<?php
$source = file_get_contents('./tok_testfile.php');
foreach (token_get_all($source) as $token) {
if (is_array($token))
echo ($token[0] === T_OPEN_TAG) ? '<?php' : $token[1];
else
echo $token;
}
?>
I'm trying to extract a zip file witch contains php files.
Taking for example a zip name 'test.zip' and inside, a zip.php file with this code:
<?php
class php{
}
?>
I've tried with two differents snippets to extract the zipe file:
$zip = zip_open ( 'test.zip' );
while($file = zip_read($zip)){
$archivo = (zip_entry_name($file));
zip_entry_open($zip, $file);
$contenido = zip_entry_read($file);
$fopen = fopen($archivo,'w+');
fwrite($fopen, $contenido);
}
<?php
$zip = new ZipArchive;
$res = $zip->open('test.zip');
if ($res === TRUE) {
$zip->extractTo('./');
$zip->close();
echo 'ok!';
} else {
echo 'ko!';
}
?>
But in both cases, the result is always the same:
<?php
class phpclass{
function clase(){
}
}
?>
The file extracted is twice longer, and has twice of empty breaklines than original.
Is there anyway to extract an identical copy of files contained in the zip file?
Please replace this:
$fopen = fopen($archivo,'w+');
... with this:
$fopen = fopen($archivo,'w+b');
The b flag stands for "binary" and disables line feed conversion. Flags are described in the fopen() manual page.
I need to process the contents of a zipped file, but I can't change the permissions on the server where my program will be hosted.
This means that I can't download the zip file to the server, so I need to read the contents of the file into a variable without writing it to the file system.
Can I grab the string contents of such variable and get the unzipped contents into a new variable?
So far, I've looked into using the zip php extension, and the pclzip library, but both need to use actual files.
This is what I want to do in pseudo code:
$contentsOfMyZipFile = ZipFileToString();
$myUnzippedContents = libUnzip($contentsOfMyZipFile);
Any ideas?
Look at this example.
<?php
$open = zip_open($file);
if (is_numeric($open)) {
echo "Zip Open Error #: $open";
} else {
while($zip = zip_read($open)) {
zip_entry_open($zip);
$text = zip_entry_read($zip , zip_entry_filesize($zip));
zip_entry_close($zip);
}
print_r($text);
?>
I use this in my project:
function unzip_file( $data ) {
//save in tmp zip data
$zipname = "/tmp/file_xxx.zip";
$handle = fopen($zipname, "w");
fwrite($handle, $data);
fclose($handle);
//then open and read it.
$open = zip_open($zipname);
if (is_numeric($open)) {
echo "Zip Open Error #: $open";
} else {
while ($zip = zip_read($open)) {
zip_entry_open($zip);
$text = zip_entry_read($zip, zip_entry_filesize($zip));
zip_entry_close($zip);
}
}
/*delete tmp file and return variable with data(in this case plaintext)*/
unlink($zipname);
return $text;
}
I hope it helps you.
I have a folder on my server called /assets/includes/updates/ with .php files inside featuring static html content.
I'd like to randomly grab a file from this folder and echo it into a div. Here is what I have:
<?php
function random_update($dir = $_SERVER['DOCUMENT_ROOT'].'/assets/includes/updates/')
{
$files = glob($dir . '/*.*');
$file = array_rand($files);
return $files[$file];
}
?>
<div class="my-div">
<?php echo random_update(); ?>
</div><!--end my-div-->
I am getting 500 errors? Also, my intention is to only echo 1 file at a time. Will the provided code accomplish that?
Php does not recognize the syntax you used. You have to bypass it like this:
<?php
function random_update($dir = NULL)
{
if ($dir === NULL) {
$dir = $_SERVER['DOCUMENT_ROOT'] . '/assets/includes/updates/';
}
$files = glob($dir . '/*.*');
$file = array_rand($files);
return $files[$file];
}
Also, you might want to enable error dumping in your development environment so you know what went wrong next time.
Aside from another answers spotted issues, for your code to do what you want, you have to replace your following code:
<?php echo random_update(); ?>
for this one:
<?php echo file_get_contents (random_update()); ?>
because your current code will print the filename inside the div, while I think you wanted the actual content of the file to be inserted in the div.
You can't use any expression as "default" function's argument value.