I am trying to detect the duration of any video file before it is uploaded with PHP
so if it is less than one minute for example I will refuse uploading it.
if it is not possible , how can I do it after uploading the video ??
You can get video duration with ffmpeg or getID3
Example
$getID3 = new getID3;
$file = $getID3->analyze($filename);
echo("Duration: ".$file['playtime_string'].
" / Dimensions: ".$file['video']['resolution_x']." wide by ".$file['video']['resolution_y']." tall".
" / Filesize: ".$file['filesize']." bytes<br />");
Or
ob_start();
passthru("ffmpeg -i working_copy.flv 2>&1");
$duration = ob_get_contents();
$full = ob_get_contents();
ob_end_clean();
$search = "/duration.*?([0-9]{1,})/";
print_r($duration);
$duration = preg_match($search, $duration, $matches, PREG_OFFSET_CAPTURE, 3);
print_r('<pre>');
print_r($matches[1][0]);
print_r($full);
Please see
http://getid3.sourceforge.net/
http://ffmpeg.org/
How to get video duration, dimension and size in PHP?
get flv video length
Thanks
:D
for people coming to check this out this is a solution a little more advanced for the year 2017
first download the latest version from the first link above in the accepted answer the (green checkmark)
require_once('getid/getid3/getid3.php'); //path to your get id file if you do not include this in your file it will result in an error meaning the code will not work
$file = "sade.mp4"; //what you want extract info from maybe mp3,or mp4 file anything you want to get file size in bytes or time duration
$uuuuu = "videos/"; //path to your video file it could also be music not only video
$getID3 = new getID3; //initialize engine
$ThisFileInfo = $getID3->analyze($uuuuu.$file);
getid3_lib::CopyTagsToComments($ThisFileInfo);
echo '<pre>'.htmlentities(print_r($ThisFileInfo, true)).'</pre>'; //use this to print array to pick whatever you like that you want value like playduration, filesize
Related
I wrote a small code in PHP in order to parse variables.
I would like each time this code is called, a new line is added in the TXT file.
Each line will contain a time stamp , ie : 09:30 and a temperature value
Once the TXT file is filled-in i would like to generate a Google Chart.
Time Stamps are going to be Abcisses (X) and corresponding temp value will be Y
So far, a new line is NOT created in the TXT file.
Would you please help me to find out why ?
<?
$File = 'live_datas.txt';
# GRAB THE VARIABLES FROM THE URL
$HeuresTronconMesure = $_GET['hour'];
$MinutesTronconMesure = $_GET['min'];
$DonneeCapteur = $_GET['data'];
# --------------------------------
$FICHIER = fopen($File, "w");
# Generate Timestamp : HH:MM
fputs($FICHIER, $HeuresTronconMesure);
fputs($FICHIER , ":");
fputs($FICHIER, $MinutesTronconMesure);
# Add 1 space
fputs($FICHIER , " ");
# Add Temperature Value
fputs($FICHIER, $DonneeCapteur);
# Add a new line
fputs ($FICHIER , "\r\n");
# Close the file
fclose($FICHIER);
?>
At the end, i expect to get "live_datas.txt" with something like :
04:50 25.29
05:00 24.30
07:30 25.20
08:45 26.00
10:15 27.50
Regards,
You have to open your file in append mode:
$FICHIER = fopen($File, "a");
What manual says about both modes:
"w" (Write only. Opens and clears the contents of file; or creates a new file if it doesn't exist)
"a" (Write only. Opens and writes to the end of the file or creates a new file if it doesn't exist)
//call function
writeData($_GET['hour'], $_GET['min'], $_GET['data']);
//function definition
function writeData($hour, $min, $temperature) {
$path = 'live_datas.txt';
$line = "{$hour}:{$min} {$temperature}\r\n";
if (file_exists($path)) {
file_put_contents($path, $line, FILE_APPEND);
}
else {
file_put_contents($path, $line);
}
}
I am reading and saving weather JSON data from forecast.io API. Because I am using free API which has 1000 requests limit per day. So I am requesting API every 10 minutes. I saving update time as timestamp and then I am using this timestamp to check to 10 minutes elapsed or not. However when I am reading JSON file and echoing it, strange number '18706' or '22659' coming out. I do not have idea where it is coming from. How to solve this problem?
Result in browser:
....madis-stations":["UTTT"],"units":"si"}}22659
PHP:
<?php
$t = time();
$last_updated_timestamp = file_get_contents("last_updated_timestamp.txt");
$delta = ($t - $last_updated_timestamp) / 60;
if ($delta > 10) {
$json = file_get_contents('https://api.forecast.io/forecast/MY_API_KEY/41.2667,69.2167?units=si&lang=ru');
$obj = json_decode($json);
echo $obj->access_token;
$fp = fopen('tw.json', 'w');
fwrite($fp, json_encode($obj));
fclose($fp);
$fp2 = fopen('last_updated_timestamp.txt', 'w');
fwrite($fp2, $t);
fclose($fp2);
}
echo readfile("tw.json");
?>
Change:
echo readfile("tw.json");
to just:
readfile("tw.json");
readfile writes the contents of the file to the output buffer, and then returns the number of bytes that it wrote. You're then echoing that number of bytes.
It seems like you confused readfile with file_get_contents, which returns the contents of the file as a string.
Remove the echo before readfile. Readfile already prints the content of the file. The return value of readfile is the number of read bytes, which you echoing.
I am trying add HTML to a file using fwrite(). My final goal is to get it to add it 15 lines above the end of the file. Here is what I have so far:
<?php
$file = fopen("index.html", "r+");
// Seek to the end
fseek($file, SEEK_END, 0);
// Get and save that position
$filesize = ftell($file);
// Seek to half the length of the file
fseek($file, SEEK_SET, $filesize + 15);
// Write your data
$main = <<<MAIN
//html goes here
MAIN;
fwrite($file, $main);
// Close the file handler
fclose($file);
?>
This just keeps overwriting the top of the file.
Thanks.
The sample code in the question does not operate based on lines, since you're working with file size (unless there is an assumption about definition of lines in the application that is not mentioned in here). If you want to work with lines, then you'd need to search for new line characters (which separates each line with the next).
If the target file is not a large file (so we could load the whole file into memory), we could use PHP built-in file() to read all the lines of the file into an array, and then insert the data after the 15th element. something like this:
<?php
$lines = file($filename);
$num_lines = count($lines);
if ($num_lines > 15) {
array_splice($lines, $num_lines - 15, 0, array($content));
file_put_contents($filename, implode('', $lines));
} else {
file_put_contents($filename, PHP_EOL . $content, FILE_APPEND);
}
I need to login to a production server retrieve a file and update my data base with the data in this file. Since this is a production database, I don't want to get the whole file every 5 minutes since the file may be huge and this may impact the server. I need to get the last 30 lines of this file every 5 minutes interval and have as little impact as possible.
The following is my current code, I would appreciate any insight to how best accomplish this:
<?php
$user="id";
$pass="passed";
$c = curl_init("sftp://$user:$pass#server1.example.net/opt/vmstat_server1");
curl_setopt($c, CURLOPT_PROTOCOLS, CURLPROTO_SFTP);
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($c);
curl_close($c);
$data = explode("\n", $data);
?>
Marc B is wrong. SFTP is perfectly capable of partial file transfers. Here's an example of how to do what you want with phpseclib, a pure PHP SFTP implementation:
<?php
include('Net/SFTP.php');
$sftp = new Net_SFTP('www.domain.tld');
if (!$sftp->login('username', 'password')) {
exit('Login Failed');
}
$size = $sftp->size('filename.remote');
// outputs the last ten bytes of filename.remote
echo $sftp->get('filename.remote', false, $size - 10);
?>
In fact I'd recommend an approach like this anyway since some SFTP servers don't let you run commands via the system shell. Plus, SFTP can work on Windows SFTP servers whereas tail is unlikely to do so even if you do have shell access. ie. overall, it's a lot more portable a solution.
If you want to get the last x lines of a file you could loop repeatedly, reading however many bytes each time, until you encounter 10x new line characters. ie. get the last 10 bytes, then the next to last 10 bytes, then the ten bytes before those ten bytes, etc.
An answer by #Sammitch to a duplicate question Get last 15 lines from a large file in SFTP with phpseclib:
The following should result in a blob of text with at least 15 lines from the end of the file that you can then process further with your existing logic. You may want to tweak some of the logic depending on if your file ends with a trailing newline, etc.
$filename = './file.txt'
$filesize = $sftp->size($filename);
$buffersize = 4096;
$offset = $filesize; // start at the end
$result = '';
$lines = 0;
while( $offset > 0 && $lines < 15 ) {
// work backwards
if( $offset < $buffersize ) {
$offset = 0;
} else {
$offset -= $buffer_size;
}
$buffer = $sftp->get($filename, false, $offset, $buffer_size));
// count the number of newlines as we go
$lines += substr_count($buffer, "\n");
$result = $buffer . $result;
}
SFTP is not capable of partial file transfers. You might have better luck using a fullblowin SSH connection and use a remote 'tail' operation to get the last lines of the file, e.g.
$lines = shell_exec("ssh user#remote.host 'tail -30 the_file'");
Of course, you might want to have something a little more robust that can handle things like net.glitches that prevent ssh from getting through, but as a basic starting point, this should do the trick.
I have an upload functionality wherein I want to check whether there is a duplicate filename in the database. If there is, I would like to rename the jpg so that the photo to be uploaded will still be uploaded.
Here's the lines of codes that I came up with:
$shuffled = "qwertyuiopasdfghjkZxcvbnm";
$shuffled = str_shuffle($shuffled);
$shuffled = $shuffled.".jpg";
rename($this->filename,$shuffled);
I am using the shuffle function here to somehow give a random new filename,
I have tried using some other steps like preg_replace, but the jpg file itself gets corrupted. Any ideas?
Your code is:
$shuffled = "qwertyuiopasdfghjkZxcvbnm";
$shuffled = str_shuffle($shuffled);
$shuffled = $shuffle.".jpg";
rename($this->filename,$shuffled);
The third line looks like it should be $shuffled = $shuffled.".jpg";
use this:
copy($oldfilename,rand(10000000000,99999999999).".jpeg");
unlink($oldfilename);
the file name (without extension) will be a number greater than 10000000000 and smallet than 99999999999
Where is the extension in your new filename???
Exmple
rename("/tmp/tmp_file.txt", "/home/user/login/docs/my_file.txt");
If you are going to use a random filename, use microtime() to generate a random string.
A nicer solution would be:
if(is_file($filename))
{
$filenameSplit = explode('.', $filename);
$i = 1;
while(is_file($filenameSplit[0] . "($i)." . $filenameSplit[1]))
{
$i++;
}
$newFilename = $filenameSplit[0] . "($i)." . $filenameSplit[1];
rename($filename, $newFilename);
}