Php передать массив в другой файл
$arr = array( "A" , "B" , "C" );
unset( $arr [ 1 ] );
// now $arr = array( "A", "C" );
?>
Unlink is for deleting files.
Using null as the key when setting an array value is NOT the same as using empty [].
$null = null ;
$testArray = [];
$testArray [ $null ] = 1 ;
$testArray [ $null ] = 2 ;
$testArray [ $null ] = 3 ;
$testArray [ $null ] = 4 ;
var_dump ( $testArray );
?>
Output:
array(1) '' =>
int(4)
>
$testArray = [];
$testArray [ null ] = 1 ;
$testArray [ null ] = 2 ;
$testArray [ null ] = 3 ;
$testArray [ null ] = 4 ;
var_dump ( $testArray );
?>
Output:
array(1) '' =>
int(4)
>
$testArray = [];
$testArray [] = 1 ;
$testArray [] = 2 ;
$testArray [] = 3 ;
$testArray [] = 4 ;
var_dump ( $testArray );
?>
Output:
array(4) [0] =>
int(1)
[1] =>
int(2)
[2] =>
int(3)
[3] =>
int(4)
>
Made this function to delete elements in an array;
function array_del_elm ( $input_array , $del_indexes ) <
if ( is_array ( $del_indexes )) <
$indexes = $del_indexes ;
> elseif( is_string ( $del_indexes )) <
$indexes = explode ( $del_indexes , " " );
> elseif( is_numeric ( $del_indexes )) <
$indexes [ 0 ] = (integer) $del_indexes ;
> else return;
$del_indexes = null ;
$cur_index = 0 ;
if ( sort ( $indexes )) for( $i = 0 ; $i < count ( $input_array ); $i ++) <
if ( $i == $indexes [ $cur_index ]) <
$cur_index ++;
if ( $cur_index == count ( $indexes )) return $output_array ;
continue;
>
$output_array [] = $input_array [ $i ];
>
return $output_array ;
>
?>
but then i saw the methods of doing the same by Tyler Bannister & Paul, could see that theirs were faster, but had floors regarding deleting multiple elements thus support of several ways of giving parameters. I combined the two methods to this to this:
function array_del_elm ( $target_array , $del_indexes ) <
if ( is_array ( $del_indexes )) <
$indexes = $del_indexes ;
> elseif( is_string ( $del_indexes )) <
$indexes = explode ( $del_indexes , " " );
> elseif( is_numeric ( $del_indexes )) <
$indexes [ 0 ] = (integer) $del_indexes ;
> else return;
unset( $del_indexes );
for( $i = 0 ; $i < count ( $indexes ); $i ++) <
unset( $target_array [ $indexes [ $i ]]);
>
return $target_array ;
>
?>
Fast, compliant and functional ;)
If an array item is declared with key as NULL, array key will automatically be converted to empty string '', as follows:
// This will show empty string for key associated with "zero" value
var_dump ( array_keys ( $a ));
// Array elements are shown
reset ( $a );
while( key ( $a ) !== NULL )
echo key ( $a ) . ": " . current ( $a ) . "
" ; // PHP_EOL
next ( $a );
>
// Array elements are not shown
reset ( $a );
while( key ( $a ) != NULL ) // '' == null => no iteration will be executed
echo key ( $a ) . ": " . current ( $a ) . "
" ; // PHP_EOL
next ( $a );
>
Converting a linear array (like a mysql record set) into a tree, or multi-dimensional array can be a real bugbear. Capitalizing on references in PHP, we can 'stack' an array in one pass, using one loop, like this:
$node [ 'leaf' ][ 1 ][ 'title' ] = 'I am node one.' ;
$node [ 'leaf' ][ 2 ][ 'title' ] = 'I am node two.' ;
$node [ 'leaf' ][ 3 ][ 'title' ] = 'I am node three.' ;
$node [ 'leaf' ][ 4 ][ 'title' ] = 'I am node four.' ;
$node [ 'leaf' ][ 5 ][ 'title' ] = 'I am node five.' ;
echo '
' , print_r ( $node [ 'tree' ], TRUE ), '' ;
?>
Note that there's no parameter checking on the array value, but this is only to keep the function size small. One could easily a quick check in there to make sure the $a parameter was in fact an array.
A small correction to Endel Dreyer's PHP array to javascript array function. I just changed it to show keys correctly:
function array2js($array,$show_keys)
$dimensoes = array();
$valores = array();
$total = count ($array)-1;
$i=0;
foreach($array as $key=>$value) if (is_array($value)) $dimensoes[$i] = array2js($value,$show_keys);
if ($show_keys) $dimensoes[$i] = '"'.$key.'":'.$dimensoes[$i];
> else $dimensoes[$i] = '"'.addslashes($value).'"';
if ($show_keys) $dimensoes[$i] = '"'.$key.'":'.$dimensoes[$i];
>
if ($i==0) $dimensoes[$i] = ' if ($i==$total) $dimensoes[$i].= '>';
$i++;
>
return implode(',',$dimensoes);
>
output:
Array ( [0] => fileno [1] => Array ( [0] => uid [1] => uname ) [2] => topingid [3] => Array ( [0] => touid [1] => Array ( [0] => 1 [1] => 2 [2] => Array ( [0] => 3 [1] => 4 ) ) [2] => touname ) )
when I hope a function string2array($str), "spam2" suggest this. and It works well~~~hope this helps us, and add to the Array function list
New value can also be added to the array as shown below.
$theVariable["google"] = "http//google.com";
or
$theVariable["1"] = "http//google.com";
Another way to create a multidimensional array that looks a lot cleaner is to use json_decode. (Note that this probably adds a touch of overhead, but it sure does look nicer.) You can of course add as many levels and as much formatting as you'd like to the string you then decode. Don't forget that json requires " around values, not '!! (So, you can't enclose the json string with " and use ' inside the string.)
И я хочу использовать $array в другом файле php. Как мне это сделать?
Если вы нашли ответ на свой вопрос, отметьте, пожалуйста, ответ, который сработал для вас, как «принятый» :)
Клиент для URL-адресов, cURL, позволяет взаимодействовать с множеством различных серверов по множеству различных протоколов с синтаксисом URL.
Если вы все еще используете PHP 7, то эта статья для вас. В PHP 8, а именно в PHP 8.1, встроены некоторые очень востребованные функции, которые вам.
За последние годы в образовании произошла большая революция, и сегодня почти все учебные заведения делают упор на эксклюзивное управление учебным.
Ответы 4
Итак . "экспорт" - неправильный термин для этого, вы смотрите на область видимости переменных.
Проще говоря, что-то, объявленное вне функции, является «глобальным», а что-то, объявленное внутри функции, является частным для этой функции.
Вы хотите передать массив из одного файла в другой? Если у вас есть 3 файла (основной, include_num1 и include_num2), это просто;
Это даст что-то вроде:
Это связано с тем, что в этом примере массив объявлен в глобальной области, если вы сделали требование наоборот - это будет ошибкой, поскольку во время дампа var $ myarray не существует
Вы можете пропустить "главное", просто включив include_num2 из include_num1 .
Если вы хотите использовать глобальную переменную внутри функции, объявите функцию как обычную и используйте доступный global ;
Вы можете сохранить свой массив в базе данных, файле, cookie, сеансе .
Это зависит от того, что вы хотите сделать, и от необходимого уровня безопасности.
Самый простой способ:
А на другой странице:
Не лучший вариант, но работает.
При попытке перехода между несколькими файлами вы можете использовать классы вместо скриптов. Это помогает лучше поддерживать код.
Скажем, второй файл был SecondFile.class. Я мог бы создать его экземпляр, а затем передать массив в качестве параметра.
Или, если вам не нужно использовать второй файл ни для чего другого, используйте более короткий синтаксис:
Вы можете использовать СЕССИИ
а во втором файле вы можете использовать код ниже
Хорошо, во втором файле я буду использовать $ array = $ _SESSION ['array']; Вы можете мне сказать, как читать эту таблицу?
$ _SESSION не лучший вариант, так как он всегда будет там - лучше всего использовать один из параметров запроса, например $ _POST, $ _GET, $ _REQUEST, поскольку они очищаются между загрузками. Если вы оставите его и проверяете каждый раз (без изменений), он всегда будет одним и тем же, что может вызвать потенциальные проблемы, помимо того факта, что он будет забирать память и не имеет отношения к сеансу (и особенно потому, что каждый раз, когда он запускает его добавляется к переменной $ _SESSION без очистки переменной $array )
он может передать переменную с помощью сеанса, а затем отключить ее от сеанса POST, get не является хорошим решением, потому что $ array может достичь максимального предела публикации и получить !!
@tobyku не получил ответа
@davithuroyan я хочу вставить этот массив php в таблицу html. Я могу это сделать?
A simple trick that can help you to guess what diff/intersect or sort function does by name.
[suffix] assoc - additional index check. Compares both value and index.
Example: array_diff_assoc, array_intersect_assoc.
[suffix] key - index only check. Ignores value of array, compares only indexes.
Example: array_diff_key, array_intersect_key.
[suffix] **empty** - no "key" or "assoc" word in suffix. Compares values only. Ignores indexes of array.
Example: array_diff, array_intersect.
[prefix] u - will do comparison with user defined function. Letter u can be used twice in some functions (like array_udiff_uassoc), this means that you have to use 2 functions (one for value, one for index).
Example: array_udiff_uassoc, array_uintersect_assoc.
This also works with array sort functions:
[prefix] a - associative. Will preserve keys.
Example: arsort, asort.
[prefix] k - key sort. Will sort array by keys.
Example: uksort, ksort.
[prefix] r - reverse. Will sort array in reverse order.
Example: rsort, krsort.
[prefix] u - sort by user defined function (same as for diff/intersect).
Example: usort, uasort.
I need to take an element from the Array and change its position within the Array by moving the rest of the elements as required.
This is the function that does it. The first parameter is the working Array. The second is the position of the element to move and the third is the position where to move the element.
The function returns the modified Array.
function array_move_elem ( $array , $from , $to ) if ( $from == $to ) < return $array ; >
$c = count ( $array );
if (( $c > $from ) and ( $c > $to )) if ( $from < $to ) $f = $array [ $from ];
for ( $i = $from ; $i < $to ; $i ++) $array [ $i ] = $array [ $i + 1 ];
>
$array [ $to ] = $f ;
> else $f = $array [ $from ];
for ( $i = $from ; $i > $to ; $i --) $array [ $i ] = $array [ $i - 1 ];
>
$array [ $to ] = $f ;
>
?>
Examples:
$array = array( 'Cero' , 'Uno' , 'Dos' , 'Tres' , 'Cuatro' , 'Cinco' , 'Seis' , 'Siete' , 'Ocho' , 'Nueve' , 'Diez' );
$array = array_move_elem ( $array , 3 , 5 ); // Move element in position 3 to position 5.
print_r ( $array );
$array = array_move_elem ( $array , 5 , 3 ); // Move element in position 5 to position 3, leaving array as it was. ;)
print_r ( $array );
?>
Return:
Array ( [ 0 ] => Cero [ 1 ] => Uno [ 2 ] => Dos [ 3 ] => Cuatro [ 4 ] => Cinco [ 5 ] => Tres [ 6 ] => Seis [ 7 ] => Siete [ 8 ] => Ocho [ 9 ] => Nueve [ 10 ] => Diez )
Array ( [ 0 ] => Cero [ 1 ] => Uno [ 2 ] => Dos [ 3 ] => Tres [ 4 ] => Cuatro [ 5 ] => Cinco [ 6 ] => Seis [ 7 ] => Siete [ 8 ] => Ocho [ 9 ] => Nueve [ 10 ] => Diez )
?>
Big arrays use a lot of memory possibly resulting in memory limit errors. You can reduce memory usage on your script by destroying them as soon as you´re done with them. I was able to get over a few megabytes of memory by simply destroying some variables I didn´t use anymore.
You can view the memory usage/gain by using the funcion memory_get_usage(). Hope this helps!
Here is a function to find out the maximum depth of a multidimensional array.
// return depth of given array
// if Array is a string ArrayDepth() will return 0
// usage: int ArrayDepth(array Array)
function ArrayDepth ( $Array , $DepthCount =- 1 , $DepthArray =array()) $DepthCount ++;
if ( is_array ( $Array ))
foreach ( $Array as $Key => $Value )
$DepthArray []= ArrayDepth ( $Value , $DepthCount );
else
return $DepthCount ;
foreach( $DepthArray as $Value )
$Depth = $Value > $Depth ? $Value : $Depth ;
return $Depth ;
>
?>
Updated code of 'indioeuropeo' with option to input string-based keys.
FUNCTION:
function array_move_elem ( $array , $from , $to ) // return if non-numeric couldn't be found or from=to
if(! is_numeric ( $from )) if( array_search ( $from , array_keys ( $array ))!== FALSE ) $from = array_search ( $from , array_keys ( $array ));
>else return $array ;
>
>
$array_numeric_keys = array();
foreach( $array as $k => $v ) $array_numeric_keys [] = $k ;
>
if ( $from == $to ) < return $array ; >
$c = count ( $array_numeric_keys );
if (( $c > $from ) and ( $c > $to )) if ( $from < $to ) $f = $array_numeric_keys [ $from ];
for ( $i = $from ; $i < $to ; $i ++) $array_numeric_keys [ $i ] = $array_numeric_keys [ $i + 1 ];
>
$array_numeric_keys [ $to ] = $f ;
> else $f = $array_numeric_keys [ $from ];
for ( $i = $from ; $i > $to ; $i --) $array_numeric_keys [ $i ] = $array_numeric_keys [ $i - 1 ];
>
$array_numeric_keys [ $to ] = $f ;
>
>
$array_new = array();
foreach( $array_numeric_keys as $v ) $array_new [ $v ] = $array [ $v ];
>
return $array_new ;
>
?>
to convert JS array to JSON string: arr.toJSONString();
to convert JSON string to PHP array: json_decode($jsonString);
You can also stringify objects, numbers, etc.
Short function for making a recursive array copy while cloning objects on the way.
function arrayCopy ( array $array ) $result = array();
foreach( $array as $key => $val ) if( is_array ( $val ) ) $result [ $key ] = arrayCopy ( $val );
> elseif ( is_object ( $val ) ) $result [ $key ] = clone $val ;
> else $result [ $key ] = $val ;
>
>
return $result ;
>
?>
I was looking for an array aggregation function here and ended up writing this one.
Note: This implementation assumes that none of the fields you're aggregating on contain The '@' symbol.
function array_group_by ( $flds , $arr ) $groups = array();
foreach ( $arr as $rec ) $keys = array_map (function( $f ) use( $rec ) < return $rec [ $f ]; >, $flds );
$k = implode ( '@' , $keys );
if (isset( $groups [ $k ])) $groups [ $k ][] = $rec ;
> else $groups [ $k ] = array( $rec );
>
>
return $groups ;
>
If you need to flattern two-dismensional array with single values assoc subarrays, you could use this function:
function arrayFlatten ( $array ) <
$flattern = array();
foreach ( $array as $key => $value ) <
$new_key = array_keys ( $value );
$flattern [] = $value [ $new_key [ 0 ]];
>
return $flattern ;
>
?>
While PHP has well over three-score array functions, array_rotate is strangely missing as of PHP 5.3. Searching online offered several solutions, but the ones I found have defects such as inefficiently looping through the array or ignoring keys.
The following array_rotate() function uses array_merge and array_shift to reliably rotate an array forwards or backwards, preserving keys. If you know you can trust your $array to be an array and $shift to be between 0 and the length of your array, you can skip the function definition and use just the return expression in your code.
function array_rotate ( $array , $shift ) if(! is_array ( $array ) || ! is_numeric ( $shift )) if(! is_array ( $array )) error_log ( __FUNCTION__ . ' expects first argument to be array; ' . gettype ( $array ). ' received.' );
if(! is_numeric ( $shift )) error_log ( __FUNCTION__ . ' expects second argument to be numeric; ' . gettype ( $shift ). " ` $shift ` received." );
return $array ;
>
$shift %= count ( $array ); //we won't try to shift more than one array length
if( $shift < 0 ) $shift += count ( $array ); //handle negative shifts as positive
return array_merge ( array_slice ( $array , $shift , NULL , true ), array_slice ( $array , 0 , $shift , true ));
>
?>
A few simple tests:
$array =array( "foo" => 1 , "bar" => 2 , "baz" => 3 , 4 , 5 );
print_r ( array_rotate ( $array , 2 ));
print_r ( array_rotate ( $array , - 2 ));
print_r ( array_rotate ( $array , count ( $array )));
print_r ( array_rotate ( $array , "4" ));
print_r ( array_rotate ( $array , - 9 ));
?>
/*to change an index without rewriting the whole table and leave at the same place.
*/
function change_index (& $tableau , $old_key , $new_key ) $changed = FALSE ;
$temp = 0 ;
foreach ( $tableau as $key => $value ) switch ( $changed ) case FALSE :
//creates the new key and deletes the old
if ( $key == $old_key ) $tableau [ $new_key ] = $tableau [ $old_key ];
unset( $tableau [ $old_key ]);
$changed = TRUE ;
>
break;
case TRUE :
//moves following keys
if ( $key != $new_key ) $temp = $tableau [ $key ];
unset( $tableau [ $key ]);
$tableau [ $key ] = $temp ;
break;
>
else < $changed = FALSE ;>//stop
>
>
array_values ( $tableau ); //free_memory
>
//Result :
$tableau = array( 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 );
$res = print_r ( $tableau , TRUE );
$longueur = strlen ( $res ) - 1 ;
echo "Old array :\n" . substr ( $res , 8 , $longueur ) . "\n" ;
change_index ( $tableau , 2 , 'number 2' );
$res = print_r ( $tableau , TRUE );
$longueur = strlen ( $res ) - 10 ;
echo "New array :\n" . substr ( $res , 8 , $longueur ) . "\n" ;
Function to pretty print arrays and objects. Detects object recursion and allows setting a maximum depth. Based on arraytostring and u_print_r from the print_r function notes. Should be called like so:
egvaluetostring ( $value ) //no max depth, or
egvaluetostring ( $value , $max_depth ) //max depth set
function egvaluetostring ( $value , $max_depth , $key = NULL , $depth = 0 , $refChain = array()) <
if( $depth > 0 )
$tab = str_repeat ( "\t" , $depth );
$text .= $tab . ( $key !== NULL ? $key . " => " : "" );
if ( is_array ( $value ) || is_object ( $value )) <
$recursion = FALSE ;
if ( is_object ( $value )) <
foreach ( $refChain as $refVal ) <
if ( $refVal === $value ) <
$recursion = TRUE ;
break;
>
>
array_push ( $refChain , $value );
>
$text .= ( is_array ( $value ) ? "array" : "object" ) . " ( " ;
if ( $recursion ) <
$text .= "*RECURSION* " ;
>
elseif (isset( $max_depth ) && $depth >= $max_depth ) <
$text .= "*MAX DEPTH REACHED* " ;
>
else <
if (!empty( $value )) <
$text .= "\n" ;
foreach ( $value as $child_key => $child_value ) <
$text .= egvaluetostring ( $child_value , $max_depth , ( is_array ( $value ) ? "[" : "" ) . $child_key . ( is_array ( $value ) ? "]" : "" ), $depth + 1 , $refChain ) . ",\n" ;
>
$text .= "\n" . $tab ;
>
>
if ( is_object ( $value )) <
array_pop ( $refChain );
>
>
else <
$text .= " $value " ;
>
Функция идентична последовательным успешным вызовам функций fopen() , fwrite() и fclose() .
Если filename не существует, файл будет создан. Иначе, существующий файл будет перезаписан, за исключением случая, если указан флаг FILE_APPEND .
Примеры
$file = 'people.txt' ;
// Открываем файл для получения существующего содержимого
$current = file_get_contents ( $file );
// Добавляем нового человека в файл
$current .= "John Smith\n" ;
// Пишем содержимое обратно в файл
file_put_contents ( $file , $current );
?>?php
$file = 'people.txt' ;
// Новый человек, которого нужно добавить в файл
$person = "John Smith\n" ;
// Пишем содержимое в файл,
// используя флаг FILE_APPEND для дописывания содержимого в конец файла
// и флаг LOCK_EX для предотвращения записи данного файла кем-нибудь другим в данное время
file_put_contents ( $file , $person , FILE_APPEND | LOCK_EX );
?>?php
Примечания
Замечание: Эта функция безопасна для обработки данных в двоичной форме.
Для этой функции вы можете использовать URL в качестве имени файла, если была включена опция fopen wrappers. Смотрите более подробную информацию об определении имени файла в описании функции fopen() . Смотрите также список поддерживаемых обёрток URL, их возможности, замечания по использованию и список предопределённых констант в разделе Поддерживаемые протоколы и обёртки.
Возвращаемые значения
Функция возвращает количество записанных байт в файл, или false в случае возникновения ошибки.
Эта функция может возвращать как логическое значение false , так и значение не типа boolean, которое приводится к false . За более подробной информацией обратитесь к разделу Булев тип. Используйте оператор === для проверки значения, возвращаемого этой функцией.
Список параметров
Путь к записываемому файлу.
Записываемые данные. Может быть типа string , array или ресурсом потока.
Если 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 | Получить эксклюзивную блокировку на файл на время записи. Другими словами, между вызовами fopen() и fwrite() произойдёт вызов функции flock() . Это не одно и то же, что вызов fopen() с флагом "x". |
Корректный ресурс контекста, созданный с помощью функции stream_context_create() .
Смотрите также
- fopen() - Открывает файл или URL
- fwrite() - Бинарно-безопасная запись в файл
- file_get_contents() - Читает содержимое файла в строку
- stream_context_create() - Создаёт контекст потока
User Contributed Notes 37 notes
File put contents fails if you try to put a file in a directory that doesn't exist. This creates the directory.
function file_force_contents ( $dir , $contents ) $parts = explode ( '/' , $dir );
$file = array_pop ( $parts );
$dir = '' ;
foreach( $parts as $part )
if(! is_dir ( $dir .= "/ $part " )) mkdir ( $dir );
file_put_contents ( " $dir / $file " , $contents );
>
?>
It should be obvious that this should only be used if you're making one write, if you are writing multiple times to the same file you should handle it yourself with fopen and fwrite, the fclose when you are done writing.
file_put_contents() for 1,000,000 writes - average of 3 benchmarks:
real 0m3.932s
user 0m2.487s
sys 0m1.437s
fopen() fwrite() for 1,000,000 writes, fclose() - average of 3 benchmarks:
real 0m2.265s
user 0m1.819s
sys 0m0.445s
function file_force_contents ( $fullPath , $contents , $flags = 0 ) $parts = explode ( '/' , $fullPath );
array_pop ( $parts );
$dir = implode ( '/' , $parts );
if( ! is_dir ( $dir ) )
mkdir ( $dir , 0777 , true );
file_put_contents ( $fullPath , $contents , $flags );
>
file_force_contents ( ROOT . '/newpath/file.txt' , 'message' , LOCK_EX );
?>
Please note that when saving using an FTP host, an additional stream context must be passed through telling PHP to overwrite the file.
/* set the FTP hostname */
$user = "test" ;
$pass = "myFTP" ;
$host = "example.com" ;
$file = "test.txt" ;
$hostname = $user . ":" . $pass . "@" . $host . "/" . $file ;
/* the file content */
$content = "this is just a test." ;
/* create a stream context telling PHP to overwrite the file */
$options = array( 'ftp' => array( 'overwrite' => true ));
$stream = stream_context_create ( $options );
/* and finally, put the contents */
file_put_contents ( $hostname , $content , 0 , $stream );
?>
It's important to understand that LOCK_EX will not prevent reading the file unless you also explicitly acquire a read lock (shared locked) with the PHP 'flock' function.
i.e. in concurrent scenarios file_get_contents may return empty if you don't wrap it like this:
$myfile = fopen ( 'test.txt' , 'rt' );
flock ( $myfile , LOCK_SH );
$read = file_get_contents ( 'test.txt' );
fclose ( $myfile );
?>
If you have code that does a file_get_contents on a file, changes the string, then re-saves using file_put_contents, you better be sure to do this correctly or your file will randomly wipe itself out.
Make sure not to corrupt anything in case of failure.
function file_put_contents_atomically ( $filename , $data , $flags = 0 , $context = null ) if ( file_put_contents ( $filename . "~" , $data , $flags , $context ) === strlen ( $contents )) return rename ( $filename . "~" , $filename , $context );
>
@ unlink ( $filename . "~" , $context );
return FALSE ;
>
This functionality is now implemented in the PEAR package PHP_Compat.
More information about using this function without upgrading your version of PHP can be found on the below link:
It's worth noting that you must make sure to use the correct path when working with this function. I was using it to help with logging in an error handler and sometimes it would work - while other times it wouldn't. In the end it was because sometimes it was called from different paths resulting in a failure to write to the log file.
__DIR__ is your friend.
File put contents fails if you try to put a file in a directory that doesn't exist. This function creates the directory.
file_force_contents ( 'test1.txt' , 'test1 content' ); // test1.txt created
file_force_contents ( 'test2/test2.txt' , 'test2 content' );
// test2/test2.txt created "test2" folder.
file_force_contents ( '~/test3/test3.txt' , 'test3 content' );
// /path/to/user/directory/test3/test3.txt created "test3" folder in user directory (check on linux "ll ~/ | grep test3").
?>
In reply to the previous note:
If you want to emulate this function in PHP4, you need to return the bytes written as well as support for arrays, flags.
I can only figure out the FILE_APPEND flag and array support. If I could figure out "resource context" and the other flags, I would include those too.
define('FILE_APPEND', 1);
function file_put_contents($n, $d, $flag = false) $mode = ($flag == FILE_APPEND || strtoupper($flag) == 'FILE_APPEND') ? 'a' : 'w';
$f = @fopen($n, $mode);
if ($f === false) return 0;
> else if (is_array($d)) $d = implode($d);
$bytes_written = fwrite($f, $d);
fclose($f);
return $bytes_written;
>
>
To upload file from your localhost to any FTP server.
pease note 'ftp_chdir' has been used instead of putting direct remote file path. in ftp_put . remoth file should be only file name
$host = '*****' ;
$usr = '*****' ;
$pwd = '**********' ;
$local_file = './orderXML/order200.xml' ;
$ftp_path = 'order200.xml' ;
$conn_id = ftp_connect ( $host , 21 ) or die ( "Cannot connect to host" );
ftp_pasv ( $resource , true );
ftp_login ( $conn_id , $usr , $pwd ) or die( "Cannot login" );
// perform file upload
ftp_chdir ( $conn_id , '/public_html/abc/' );
$upload = ftp_put ( $conn_id , $ftp_path , $local_file , FTP_ASCII );
if( $upload ) < $ftpsucc = 1 ; >else < $ftpsucc = 0 ; >
// check upload status:
print (! $upload ) ? 'Cannot upload' : 'Upload complete' ;
print "\n" ;
// close the FTP stream
ftp_close ( $conn_id );
?>
A more simplified version of the method that creates subdirectories:
function path_put_contents($filePath, $contents, $flags = 0)
if (! is_dir($dir = implode('/', explode('/', $filePath, -1))))
mkdir($dir, 0777, true);
file_put_contents($filePath, $contents, $flags);
>
I suggest to expand file_force_contents() function of TrentTompkins at gmail dot com by adding verification if patch is like: "../foo/bar/file"
if (strpos($dir, "../") === 0)
$dir = str_replace("..", substr(__DIR__, 0, strrpos(__DIR__, "/")), $dir);
file_put_contents does not issue an error message if file name is incorrect(for example has improper symbols on the end of it /n,/t)
that is why use trim() for file name.
$name=trim($name);
file_put_contents($name,$content);
I had some troubles using file_put_contents with an absolute but no canonicalized path (eg. w:/htdocs/pri/../test/log.txt): on windows environment php was unable to create the file also using the realpath function .
I had to use fopen and frwite functions to write the data.
I wrote this script implementing the file_put_contents() and file_get_contents() functions to be compatible with both php4.* and php 5.*. It is a PHP Command line interface script which searches and replaces a specific word recursively through all files in the supplied directory hierarchy.
Usage from a Linux command line: ./scriptname specifieddirectory searchString replaceString
if( $argc != 4 )
echo "This command replaces a search string with a replacement string\n for the contents of all files in a directory hierachy\n" ;
echo "command usage: $argv [ 0 ] directory searchString replaceString\n" ;
echo "\n" ;
exit;
>
?>
if (! function_exists ( 'file_put_contents' )) function file_put_contents ( $filename , $data ) $f = @ fopen ( $filename , 'w' );
if (! $f ) return false ;
> else $bytes = fwrite ( $f , $data );
fclose ( $f );
return $bytes ;
>
>
>
function get_file_contents ( $filename )
/* Returns the contents of file name passed
*/
if (! function_exists ( 'file_get_contents' ))
$fhandle = fopen ( $filename , "r" );
$fcontents = fread ( $fhandle , filesize ( $filename ));
fclose ( $fhandle );
>
else
$fcontents = file_get_contents ( $filename );
>
return $fcontents ;
>
?>
function openFileSearchAndReplace ( $parentDirectory , $searchFor , $replaceWith )
//echo "debug here- line 1a\n";
//echo "$parentDirectory\n";
//echo "$searchFor\n";
//echo "$replaceWith\n";
if ( $handle = opendir ( " $parentDirectory " )) while ( false !== ( $file = readdir ( $handle ))) if (( $file != "." && $file != ".." ) && ! is_dir ( $file )) chdir ( " $parentDirectory " ); //to make sure you are always in right directory
// echo "$file\n";
$holdcontents = file_get_contents ( $file );
$holdcontents2 = str_replace ( $searchFor , $replaceWith , $holdcontents );
file_put_contents ( $file , $holdcontents2 );
// echo "debug here- line 1\n";
// echo "$file\n";
>
if( is_dir ( $file ) && ( $file != "." && $file != ".." ))
$holdpwd = getcwd ();
//echo "holdpwd = $holdpwd \n";
$newdir = " $holdpwd " . "/ $file " ;
//echo "newdir = $newdir \n"; //for recursive call
openFileSearchAndReplace ( $newdir , $searchFor , $replaceWith );
//echo "debug here- line 2\n";
//echo "$file\n";
>
>
closedir ( $handle );
>
>
$parentDirectory2 = $argv [ 1 ];
$searchFor2 = $argv [ 2 ];
$replaceWith2 = $argv [ 3 ];
//Please do not edit below to keep the rights to this script
//Free license, if contents below this line is not edited
echo "REPLACED\n' $searchFor2 ' with ' $replaceWith2 ' recursively through directory listed below\nFor all files that current user has write permissions for\nDIRECTORY: ' $parentDirectory2 '\n" ;
echo "command written by Kolapo Akande :) all rights reserved :)\n" ;
$holdpwd = getcwd ();
//echo "$holdpwd\n";
chdir ( $parentDirectory2 );
openFileSearchAndReplace ( $parentDirectory2 , $searchFor2 , $replaceWith2 );
exit;
?>
Например, определим следующий файл users.php :
В данном случае мы предполагаем, что параметр "users", который передается в запросе типа GET, будет представлять массив. И соответствено мы сможем получить из него данные.
Чтобы передать массив этому скрипту, обратимся к нему со следующим запросом:
Чтобы определить параметр строки запроса как массив, после названия параметра указываются квадраные скобки []. Затем мы можем присвоить некоторое значение: users[]=Tom . И сколько раз подобным образом будет присвоено значений, столько значений и будет в массиве. Все значения, как и обычно, отделяются амперсандом. Так, в данном случае в массив передаются три значения.
Подобным образом мы можем отправлять данные в запросе POST из формы. Например, определим следующий скрипт:
Как известно, название ключа передаваемых на сервер данных соответствует значению атрибута name у элемента формы. И чтобы указать, что какое-то поле ввода будет поставлять значение для массива, у атрибут name поля ввода в качестве значения принимает название массива с квадратными скобками:
Соответственно, сколько полей ввода с одним и тем же именем массива мы укажем, столько значений мы сможем передать на сервер. Так, в данном случае на сервер передается три значения в массиве users:
Причем данный принцип применяется и к другим типам полей ввода формы html.
При этом в примерах выше передавался обычный массив, каждый элемент которого в качестве ключа имеет числовой индекс. Соотвенно, используя индекс, мы можем получить определенный элемент массива:
Но также мы можем в элементах формы явным образом указать ключи:
Например, первое поле добавляет в массив элемент с ключом "first"
Поэтому на сервере мы можем с помощью данного ключа получить соответствующий элемент:
Читайте также: