Call a php file in webroot from a controller using cake php - php

I have a php file in webroot.which returns an array of filenames.So I want to call this php file from a controller.can u give me an ideaa how ll I do this...??the content of this php file is given below:
<?php
//if($_SERVER['REMOTE_ADDR']=='10.1.31.77'){debugbreak();}
include ("../vendors/xmlrpc.inc");
?>
<html>
<head>
<title>XML-RPC PHP Demo</title>
</head>
<body>
<h1>XML-RPC PHP Demo</h1>
<?php
$client = new xmlrpc_client('/individual-trade-server-manager/list-binaries-on-trade-server.php',
'125.20.11.245', 80);
//$client->return_type = 'phpvals';
//$client->setDebug ( 2 );
$stringToEcho = 'Hello World';
// Send a message to the server.
$message = new xmlrpcmsg('rpc.FnListAllBinaryFiles',array(php_xmlrpc_encode ( $stringToEcho )));
$result = $client->send($message);
// Process the response.
if (!$result) {
print "<p>Could not connect to HTTP server.</p>";
} elseif ($result->faultCode()) {
print "<p>XML-RPC Fault #" . $result->faultCode() . ": " .
$result->faultString();
} else {
$output=php_xmlrpc_decode($result->value());
$output=explode('*',$output);
//echo "<pre>";
// print_r($output);
}
//echo "<pre>";
// print_r($output);
?>
<table>
<tr><th>Binary Filenames</th></tr>
<?php
foreach($output as $val)
{
//echo "<pre>";
//print_r($val);
?>
<tr><td><?php echo $val; ?></td></tr>
<?php
}
?>
</table>
</body></html>
So i just want call this page from a controller so how ll i call this page,and set this this $output array in the controller.
thanks in advance

I would suggest you create a class with static function in the vendors folder.
The static function will return your array and you will be able to invoke the method from your controller using Myclass::mymethod();

Related

How to include file in PHP with user defined variable

I am trying to include file in string replace but in output i am getting string not the final output.
analytic.php
<?php echo "<title> Hello world </title>"; ?>
head.php
<?php include "analytic.php"; ?>
index.php
string = " <head> </head>";
$headin = file_get_contents('head.php');
$head = str_replace("<head>", "<head>". $headin, $head);
echo $head;
Output i am getting :
<head><?php include "analytic.php"; ?> </head>
Output i need :
<head><title> Hello world </title> </head>
Note : Please do not recommend using analytic.php directly in index.php because head.php have some important code and it has to be merged analytic.php with head.php and then index.php
To get the desired output :
function getEvaluatedContent($include_files) {
$content = file_get_contents($include_files);
ob_start();
eval("?>$content");
$evaluatedContent = ob_get_contents();
ob_end_clean();
return $evaluatedContent;
}
$headin = getEvaluatedContent('head.php');
string = " <head> </head>";
$head = str_replace("<head>", "<head>". $headin, $head);
echo $head;
Output will be output string not file string :
<head><title> Hello world </title> </head>
I think your approach is pretty basic (you try to hardcore modify - programmerly edit - the template script, right?) but anyway:
$file = file('absolut/path/to/file.php');
foreach ($file as $line => $code) {
if (str_contains($code, '<head>')) {
$file[$line] = str_replace('<head>', '<head>' . $headin, $code);
break;
}
}
file_put_contents('absolut/path/to/file.php', $file);

Add array value after echoed

I'm creating a web app where I want to include JavaScript files with all file sources in an array, but I can't do that.
Header.php
<head>
<?php
$import_scripts = array(
'file01.js',
'file02.js'
);
foreach ($import_scripts as $script) {
echo '<script src="' . $script . '"></script>';
}
?>
</head>
<body>
Index.php
<?php
include('header.php');
array_push($import_scripts,'file03.js')
?>
But this only includes file01.js and file02.js, JavaScript files.
Your issue is that you've already echo'ed the scripts in headers.php by the time you push the new value into the array in index.php. So you need to add to extra scripts before you include headers.php. Here's one way to do it (using the null coalescing operator to prevent errors when $extra_scripts is not set):
header.php
<?php
$import_scripts = array_merge(array(
'file01.js',
'file02.js'
), $extra_scripts ?? []);
?>
<!DOCTYPE html>
<html>
<head>
<!-- Scripts Section -->
<?php
foreach ($import_scripts as $script) {
echo '<script src="' . $script . '"></script>' . PHP_EOL;
}
?><title>Demo</title>
</head>
<body>
<p>Blog</p>
index.php
<?php
$extra_scripts = ['file03.js'];
include 'header.php';
?>
Output (demo on 3v4l.org)
<!DOCTYPE html>
<html>
<head>
<!-- Scripts Section -->
<script src="file01.js"></script>
<script src="file02.js"></script>
<script src="file03.js"></script>
<title>Demo</title>
</head>
<body>
<p>Blog</p>
header.php
<?php
function scripts()
{
return [
'file01.js',
'file02.js'
];
}
function render($scripts)
{
foreach ($scripts as $script) {
echo '<script src="' . $script . '"></script>';
}
}
?>
<head>
index.php:
<?php
include 'header.php';
$extra_scripts = scripts();
$extra_scripts[] = 'script3.js';
render($extra_scripts);
?>
</head>
<body>
PHP is processed top down so it will currently be adding file03.js to the array after the foreach has been run.
This means you have two options:
Run the scripts after the header (Not reccomended)
Like Nick suggested, in index.php, specify additional scripts before the header is called
Other answers have answered why (you output content before adding the item to the array).
The best solution is to do all your processing before your output. Also helps with error trapping, error reporting, debugging, access control, redirect control, handling posts... as well as changes like this.
Solution 1: Use a template engine.
This may be more complex than you need, and/or add bloat. I use Twig, have used Smarty (but their site is now filled with Casino ads, so that's a concern), or others built into frameworks. Google "PHP Template engine" for examples.
Solution 2: Create yourself a quick class that does the output. Here's a rough, (untested - you will need to debug it and expand it) example.
class Page
{
private string $title = 'PageTitle';
private array $importScripts = [];
private string $bodyContent = '';
public setTitle(string $title): void
{
$this->title = $title;
}
public addImportScript(string $importScript): void
{
$this->importScripts[] = $importScript;
}
public addContent(string $htmlSafeBodyContent): void
{
$this->bodyContent .= $bodyContent;
}
public out(): void
{
echo '<!DOCTYPE html>
<html>
<head>
<!-- Scripts Section -->
';
foreach ($this->importScripts as $script) {
echo '<script src="' . htmlspecialchars($script) . '"></script>' . PHP_EOL;
}
echo '
<!-- End Scripts Section -->
<title>' . htmlspecialchars($this->title) . '</title>
</head>
<body> . $this->bodyContent . '
</body>
</html>';
exit();
}
}
// Usage
$page = new page();
$page->setTitle('My Page Title'); // Optional
$page->addImportScript('script1');
$page->addImportScript('script2');
$page->addContent('<h1>Welcome</h1>');
// Do your processing here
$page->addContent('<div>Here are the results</div>');
$page->addImportScript('script3');
// Output
$page->out();
I'd create a new php file, say functions.php and add the following code into it.
<?php
// script common for all pages.
$pageScripts = [
'common_1.js',
'common_2.js',
];
function addScripts(array $scripts = []) {
global $pageScripts;
if (!empty ($scripts)) { // if there are new scripts to be added, add it to the array.
$pageScripts = array_merge($pageScripts, $scripts);
}
return;
}
function jsScripts() {
global $pageScripts;
$scriptPath = './scripts/'; // assume all scripts are saved in the `scripts` directory.
foreach ($pageScripts as $script) {
// to make sure correct path is used
if (stripos($script, $scriptPath) !== 0) {
$script = $scriptPath . ltrim($script, '/');
}
echo '<script src="' . $script .'" type="text/javascript">' . PHP_EOL;
}
return;
}
Then change your header.php as
<?php
include_once './functions.php';
// REST of your `header.php`
// insert your script files where you needed.
jsScripts();
// REST of your `header.php`
Now, you can use this in different pages like
E.g. page_1.php
<?php
include_once './functions.php';
addScripts([
'page_1_custom.js',
'page_1_custom_2.js',
]);
// include the header
include_once('./header.php');
page_2.php
<?php
include_once './functions.php';
addScripts([
'./scripts/page_2_custom.js',
'./scripts/page_2_custom_2.js',
]);
// include the header
include_once('./header.php');
You are adding 'file03.js' to $import_scripts after including 'header.php', so echoing scripts it have been done yet. That's why 'file03.js' is not invoked.
So, you need to add 'file03.js' to $import_scripts before echoing scripts, this means before include 'header.php'.
A nice way is to move $import_scripts definition to index.php, and add 'file03.js' before including 'header.php'.
But it seems that you want to invoke certain JS scripts always, and add some more in some pages. In this case, a good idea is to define $import_scripts in a PHP file we can call init.php.
This solution will be as shown:
header.php
<head>
<?php
foreach ($import_scripts as $script) {
echo '<script src="' . $script . '"></script>';
}
?>
</head>
<body>
init.php
<?php
$import_scripts = array(
'file01.js',
'file02.js'
);
index.php
<?php
require 'init.php';
array_push($import_scripts,'file03.js');
include 'header.php';
header.php
<?php
echo "<head>";
$importScripts = ['file01.js','file02.js'];
foreach ($importScripts as $script) {
echo '<script src="' . $script . '"></script>';
}
echo "</head>";
echo "<body>";
index.php
<?php
include 'header.php';
array_push($importScripts, 'file03.js');
print_r($importScripts);
Output
Array ( [0] => file01.js [1] => file02.js [2] => file03.js )

Call a php function in another php file?

I need to call a function from index.php in another file example.php. If I use include it also takes all the html from index.php. I just want the result of the function. Any way to do this?
$rs = odbc_exec($con, $sql);
if (!$rs) {
exit("There is an error in the SQL!");
}
$data[0] = array('D','CPU_Purchased_ghz');
$i = 1;
while($row = odbc_fetch_array($rs)) {
$data[$i] = array(
$row['D'],
$row['CPU_Purchased_ghz']
);
$i++;
}
//odbc_close($con); // Closes the connection
$json = json_encode($data); // Generates the JSON, saves it in a variable
echo $json;
Basically that piece of code in index.php takes info from a file which queries a db and encodes it in json. Instead of echoing I wanted to make a function that echos the json and call it in a new file to only get the json displayed on the page
create a functions.php file. Add the function to that file and include the file in your example.php file
Include the file before you call the function.
See below examples:
index.php
<?php
function myFunction() { //function .
return "FirstProgram"; //returns
}
?>
Now Using include http://php.net/include to include the index.php to make its content available for use in the second file:
example.php
<?php
include('index.php');
echo myFunction(); //returns myFunction();
?>
index.php
function myFunction() {
return "It works!";
}
example.php
include('index.php');
echo myFunction();

AWeber API: subscribers->create() not working as expected in script

The extent to which the AWeber API is not clearly documented cannot be underscored enough (nor do their example scripts work very well). The below script was written so I could subscribe one user to multiple lists selected from a form.
Anyway, this script works when the subscribers->create method is commented out. I'm able to see my separate list ids feed to the list urls and then the list array data is fetched and returned. But once the create method is added back in, it only does one trip through the loop, subscribes the email parameter to the first list it finds and then the script stops:
<!DOCTYPE html>
<html>
<body>
<?php
require_once('aweber_api/aweber_api.php');
require_once('aweber_api/aweber_creds.php');
print "----<br>";
$aweber->adapter->debug = true;
print "----<br>";
//call the api key...
$aweber = new AWeberAPI($consumerKey, $consumerSecret);
$account = $aweber->getAccount($accessKey, $accessSecret);
$feeds = array_values($_GET);
//print form array
print "FORM ARRAY ";
print_r ($feeds);
echo "--<br>";
foreach($feeds[1] as $feed){
echo "--<br>";
try {
print "<br> Feed : $feed";
$listURL = "/accounts/{$account_id}/lists/{$feed}";
$list = $account->loadFromUrl($listURL);
$lists = $account->lists->find(array('name' => $listName));
print_r ($list);
print "<br><br><br>";
# create a subscriber
$params = array(
'email' => $feeds[0],
);
$subscribers = $list->subscribers;
$new_subscriber = $subscribers->create($params);
print "HERE " . $new_subscriber->email;
# success!
print "$new_subscriber->email was added to the $list->name list!";
} catch(AWeberAPIException $exc) {
print "<h3>AWeberAPIException:</h3>";
print " <li> Type: $exc->type <br>";
print " <li> Msg : $exc->message <br>";
print " <li> Docs: $exc->documentation_url <br>";
print "<hr>";
}
}
?>
</body>
</html>
And for the sake of context, here are some form parameters being passed into this script:
somehostnamehere.com/phptest/aweber_api/hltmt_addsubsv1.php?email=user22344%40gmail.com&aweber_list%5B%5D=2531241&aweber_list%5B%5D=2531242&aweber_list%5B%5D=2531243&aweber_list%5B%5D=2531244
you should have such : ...php?email=user22344#gmail.com
so, use urldecode(), for example:
$final = 'somehostnamehere.com/phptest/aweber_api/hltmt_addsubsv1.php?'. urldecode('email=user22344%40gmail.com&aweber_list%5B%5D=2531241&aweber_list%5B%5D=2531242&aweber_list%5B%5D=2531243&aweber_list%5B%5D=2531244');
echo $final;

Merge 2 php scripts

I need some help with some php scripting. I wrote a script that parses an xml and reports the error lines in a txt file.
Code is something like this.
<?php
function print_array($aArray)
{
echo '<pre>';
print_r($aArray);
echo '</pre>';
}
libxml_use_internal_errors(true);
$doc = new DOMDocument('1.0', 'utf-8');
$xml = file_get_contents('file.xml');
$doc->loadXML($xml);
$errors = libxml_get_errors();
print_array($errors);
$lines = file('file.xml');
$output = fopen('errors.txt', 'w');
$distinctErrors = array();
foreach ($errors as $error)
{
if (!array_key_exists($error->line, $distinctErrors))
{
$distinctErrors[$error->line] = $error->message;
fwrite($output, "Error on line #{$error->line} {$lines[$error->line-1]}\n");
}
}
fclose($output);
?>
The print array is only to see the errors, its only optional.
Now my employer found a piece of code on the net
<?php
// test if the form has been submitted
if(isset($_POST['SubmitCheck'])) {
// The form has been submited
// Check the values!
$directory = $_POST['Path'];
if ( ! is_dir($directory)) {
exit('Invalid diretory path');
}
else
{
echo "The dir is: $directory". '<br />';
chdir($directory);
foreach (glob("*.xml") as $filename) {
echo $filename."<br />";
}
}
}
else {
// The form has not been posted
// Show the form
?>
<form id="Form1" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Path: <input type="text" name="Path"><br>
<input type="hidden" name="SubmitCheck" value="sent">
<input type="Submit" name="Form1_Submit" value="Path">
</form>
<?php
}
?>
That basically finds all xmls in a given directory and told me to combine the 2 scripts.
That i give the input directory, and the script should run on all xmls in that directory and give reports in txt files.
And i don't know how to do that, i'm a beginner in PHP took me about 2-3 days to write the simplest script. Can someone help me with this problem?
Thanks
Make a function aout of your code and replace all 'file.xml' to a parameter e.g. $filename.
In the second script where the "echo $filename" is located, call your function.

Categories