I'm currently having a horrible time with SFTP.
Is there a way to use ftp_fget using SFTP?
I'm using the phpseclibrary, but it only offers their own implementation of $sftp->get() howver I would like $sftp->fget();
In the latest Git version (ie. later than 0.3.7), instead of $sftp->fget(), you can do something like this:
$fp = fopen('filename.ext', 'w');
$sftp->get('file_to_download.ext', $fp);
fclose($fp);
You could also alternatively use Net/SFTP/Stream.php . eg.
$resFile = fopen("sftp://{$resSFTP}/".$filename, 'w');
$srcFile = fopen("/home/myusername/".$filename, 'r');
$writtenBytes = stream_copy_to_stream($srcFile, $resFile);
fclose($resFile);
fclose($srcFile);
Related
I've tried to find answers online, but couldn't find anything that helped me...
I am trying to convert a PCM stream into a WAV file using PHP (7.2) and save it on the server.
Specifically, I am generating speech via Amazon Polly with the below code:
try {
$result = $client->synthesizeSpeech([
'Text' => 'Dies ist ein Test.',
'OutputFormat' => 'pcm',
'SampleRate' => '8000',
'VoiceId' => 'Hans'
]);
$resultData = $result->get('AudioStream')->getContents();
}
I need a WAV file for use with different code later on.
Many thanks for your help!
You just need to add a header and append the PCM data.
http://soundfile.sapp.org/doc/WaveFormat/
I couldn't find any PHP library for this, so I wrote a simple PHP program to do so:
<?php
$pcm = file_get_contents('polly.raw');
//$pcm = $result->get('AudioStream')->getContents();
//Output file
$fp = fopen('file.wav', 'wb');
$pcm_size = strlen($pcm);
$size = 36 + $pcm_size;
$chunk_size = 16;
$audio_format = 1;
$channels = 1; //mono
/**From the AWS Polly documentation: Valid values for pcm are "8000" and "16000" The default value is "16000".
* https://docs.aws.amazon.com/polly/latest/dg/API_SynthesizeSpeech.html#polly-SynthesizeSpeech-request-OutputFormat
**/
$sample_rate = 16000; //Hz
$bits_per_sample = 16;
$block_align = $channels * $bits_per_sample / 8;
$byte_rate = $sample_rate * $channels * $bits_per_sample / 8;
/**
* http://soundfile.sapp.org/doc/WaveFormat/
* https://github.com/jwhu1024/pcm-to-wav/blob/master/inc/wave.h
* https://jun711.github.io/aws/convert-aws-polly-synthesized-speech-from-pcm-to-wav-format/
**/
//RIFF chunk descriptor
fwrite($fp, 'RIFF');
fwrite($fp,pack('I', $size));
fwrite($fp, 'WAVE');
//fmt sub-chunk
fwrite($fp, 'fmt ');
fwrite($fp,pack('I', $chunk_size));
fwrite($fp,pack('v', $audio_format));
fwrite($fp,pack('v', $channels));
fwrite($fp,pack('I', $sample_rate));
fwrite($fp,pack('I', $byte_rate));
fwrite($fp,pack('v', $block_align));
fwrite($fp,pack('v', $bits_per_sample));
//data sub-chunk
fwrite($fp, 'data');
fwrite($fp,pack('i', $pcm_size));
fwrite($fp, $pcm);
fclose($fp);
You can use FFmpeg as well to achieve this, but my solution is purely written in PHP.
I hope I could help you!
PHP extension functions and/or classes that can be called from PHP scripts
https://www.php-cpp.com/documentation/functions
Simple Native wave file writer example:
https://www3.nd.edu/~dthain/courses/cse20211/fall2013/wavfile/
Disclaimer: I am very unfamiliar with PHP. The answers I have seen floating around Stack don't seem applicable to my situation. This could be due to my unfamiliarity.
I need to write to an existing array in a JSON file:
[
[
// data should be written to this array
],
[]
]
My PHP looks like so:
<?php
$ip = $_POST["ip"];
$likes = "../data/likes.json";
$fp = fopen($likes, "a");
fwrite($fp, json_encode($ip) . ", ");
fclose($fp);
?>
When the PHP runs it writes to the end of the file like so (as you'd expect):
[
[
],
[]
]"data",
How do I resolve my PHP to do so?
Open the file:
$filename = '../data/likes.json'
$fp = fopen($filename, 'r');
Then read the existing data structure into a variable:
$data = json_decode(fread($fp, filesize($filename)));
Add the data to the correct array entry:
$data[0][] = $ip;
Close and reopen the file with write privileges, so that we overwrite its contents:
fclose($fp);
$fp = fopen($filename, 'w');
And write the new JSON:
fwrite($fp, json_encode($data));
$ip = $_POST["ip"];
$likes = json_decode(file_get_contents("../data/likes.json"), true);
$likes[] = $ip;
file_put_contents("../data/likes.json", json_encode($likes));
You can not fimply add record to file and get valid json jbject.
So idea of that code:
we read all from file, append array with new data, and rewrite file with new data
I use these two functions to encrypt / decrypt files :
private function encrypt_file($source,$destination,$passphrase,$stream=NULL) {
// $source can be a local file...
if($stream) {
$contents = $source;
// OR $source can be a stream if the third argument ($stream flag) exists.
}else{
$handle = fopen($source, "rb");
$contents = #fread($handle, filesize($source));
fclose($handle);
}
$iv = substr(md5("\x1B\x3C\x58".$passphrase, true), 0, 8);
$key = substr(md5("\x2D\xFC\xD8".$passphrase, true) . md5("\x2D\xFC\xD9".$passphrase, true), 0, 24);
$opts = array('iv'=>$iv, 'key'=>$key);
$fp = fopen($destination, 'wb') or die("Could not open file for writing.");
stream_filter_append($fp, 'mcrypt.tripledes', STREAM_FILTER_WRITE, $opts);
fwrite($fp, $contents) or die("Could not write to file.");
fclose($fp);
}
private function decrypt_file($file,$passphrase) {
$iv = substr(md5("\x1B\x3C\x58".$passphrase, true), 0, 8);
$key = substr(md5("\x2D\xFC\xD8".$passphrase, true) .
md5("\x2D\xFC\xD9".$passphrase, true), 0, 24);
$opts = array('iv'=>$iv, 'key'=>$key);
$fp = fopen($file, 'rb');
stream_filter_append($fp, 'mdecrypt.tripledes', STREAM_FILTER_READ, $opts);
return $fp;
}
It works perfectly for most files. But there is a problem with SVG or XML files in general. Decryption of an SVG file for example gives characters "NUL NUL ..." in the last line. As you can see in this picture:
You may have copied the code straight from the PHP documentation. But: As it says on the same page, there are several issues with this code. Basically using md5 for key derivation is far from optimal. See http://www.cryptofails.com/post/70059608390/php-documentation-woes for full description. This and encryption filters are deprecated (see same link), I would recommend abandoning this style of cryptography.
I would also recommend using some tested PHP crypto library like libsodium-php. This will also be integrated into php7 itself. (Source)
Back to topic: What you are seeing is the encryption padding. For the block cipher (in your case DES) to work, each chunk has to have the size given by the algorithm. Since most data doesn't care about chunk size, the algorithm has to apply some kind of padding.
When decrypting, you also receive the padded value. To get to your output value, you need to remove the padding afterwards. In your case this would be to trim the tailing NUL charachters. Its already in the documentation (thanks to #James for pointing this out)
$data = rtrim(stream_get_contents($fp)); //trims off null padding
I have this code:
libxml_use_internal_errors(TRUE);
$dom = new DOMDocument;
$dom->Load('/home/dom/public_html/cache/feed.xml');
$xmlor = '/home/dom/public_html/cache/feed.xml';
// open file and prepare mods
$fh = fopen($xmlor, 'r+');
$data = fread($fh, filesize($xmlor));
$dmca_claim_jpg = array( 'baduser_.jpg','user78.jpg' );
$dmca_claim_link = array( 'mydomain.com/baduser_','mydomain.com/user78' );
echo "Opening local XML for edit..." . PHP_EOL;
$new_data = str_replace("extdomain.com", "mydomain.com", $data);
$new_data2 = str_replace($dmca_claim_jpg, "DMCA.jpg", $data);
$new_data3 = str_replace($dmca_claim_link, "#", $data);
fclose($fh);
// run mods
$fh = fopen($xmlor, 'r+');
fwrite($fh, $new_data);
fwrite($fh, $new_data2);
fwrite($fh, $new_data3);
echo "Updated feed URL and DMCA claims in local XML..." . PHP_EOL;
fclose($fh);
It does not give any errors when executing but messes up the xml file by removing the first two lines (weird) when fwriting $new_data2 and $new_data3 to xml file.
It works fine writing only $new_data...
I think it has to do with the $dmca_claim_jpg/link arrays.
Parse XML using SimpleXML or DOMDocument it's cleaner and you have a standard OOP way of accessing nodes
I've been playing around with SSH and now I need to change a user's password via the PHP's ssh2,
Here's my code:
$stream = ssh2_exec($ssh, 'passwd test1234');
stream_set_blocking($stream, true);
$data = '';
while($buffer = fread($stream, 4096)) {
$data .= $buffer;
}
fclose($stream);
echo $data."<hr/>";
$stream = ssh2_exec($ssh, 'saulius123');
stream_set_blocking($stream, true);
$data = '';
while($buffer = fread($stream, 4096)) {
$data .= $buffer;
}
echo $data."<hr/>";
$stream = ssh2_exec($ssh, 'saulius123');
stream_set_blocking($stream, true);
$data = '';
while($buffer = fread($stream, 4096)) {
$data .= $buffer;
}
echo $data."<hr/>";
However this just make's my PHP script hang, any ideas?
ssh2_exec invokes the command; to send input, you'll need to write to the stream.
That is, $stream gives you access to standard input and standard output. So you'll need to write the password you wish to set using fwrite on $stream before trying to read back the output.
Since you've put the stream in blocking mode, passwd is awaiting your input (the password) at the same time your script is waiting for passwd. As a result, the script hangs.
Personally, I'd use phpseclib, a pure PHP SSH implementation. Example:
<?php
include('Net/SSH2.php');
$key = new Crypt_RSA();
//$key->setPassword('whatever');
$key->loadKey(file_get_contents('privatekey'));
$ssh = new Net_SSH2('www.domain.tld');
if (!$ssh->login('username', $key)) {
exit('Login Failed');
}
echo $ssh->read('username#username:~$');
$ssh->write("ls -la\n");
echo $ssh->read('username#username:~$');
?>
The biggest advantage of it over libssh2 is portability. We use Amazon Web Services were I work and sometimes we move over to new prod servers or dev servers and the most difficult part in setting them up is installing all the PECL extensions and what not.
phpseclib, in contrast, doesn't have any requirements.