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.
Related
I am trying to create a gallery that uses PHP to go through asset folders and serve as sort of an album system. The code below retrieves files as albums :
<?php
include_once("../PhpScript/RetAlbInfo.php");
$files = array_slice(scandir('../Assets/Gallery/'), 2);
for($albflcnt = 0;$albflcnt<count($files);$albflcnt++){
echo "<div style='...'><div class='albm' style='...' onmousedown='gotoalbum();albnm();'></div><p style='...'>".$files[$albflcnt]."</p></div>";
}
?>
The problem is that I cannot find a way to get folder names from each <p> tag and append it to the url so it would show it's sub folder.
you can use glob() with GLOB_ONLYDIR option
<?php
foreach (glob("*.txt") as $filename) {
echo "$filename size " . filesize($filename) . "\n";
}
?>
or
<?php
$dirs = array_filter(glob('*'), 'is_dir');
print_r( $dirs);
?>
You might be wanting a RecursiveDirectoryIterator? Not 100% sure. Here is a basic example. There are portions that may or may not be relevant. This basically builds a bread crumb system of sorts, but there may be parts you are looking for:
<?php
# Create some defines in the root of the website if not already done
# This is your url
define('SITE_URL','http://www.example.com');
# This is the root path
define('BASE_DIR',__DIR__);
# This is where everyour files are stored
define('MEDIA_DIR',__DIR__.'/media/');
/*
** #description This is just a link builder, there may be some functionality you could use here
** #param $path [string] Relative path
** #param $pathStr [string] Absolute path
** #param $append [string | empty] This is just append to whatever page processes this script
*/
function createLinks($path,$pathStr,$append = '/index.php')
{
# Used for the link
$url = SITE_URL.$append;
# Explodes relative path
$arr = array_filter(explode('/',$path));
# Loop through to create break crumb
foreach($arr as $dir) {
$pathStr .= '/'.$dir;
$new[] = '/'.$dir.'';
}
# Return final bread crumb
return implode('',$new);
}
# Decodes the path name, you should probably do a more secure encryption / decription method
function getPathFromRequest($path)
{
return base64_decode(urldecode($path));
}
# Set base absolute path
$core = MEDIA_DIR;
# Process the absolute path
if(!empty($_GET['goto'])) {
$base = str_replace('//','/',getPathFromRequest($_GET['goto']));
if(is_dir($base))
$base = $base.'/';
}
else
$base = $core;
# If is a directory, recurse and show the bread crumbs
if(is_dir($base)){
$skip = RecursiveDirectoryIterator::SKIP_DOTS;
$sFirst = RecursiveIteratorIterator::SELF_FIRST;
$dir = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($base,$skip),$sFirst);
# Loop through the file paths
foreach($dir as $file) {
$fname = $file->__toString();
if(is_file($fname)) {
$abs = str_replace($base,'',$fname);
$useType = (!empty($_GET['goto']))? $base : $core;
echo createLinks($abs,$useType).'<br />';
}
}
}
else {
# Redirect to file if is a file
if(is_file($base)) {
header('Location: '.SITE_URL.'/'.str_replace(BASE_DIR,'',$base));
exit;
}
}
Base view in the browser gives you something like (this is just from a directory I have):
/css/form.css
/css/styles.css
/images/bkg/bkg_white.png
/images/bkg/row_grad01.png
Then html source would look like:
/css/form.css<br />
/css/styles.css<br />
/images/bkg/bkg_white.png<br />
/images/bkg/row_grad01.png<br />
If you were to click the bkg in the 3rd or 4th link, it would display:
/bkg_white.png
/row_grad01.png
Clicking one of those would open the file in the browser. Anyway, you might be interested in some of this, all of it, or none of it! It's hard to guess with out seeing what you currently have vs what you are trying to achieve.
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).
I am new to php, and want a script that can recognise text between certain tags in an external file.
I managed to find an answer here, that recognises the text in tags in a set string, but I am unsure of how to get the file to recognise the tags in an external text file.
PHP:
<?php
function innerh($string, $start, $end){
$string = " ".$string;
$ini = strpos($string,$start);
if ($ini == 0) return "";
$ini += strlen($start);
$len = strpos($string,$end,$ini) - $ini;
return substr($string,$ini,$len);
}
$fullstring = "The <tag>Output</tag>"; // this is the string
$parsed = innerh($fullstring, "<tag>", "</tag>");
echo $parsed;
?>
External File:
<tag>This text</tag> <!-- This is the target -->
Similar to what you are already doing. Currently you are making a string with that tag and when you want to read it from a file you can simply do
$fullstring = file_get_contents('your-file.html');
No other changes are required. You might need to provide full path of that file but that's about it.
That function reads a file and returns its contents in a string which you can save in your variable just like you built the variable manually.
Your code must be somthing like this:
<?php
function innerh($string, $start, $end){
$string = " ".$string;
$ini = strpos($string,$start);
if ($ini == 0) return "";
$ini += strlen($start);
$len = strpos($string,$end,$ini) - $ini;
return substr($string,$ini,$len);
}
// Open a file with READ-ONLY flag ("r") and start of begining for read.
// See: http://php.net/manual/en/function.fopen.php
$fp = fopen("/path/to/file", "r");
// Check that file is opened and ready for read
if ($fp) {
// Until we have content on file, we resume reading
while (!feof($fp)) {
// Read from file, line by line.
// See: http://php.net/manual/en/function.fgets.php
$line = fgets($fp);
// Process line by line and print result
$parsed = innerh($line, "<tag>", "</tag>");
echo $parsed;
/* If your input file is a file without a new line or something like it,
just add a `$line = '';` before while line and change read line with
`$line .= fgets($fp);`, also remove process line and print line. After
that your file is on $line variable ;). */
}
}
?>
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";
}
?>
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.