How to download part of file from the url? - download

A huge file was located on the url .
http://gensho.acc.umu.se/debian-cd/8.2.0/amd64/iso-cd/debian-8.2.0-amd64-lxde-CD-1.iso
Now i want to download 10000 bytes between 10000th byte and 19999th byte on the file .
HOW to write the php command?

This would read 8K of binary data from the URL:
$filename = "http://gensho.acc.umu.se/debian-cd/8.2.0/amd64/iso-cd/debian-8.2.0-amd64-lxde-CD-1.iso";
$handle = fopen($filename, "rb");
$contents = fread($handle, 8192);
fclose($handle);
see http://php.net/manual/en/function.fread.php
In order to read from the 10,000nd byte up to the 19,999th you need to skip the first 10,000 bytes, as there is no "filepointer" which can be positioned w/o reading like fseek on normal files:
...
$skip= fread($handle, 10000);
$contents = fread($handle, 9999);
...

Related

How to generate multiple qr codes in laravel

I am working on a project in which i have to generate QR codes based on number of members in database. Each qrcode will have a unique string so i am generating a random string of 30 chracters. As of now i have 5000 members in database and i need to generate 5000 QR Codes.
When i run the application it fetches total number of records from database and in foreach loop i am generating QR Code, but the server responds to 503 error after 40-50 seconds though i set the limit in php ini setting for max execution time at 3600. below is the my code. I need advice on how can i achieve my goal what is best practice and how i can generate QR code in bulk with unique string and avoid duplicating qr code and store the qr image in storage folder as well its filename in database for later use to print it.
$data = \DB::connection('mysql2')->table('basicinfo')->where('is_approved','=','1')->whereIn('classOfMembership',$member_arr)->get(); //this return 4808 records
foreach($data as $d){
$randomStr = Str::random(33);
$image = QrCode::format('png')
->size(200)->errorCorrection('H')
->generate('https://example.com/'.$randomStr);
$time_now = time();
$output_file = '/qr-code/election-'.$request->election_year.'/img-' . $time_now . '.png';
$image_name = 'img-' . $time_now . '.png';
$insert_arr[] = [
'election_year' => $request->election_year,
'position' => $request->post,
'qr_hash' => $randomStr,
'qr_code_image' => $image_name
];
Storage::disk('local')->put($output_file, $image);
}
Ballot::insert($insert_arr);

Writing binary file using in Extendscript. Incorrect file size

Further to my question here I'm writing a list of hex colours to a binary file from within Photoshop using Extendscript. So far so good.
Only the binary file written with the code below is 119 bytes. When cut and pasted and saved using Sublime Text 3 it's only 48 bytes, which then causes complications later on.
This is my first time in binary land, so I may be a little lost. I suspect it's an either an encoding issue (which could explain the 2.5 file size), or doing something very wrong trying to recreate the file in a literal, character for character sense. *
// Initially, my data is a an array of strings
var myArray = [
"1a2b3c",
"4d5e6f",
"a10000",
"700000",
"d10101",
"dc0202",
"c30202",
"de0b0b",
"d91515",
"f06060",
"fbbaba",
"ffeeee",
"303030",
"000000",
"000000",
"000000"
]
// I then separate them to four character chunks
// in groups of 8
var data = "1a2b 3c4d 5e6f a100 0070 0000 d101 01dc\n" +
"0202 c302 02de 0b0b d915 15f0 6060 fbba\n" +
"baff eeee 3030 3000 0000 0000 0000 0000";
var afile = "D:\\temp\\bin.act"
var f = new File(afile);
f.encoding = "BINARY";
f.open ("w");
// f.write(data);
// amended code
for (var i = 0; i < data.length; i++)
{
var bytes = String.fromCharCode(data.charCodeAt(i));
f.write(bytes);
}
f.close();
alert("Written " + afile);
* ...or it's the tracking on my VHS.
I'm rubbish at JavaScript but I have hacked something together that will show you how to write 3 bytes of hex to a file in binary. I hope it is enough for you to work out how to do the rest!
I saved this file as /Users/mark/StackOverflow/AdobeJavascript.jsx
alert("Starting");
// Open binary file
var afile = "/Users/mark/StackOverflow/data.bin"
var f = new File(afile);
f.encoding = "BINARY";
f.open ("w");
// Define hex string
str = "1a2b3c"
for(offset=0;offset<str.length;offset+=2) {
i = parseInt(str.substring(offset, offset+2), 16)
f.write(String.fromCharCode(i));
}
f.close();
alert("Done");
If you dump the data.bin you'll see 3 bytes:
xxd data.bin
00000000: 1a2b 3c
You can write more of your values by simply changing the string to:
str = "1a2b3c"+ "4d5e6f"+ "a10000";
I also discovered how to run ExtendScript from a shell script in Terminal which is my "happy place" so I'll add that in here for my own reference:
#!/bin/bash
osascript << EOF
tell application "Adobe Photoshop CC 2019"
do javascript "#include /Users/mark/StackOverflow/AdobeJavascript.jsx"
end tell
EOF
The corresponding reading part of this answer is here.

Powershell, download CSV into string

In Powershell, instead of downloaded a CSV file to drive from a web request, can you download a file directly into a string? I often pull earthquake data from the USGS database which outputs the data as a downloadable CVS file. The issue is data is pulled per day and when pulling years of data I end up pulling a thousand or more files, then pipe them together. If I can download directly into a string I could eliminate the read write file time needed for a thousand or more files by doing it all in memory.
The basic portion of code used to pull the file is:
$U = $env:userprofile
$Location = "Region_Earthquakes"
$MaxLat = "72.427"
$MinLat = "50.244"
$MaxLon = "-140.625"
$MinLon = "-176.133"
$yearspulled = 1
$ts = New-TimeSpan -Days 1
$Today = Get-Date
$StartDate = [datetime](((Get-Date -format "yyyy") - $yearspulled + 1).ToString() + "-01-01 00:00:00")
While ($StartDate -le $Today)
{$EndDate = $Startdate + $ts
$Start = $StartDate.ToString("yyyy-MM-dd HH:mm:ss")
$FileDate = $StartDate.ToString("yyyy_MM_dd")
$End = $EndDate.ToString("yyyy-MM-dd HH:mm:ss")
$url = "http://earthquake.usgs.gov/fdsnws/event/1/query.csv?starttime=$Start&endtime=$End&minmagnitude=-1.00&maxmagnitude=10.00&maxlatitude=$MaxLat&minlatitude=$MinLat&maxlongitude=$MaxLon&minlongitude=$MinLon&eventtype=earthquake&orderby=time"
$output = "$U\DownLoads\$Location" + "_$FileDate.csv"
(New-Object System.Net.WebClient).DownloadFile($url, $output)
Write-Output "Date pulled for $Start"
$Startdate = $Startdate + $ts}
When in doubt, read the documentation. The System.Net.WebClient class has a method DownloadString() that does exactly what you're asking.
WebClient.DownloadString Method
Namespace: System.Net
Assemblies: System.dll, netstandard.dll, System.Net.WebClient.dll, System.Net.dll
Downloads the requested resource as a String. The resource to download may be specified as either String containing the URI or a Uri.
Emphasis mine.
$s = (New-Object System.Net.WebClient).DownloadString($url)

move_uploaded_file two or more different image names moves only one

i am trying to move five different files in one form at the same time but only one image moves. I have five columns for each filename in my database table. The uploaded image names saves in the database column but the only problem is only one file is moved instead of all the files uploaded. Below is code:
//form isValid...
$post = $form2->getData();
$imageonetmp = $post["imageone"]["tmp_name"];
$imageonename = $post["imageone"]["name"];
$imagetwotmp = $post["imagetwo"]["tmp_name"];
$imagetwoname = $post["imagetwo"]["name"];
$imagethreetmp = $post["imagethree"]["tmp_name"];
$imagethreename = $post["imagethree"]["name"];
$imagefourtmp = $post["imagefour"]["tmp_name"];
$imagefourname = $post["imagefour"]["name"];
$imagefivetmp = $post["imagefive"]["tmp_name"];
$imagefivename = $post["imagefive"]["name"];
$filepath = $this->_dir.$imageonename;
$filepath = $this->_dir.$imagetwoname;
$filepath = $this->_dir.$imagethreename;
$filepath = $this->_dir.$imagefourname;
$filepath = $this->_dir.$imagefivename;
move_uploaded_file($imageonetmp, $filepath);
move_uploaded_file($imagetwotmp, $filepath);
move_uploaded_file($imagethreetmp, $filepath);
move_uploaded_file($imagefourtmp, $filepath);
move_uploaded_file ($imagefivetmp, $filepath);
/*set image names to db here*/
$entityManager->persist($autos);
$entityManager->flush();
Hope someone can help.
You are using the same variable name $filepath to write the files. Meaning you are moving each file but overwriting the previous move.
You should use different variable names e.g. $filepath1, $filepath2, etc...
Or
$filepath = file location...
Move file...
And repeat.

Simultaneous AJAX calls during HTTP streaming

I have an Apache server running a web application. In this webapplication I show a video using JWPlayer. JWPlayer uses http pseudostreaming to fetch the video from a PHP script which serves up this video. All this works well and the video is streamed well.
The problem I am having is while the video is streaming I also use AJAX calls to fetch some XML files which are used by Adobe Flash files on the same page. While streaming these XML file fetches are kept 'pending' until the entire video is loaded. Using Chrome I can see that the video gets loaded byte by byte. When the video is entirely loaded, then the XML files are fetched. Also if I open another tab in my browser while a video is streaming and try to load the web application again, it will also not show until the video is entirely loaded.
This seems te be an Apache setting of some sort. The MPM settings for apache are:
ThreadsPerChild 150
MaxRequestsPerChild 0
This seems to be correct. Any ideas what could be wrong?
If you are using PHP sessions then this is probably what is causing the IO blocking.
php blocking when calling the same file concurrently
I was making a system with private video streaming. So, i was needing a streaming via php, because using php programming i was able to restringe user access.
I was having troubles to streaming video and execute other script on the server.
Using the session_write_close() solve the problem to open another scripts and i found that script on web that helps me sooooo much.
I want to share, because that script makes a real streaming.
I found it on http://www.tuxxin.com/php-mp4-streaming/ website.
All thanks to the author of this code =D
ENJOY !
<?php
$file = 'video360p.mp4';
$fp = #fopen($file, 'rb');
$size = filesize($file); // File size
$length = $size; // Content length
$start = 0; // Start byte
$end = $size - 1; // End byte
header('Content-type: video/mp4');
//header("Accept-Ranges: 0-$length");
header("Accept-Ranges: bytes");
if (isset($_SERVER['HTTP_RANGE'])) {
$c_start = $start;
$c_end = $end;
list(, $range) = explode('=', $_SERVER['HTTP_RANGE'], 2);
if (strpos($range, ',') !== false) {
header('HTTP/1.1 416 Requested Range Not Satisfiable');
header("Content-Range: bytes $start-$end/$size");
exit;
}
if ($range == '-') {
$c_start = $size - substr($range, 1);
}else{
$range = explode('-', $range);
$c_start = $range[0];
$c_end = (isset($range[1]) && is_numeric($range[1])) ? $range[1] : $size;
}
$c_end = ($c_end > $end) ? $end : $c_end;
if ($c_start > $c_end || $c_start > $size - 1 || $c_end >= $size) {
header('HTTP/1.1 416 Requested Range Not Satisfiable');
header("Content-Range: bytes $start-$end/$size");
exit;
}
$start = $c_start;
$end = $c_end;
$length = $end - $start + 1;
fseek($fp, $start);
header('HTTP/1.1 206 Partial Content');
}
header("Content-Range: bytes $start-$end/$size");
header("Content-Length: ".$length);
$buffer = 1024 * 8;
while(!feof($fp) && ($p = ftell($fp)) <= $end) {
if ($p + $buffer > $end) {
$buffer = $end - $p + 1;
}
set_time_limit(0);
echo fread($fp, $buffer);
flush();
}
fclose($fp);
exit();
?>

Resources