Is it possible to make a POST from a file automatically?

Asked

Viewed 638 times

6

I’m using the Cron to run a PHP script. I want to do a file upload load test for my server and Cron is in charge of this (the server then sends to Amazon).

I was thinking of using the file-get-Contents to upload files to the server but how do I remove the information from the file? (filename, type, etc)

I saw this function in Javascript to make a POST and send automatically. I can do this in pure PHP?

  • You want to create a request via file_get_contents ou curl with a file upload together?

  • Yes, you’ve lost someone who understands me :)

3 answers

5

You can use AWS SDK for PHP - (http://aws.amazon.com/pt/sdk-for-php/ )!

There you can control and send files to Amazon through php, even if it is a script running on cron.

Now, to read the folder information, you can use the function opendir.

<?php
$dir = "/etc/php5/";

// Abre um diretorio conhecido, e faz a leitura de seu conteudo
if (is_dir($dir)) {
    if ($dh = opendir($dir)) {
        while (($file = readdir($dh)) !== false) {
            echo "filename: $file : filetype: " . filetype($dir . $file) . "\n";
        }
        closedir($dh);
    }
}
?>
  • I already have the REST API working, I lack to know how to make an automatic POST for PHP

2

By properly configuring the request header it is possible to send a file upload, both with the Curl or file_get_contents.

//post_false.php

<?php

define('MULTIPART_BOUNDARY', '---'.microtime(true));
define('FORM_FIELD', 'uploaded_file');

$header = 'Content-Type: multipart/form-data; boundary='.MULTIPART_BOUNDARY;


$filename = "c:\\teste.txt";
$file_contents = file_get_contents($filename); //carrega o arquivo falso

$content =  "--". MULTIPART_BOUNDARY ."\r\n".
        "Content-Disposition: form-data; name=\"". FORM_FIELD. "\"; filename=\"".basename($filename)."\"\r\n".
        "Content-Type: application/zip\r\n\r\n". //define o mime type

        $file_contents."\r\n";

//adiciona uma campo chamado foo com o valor bar.
$content .= "--".MULTIPART_BOUNDARY."\r\n".
        "Content-Disposition: form-data; name=\"foo\"\r\n\r\n"."bar\r\n";

// fecha o cabeçalho, é obrigatório usar dois traços a mais
$content .= "--".MULTIPART_BOUNDARY."--\r\n";


//Define o cabeçalho http
$context = stream_context_create(array(
        'http' => array(
                'method' => 'POST',
                'header' => $header,
                'content' => $content,
                'user_agent' => '?',
        )
));

$response = file_get_contents('http://teste/gravar.php', false, $context);
echo $response;

write php.

<?php
echo '<pre>';
print_r($_POST);
print_r($_FILES);
move_uploaded_file($_FILES['uploaded_file']['tmp_name'],
                  'caminho\nome_do_arquivo'. $_FILES['uploaded_file']['name']);

Reunions:

Upload a file using file_get_contents

How to post data in PHP using file_get_contents?

How does HTTP file upload work?

  • I didn’t quite understand the last part of $response = ....

  • @Jorgeb. serves to display the return of file_get_contents or if you need to validate the 'output how to search operação realizada com sucesso or erro: ....

  • Something’s passing me by... I’ve got one .php that is waiting for a POST and when receiving a POST if it is a file stores the data in the BD and sends it to Amazon.

  • Me making this line : $response = file_get_contents('http://teste/gravar.php', false, $context); prints me the contents of the save.php file

  • @Jorgeb. prints the source code or values of $_POST and $_FILES

  • @Jorgeb. in your example the address looks something like this: http://localhost/nome_projeto/gravar.php ? the php opening tag is the <?php

  • and so: file_get_contents('http://localhost/gravar.php');

Show 3 more comments

1


With the help of reply from @Math remembered the Curl to create the POST.

So I started creating my own script PHP(upload_test.php) where do I post my file(myfile_test.zip) to the gravar.php and keep the result in teste_results.txt.

upload_test.php:

$user_id = rand( 1, 10 );

$local_file = '/my_dir/myfile_test.zip';

$ch = curl_init();
curl_setopt( $ch, CURLOPT_HEADER, 0                              );
curl_setopt( $ch, CURLOPT_VERBOSE, 0                             );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true                   );
curl_setopt( $ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible;)" );
curl_setopt( $ch, CURLOPT_POST, true                             );
curl_setopt( $ch, CURLOPT_URL, 'http://localhost/gravar.php'     );

$post_array = array(
    "uploaded_file" => "@" . $local_file,
    "function" => "upload",
    "user_id" => "$user_id",
);
curl_setopt( $ch, CURLOPT_POSTFIELDS, $post_array );
$response = curl_exec( $ch );

$myfile = fopen( "/my_dir/teste_results.txt", "a+" ) or die( "Unable to open file!" );

$txt = "\n=> AUTO_UPLOAD " . date( 'Y-m-d H:i:s' ) . "\n";
fwrite( $myfile, $txt );

fwrite( $myfile, "Fez upload? = " . $response . "\n" );

fwrite( $myfile, "\n" );

fflush( $myfile );
fclose( $myfile );

Curl source

On the side of gravar.php get the file like this:

$uploaded = (object) $_FILES['uploaded_file'];

$file_name = $uploaded->name;
$file_tmp  = $uploaded->tmp_name;
$file_type = $uploaded->type;
$file_size = $uploaded->size;

Then just add the execution line to the Crontab and I can create the lines you want to test my server load.

At the command line:

$ crontab -e

Insert next row and save: (10 in 10 minutes)

*/10 * * * * /usr/bin/php /var/www/html/my_dir/upload_test.php

Crontab source

  • It’s even simpler, +1

Browser other questions tagged

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