Php send string as file

Php – Send string as a file using curl and php

I know I can use this syntaxt to send a file using php, post and curl.

$post = array( "file_box"=>"@/path/to/myfile.jpg", ); curl_setopt($ch, CURLOPT_POSTFIELDS, $post); 

How can I take a string, build a temp file and send it using the exact same syntax ?

Update:
I would prefer using tmpfile() or php://memory so I don’t have to handle file creation.

Best Solution

You can create a file using tempnam in your temp directory:

$string = 'random string'; //Save string into temp file $file = tempnam(sys_get_temp_dir(), 'POST'); file_put_contents($file, $string); //Post file $post = array( "file_box"=>'@'.$file, ); curl_setopt($ch, CURLOPT_POSTFIELDS, $post); //do your cURL work here. //Remove the file unlink($file); 
How to send a header using a HTTP request through a cURL call
 -H/--header (HTTP) Extra header to use when getting a web page. You may specify any number of extra headers. Note that if you should add a custom header that has the same name as one of the internal ones curl would use, your externally set header will be used instead of the internal one. This allows you to make even trickier stuff than curl would normally do. You should not replace internally set headers without knowing perfectly well what you're doing. Remove an internal header by giving a replacement without content on the right side of the colon, as in: -H "Host:". curl will make sure that each header you add/replace get sent with the proper end of line marker, you should thus not add that as a part of the header content: do not add newlines or carriage returns they will only mess things up for you. See also the -A/--user-agent and -e/--referer options. This option can be used multiple times to add/replace/remove multi- ple headers. 

Example:

curl --header "X-MyHeader: 123" www.google.com 

You can see the request that curl sent by adding the -v option.

Читайте также:  Html img class size
Php – startsWith() and endsWith() functions in PHP

PHP 8.0 and higher

Since PHP 8.0 you can use the

Источник

Creating streams from strings in PHP

I’m in the process of writing an API that relies on (file-)streams to be passed around.

There are situations where a string instead needs to be used, and for these purposes the data: stream wrapper is used. Initially I thought it was only possible to encode the actual string in base64, which I didn’t like because of the added footprint.

 $string = "I should have really done some laundry tonight."; $stream = fopen('data://text/plain;base64,' . base64_encode($string),'r'); echo stream_get_contents($stream); ?> 

Quickly checking out the rfc, it turns out that ‘;base64’ can be omitted to just pass along the raw data, which makes a lot more sense in the context of PHP.

Thankfully, PHP gladly supports it:

 $string = "I tried, honestly!"; $stream = fopen('data://text/plain,' . $string,'r'); echo stream_get_contents($stream); ?> 

Update June 23th, 2013

Just in case anyone stumbles upon this, I would no longer recommend using the data uri for this purpose.

Since PHP 5.1 we have php://memory and php://temp . The former keeps the entire string into memory, and the latter automatically writes to a file as soon as the stream exceeds a certain amount of memory.

 $string = 'Some bad-ass string'; $stream = fopen('php://memory','r+'); fwrite($stream, $string); rewind($stream); echo stream_get_contents($stream); 

A bit more info can be found on php.net.

Looking for a CTO or senior developer for your next project? I’m looking for contracts or full-time gigs! Check out my resume or drop me a line! —>

Web mentions

Comments

Josh • Jan 30, 2009 My favorite usage of the data: wrapper is for raw uploaded csv data. If you let user’s cut-n-paste a csv for upload you can use the data: wrapper to fopen the POST data then fgetcsv() on it to save yourself from parsing it manually.

Michael Gauthier • Jan 30, 2009 Great tip, thanks! I might use this to simplify some code I have that works with either IPC pipes or strings.

aparimana • Jun 23, 2013 remember to urlencode() your $string before passing it to fopen — PHP will always urldecode(), to serve the data up, which will cause problems if your input data happens to contain sequences that look like URL encoded characters ( eg input string ‘this%26that’ will be output ‘this&that’)

Evert • Jun 23, 2013 I should really update this post, but I would _not_ recommend using the data:// url. Use php://memory and php://temp instead!

Nicholas Ruunu • Apr 23, 2017 Is it possible to write initial data to a read only stream with php://temp?

Markus • Nov 25, 2013 instead of base64_encode() in php which consumes a lot of php memory you should use stream_filter_append($fh, ‘convert.base64-encode’);
which is not limited by php-memory limits AFAIK

Jasmine Hegman • Jul 28, 2015 Thank you for this fine article w/ update! I know this is old and sort of minor but in your last code example you open the php://memory string with ‘r+’ and then write to it — I think that should be ‘w+’ :o)

Evert • Jul 28, 2015 r+ actually works too. Judging from the documentation is looks like the only difference is that w+ creates a new file if it doesn’t already exist, but that’s not really relevant here.

Jasmine Hegman • Jul 30, 2015 Oh you are so right, I don’t know what I was thinking! I guess my brain decided to pretend the + symbol was meaningless. :3

linoge • Jun 04, 2016 Thank you very much for the article, I was looking exactly for this, and it’s such a nice thing that you added the update c;

Hugo Franco de Campos • Nov 30, 2016 Is there any concern about keep large strings in memory using fopen? I’m sending a large csv string to a file storage and I have no idea if I should use memory, temp or anything else.

rinogo • Sep 02, 2017 Thanks for your short examples on this, especially for the 2013 update! Exactly what I was looking for.

Источник

file_put_contents

Функция идентична последовательным успешным вызовам функций fopen() , fwrite() и fclose() .

Если filename не существует, файл будет создан. Иначе, существующий файл будет перезаписан, за исключением случая, если указан флаг FILE_APPEND .

Список параметров

Путь к записываемому файлу.

Записываемые данные. Может быть string , array или ресурсом stream .

Если data является ресурсом stream , оставшийся буфер этого потока будет скопирован в указанный файл. Это похоже на использование функции stream_copy_to_stream() .

Также вы можете передать одномерный массив в качестве параметра data . Это будет эквивалентно вызову file_put_contents($filename, implode(», $array)).

Значением параметра flags может быть любая комбинация следующих флагов, соединенных бинарным оператором ИЛИ (|).

Доступные флаги

Флаг Описание
FILE_USE_INCLUDE_PATH Ищет filename в подключаемых директориях. Подробнее смотрите директиву include_path.
FILE_APPEND Если файл filename уже существует, данные будут дописаны в конец файла вместо того, чтобы его перезаписать.
LOCK_EX Получить эксклюзивную блокировку на файл на время записи.

Корректный ресурс контекста, созданный с помощью функции stream_context_create() .

Возвращаемые значения

Функция возвращает количество записанных байт в файл, или FALSE в случае ошибки.

Эта функция может возвращать как boolean FALSE , так и не-boolean значение, которое приводится к FALSE . За более подробной информацией обратитесь к разделу Булев тип. Используйте оператор === для проверки значения, возвращаемого этой функцией.

Примеры

Пример #1 Пример простого использования

$file = ‘people.txt’ ;
// Открываем файл для получения существующего содержимого
$current = file_get_contents ( $file );
// Добавляем нового человека в файл
$current .= «John Smith\n» ;
// Пишем содержимое обратно в файл
file_put_contents ( $file , $current );
?>

Пример #2 Использование флагов

$file = ‘people.txt’ ;
// Новый человек, которого нужно добавить в файл
$person = «John Smith\n» ;
// Пишем содержимое в файл,
// используя флаг FILE_APPEND flag для дописывания содержимого в конец файла
// и флаг LOCK_EX для предотвращения записи данного файла кем-нибудь другим в данное время
file_put_contents ( $file , $person , FILE_APPEND | LOCK_EX );
?>

Список изменений

Версия Описание
5.1.0 Добавлена поддержка LOCK_EX и возможность передачи потокового ресурса в параметр data

Примечания

Замечание: Эта функция безопасна для обработки данных в двоичной форме.

Для этой функции вы можете использовать URL в качестве имени файла, если была включена опция fopen wrappers. Смотрите более подробную информацию об определении имени файла в описании функции fopen() . Смотрите также список поддерживаемых оберток URL, их возможности, замечания по использованию и список предопределенных констант в Поддерживаемые протоколы и обработчики (wrappers).

Смотрите также

  • fopen() — Открывает файл или URL
  • fwrite() — Бинарно-безопасная запись в файл
  • file_get_contents() — Читает содержимое файла в строку
  • stream_context_create() — Создаёт контекст потока

Источник

Returning or Downloading Files with an HTTP Request

Learn how to force download files in PHP and how to generate a TXT, CSV, or JSON file on the fly from a string and send it to the browser.

The following code reads an image file and sends it to the web browser for download.

 $mimeType = mime_content_type($file_path . $file_name); $fileSize = filesize ($file_path . $file_name); header("Content-Type: $mimeType"); header("Content-Length: $fileSize"); header("Content-Disposition: attachment; filename=$file_name"); header('Expires: 0'); header('Cache-Control: must-revalidate'); header('Pragma: public'); readfile($file_path . $file_name); exit;

When a PHP script shall return a (downloadable) file instead of HTML, the correct HTTP headers have to be sent:

  • Content-Disposition for the (proposed) name of the file
  • Content-Length for the file size
  • Content-Type for the MIME type of the file

Cache-related headers:

  • Expires: 0 the date/time after which the response is considered stale. A stale cache entry may not normally be returned by a cache.
  • Cache-Control: must-revalidate : cache must not use the entry after it becomes stale to respond to a subsequent request without first revalidating it with the origin server.
  • Pregma: public cache setting for internet explorer.

The readfile() function opens a file and directly outputs its contents, so you don’t need to use the print or echo to output content.

Sending a String as a File

You can respond with a file that does not exist on the server, such as a TXT, CSV, or a JSON generated on the fly from a string:

Example: Sending a string as a text file:

Example: Sending a string as a JSON file:

'brainbell', 'email'=>'admin@brainbell.com']; $json = json_encode ( $array ); $file_name = 'info.json'; $mimeType = 'application/json'; $fileSize = strlen ( $json); header("Content-Type: $mimeType"); header("Content-Length: $fileSize"); header("Content-Disposition: attachment; filename=$file_name"); header('Expires: 0'); header('Cache-Control: must-revalidate'); header('Pragma: public'); echo $json; exit;

Working with Files in PHP:

Источник

Оцените статью