Uploading files working with sockets in PHP

2

A little while ago, I decided to explore and study some sockets to be worked on in PHP. So I got a good tutorial on the internet and I decided to create a very simple chat where I connect the server and two machines access the address to do the communication.

After having done this chat, the idea arose of uploading a file in the chat itself, but I do not know if it is possible, or rather, how can I work with files inside a chat making communication via socket? >

Source used for chat creation:

link

    
asked by anonymous 04.05.2018 / 13:24

1 answer

2

You can send the files using base64, see a simple example of conversion using php:

$image64 = base64_encode('caminho/da_img.jpg');

To decode it's pretty simple too:

function base64_to_jpeg($base64_string, $output_file) {
    $ifp = fopen( $output_file, 'wb' ); 
    $data = explode( ',', $base64_string );
    fwrite( $ifp, base64_decode( $data[ 1 ] ) );
    fclose( $ifp ); 
    return $output_file; 
}
base64_to_jpeg($image64, 'novo_caminho/da_img.jpg');

Or simply you can send as base64 and work with it in base64 without conversion, for example to show an image:

$base64 = 'data:image/' . $type . ';base64,' . base64_encode($image64);
...
<img src="<?php $base64 ?>"/>

So the image is shown on the screen normally.

Sources:

How to convert an image to base64 encoding?

Convert Base64 string to an image file?

    
04.05.2018 / 13:34