the problem is that I have a remote js file to include in a page and it has to be included the last version of it. To be more specific:
The file is for example: http://example.com/javascript/v03/header.js
The problem is that when they generate a new javascript file the url will be changed to http://example.com/javascript/v04/header.js for example.
The URL will be changed to a new version number.
My question is what will be the best/clean way to detect a new version of that file in Php?
Thank you!
Untested but should work.
You file_get_contents the versions and when it returns false you have gone to far.
$link = "http://example.com/javascript/VERSION/header.js";
For($i=1; $i<100; $i++){
$test= str_replace("VERSION", "v" . str_pad($i, 2, "0", STR_PAD_LEFT), $link);
If(file_get_contents($test)){
$latest = $test;
}else{
Break;
}
}
Echo "latest version is " . $latest;
Then optionally you save the $i number somewhere and use that the next time you run it so that you don't need to recheck version 1-4 every time.
EDIT, noticed I had $str instead of $link.
Related
I am trying to use the solution called in here:
How to keep session alive without reloading page?
Unfortunately I can't get it to work, I have very limited experience with Javascript and jQuery.
This is my index.php
<?php
session_start();
echo session_id();
$_SESSION['id'] = session_id(); //just so there is a variable within the session
?>
EDIT: added jquery library after comment/answer
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script>
setInterval(function(){
$.post('refresh_session.php');
}, 60000);
</script>
And this is the refresh_session.php where I write to a file, so I can test if the file is actually being called.
<?php
session_start();
if (isset($_SESSION['id'])){
$_SESSION['id'] = $_SESSION['id']; // or if you have any algo.
}
$date = new DateTime();
$fp = fopen('data.txt', 'a');
fwrite($fp, $date->format('Y-m-d H:i:s') . " " . session_id() ."\n");
fclose($fp);
?>
If I call refresh_session.php manually, I see the date showing up in data.txt.
If I open up index.php and wait for the data.txt file to change, nothing happens.
What am I missing here?
I don't know why, but after copy-paste your javascript code – I've got strange characters in Code Snipped. It can be charset problem. Code looks good, but bracket only looks like bracket. It's not bracket. What it is? I don't know, but look at that what I've got in Code Snipped after pasting your code:
Code will execute if you write it using good charset. Take that working code:
setInterval(function(){
$.post('refresh_session.php');
alert("dsa");
}, 5000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
By the way – alert is of course only test, you can delete this.
So, the answer is – check your charset.
Hello ive searched everywhere to find the answer however none of the solutions ive tried helped
What i am building is a site which connects to Youtube to allow users to search and download videos as MP3 files. I have built the site with the search etc however i am having a problem with the download part (ive worked out how to get the youtube audio file). The format for the audio is originally audio/mp4 so i need to convert it to mp3 however first i need to get the file on the server
So on the download page ive made a script that sends an ajax request to the server to start downloading the file. It then sends a request to a different page every few seconds to find out the progress and update it on the page the user is viewing.
However the problem is while the video is downloading the whole website freezes (all the pages dont load until the file is fully downloaded) and so when the script tries to find out the progress it cant until its fully done.
The file which downloads:
<?php
session_start();
if (isset($_GET['yt_vid']) && isset($_GET['yrt'])) {
set_time_limit(0); // to prevent the script from stopping execution
include "assets/functions.php";
define('CHUNK', (1024 * 8 * 1024));
if ($_GET['yrt'] == "gphj") {
$vid = $_GET['yt_vid'];
$mdvid = md5($vid);
if (!file_exists("assets/videos/" . $mdvid . ".mp4")) { // check if the file already exists, if not proceed to downloading it
$url = urlScraper($vid); // urlScraper function is a function to get the audio file, it sends a simple curl request and takes less than a second to complete
if (!isset($_SESSION[$mdvid])) {
$_SESSION[$mdvid] = array(time(), 0, retrieve_remote_file_size($url));
}
$file = fopen($url, "rb");
$localfile_name = "assets/videos/" . $mdvid . ".mp4"; // The file is stored on the server so it doesnt have to be downloaded every time
$localfile = fopen($localfile_name, "w");
$time = time();
while (!feof($file)) {
$_SESSION[$mdvid][1] = (int)$_SESSION[$mdvid][1] + 1;
file_put_contents($localfile_name, fread($file, CHUNK), FILE_APPEND);
}
echo "Execution time: " . (time() - $time);
fclose($file);
fclose($localfile);
$result = curl_result($url, "body");
} else {
echo "Failed.";
}
}
}
?>
I also had that problem in the past, the reason that it does not work is because the session can only be once open for writing.
What you need to do is modify your download script and use session_write_close() each time directly after writing to the session.
like:
session_start();
if (!isset($_SESSION[$mdvid])) {
$_SESSION[$mdvid] = array(time(), 0, retrieve_remote_file_size($url));
}
session_write_close();
and also in the while
while (!feof($file)) {
session_start();
$_SESSION[$mdvid][1] = (int)$_SESSION[$mdvid][1] + 1;
session_write_close();
file_put_contents($localfile_name, fread($file, CHUNK), FILE_APPEND);
}
I am trying to create and save a file to the root directory of my site, but I don't know where its creating the file as I cannot see any. And, I need the file to be overwritten every time, if possible.
Here is my code:
$content = "some text here";
$fp = fopen("myText.txt","wb");
fwrite($fp,$content);
fclose($fp);
How can I set it to save on the root?
It's creating the file in the same directory as your script. Try this instead.
$content = "some text here";
$fp = fopen($_SERVER['DOCUMENT_ROOT'] . "/myText.txt","wb");
fwrite($fp,$content);
fclose($fp);
If you are running PHP on Apache then you can use the enviroment variable called DOCUMENT_ROOT. This means that the path is dynamic, and can be moved between servers without messing about with the code.
<?php
$fileLocation = getenv("DOCUMENT_ROOT") . "/myfile.txt";
$file = fopen($fileLocation,"w");
$content = "Your text here";
fwrite($file,$content);
fclose($file);
?>
This question has been asked years ago but here is a modern approach using PHP5 or newer versions.
$filename = 'myfile.txt'
if(!file_put_contents($filename, 'Some text here')){
// overwriting the file failed (permission problem maybe), debug or log here
}
If the file doesn't exist in that directory it will be created, otherwise it will be overwritten unless FILE_APPEND flag is set.
file_put_contents is a built in function that has been available since PHP5.
Documentation for file_put_contents
fopen() will open a resource in the same directory as the file executing the command. In other words, if you're just running the file ~/test.php, your script will create ~/myText.txt.
This can get a little confusing if you're using any URL rewriting (such as in an MVC framework) as it will likely create the new file in whatever the directory contains the root index.php file.
Also, you must have correct permissions set and may want to test before writing to the file. The following would help you debug:
$fp = fopen("myText.txt","wb");
if( $fp == false ){
//do debugging or logging here
}else{
fwrite($fp,$content);
fclose($fp);
}
I am currently working on a project where i wanna implement jQuery to cakephp 2.0.
I have followed the guide at:
http://book.cakephp.org/2.0/en/core-libraries/helpers/js.html
i.e. I have downloaded jquery-1.8.1.js (also tried the .min.js file) and put it in app/webroot/js.
In the default layout file i have added
echo $this->Html->script('jquery');
and just before the end of the body tag i have added
echo $this->Js->writeBuffer();
In my controller i have added
public $helpers = array('Js' => array('Jquery'));
When i reload my page and check the source code I see that the link to the jQuery file works correctly.
But when I try to add a simple script (just adding an alert) like this (in the view file):
$alert = $this->Js->alert('Hey there');
nothing happens...
Any kind person out there that might have any suggestion to what I do wrong?
I have spent hours looking looking at the internet and following different guides but still can get a simple thing as an alert working.
According to CakePHP 2.0 documentation: "by default, alert does not buffer, and returns the script snippet."
So by default:
echo $this->Js->alert('Hey there'); // outputs alert("Hey there");
To override this behaviour and add the script to the buffer:
echo $this->Js->alert('Hey there', true);
To write the buffer (commonly right before </body>):
echo $this->Js->writeBuffer();
As an alternative you can use scriptBlock:
$jscript = "alert('Hey there!');";
echo $this->Html->scriptBlock($jscript, array('inline'=>false));
CSS and Javascript files don't change very often, so I want them to be cached by the web browser. But I also want the web browser to see changes made to these files without requiring the user to clear their browser cache. Also want a solution that works well with a version control system such as Subversion.
Some solutions I have seen involve adding a version number to the end of the file in the form of a query string.
Could use the SVN revision number to automate this for you: ASP.NET Display SVN Revision Number
Can you specify how you include the Revision variable of another file? That is in the HTML file I can include the Revision number in the URL to the CSS or Javascript file.
In the Subversion book it says about Revision: "This keyword describes the last known revision in which this file changed in the repository".
Firefox also allows pressing CTRL+R to reload everything on a particular page.
To clarify I am looking for solutions that don't require the user to do anything on their part.
I found that if you append the last modified timestamp of the file onto the end of the URL the browser will request the files when it is modified. For example in PHP:
function urlmtime($url) {
$parsed_url = parse_url($url);
$path = $parsed_url['path'];
if ($path[0] == "/") {
$filename = $_SERVER['DOCUMENT_ROOT'] . "/" . $path;
} else {
$filename = $path;
}
if (!file_exists($filename)) {
// If not a file then use the current time
$lastModified = date('YmdHis');
} else {
$lastModified = date('YmdHis', filemtime($filename));
}
if (strpos($url, '?') === false) {
$url .= '?ts=' . $lastModified;
} else {
$url .= '&ts=' . $lastModified;
}
return $url;
}
function include_css($css_url, $media='all') {
// According to Yahoo, using link allows for progressive
// rendering in IE where as #import url($css_url) does not
echo '<link rel="stylesheet" type="text/css" media="' .
$media . '" href="' . urlmtime($css_url) . '">'."\n";
}
function include_javascript($javascript_url) {
echo '<script type="text/javascript" src="' . urlmtime($javascript_url) .
'"></script>'."\n";
}
Some solutions I have seen involve adding a version number to the end of the file in the form of a query string.
<script type="text/javascript" src="funkycode.js?v1">
You could use the SVN revision number to automate this for you by including the word LastChangedRevision in your html file after where v1 appears above. You must also setup your repository to do this.
I hope this further clarifies my answer?
Firefox also allows pressing CTRL + R to reload everything on a particular page.
In my opinion, it is better to make the version number part of the file itself e.g. myscript.1.2.3.js. You can set your webserver to cache this file forever, and just add a new js file when you have a new version.
When you release a new version of your CSS or JS libraries, cause the following to occur:
modify the filename to include a unique version string
modify the HTML files which reference the library to point at the versioned file
(this is usually a pretty simple matter for a release script)
Now you can set the Expires for the CSS/JS to be years in the future. Whenever you change the content, if the referencing HTML points to a new URI, browsers will no longer use the old cached copy.
This causes the caching behavior you want without requiring anything of the user.
I was also wondering how to do this, when I found grom's answer. Thanks for the code.
I struggled with understanding how the code was supposed to be used. (I don't use a version control system.) In summary, you include the timestamp (ts) when you call the stylesheet. You're not planning on changing the stylesheet often:
<?php
include ('grom_file.php');
// timestamp on the filename has to be updated manually
include_css('_stylesheets/style.css?ts=20080912162813', 'all');
?>