Lost variable i script - javascript

I have some problem with a variable in my script I need to "send" the variable through some different files
The variable comes from the link:
index.php?email=emailname#emailname.com
The script is a file upload script. It's using 3 files in the process, please here:
/public_html/upload/index.php
/public_html/upload/content/index.php
/public_html/upload/content/UploadHandler.php
/public_html/upload/index.php is that runs the script and where the variable is received from the link:
index.php?email=emailname#emailname.com
The file code of /public_html/upload/index.php looks like:
<?php
// change the name below for the folder you want
$dir = "content/".$_GET["email"];
$file_to_write = 'test.txt';
$content_to_write = "The content";
if( is_dir($dir) === false )
{
mkdir($dir);
}
$file = fopen($dir . '/' . $file_to_write,"w");
// a different way to write content into
// fwrite($file,"Hello World.");
fwrite($file, $content_to_write);
// closes the file
fclose($file);
// this will show the created file from the created folder on screen
include $dir . '/' . $file_to_write;
$_SESSION['tmem']= $_GET["email"];
?>
I know that $_GET["email"] works since I can the code: <?=$_GET["email"]?> on the index.php file to see if it receive the variable.
The code:
$_SESSION['tmem']= $_GET["email"];
should forward the variable to the next file:
/public_html/upload/content/index.php
that looks like this:
session_start();
$dir = "content/" . $_GET["email"];
error_reporting(E_ALL | E_STRICT);
require('UploadHandler.php');
$upload_handler = new UploadHandler( array ('upload_url' =>$dir) );
And that code should forward the variable to the codes of the script where the upload patch is. Codes on the file: /public_html/upload/content/UploadHandler.php looks like:
'script_url' => $this->get_full_url().'/'.$this->basename($this->get_server_var('SCRIPT_NAME')),
'upload_dir' => dirname($this->get_server_var('SCRIPT_FILENAME')).'/'.$_GET['email'].'/',
'upload_url' => $this->get_full_url().'/'.$_GET['email'].'/',
'input_stream' => 'php://input',
'user_dirs' => false,
'mkdir_mode' => 0755,
'param_name' => 'files',
Can somebody see where in the process I lose the variable?

I think, in this part of code:
session_start();
$dir = "content/" . $_GET["email"];
you try to get your "email" from URI instead of getting it from session (tmem).

Related

Single page application with file treeview using ajax/php

I am currently working with a web-based document management system, I am creating it as a single page using ajax/php connection. I have my file tree view, that displays the folders and files using this code:
if (isset($_GET['displayFolderAndFiles'])) {
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
}
else {
// this is the directory
// do the list it again!
echo "<li><span class='fa fa-chevron-right caret'></span><button class='btn-der' id='directory" . $id . "' onclick='directoryAction(this);' value='" . $path . $item . "/'>" . $item . "</button>";
echo "<ul class='nested'>";
listIt($path . $item . "/");
//echo("<input type='text' value='".$path.$item."/'>");
echo "</ul></li>";
}
$id++;
}
}
}
listIt("./My Files/");
}
with this code it is hard for me to manipulate the tree view. I use ajax to get the result.
What I want is to reload the tree view when i add, delete file or folder. I also want to load the page once I do some queries in my application without refreshing the page.
I want to have the functionalities like the sample image, the application is FileRun.
Can someone recommend or suggest some ways to address my problem.
Will I use some javascript library or else?
Reference/Sample: Web-based Document Management System (FileRun)
You can use something like this:
public function treeArr($dir){
// First we get the directory
$paths = scandir($dir, SCANDIR_SORT_NONE);
// We remove .. && . from our array
unset($paths[array_search('.', $paths, true)]);
unset($paths[array_search('..', $paths, true)]);
// Add empty array for our tree
$arr = [];
// Check isour paths array empty
if (count($paths) < 1)
return;
// If not empty we get through all paths and add what we want
foreach($paths as $path){
$current_dir = $dir.'/'.$path;
$isDir = is_dir($current_dir);
$expandable = count( scandir( $current_dir ) ) > 2 ? true : false;
// In my case, I needed path name
// Is it expandable (as is it directory and does it contains or is it empty)
// Is it dir or file, if it is not dir it will be false so its file
// And path for that folder or file
$path_data = [
'name' => $path,
'expandable' => $expandable,
'isDir' => $isDir,
'path' => $current_dir,
];
if($expandable) $path_data['data'] = $this->treeArr($dir.'/'.$path);
// If our dir is expandable we go to read files and folders from in it and call self function with that path
array_push($arr, $path_data);
// At the end we add everything into array
}
return $arr;
}
It works for my needs and on client side you can style and add this as you like.
Within foreach you can check for other things, like file extension, date, size and pass everything you need about that. Like if it is html file and you have some live editor, you can check is it html and if it is add like 'isHTML' => true, and then on front:
if(file.isHTML) { //run the code }

Auto Uploading file

I've created a website with html and javascript that gets access to your webcam and when users press take photo button a photo is captured. How would I go about directly uploading this to some cloud folder where it is stored?
Thanks
On the page where the button is,:
Create the button which snaps the photo(I don't kbnow how that is done)
<button>Snap photo!</button>
Create a form (invisible form) with the value of anything....anything can be the value just make sure it isn't empty
Use javascript so that when the button is clicked,the form is submitted to a php page
Mke the target of the form be an iframe that you have created so that when they snap the photo,it leads to the same page,without reloading the page]
Here's the code for what I just said:
Snap
</form>
<script>
function rad(){
document.getElementById("crap").submit();
</div>
Make the file handler with this code:
$errors = []; // Store all foreseen and unforseen errors here
$fileExtensions = ['jpeg','jpg','png']; // Get all the file extensions
$fileName = $_FILES['myfile']['name'];
$fileSize = $_FILES['myfile']['size'];
$fileTmpName = $_FILES['myfile']['tmp_name'];
$fileType = $_FILES['myfile']['type'];
$fileExtension = strtolower(end(explode('.',$fileName)));
$uploadPath = $currentDir . $uploadDirectory . basename($fileName);
if (isset($_POST['submit'])) {
if (! in_array($fileExtension,$fileExtensions)) {
$errors[] = "This file extension is not allowed. Please upload a JPEG or PNG file";
}
if ($fileSize > 1000000000) {
$errors[] = "This file is more than 1GB. Sorry, it has to be less than or equal to 1GB";
}
if (empty($errors)) {
$didUpload = move_uploaded_file($fileTmpName, $uploadPath);
if ($didUpload) {
echo basename($fileName) ;
} else {
echo "An error occurred somewhere. Try again or contact the admin";
}
} else {
foreach ($errors as $error) {
echo $error . "These are the errors" . "\n";
}
}
}
?>
The only thing is that this uploads the image to your server not a 'cloud folder' ...but it is a folder just place the cloud folder in your webserver then specify the name of the cloud folder in the$uploadDirectory = "/uploads/"; ie change 'uploads' to the name of your cloud folder....
Hopes this helps

Php array returns null?

I have php file which reads a file and puts it's contents in specific arrays. This php file is a file on it's own. So I included it on another page. When I want to access one of the arrays on the other site, the output is "array(0) { }". The var_dump on the file below, however returns a full array with all 6 items(as expected).
Here my php file:
<?php
$englishTranslationsList = array();
$germanTranslationsList = array();
$timestampList = array();
$noteList = array();
function extractTranslationsFromFile($file){
$handle = fopen($file, "r");
if ($handle){
while (($line = fgets($handle)) !== false) {
$notelist[] = $line;
$lineContent = substr($line, 3, strlen($line) - 1);
switch(substr($line, 0, 3)):
case "de:": $germanTranslationsList[] = $lineContent; break;
case "en:": $englishTranslationsList[] = $lineContent; break;
case "ts:": $timestampList[] = $lineContent; break;
default: break;
endswitch;
}
fclose($handle);
}else{
echo "<script>alert('ERROR')</script>";
}
echo var_dump($germanTranslationsList);
}
?>
On the site where I included it, I used
<p><?php echo var_dump($germanTranslationsList); ?></p>
Which just shows an empty array as said above...
What have I done wrong? Is there a way to fix it?
You need to bring the global variables into the function's scope using the global keyword:
<?php
$englishTranslationsList = array();
$germanTranslationsList = array();
$timestampList = array();
$noteList = array();
function extractTranslationsFromFile($file) {
global $englishTranslationsList;
global $germanTranslationsList;
global $timestampList;
global $noteList;
// ...
}
Warning
When you include B.php in A.php, you should careful about the file path that you define in B.php.
So, I guess you defined some relative file path.
Example
Directory_stucture
.
├── A.php
└── dir
├── a.txt
└── B.php
A.php
require_once('dir/B.php');
B.php
$handle = fopen("a.txt", "r") or die("Unable to open file!");
echo fread($handle,filesize("a.txt"));
fclose($handle);
a.txt
Hello, world!
Result
Run B.php works fine, print 'Hello, world!'
But if you run A.php ,it print 'Unable to open file!'
Reason
When run B.php, fopen() search 'a.txt' in the dir that B.php live.
But when run A.php, fopen() search 'a.txt' in the dir that A.php live.
Advice
Use absolute file path instead of relative.

PHP random file display

I am using the same script from the link given below to display the files in the directory.
Link list based on directory without file extension and hyphens in php
$directory = 'folder/';
$blacklist = array(
'index'
);
foreach (glob($directory . "*.php") as $file) {
$parts = pathinfo($file);
if (!in_array($parts['filename'], $blacklist)) {
$name = preg_replace("/-/", "", $parts['filename']);
echo "<li>{$name}</li>";
}
}
The above script displays all the files (except index.php) in a folder. But I just want to display five random files. Is this possible?
http://s30.postimg.org/hbb1ce67l/screen.jpg
Based off your edit, I think this is what you're trying to do?
<?php
// Get all files ending in .php in the directory
$rand_files = glob("*.php");
// If the string "index.php" is contained in these results, remove it
// array_search returns the key of the $needle parameter (or false) if not found
if (($location = array_search("index.php", $rand_files)) !== false) {
// If "index.php" was in the results, then delete it from the array using unset()
unset($rand_files[$location]);
}
// Randomly choose 5 of the remaining files:
foreach (array_rand($rand_files, 5) as $rand_index) {
$fname = $rand_files[$rand_index];
echo "<a href='$fname'>$fname</a>\n";
}
?>

Struggling to create a php array to fetch photos from directory that can be used as an array in JavaScript

Basically I am trying to create a photo slideshow that will display specific photos depending on the userid. These photos will be stored in the directory of my web server space. Currently I have a html (not changed into php) file with basic html layout, css style sheet and an external js file that has my code that makes the photos fade in and out. I have added php at the bottom of my html. This is what I have:
$user_id = $_GET['userid'];
print "<h1> Hi, $user_id </h1>";
function returnimages($dirname = "Photos/1") { //will replace 1 with userid once something starts working
$pattern="(\.jpg$)|(\.png$)|(\.jpeg$)|(\.gif$)"; //valid image extensions
$files = array();
$curimage=0;
if($handle = opendir($dirname)) {
while(false !== ($file = readdir($handle))){
if(eregi($pattern, $file)){ //if this file is a valid image
//Output it as a JavaScript array element
echo 'galleryarray['.$curimage.']="'.$file .'";';
$curimage++;
}
}
closedir($handle);
}
return($files);
}
echo 'var galleryarray=new Array();'; //Define array in JavaScript
returnimages() //Output the array elements containing the image file names
?>
and in my javscript, the code I had before for the array of photos:
// List of images for user one
var userphoto = new Array();
userphoto[0] = "Photos/1/1.jpg";
userphoto[1] = "Photos/1/2.jpg";
userphoto[2] = "Photos/1/1.jpg";
userphoto[3] = "Photos/1/1.jpg";
userphoto[4] = "Photos/1/1.jpg";
which I have now commented out and replaced it with this:
var userphoto = <? echo json_encode($galleryarray); ?>;
I am hoping to be able to change the src of photodisplay with the new array:
photodisplay[x].attr("src", userphoto[x]);
Sorry if my problem is not clear at all. I am very confused myself. :( hopefully someone can help!
$user_id = (int) $_GET['userid'];
print "<h1> Hi, $user_id </h1>";
function returnimages($dirname = "Photos/1") {
$dirname = str_replace('..', '.', $dirname); //only remove this if you know why it's here
$pattern = "*{.jpg,.png,.jpeg,.gif}"; //valid image extensions
return glob($dirname . DIRECTORY_SEPARATOR . $pattern, GLOB_BRACE);
}
echo "var galleryarray = ".json_encode(returnimages()).";\n";
?>
Also, you should use <?= json_encode($ret) ?> because the PHP short tag (<?) is deprecated, but <?= is not, and is the equivalent of <?php echo.

Categories

Resources