Upload files working with PHP sockets

Asked

Viewed 151 times

2

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

After having done this chat, came the idea of uploading a file in the chat itself, but I do not know if it is possible, or better, how to work with files within a chat communicating via socket?

Source I used for chat creation:

https://phppot.com/php/simple-php-chat-using-websocket/

  • 1

    You can send the files by converting to Base64, so you send them as text and then decodes.

  • Or you can simply show in Base64 also rsrs

1 answer

2

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

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

To decode is very 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 on 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 normally shown on the screen.

Sources:

How to Convert an image to Base64 encoding?

Convert Base64 string to an image file?

  • Um, I hadn’t stopped to think about it, I found the idea interesting. What if I wanted to upload files in addition to image, such as going up a txt ? This alternative would work?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.