Asked  7 Months ago    Answers:  5   Viewed   34 times

I am developing mobile app which talks with server via PHP Webservice. This is my first time using PHP. I managed to upload data in to database. Now i need to send an image to store it in ftp server. For that i converted image->hex and sent from my app.

Server Side

I got the hex code but not sure how to convert it in to an image and store in in ftp server. I am really struggling here. I googled it but couldn't find exact one.

Any help is much appreciated.

 Answers

83

Convert the HEX string to binary:

$binary = pack("H*", $hex);

pack("H*", ...) is equivalent to hex2bin, which is available since PHP 5.4.

Write it to disk:

file_put_contents("file.png", $binary);
Wednesday, March 31, 2021
 
Niels
answered 7 Months ago
96

To convert from hex to decimal, there are many ways to do it in the shell or with an external program:

With bash:

$ echo $((16#FF))
255

with bc:

$ echo "ibase=16; FF" | bc
255

with perl:

$ perl -le 'print hex("FF");'
255

with printf :

$ printf "%dn" 0xFF
255

with python:

$ python -c 'print(int("FF", 16))'
255

with ruby:

$ ruby -e 'p "FF".to_i(16)'
255

with node.js:

$ nodejs <<< "console.log(parseInt('FF', 16))"
255

with rhino:

$ rhino<<EOF
print(parseInt('FF', 16))
EOF
...
255

with groovy:

$ groovy -e 'println Integer.parseInt("FF",16)'
255
Tuesday, June 15, 2021
 
khaverim
answered 4 Months ago
91

Normally, if you just use a prepared statement in place of a plain query, it's marginally slower since the query is prepared and executed in two steps instead of one. Prepared statements become faster only when you're preparing the statement and then executing it multiple times.

However, in this case you're using mysql_real_escape_string, which does a roundtrip to the database. Even worse, you're doing it inside a loop, so, executing it multiple times per query. So, in this case replacing all of those roundtrips with a single prepared statement is a win-win-win.

Regarding your last question, there's no reason you can't use the same query with a prepared statement as you would through the normal query parser (i.e. no reason to execute one version with an IN and the other with a bunch of ORs). The prepared statement can have IN (?, ?, ?), and then you just bind that number of parameters.

My advice would be to always use prepared statements. In cases where they add a marginal performance overhead, they're still worth it for the security (no SQL injection) and readability benefits. For sure, anytime you find yourself resorting to mysql_real_escape_string, you should use a prepared statement instead. (For simple one-off queries where there's no need to escape variable inputs, they aren't strictly necessary.)

Thursday, July 29, 2021
 
Eugenie
answered 3 Months ago
59

Since you didn't provide a handpoint link, here is some notes, following own tests!

I guess the issue comes from the wss part, php needs to retrieve the certificate first, so it can encrypt the data.

Your code should work just fine on a ws:// stream.

To connect to a regular ws:// stream, one can simply use fsockopen().

<?php
$fp = fsockopen("udp://echo.websocket.org", 13, $errno, $errstr);
if (!$fp) {
    echo "ERROR: $errno - $errstr<br />n";
} else {
    fwrite($fp, "n");
    echo "Connected!";
    echo fread($fp, 26);
    fclose($fp);
}

But to connect to a wss:// secure websocket stream, using php, without libraries, we need to create a tunnel first, by querying the public key with stream_socket_client.

This is a handshake mechanism. This can be done as follow.

Notice the first ssl:// call. This is the TLS 1.0 protocol.

<?php  
$sock = stream_socket_client("ssl://echo.websocket.org:443",$e,$n,30,STREAM_CLIENT_CONNECT,stream_context_create(null));
if(!$sock){
 echo"[$n]$e".PHP_EOL;
} else {
  fwrite($sock,"GET / HTTP/1.1rnHost: echo.websocket.orgrnAccept: */*rnConnection: UpgradernUpgrade: websocketrnSec-WebSocket-Version: 13rnSec-WebSocket-Key: ".rand(0,999)."rnrn");
  while(!feof($sock)){
    var_dump(fgets($sock,2048));
  }
}

The output should looks like:

string(44) "HTTP/1.1 101 Web Socket Protocol Handshake"
string(21) "Connection: Upgrade"
string(37) "Date: Thu, 12 Dec 2019 04:06:27 GMT"
string(52) "Sec-WebSocket-Accept: fTYwcEa6D9kJBtghptkz1e9CtBI="
string(25) "Server: Kaazing Gateway"
string(20) "Upgrade: websocket"

Same base code, another example, pulling data from Binance wss:// stream.

We can also use TLS 1.2, with a tls:// handshake instead. Works on most servers.

<?php
$sock = stream_socket_client("tls://stream.binance.com:9443",$error,$errnum,30,STREAM_CLIENT_CONNECT,stream_context_create(null));
if (!$sock) {
    echo "[$errnum] $error" . PHP_EOL;
} else {
  echo "Connected - Do NOT get rekt!" . PHP_EOL;
  fwrite($sock, "GET /stream?streams=btcusdt@kline_1m HTTP/1.1rnHost: stream.binance.com:9443rnAccept: */*rnConnection: UpgradernUpgrade: websocketrnSec-WebSocket-Version: 13rnSec-WebSocket-Key: ".rand(0,999)."rnrn");
  while (!feof($sock)) {
    var_dump(explode(",",fgets($sock, 512)));
  }
} 

Here is a way to retrieve only the ssl RSA public key of a remote handpoint, from php. Can be used to speed up later connections.

<?php
$opt = [
  "capture_peer_cert" => true,
  "capture_peer_cert_chain" => true
];
$a = stream_context_create(["ssl"=>$opt]);
$b = stream_socket_client("ssl://stream.binance.com:9443", $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $a);
$cont = stream_context_get_params($b);
$key = openssl_pkey_get_public($cont["options"]["ssl"]["peer_certificate"]);
$c = openssl_pkey_get_details($key);
var_dump($c["key"]);

Output something like:

-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhki(...)7aEsFtUNkwM5R5b1mpqzAwqHyvdamJx20bT6SS6
PYXSr/dv8ak1d4e2Q0nIa1O7l3w0bZZ4wnp5B8Z+tjPd1W8uaZoRO2iVkPMh2yPl
j0mmtUw1YlfDyutH/t4FlRCDiD4JjdREQGs381/+jbkdjl2SIb1IyNiCdAXA6zsq
xwIDAQAB
-----END PUBLIC KEY-----

There is possibly other quircks, to be sure, we need the main handpoint^. Would be glad to test that. Otherwise good luck, there is a big lack of documentation on the subject.

This is still a new born protocol (2011!). Best details are in the RFC specification:

The WebSocket protocol was standardized by the IETF as RFC 6455 in 2011

About the handshake, it must be initiated by a GET request.

The client will send a pretty standard HTTP request with headers that looks like this (the HTTP version must be 1.1 or greater, and the method must be GET)

Writing_WebSocket_servers#Client_handshake_request


In short:

If unencrypted WebSocket traffic flows through an explicit or a transparent proxy server without WebSockets support, the connection will likely fail.

WebSocket#Proxy_traversal

Transport_Layer_Security#Digital_certificates

Wednesday, August 4, 2021
 
ala
answered 3 Months ago
ala
100

It's fairly simple, documented here

The parameters:

1) $dst_image, a valid GD handle representing the image you want to copy INTO
2) $src_image, a valid GD Handle represending the image you're copying FROM

3) $dst_x - X offset in the destination image you want to place the resampled image into
4) $dst_y - Y offset, ditto

5) $src_x - X offset in the source image you want to start copying from
6) $src_y - Y offset, ditto

7) $dst_x - X width of the newly resampled image in $dst_image
8) $dst_y - Y width, ditto

9) $src_x - X width of the area to copy out of the $src_image
10) $src_y - Y width, ditto

So...

You've got a $src_image that's 800x536, and a $dst_image that's 75x75

       $width = 800                                $new_width = 75
+-----------------------+                        +----+
|                       |                        |    |
|                       |                        |    | $new_height = 75
|                       | $height = 536          +----+
|                       |
|                       |
+-----------------------+

Sounds like you want to take the middle chunk of the source image and make a thumbnail from that, right? This middle chunk should represent half the height & width of the original image, so you want:

$start_X = floor($width / 4); //  200
$width_Y = floor($height / 4); // 134

  200     400      200       
+-----------------------+
|     |          |      | 134
|-----+----------+------|
|     | This part|      | 268
|-----+----------+------|
|     |          |      | 134
+-----------------------+

$end_x = $start_X + (2 * $start_x) // 3 * $start_x = 600
$end_y = $start_Y + (2 * $start_y) // 3 * $start_y = 402

imagecopyresampled($src, $dst, 0, 0, $startX, $start_y, 75, 75, $end_x, $end_y);
                               a  b  c        d         e   f   g       h

a,b - start pasting the new image into the top-left of the destination image
c,d - start sucking pixels out of the original image at 200,134
e,f - make the resized image 75x75 (fill up the thumbnail)
g,h - stop copying pixels at 600x402 in the original image

Now, this is assuming that you want the thumbnail to be completely filled up. If you want the source image to be shrunk proportionally (so it has the same ration of height/width as the original, then you'll have to do some math to adjust the a,b and e,f parameters.

Thursday, August 5, 2021
 
SuperString
answered 3 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :