update value in config.php with another php script - php

I include a config.php file in all of my pages.
I also have a cron job which updates a total count of a table, into another table each hour.
I want to also write that value into the config and save if possible.
my config is in the structure:
return array(
'stats' => array(
'total_count' => 130000,
'another_stat' => 100000,
),
'other_config_value' => 'value',
)
and I include it in my pages, at the top like:
$config = include('../php/config.php');
$total_count = $config['stats']['total_count']
just so I don't have to query the database on each page, every time it loads as I want to show that total on all pages.

You can keep your config in JSON format and use functions json_decode() to read it. If yout want update it you can use json_decode() to make an array from JSON string, update this value in array and use json_encode() to make JSON string from array. After that you can save it to file with file_put_contents().
$config = json_decode(file_get_contents('config.json'));
$config['value'] = $newValue;
file_put_contents('config.json', json_encode($config));

Related

Get and store a URL segment into a cookie with CodeIgniter

For a kind of conversion tracking, I want to store a part of the URL into a cookie and use this into my model functions.
So I think about https//:www.example.com?track=this
How I can get the part of the track (=this) with CodeIgniter and save it into a cookie?
To create a cookie I think that's the way,
$this->load->helper('cookie');
$cookie = array(
'name' => 'track',
'value' => '???',
'expire' => '300',
'secure' => TRUE
);
set_cookie($cookie);
How I can get the part of URL and set cookie etc with CodeIgniter on every possible page? So I mean, no matter over which page the user call the website, I need to make sure that this tracking info is stored in every case.
Go get the cookie later, I think I can use $cookie= get_cookie('track');
Thanks for showing me the way to do it with CodeIgniter.
Mainly you need to use parse_url to extract url to query string and then parse_str to extract query string.
First, you need to get query string from you URL
$query = parse_url('https//:www.example.com?track=this&h=1');
echo'<pre>';print_r($query);
Output:
Array
(
[path] => https//:www.example.com
[query] => track=this&h=1
)
Then you need to extract query
parse_str($query['query'],$array);
echo'<pre>';print_r($array);die;
Output:
Array
(
[track] => this
[h] => 1
)
From here you can store your above array information in cookies
to get the wanted part of the query-string there is a built-in function of Codeigniter
$myval=$this->input->get('track', TRUE);
I've add this with a part to store and get the cookie in the header of my mainlayout-theme.
So it will works :-)

Can't see created folder in teamdrive root

I'm creating a folder inside teamdrive root with google-drive-sdk and it works but with some delay after API call finished. If I try to query root folder with the name of newly created folder right after creation - I get an empty array. But if I do the same after couple of seconds I see the new item.
$file = $service->files->create(
$folder,
[
"supportsTeamDrives" => true
]
);
printf("Folder ID: %s\n", $file->id);
I see the folder ID
$params = [
"q" => "'{$teamDriveId}' in parents and trashed = false and mimeType = 'application/vnd.google-apps.folder' and name ='$path'",
"pageSize" => 1,
"corpora" => "teamDrive",
"includeTeamDriveItems" => true,
"supportsTeamDrives" => true,
"teamDriveId" => $teamDriveId
];
$files = $service->files->listFiles($params);
$list = $files->getFiles();
var_dump($list);
Empty array
But if I do 'sleep(3)' before query - an array is not empty and contains new folder.
I didn't find any information about this delay in documentation. What is it and is there a way to get the result without delays?
While I can't speak to the internals of the Drive API, I can imagine that any delay between creating the folder, and the folder being queryable from Files.list(), is due to internal indexing and data propagation for Team Drives, since they are different than the regular Drive files.
Note that such an use case -- I create this file then immediately need to find it -- is avoidable - the act of creating the file has a return value that includes the direct handle to the file created.
Response
If successful, this method returns a Files resource in the response body.

Any way to offset results with AWS SDK for PHP?

I'm currently working on scanning a folder in my S3 bucket and removing files that are no longer in my database. The problem is that I have millions of files, so no way of scanning this in one go.
// get files
$files = $s3->getIterator('ListObjects', array(
"Bucket" => $S3Bucket,
"Prefix" => 'collections/items/',
"Delimiter" => '/'
), array(
'return_prefixes' => true,
'names_only' => true,
'limit' => 10
));
The documentation included something about limiting results, but I can't find anything about offsetting. I want to be able to start from 0, scan 500 items, remove them, stop, save the last scanned index and then run the script again, start from the saved index (501), scan 500 items, and so on.
Does the SDK offer some sort of offset option? Is it called something else? Or can you recommend a different method of scanning such a large folder?
Remember the last key you processed and use it as the Marker parameter.
$files = $s3->getIterator('ListObjects', array(
"Bucket" => "mybucket",
"Marker" => "last/key"
));
BTW, dont set Limit, its slowing down. Limit 10 will cause a request to the API every 10 objects, the API can return up to 1000 objects per request.

Pootle exports incorrect PHP array files

I've been using Pootle recently for translating a small PHP project. Our i18n files are as php arrays, example:
return array(
'word.in' => 'en',
'word.yes' => 'Sí',
'word.no' => 'No',
'word.with' => 'con',
);
So I created a Project in Pootle's admin panel and set the source files are PHP arrays. I can upload and translate files perfectly fine afterwards.
The problem comes when I try to export, the file rendered has the following syntax:
return array->'word.in'='for';
return array->'word.yes'='Yes';
return array->'word.no'='No';
return array->'word.with'='with';
Which afaik isn't even valid PHP syntax.
I've read through the Pootle and Translation Toolkit's documentations and I've found that it passes through some sort of 'template' to generate that crappy output.
Any ideas how I can fix this and be able to export my PHP array with exactly the same syntax I uploaded it? Any help greatly appreciated!
Any ideas how I can fix this and be able to export my PHP array with exactly the same syntax I uploaded it?
Before return statement, if You need to actually write that array to file and read it later again, I would do something like this ..
$arrayExport = var_export(
array(
'word.in' => 'en',
'word.yes' => 'Sí',
'word.no' => 'No',
'word.with' => 'con',
), true);
Than write down $arrayExport .. for example:
file_put_contents($filePathName,
'<?php $exportedArrayName = '.$arrayExport.";\n ?>",
LOCK_EX);
...than goes the rest of weird Pootle and translation ...
But if You need to read it again after a while without storing it, use $_SESSIONS and serialization.
$_SESSION['exportedArray'] = serialize(array(
'word.in' => 'en',
'word.yes' => 'Sí',
'word.no' => 'No',
'word.with' => 'con',
));
To read from session ..
$exportedArray = unserialize($_SESSION['exportedArray']);

PHP - open, read and delete data from a file

I have a file called functions.php.
It contains a lot of data in over 3000 lines.
Somewhere in the middle of this file there is code:
/*****************************************
My Custom Code
*****************************************/
if ( function_exists('my_code') )
my_code(array(
'name' => 'First instance',
'description' => 'Hello, hello.',
));
if ( function_exists('my_code') )
my_code(array(
'name' => 'Second instance',
'description' => 'Haha :)',
));
I'm listing all my_code arrays and I'm getting:
First Instance
Second Instance
Now, what I want to achieve, is, when user clicks X next to "First instance" PHP opens functions.php file in the background, finds the exact function and deletes it without touching anything else.
So after deleting "First Instance" functions.php file should look like this:
/*****************************************
My Custom Code
*****************************************/
if ( function_exists('my_code') )
my_code(array(
'name' => 'Second instance',
'description' => 'Haha :)',
));
Any idea how to achieve this? I know how to open files, write, delete, but I'm not sure how to wipe out not only a single line but a few lines around? :)
If your code is always in the format you described you could read each 5 lines from your file and if it's the instance you want to keep, output them to a string. Then write the string back to the original file.
But again yes, code modifying code IS PAIN. Storing your instances in a data structure such as databases or a formatted file is much better.
I think the best way would be to open the file and loop through the lines. You'll need to match each line of your function, or you would need match the first line and track the number of open and close brackets { } to know when you've reached the end of it.
If a line doesn't match you write that out to a new file. If it does match you ignore it. Then finally you make an system call to do a syntax check on the new file (in case something went wrong with your line matching):
system( "php -l newfile.php", &$retval );
Then check the return value $retval to make sure it was ok (it will be exactly equal to 0). If it is okay then you overwrite functions.php with your new file.
if( $retval === 0 ) {
// the syntax is good
rename( "newfile.php", "functions.php");
}
You would need to set the appropriate paths for this to work.
Now all of that said, this is not a very good idea and I would advise you not to implement it. A better method would be to break your functions out into separate files. Then use an INI config file or a database to keep track of what you should load. Either of those have the ability to be edited. Even a text data file would be better than mucking with the actual code.
Once you know what you're supposed to load then at the beginning require or include the appropriate file.
Here's a simple example of doing it with a database:
$res = mysql_query("SELECT file_name FROM load_functions");
if( mysql_error() ) {
// do something because the query failed
}
else {
while( list($file_name) = mysql_fetch_row($res) ) {
if( file_exists($file_name) ) {
require_once( $file_name );
}
else {
// warn because a file requested didn't exist
}
}
}
Hope that helps

Categories