Adding to a data array externally PHP - php

I'm trying to figure out how to add to a PHP data array externally using PHP.
Say if this array, below. Was in a file called Index.php
$data=array("user1"=>array("url"=>"user1.pdf","password"=>"pass1"),
"user2"=>array("url"=>"user2.php","password"=>"pass2"));
and I wanted to add third user using a different Php file taking inputs from somewhere else to insert into the url, password and user namespace.
Thanks.

$data['user3']=array("url"=>"user3.pdf","password"=>"pass3")

I believe include_once() or require_once() should do the trick.
include_once('index.php');
array_push($data,"user3"=>array("url"=>"user3.pdf","pass"=>"123"));
include_once or require_once functions are similar to executing that file once and continuing further. http://in1.php.net/include_once
Alternatively, php now allows for object-oriented programming, so if you are familiar with it you can take a shot at that

If you need it from different file, then the simplest way is to include the other file, which adds users to $data.
index.php
$data = array(
"user1"=>array("url"=>"user1.pdf","password"=>"pass1"),
"user2"=>array("url"=>"user2.php","password"=>"pass2")
);
other_file.php
include "other_file.php";
$data["user3"] = array("url"=>"user3.php","password"=>"pass3");
// or
array_push($data, array("user3" => array("url"=>"user3.php","password"=>"pass3"));
Are you sure you need that other file?

Related

How to know if a script was included inside another script

I am new to PHP and very likely I am using the incorrect approach because I am not used to think like a PHP programmer.
I have some files that include other files as dependencies, these files need to have global code that will be executed if $_POST contains certain values, something like this
if (isset($_POST["SomeValue"]))
{
/* code goes here */
}
All the files will contain this code section, each one it's own code of course.
The problem is that since the files can be included in another one of these files, then the code section I describe is executed in every included file, even when I post trhough AJAX and explicitly use the URL of the script I want to POST to.
I tried using the $_SERVER array to try and guess which script was used for the post request, and even though it worked because it was the right script, it was the same script for every included file.
Question is:
Is there a way to know if the file was included into another file so I can test for that and skip the code that only execute if $_POST contains the required values?
Note: The files are generated using a python script which itself uses a c library that scans a database for it's tables and constraints, the c library is mine as well as the python script, they work very well and if there is a fix for a single file, obviously it only needs to be performed to the python script.
I tell the reader (potential answerer) about this because I think it makes it clear that I don't need a solution that works over the already existant files, because they can be re-generated.
From the sounds of it you could make some improvements on your code structure to completely avoid this problem. However, with the information given a simple flag variable should do the trick:
if (!isset($postCodeExecuted) && isset($_POST["SomeValue"]))
{
/* code goes here */
$postCodeExecuted = true;
}
This variable will be set in the global namespace and therefore it will be available from everywhere.
I solved the problem by doing this
$caller = str_replace($_SERVER["DOCUMENT_ROOT"], "", __FILE__);
if ($_SERVER["REQUEST_METHOD"] === "POST" and $caller === $_SERVER["PHP_SELF"])
performThisAction();

Open file from a php document, and close it from another?

I am trying to do the following:
Open a file, say "myfile.json" from a php- let's call it "utils.php"; Use it in other php pages; close it from another php.
I have tried to include "utils.php" in the other files and write in the utils file, but it does not seem to work. I suppose this happens because utils.php is never actually executed, only included, but if I should execute it, how can I do it without having to refresh any page, preferably right when the user gets on the main page? This should not be seen by the user, what he sees should remain the main page.
Thanks in advance, I am quite new to php, and am trying to learn.
When you include a file, you are running all code inside it. The functions and classes will not be evaluated but will be defined for future use. If you open your file as this example:
util.php
<?php
$file_hand = fopen('/tmp/file.txt','r');
You will have a handle if the operation is completed. However, the variable $file_hand is global. If you need to use a function to close it, you will need the following code to do it:
other.php
function close_file(){
global $file_hand;
fclose($file_hand)
}
or you can pass the handle as parameter like:
function close_file($file_hand){
fclose($file_hand)
}
Doesn't matter how you will close the file. You have to make sure the variable you are using is the same created in utils.php. If you close like this:
function close_file(){
fclose($file_hand)
}
The variable you've created in until.php file is different of this one.

How to load the result of a php function into a variable

I have a php file on my server that takes in two inputs through the URL and then comes back with a result. When a page is loaded, I'd like to have the result of that calculation already loaded. For example:
$var = load("http://mysite.com/myfile.php?&var1=var1&var2=var2");
I know that load isn't a real function for this, but is there something simple that suits what I'm looking for? thanks
Use file_get_contents
$foo = file_get_contents('http://mysite.com/myfile.php?&var1=var1&var2=var2');
Or, a better solution if the file is located on your server:
include('myfile.php');
and either set the $_GET variables in the included script itself, or prior to including it.
If they are running on the same server, consider calling the script directly?
$_GET["var1"] = "var1";
$_GET["var2"] = "var2";
include "myfile.php";
You could use file_get_contents, but it may be a more practical solution to simply include the file and call the function directly in the file, rather than trying to manually load the file.

passing URL variables to exec() with php

I have a dedicated server that I use to crunch lots of data. The way I have it now, I can open a script with a process ID like example.php?ex_pid=123 and just let it go. It downloads a small portion of data, processes it, then uploads it into a database then starts again.
Ideally, I would like to call example.php?ex_pid=123 directly and not by passing a variable to example.php like exec('./example.php'.' '.EscapeShellArg($variable)); to keep it from acting globally.
I don't care about the output, if it could execute in the background, that would be brilliant. The server is an Ubuntu distribution btw.
Is this even possible? If so, any help and examples would be more then appreciated.
You could do something like:
exec("./example.php '".addslashes(serialize($_GET))."');
And then in example.php do something like this:
count($_GET) == 0 && $_GET = unserialize(stripslashes($_SERVER['argv'][1]))
The main issue with that is that ?ex_pid is GET data which is generally associated with either including the file or accessing it through a browser. If you were including the file or accessing it from a web browser this would be trivial, but running it as CLI, your only option would be to pass it as an argument, unfortunately. You can pass it as ex_pid=123 and just parse that data, but it would still need to be passed as an argument but doing that you could use parse_str() to parse it.
Depending on what the script does, you could call lynx to call the actual page with the get data attached and generate a hash for an apikey required to make it run. Not sure if that is an option, but it is another way to do it how you want.
Hope that helps!
I had a real problem with this and couldn't get it to work running something like example.php?variable=1.
I could however get an individual file to run using the exec command, without the ?variable=1 at the end.
What I decided to do was dynamically change the contents of a template file , depending on the variables I wanted to send. This file is called template.php and contains all the code you would normally run as a $_GET. Instead of using $_GET, set the value of the variable right at the top. This line of code is then searched and replaced with any value you choose.
I then saved this new file and ran that instead.
In the following example I needed to change an SQL query - the template file has the line $sql="ENTER SQL CODE HERE";. I also needed to change the value of a a variable at the top.
The line in template.php is $myvar=999999; The code below changes these line in template.php to the new values.
//Get the base file to modify - template.php
$contents=file_get_contents("template.php");
$sql="SELECT * FROM mytable WHERE foo='".$bar."'";
$contents=str_replace("ENTER SQL CODE HERE",$sql,$contents);
//Another search
$contents=str_replace("999999",$bar,$contents);
$filename="run_standalone_code".$bar.".php";
//If the file doesnt't exist, create it
if(!file_exists($filename)){
file_put_contents($filename, $contents);
}
//Now run this file
$cmd="/usr/local/bin/php ".$filename." >/dev/null &";
exec($cmd);
I had completely forgotten about this question until #Andrew Waugh commented on it (and I got an email reminder).
Anyways, this question stemmed from a misunderstanding as to how the $argv array is communicated to the script when using CLI. You can pretty much use as many arguments as you need. The way I accomplish this now is like:
if (isset($argv)) {
switch ($argv[1]) {
case "a_distinguishing_name_goes_here":
$pid = $argv[2];
sample_function($pid);
break;
case "another_name_goes_here":
do_something_else($argv[2]);
break;
}
}

php include problem with urls with options ?view=task&others file not found

I really have read the other articles that cover this subject. But I seem to be in a slightly different position. I'm not using modrewrite (other articles).
I would like to 'include' a webpage its a 'Joomla php' generated page inside a php script. I'd hoped to make additions on the 'fly' without altering the original script. So I was going to 'precomplete' elements of the page by parasing the page once it was included I hadent wanted to hack the original script. To the point I can't include the file and its not because the path is wrong -
so
include ("/home/public_html/index.php"); this would work
include ("/home/public_html/index.php?option=com_k2&view=item&task=add"); this would not!
I've tried a variety of alternates, in phrasing, I can't use the direct route "http:etc..." since its a current php version so must be a reference to the same server. I tried relative, these work without the ?option=com_k2&view=item&task=add
It may be the simple answer that 'options' or variables can be passed.
Or that the include can't be used to 'wait' for a page to be generated - i.e. it will only return the html.
I'm not the biggest of coders but I've done alot more than this and I thought this was so basic.
this would work include ("/home/public_html/index.php?option=com_k2&view=item&task=add"); this would not!
And it never will: You are mixing a filesystem path with GET parameters, which can be passed only through the web server (utilizing a http:// call... But that, in turn, won't run the PHP code the way you want.)
You could set the variables beforehand:
$option = "com_k2";
$view = "item";
$task = "add";
include the file the normal way:
include ("/home/public_html/index.php");
this is assuming that you have access to the file, and can change the script to expect variables instead of GET parameters.

Categories