how to call a seperate php file each day of the year? - php

I am a beginner in PHP and would like to load a daily meditation every day that is specific to that day.
So on January 1st, I would call the quote from 1_1.php and on the 2nd 1_2.php, and so on until February 1st which would call 2_1.php and on the 2nd 2_2.php on the third 2_3.php.
Is this possible and how hard would it be?
It would also be acceptable to have 365 files where it just called the next one in order every twenty-four hours, or one file with 365 lines and called a different line every day, but I do not know how to do this as I only know how to build in html and design so any help or advice would be great.

I would most definitely not use 365 different files. It might be sensible to use a database, but since these seem to be one-liners and you are new to PHP, the simples method is to them in a big array. The downside of this is that the whole array will be read and parsed on each page load. But I wouldn't worry about the performance of that until it becomes a problem.
$meditations = array(
'1-Jan' => "Some meditation for today",
'2-Jan' => "Some meditation for tomorrow",
...
...
'28-Dec' => "Something for today",
'29-Dec' => "Something for tomorrow",
'30-Dec' => "Something for tomorrow2",
'31-Dec' => "Something for new year's eve"
);
Then access them as:
echo $meditations[date('j-M')];
// Today will output
//something for today
If you prefer, insted of using the format dd-Mon for array keys, you can use numeric months as in:
array('28-12' => "something for today");
// Access as:
echo $meditations[date('j-m')];
The complete bit to include inside your PHP page (note it will need to be a .php page, rather than .html) is:
<?php
$meditations = array(
'1-1' => "Some meditation for today",
'2-1' => "Some meditation for tomorrow",
// etc....
);
echo $meditations[date('j-m')];
?>
You can alternatively store the huge array in its own file called meditations.php, and include it:
File meditations.php
<?php
$meditations = array(
'1-1' => "Some meditation for today",
'2-1' => "Some meditation for tomorrow",
// etc....
);
?>
Main file:
<?php
include("meditations.php");
echo $meditations[date('j-m')];
?>
To include this in a plain HTML page (not .php), you'll need an <iframe>. Assuming your PHP is working correctly in a file called meditations.php, call the <iframe> like this:
<iframe src='meditations.php' />

I would use a database personally, but this is possible if you wanted to do it:
<?php
include(date("n_j").".php");
?>

The proper way to do it, is to have one PHP file which loads data from some sort of storage (most preferably database table) and each day load a record for that particular day.
If you want to stick with your multiple files you can do:
<?php
$filename = date("m")."_".date("d").".php";
if (file_exists($filename)) include($filename);
?>

Related

Changing the description of a MP3 file?

I am currently using simple_html_dom to parse some MP3 files from another website, and store them onto my own server. However I've noticed that some of them contain a tag which indicates the location they originated from within the comment portion of the ID3 properties.
I need to make this website, say my own websites name. However, the only solution that I've found to doing this with PHP is beyond complicated using something called GETID3.php You can view the github link by clicking the name.
I don't really understand the documentation can someone help me find an easier way of doing this please?
Here's the part of my code that matters, I guess.
$mp3title = ''.$thetitle.' - Oursite.com';
file_put_contents($DPATH.'/temp/'.$mp3title.'.mp3',file_get_contents($filepath));
$file = $DPATH.'/temp/'.$mp3title.'.mp3';
Provided you're not interested in also updating the image of the file, you can look into just using something simple like the default php function id3_set_tag however for more complex usages like updating the artwork then you're going to have to use the library you mentioned before.
$data = array(
"title" => "Re:Start",
"artist" => "Re:\Legion",
"comment" => "YourWebsiteName.com"
);
$result = id3_set_tag($DPATH.'/temp/'.$mp3title.'.mp3', $data, ID3_V1_0 );
if ($result === true) {
echo "Tag successfully updated\n";
}

PHP PDO MySql query results not updated

hopefully I can explain this clearly enough.
On my profile page (let's call it profile.php), I am including a header file (header.php) that contains all the HTML header code and menu, as well as some queries to show stats to a user (how many surveys they have completed, and rewards earned). There are multiple queries on this page, but all work as expected, such as
header.php
<h3>
<?php
$whereCnt = array(
array('svy_end_status','=',1),
array('svy_end_mem_id','=',$member_id)
);
$svycnt = DB::getInstance()->get( 'COUNT(*) AS Count', 'survey_end', $whereCnt );
echo $svycnt->first()->Count;
?>
</h3>
Back in profile.php I have another query to get all the user profile information:
$wheremem = array(
array( 'member-uid', '=', $member_id ));
$completeprofileqry = DB::getInstance()->get('*','members',$wheremem);
NOTE: This is using a DB class based from Codecourse's Login/Register tutorial but is using PDO as the method.
Now, when I do a
if ($completeprofileqry->count()){
echo '<pre>';
print_r($completeprofileqry->first());
echo '</pre>';
I get as the output:
stdClass Object
(
[Count] => 2
)
This output directly correlates with the first query from the included header file, rather than the new query.
Is this due to the 'instance' still being the same?
I should also note, that on my index.php page, I am doing other queries, as well as using the same included header.php, but I am having NO issues with these query results.
Can anyone help narrow down where the problem might be?
EDIT: I am an idiot
It was meant to be 'member_uid' NOT 'member-uid' (underscore not hyphen !!!)

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

Best way to manage text displayed to users in PHP

Ok for sure this has been asked and answered already but i somehow can't find a proper tutorial.
I want to keep the text displayed to users somewhere else and to prevent my code from becoming too large and unreadable.
My site won't be internationalized. I just want to have some kind of file with key-value structure and get the text from there. I want to keep the text in files, not in the database as some tutorials suggest.
I found a solution which will work but i am not sure whether this is a good approach.
I am thinking of using parse_ini_file and to keep my texts in .ini file. Is there something wrong with this approach? Could you suggest something better?
I put all language data in arrays. Its easy and also we can add multi-language support
lang/en.php
<?php
return array(
'index' => 'Homepage',
'feedback' => 'Feedback'
'logout' => 'Logout from profile',
)
?>
lang/ru.php
<?php
return array(
'logout' => 'Выйти из профиля',
)
?>
Then we can load languages:
$lang = include('lang/en.php');
if(isset($_GET['lang']))
{
$lang = array_merge($lang, include('lang/ru.php'));
}
After all it $lang will look like:
Array
(
[index] => Homepage
[feedback] => Feedback
[logout] => Выйти из профиля
)
And we can very simple use it:
function __($name) {
global $lang;
return $lang[$name];
}
Somewhere in the site template:
...
<title><?=__('index')?></title>
</head>
<body>
<?=__('feedback')?>
why not use a plain text file with commas or some uncommon character to hold this data? you can read it and parse it into an array with
$file = file_get_contents("/path/to/file");
$lines = explode('\r', $file);
foreach($lines as $line) $message[substr($line, 0, strpos($line, ','))] = substr($line, strpos($line, ','));
then you should have an array like $messages[3] = "No soup for you!";
the file might look like:
1,The site is down.
2,Try again.
3,No soup for you!
4,Signs point to yes.
(I probably have some of the arguments misplaced in those functions - i always forget which is the needle and which the haystack.)
You can process your data in a script. In this script, you call a certain source (e.g. the ini file you suggest). Then you use a template engine. For this engine, you point towards a template file and give the template all the variables.
The template generates the html and inserts the variables at the right place. This way, you keep you php (business logic) code clean, away from the presentation (the template). Also you can manage the variables in one file (ini/xml but this can be something completely different).
For template engines, Smarty is the most known of all. There are also pure php-based template systems, just Google for them to find one that suits your needs.
I do like this:
$defaultLang = array('Home','Logout',etc)
$otherLang=array( 'ru' => array('Home_in_ru','logout_in_ru',etc);
you translate like this:
echo translate('Home');
function is:
function translate($msg) {
if ($_GET['lang']=='en')
return $msg;
return $otherLang[$_GET['lang']][array_search($msg,$defaultLang)];
}
// Note the function is simplified up there
As you can see the default case deosnt' need to load anything or do any operation, the function just returns back the argument passed
i like the answer with the lang/en.php file. but instead of a file for each language, i use a file for each web page (or class, etc). this keeps file sizes lower and i create a 3D array:
`return array( "EN" => array( "title" => "Welcome - Good Morning", ...),
"TG" => array( "title" => "Mabuhay - Magandang Umaga Po", ...)
);'
Real easy to add new language strings too...
This makes it real easy for language translation contractors since they can see the native language in close proximity to the foreign in 1 editor,,,

Dynamic PHP website with MySql database; How to create a sitemap for this?

I have a classifieds website. The website is php based, and uses a mysql database.
Today, I have a sitemap which I have to update using an external php script.
This php script takes all classifieds from the database and creates an xml sitemap, fresh.
Problem is I have to do this manually, by first opening the php script, then waiting for it to complete, then submitting the sitemap to google again (even though the last step is optional I still do it).
I must also point out that even though I do submit this to google, it still isn't indexed (doesn't come up in the search results), which I want it to.
I want the classifieds to show up in google SERPS as soon as possible. Currently this is taking too long... Like a week or so.
Anyways, I need to know how to improve this method I have.
Should I open and write to the xml file on every new classified?
I hesitat to do that because this means the file is open almost all the time, because new classifieds are frequent, and sometimes there are several new classifieds at the same time, so how would this impact the opening and writing to file if the file is already in use etc etc...
Is there any other method, like submitting a php sitemap to google, and whenever google accesses this php file, a new xml is dynamically created?
Need some ideas on how to do this in best way please...
Also, question 2:
If I dont have any links to a specific page on my server, except for a link in a sitemap, will this page be indexed anyways?
Thanks
You are asking too much from Google. They aren't magic. Indexing the whole internet is a big task. And they aren't out there to do what you want. However, there are ways to get the google to notice things fasterish and also ways to get more up-to-the-moment searching through other means.
Step one. The xml sitemap is good, but it still helps to have a legit html everything-everywhere link list/map. This is because links are in general of higher importance than a site map. So many search engines get to them faster.
On that note, not being the only dood linking to your stuff is a HUGE help. The way indexing works means that getting on the list sooner means being updated in the google sooner. More links from outside means more points of entry.
Also, the way google determines how important your site is comes, in part, from how much others link to you. More importance means being crawled for new info more often.
Now, about real time search. The 'next big thing' in search is using real time items to get more relevant results. Google already is doing some of this for certain things. Sports, big events like the recent spacex launch, so on. They are using Buzz and Twitter. Others are using facebook and a few other services.
Encouraging your users to tweet/like your items can make you more real-time search-able. So the moment a new listing comes out, a bunch of links may show up on twitter, and then they are more likely to show up in a real-time search.
You could put the script that builds the sitemap in the logic loop that creates a new classified ad. That way every time a new ad is created, the sitemap is updated.
Google has advice on using HTTP ping service to submit the sitemap automatically. You can use PHP's Client URL Library to create the ping.
Finally, you're out of luck trying to get Google to index your pages faster. As they say in their Webmaster Guidelines (in the sitemap section):
Google doesn't guarantee that we'll crawl or index all of your URLs.
In short: until Google's algorithm starts to believe your website is HotShitTM, they won't index every URL, and will usually take their time about it, sitemap or not.
I have created a small sitemap for the Laravel website. Since its an MVC arch structure remains the same.
Routing part:
Route::get('/sitemap', ['as' => 'Sitemap index', 'uses' => 'SiteMapController#index']);
Route::get('/sitemap/page', ['as' => 'Sitemap page', 'uses' => 'SiteMapController#page']);
View part two files Index.php this will be main sitemap index file
<?xml version="1.0" encoding="UTF-8"?>
<sitemapindex xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/siteindex.xsd" xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<sitemap>
<loc><?php echo url('/') ?>/sitemap/page</loc>
<lastmod><?php echo date('c', time()); ?></lastmod>
</sitemap>
<sitemap>
<loc><?php echo url('/') ?>/sitemap/exchanges</loc>
<lastmod><?php echo date('c', time()); ?></lastmod>
</sitemap>
page.php this is accessory files for individual urlset
<?php echo '<?xml version="1.0" encoding="UTF-8"?>'; ?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<?php foreach ($posts as $post) { ?>
<url><loc><?php echo url('/') ?>/<?php echo $post['uri']; ?></loc><lastmod><?php echo $post['time']; ?></lastmod> <changefreq><?php echo $post['freequency']; ?></changefreq>
<priority><?php echo $post['priority']; ?></priority>
</url>
<?php } ?>
</urlset>
Now, controller, where you run the show:SitemapController.php you can change the time based on the frequency and freshness of the updates you provide in the content.
class SiteMapController extends Controller {
public function index() {
return response()->view('sitemap.index')->header('Content-Type', 'text/xml');
}
public function page() {
$posts = array(
array("uri" => "", "time" => date('c', time()), "freequency" => "Daily", "priority" => "0.8"),
array("uri" => "about-us", "time" => "2018-08-17", "freequency" => "Monthly", "priority" => "0.5"),
array("uri" => "contact-us", "time" => "2018-08-17", "freequency" => "Monthly", "priority" => "0.5"),
array("uri" => "privacy-policy", "time" => "2018-08-17", "freequency" => "Monthly", "priority" => "0.5"),
array("uri" => "cookie-policy", "time" => "2018-08-17", "freequency" => "Monthly", "priority" => "0.5"),
array("uri" => "thank-you", "time" => "2018-08-17", "freequency" => "Monthly", "priority" => "0.5"),
);
return response()->view('sitemap.page', ['posts' => $posts])->header('Content-Type', 'text/xml');
}
}

Categories