Passing session variables into new tab - javascript

I am attempting to pass session variables into a new tab that gets opened in my PHP script so I can loop through the script multiple times in the same sequence. However, the $_SESSION data appears to not be getting passed to the new tab.
Here's the code from the original tab:
if ($dir = opendir($filefolder)) {
$fileCount = 0;
while (($file = readdir($dir)) !== false) {
echo "filename: " . $file . " " . filemtime($filefolder . $file);
$fileInfo = new SplFileInfo($file);
if (filemtime($filefolder . $file) > $lastcheck &&*/ $fileInfo->getExtension() == '7z') {
copy($filefolder . $file, $workingFolder . $file);
$_SESSION{'filename'} = $file;
$_SESSION['filepath'] = $workingFolder . $file;
?>
<script>
workingWindow = window.open("<?php xecho($set->url); ?>/?module=upload&mode=automatic&step=0");
</script>
<?php
$fileCount++;
}
}
And here is the code from the new tab:
$filefolder = $_SESSION['filepath'];
$filename = $_SESSION['filename'];
$filepath = $filefolder . $filename;
The error I'm getting on the new tab is:
Notice: Undefined index: filepath in C:\xampp\htdocs\datascrape\lib\functions\modules\upload\automatic\automaticStep0.php on line 22
Notice: Undefined index: filename in C:\xampp\htdocs\datascrape\lib\functions\modules\upload\automatic\automaticStep0.php on line 23

$_SESSION{'filename'} = $file;
$_SESSION['filepath'] = $workingFolder . $file;
Shouldnt the code to put $file into the SESSION have square brackets?
$_SESSION['filename'] = $file;
$_SESSION['filepath'] = $workingFolder . $file;

Related

Returning array values (image file names to javascript) from php

Hi I have a php file which is reading all the image files in a directory as so:
<?php
$dir = "Images/";
$arrayjs = array();
// Open a directory, and read its contents
if (is_dir($dir)){
if ($dh = opendir($dir)){
while (($file = readdir($dh)) !== false){
if($file != "." && $file != ".."){
$arrayjs[] = $file;
echo "filename:" . $file . "<br>";
}
}
closedir($dh);
}
}
header('Content-type:application/json;charset=utf-8');
echo json_encode($arrayjs);
?>
and I want to get the resulting array in javascript. This code is not working. Any idea why?
<script type = "text/javascript">
$(function() {
$.getJSON('fileNames.php', function(data) {
console.log('yaa');
$(data).each(function(key, value) {
console.log(value);
});
});
});
</script>
getJson performs an ajax call, which will read the contents of the file as its written/displayed, so your echo "filename:" . $file . "<br>"; is becoming part of that meaning your json is becoming invalid
comment out that line and you should be fine
<?php
$dir = "Images/";
$arrayjs = array();
// Open a directory, and read its contents
if (is_dir($dir)){
if ($dh = opendir($dir)){
while (($file = readdir($dh)) !== false){
if($file != "." && $file != ".."){
$arrayjs[] = $file;
//echo "filename:" . $file . "<br>";
}
}
closedir($dh);
}
}
header('Content-type:application/json;charset=utf-8');
echo json_encode($arrayjs);
?>
The method wants nothing but valid json to be echo'd/displayed

How to replace the variable from controller to into a (.php) file

I have an empty test.php file,in that file, I've inserted data below shown.
This code is form controller. This trace data coming from UI using ajax.
Here my $trace array data like this :
array(
[0] => $test1 = "1,2,3,4,5,6,7";
[1] => $test2 = "1,2,3,4,7";
[2] => $test3 = "1,4,6,7,9,0";
)
This is coming from UI
$trace = $this->input->post('trace');
$viewsDir = 'C:/xampp/htdocs/project/application/views/html_v3/';
$fp = fopen($this->viewsDir.'test.php', 'w');
fwrite($fp, "<?php \n\n");
$i = 0;
if($trace){
foreach ($trace as $value) {
fwrite($fp, $trace[$i]."\n");
$i++;
}
}
fwrite($fp, "\n?>");
fclose($fp);
After inserted my data into test.php file then the file look like this:
<?php
$test1 = "1,2,3,4,5";
$test2 = "5,2,0,6,5";
$test3 = "4,8,9,7,1";
?>
Here, if once again I want to insert data into test.php file, my $trace array data like this:
aray(
[0] => $test1 = "9,9,9,9,9";
[1] => $test2 = "1,1,1,1,1";
[2] => $test4 = "1,2,6,7,8";
)
Here my query is how can I replace this ($trace)array variables if matched with test.php. If not matched it should be added to the test.php file.
Here my expected output is:
<?
$test1 = "9,9,9,9,9";
$test2 = "1,1,1,1,1";
$test3 = "4,8,9,7,1";
$test4 = "1,2,6,7,8";
?>
I tried like this,but i don't know how to compare my array($trace) and content of test.php
$file = $this->viewsDir.'test.php';
$contents = file_get_contents($file);
echo $contents; //i will get content of test.php based on this i have to replace or add
Please help me,
Thanks.
I'm not even sure I should help you with that. There is possibly something very wrong with your design if you're passing php code via POST and save it to a source file.
Anyways...
I'd declare helper function that 'parses' entry string line as key $trace1 and value "1,2,3,4,5" and adds it to array $arr
function addToTrace(&$arr, $entry) {
$entry = trim($entry);
if(substr($entry, 0, 1) == "$") {
$elements = explode("=", $entry);
if(count($elements) !== 2) {
return false;
}
$elements = array_map('trim', $elements);
$arr[$elements[0]] = $elements[1];
return true;
}
return false;
}
After that it's only a matter of reading the file first, adding all entries to new array $currTrace
$currTrace = [];
$fp = fopen($this->viewsDir . 'test.php', 'r');
if($fp) {
while (!feof($fp)) {
$line = fgets($fp);
addToTrace($currTrace, $line);
}
fclose($fp);
}
than adding new trace from post (ovewriting matching keys):
if($trace){
foreach ($trace as $value) {
addToTrace($currTrace, $value);
}
}
and saving $currTrace to file:
$fp = fopen($this->viewsDir . 'test.php', 'w');
fwrite($fp, "<?php \n\n");
foreach($currTrace as $key => $value) {
fwrite($fp, $key . " = " . $value . "\n");
}
fclose($fp);

PHP & ZipArchive() - Failed to load PDF document

Good afternon, i have a form that in determined field it open a window or windows to display a specific PDF. The folder where is the path, it can there is just a PDF or a ZIP file with multiples PDF's inner according to the input filled value.
This is blur() event part on the whole my code that calls the windows and pass the values to the "arquivo.php" and "pdf.php", one is to check if is just a PDF or a ZIP, if was a PDF this return on my form informing that is a PDF just and after open just a window to display, this part is ok
JavaScript/HTML code:
///////////PASS THE VALUES TO "arquivo.php"////////////////
$.post("arquivo.php", {nprocesso: document.getElementById("processo").value}, function(data){
$( "#content3" ).html( data ); /*<-- return in this content if is a PDF or a ZIP(when is a zip it returns how many PDF's there are inner ZIP file too)*/
////////////THIS PART IS TO CREATE JUST A WINDOW OR MULTIPLES WINDOWS PASSING THE VALUES RETURNED IN THE "content3" TO "pdf.php" TO DISPLAY IT/THEM//////////////////
setTimeout(function(){
if(document.getElementById("content3").innerText == "PDF"){
window.open("pdf.php/"+document.getElementById("processo").value, '_blank', "toolbar=yes,scrollbars=yes,resizable=yes,width=800,height=800");
}else{
var QuantPDF = Number(document.getElementById("content3").innerText.slice(Number(document.getElementById("content3").innerText.lastIndexOf(','))+1, document.getElementById("content3").innerText.length));//Number(document.getElementById("content3").innerText.replace(/[^0-9]/g, ""));
var NomesPDFS = []; NomesPDFS = document.getElementById("content3").innerText.slice(3, document.getElementById("content3").innerText.length-2).split(',');
if(QuantPDF > 1){
for(var i = 0; i < QuantPDF; i++){
window.open("pdf.php/"+document.getElementById("processo").value+"/"+NomesPDFS[i], '_blank', "toolbar=yes,scrollbars=yes,resizable=yes,width=800,height=800");
}
}else{
window.open("pdf.php/"+document.getElementById("processo").value, '_blank', "toolbar=yes,scrollbars=yes,resizable=yes,width=800,height=800");
}
}
document.getElementById('closeBtn').click();
}, 1000);
}
This is the "arquivo.php", where check if is just a PDF or a ZIP file, and extract if was a zip
Arquivo.php code:
<?php
session_start();
//////////THIS PART CHECK THAT FILE IS A PDF AND RETURN TO MY JAVASCRIPT CODE/////////
if(file_exists('//dsbimrj16/Vinculacao_Cadastro_Gestor/'.$_POST['nprocesso'].'.pdf')){
echo 'PDF';
$_SESSION['file'] = "PDF";
}else{
//////////THIS PART CHECK THAT FILE IS A ZIP AND RETURN TO MY JAVASCRIPT CODE/////////
echo 'ZIP';
$_SESSION['file'] = "ZIP";
$zip = new ZipArchive;
$path = '//dsbimrj16/Vinculacao_Cadastro_Gestor/'.$_POST['nprocesso'].'.zip';
///////////////////////////////////////////////////////////////////
if($zip->open($path) === true){
//////////THIS PART IT OPENS THE ZIP AND EXTRACT/////////
if(!file_exists('//dsbimrj16/Vinculacao_Cadastro_Gestor/'.$_POST['nprocesso'])){
mkdir('//dsbimrj16/Vinculacao_Cadastro_Gestor/'.$_POST['nprocesso'], 0777, true);
}
for($i = 0; $i < $zip->numFiles; $i++){
$zip->extractTo('//dsbimrj16/Vinculacao_Cadastro_Gestor/'.$_POST['nprocesso'], array($zip->getNameIndex($i)));
$path = '//dsbimrj16/Vinculacao_Cadastro_Gestor/'.$_POST['nprocesso'];
$files = scandir($path); array_shift($files); array_shift($files);
$file = array(); $filename = array();
///////NOW I CATCH THE PDF's NAMES AND THE QUANTITY AND RETURN TO JAVASCRIPT CODE///////
$file[$i] = '//dsbimrj16/Vinculacao_Cadastro_Gestor/'.$_POST['nprocesso'].'/'.$files[$i];
$filename[$i] = '//dsbimrj16/Vinculacao_Cadastro_Gestor/'.$_POST['nprocesso'].'/'.$files[$i];
$nomes_pdfs = array();
$nomes_pdfs[$i] = substr(substr($filename[$i], strpos($filename[$i], $_POST['nprocesso'])+26, strlen($filename[$i])), 0, strpos(substr($filename[$i], strpos($filename[$i], $_POST['nprocesso'])+26, strlen($filename[$i])), '.pdf')).',';
echo $nomes_pdfs[$i];
}
$zip->close();
$path = '//dsbimrj16/Vinculacao_Cadastro_Gestor/'.$_POST['nprocesso'];
$files = scandir($path);
array_shift($files); array_shift($files); $_SESSION['quantidade_pdf'] = count($files);
echo $_SESSION['quantidade_pdf'];
}
}
?>
My problem actually is partially on "pdf.php" where the window load with the values returned of the "content3". When is a single PDF, the window display normally, but when is a ZIP file with multiples PDF's, the first PDF display correctcly, but starting in the second and on, it doesn't display. show a this error: "Failed to load PDF document".
pdf.php code:
<?php
header ('Content-type: text/html; charset=utf-8');
if(file_exists('//dsbimrj16/Vinculacao_Cadastro_Gestor/'.substr($_SERVER['REQUEST_URI'], strrpos($_SERVER['REQUEST_URI'], '/')+1).'.pdf') && is_file('//dsbimrj16/Vinculacao_Cadastro_Gestor/'.substr($_SERVER['REQUEST_URI'], strrpos($_SERVER['REQUEST_URI'], '/')+1).'.pdf')){
$processo = substr($_SERVER['REQUEST_URI'], strrpos($_SERVER['REQUEST_URI'], '/')+1);
$file = '//dsbimrj16/Vinculacao_Cadastro_Gestor/'.$processo.'.pdf';
$filename = '//dsbimrj16/Vinculacao_Cadastro_Gestor/'.$processo.'.pdf';
header('Content-type: application/pdf');
header('Content-Disposition: inline; filename="' . $filename . '"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($file));
header('Accept-Ranges: bytes');
#readfile($file);
}else{
/////////////////////HERE IS THE PART WHEN IS A ZIP////////////////////////
///////*This part it's only to check if the folder extract exists*/////////
function folder_exist($folder){ $path = realpath($folder); return ($path !== false AND is_dir($path)) ? $path : false; }
chdir('//dsbimrj16/Vinculacao_Cadastro_Gestor/');
$folder = '/'.substr(substr($_SERVER['REQUEST_URI'], strpos($_SERVER['REQUEST_URI'], 'p/')+2), 0, strpos(substr($_SERVER['REQUEST_URI'], strpos($_SERVER['REQUEST_URI'], 'p/')+2), '/')).'/';
if(FALSE !== ($path = folder_exist($folder))){
/////*Here start the part where the code catch the PDF's and display*/////
$pasta = substr(substr($_SERVER['REQUEST_URI'], strpos($_SERVER['REQUEST_URI'], 'p/')+2), 0, strpos(substr($_SERVER['REQUEST_URI'], strpos($_SERVER['REQUEST_URI'], 'p/')+2), '/'));
$processo = substr($_SERVER['REQUEST_URI'], strrpos($_SERVER['REQUEST_URI'], '/')+1);
$file = '//dsbimrj16/Vinculacao_Cadastro_Gestor/'.$pasta.'/'.$processo.'.pdf';
$filename = '//dsbimrj16/Vinculacao_Cadastro_Gestor/'.$pasta.'/'.$processo.'.pdf';
header('Content-type: application/pdf');
header('Content-Disposition: inline; filename="' . $filename . '"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($file));
header('Accept-Ranges: bytes');
#readfile($file);
}else{
die('<h2 style="background-color:#FA5858"><center>Não foi encontrado a inicial do processo. Verifique se o mesmo encontra-se na pasta.</center></h2>');
}
}
?>
What i'm doing wrong ? I've already checked the folder, the file is in and the name and the path is the same that the code are putting to display

image retrieval from directory and session variable issues - php

I have a problem when retrieving the images from a directory on my server, so what the main sequence is: in a page (multiupload.php) I added the input, allowed the image to be previewed and when the user submitted, a new directory with their session id would be created, the images would then be stored in the unique directory and the page would then be directed to (drag.php). The newly loaded page has a canvas with different divs to controls filters that are attached to that canvas. My problem lies with retrieving the image with the specified s_id as a directory name from one page to the other.
Q: Am i retrieving session variables properly? or using them appropriately?
This is the necassary snippets from multiupload.php's upload script.
<?php
$dir_id = session_id(md5(uniqid()));
session_start($dir_id);
$path = "uploads/";
$dir = $path.$dir_id;
$path = $path.$dir_id."/";
if (file_exists($dir)) {
system('/bin/rm -rf ' . escapeshellarg($dir));
} else {
mkdir($path);
chmod($path, 0722);
}
$_SESSION["id"] = $dir_id;
$_SESSION["directory"] = "/" . $dir;
$_SESSION["path_name"] = $path;
?>
I define the directory, whole path and the id for the directory. I would like to retrieve the id in the next page, but it's not doing it correctly.
and this is the retrieval code from drag.php
$realPath = 'uploads/'. echo $_SESSION['id'];
$handle = opendir(dirname(realpath(__FILE__)).$realPath;
while($file = readdir($handle)){
if($file !== '.' && $file !== '..'){
echo '<img src="uploads/'.$file.'" border="0" />';
}
}
My end result is that I would like all images to be drawn on the page. For now I would like them to be drawn anywhere aslong as they're visible.
If my question isn't clear, feel free to edit or comment where I should change. If you need more code or information, please let me know.
Please modify your code to this code:
<?php
$dir=$_SESSION['id'];
$realPath = '/uploads/'.$dir;
$handle = opendir(dirname(realpath(__FILE__)).$realPath);
while($file = readdir($handle)){
if($file !== '.' && $file !== '..'){
echo '<img src="'.$realPath.'/'.$file.'" border="0" width="200" />';
}
}
?>
I have use this code an I get the o/p like this:
<?php
$dir_id = session_id(md5(uniqid()));
session_start();
$path = "uploads/";
$dir = $path.$dir_id;
$path = $path.$dir_id."/";
if (file_exists($dir)) {
system('/bin/rm -rf ' . escapeshellarg($dir));
} else {
mkdir($path);
chmod($path, 0722);
}
$_SESSION["id"] = $dir_id;
$_SESSION["directory"] = "/" . $dir;
$_SESSION["path_name"] = $path;
?>
In any file.php, which u need get session:
<?php
session_start();
$realPath = 'uploads/'.$_SESSION['id'];
$handle = opendir(dirname(realpath(__FILE__)).$realPath;
while($file = readdir($handle)){
if($file !== '.' && $file !== '..'){
echo '<img src="uploads/'.$file.'" border="0" />';
}
}
?>
I advice to you read that: http://www.w3schools.com/php/php_sessions.asp when i was started with php 6 years ago - it was rly helpful
session_start does not take any argument. It's just to put a cookie and to read the session variables. (exposed in $_SESSION). You have to use session_start() on every pages to be able to read the $_SESSION variables.
this will give only image file from directory using session variable.
<?php
$dir=$_SESSION['id'];
$realPath = '/uploads/'.$dir;
$handle = opendir(dirname(realpath(__FILE__)).$realPath);
while($file = readdir($handle)){
if($file !== '.' && $file !== '..'){
if(fnmatch('*.jpg', $file) || fnmatch('*.png', $file) || fnmatch('*.jpeg', $file)){
echo '<img src="'.$realPath.'/'.$file.'"/>';
}
}
}
?>

how to know all file names of the images from whole website?

I want to get all images of my whole website in an array, and all of my images are in a folder called images and within that folder many subfolders are there, So now how can I get all the images' path in an array?
Is it possible just with jquery, javascript? If not, php is ok.
I found this recursive function that can give you the tree of a given directory, you can use the $exclude param to filter only image files
<?php
/**
* Get an array that represents directory tree
* #param string $directory Directory path
* #param bool $recursive Include sub directories
* #param bool $listDirs Include directories on listing
* #param bool $listFiles Include files on listing
* #param regex $exclude Exclude paths that matches this regex
*/
function directoryToArray($directory, $recursive = true, $listDirs = false, $listFiles = true, $exclude = '') {
$arrayItems = array();
$skipByExclude = false;
$handle = opendir($directory);
if ($handle) {
while (false !== ($file = readdir($handle))) {
preg_match("/(^(([\.]){1,2})$|(\.(svn|git|md))|(Thumbs\.db|\.DS_STORE))$/iu", $file, $skip);
if($exclude){
preg_match($exclude, $file, $skipByExclude);
}
if (!$skip && !$skipByExclude) {
if (is_dir($directory. DIRECTORY_SEPARATOR . $file)) {
if($recursive) {
$arrayItems = array_merge($arrayItems, directoryToArray($directory. DIRECTORY_SEPARATOR . $file, $recursive, $listDirs, $listFiles, $exclude));
}
if($listDirs){
$file = $directory . DIRECTORY_SEPARATOR . $file;
$arrayItems[] = $file;
}
} else {
if($listFiles){
$file = $directory . DIRECTORY_SEPARATOR . $file;
$arrayItems[] = $file;
}
}
}
}
closedir($handle);
}
return $arrayItems;
}
?>
source
And about the jQuery way, you can't access to the directory directly, you have to provide the list with an ajax call to your backend and give a json object so you render it with jQuery
try this PHP Script:
$dir = "images/*/";
//get all files with .jpg
$images = glob("" . $dir . "*.jpg");
$imgs = array();
// store images in $imgs - after that optional display
foreach($images as $image) {
$imgs[] = $image;
}
//display
foreach ($imgs as $img) {
echo '<img src="'.$img.'" />';
}
to store in a JS array:
$JSarray = json_encode($imgs);
echo "var JSarray = ". $JSarray . ";\n";
Use RecursiveDirectoryIterator , RecursiveIteratorIterator and RegexIterator to achieve this .
$imagesExtensions = array('jpg','png','gif'); //<=-- Add your extensions
$extensions = implode('|',$imagesExtensions);
$directory = new RecursiveDirectoryIterator('images');
$iterator = new RecursiveIteratorIterator($directory);//RecursiveDirectoryIterator::SKIP_DOTS);
$regex = new RegexIterator($iterator, "/^.+\.$extensions$/i", RecursiveRegexIterator::GET_MATCH);
foreach ($regex as $filename=>$object) {
echo $filename . '<br>';
$images[] = $filename; //<----- All images are stored in this array sequentially
}
OUTPUT :
images\google\client\ext\resources\themes\images\access\boundlist\trigger-arrow.png
images\google\client\ext\resources\themes\images\access\box\corners-blue.gif
images\google\client\ext\resources\themes\images\access\box\corners.gif
//....... Goes on..

Categories

Resources