Php create file name from string

PHP Create File

Summary: in this tutorial, you will learn a couple of ways to create a new file in PHP.

Creating a file using the fopen() function

The fopen() function opens a file. It also creates a file if the file doesn’t exist. Here’s the syntax of the fopen() function:

fopen ( string $filename , string $mode , bool $use_include_path = false , resource $context = ? ) : resourceCode language: PHP (php)

To create a new file using the fopen() function, you specify the $filename and one of the following modes:

Mode File Pointer
‘w+’ At the beginning of the file
‘a’ At the end of the file
‘a+’ At the end of the file
‘x’ At the beginning of the file
‘x+’ At the beginning of the file
‘c’ At the beginning of the file
‘c+’ At the beginning of the file

Except for the ‘a’ and ‘a+’ , the file pointer is placed at the beginning of the file.

Читайте также:  Булевы переменные в javascript

If you want to create a binary file, you can append the character ‘b’ to the $mode argument. For example, the ‘wb+’ opens a binary file for writing.

The following example uses fopen() to create a new binary file and write some numbers to it:

 $numbers = [1, 2, 3, 4, 5]; $filename = 'numbers.dat'; $f = fopen($filename, 'wb'); if (!$f) < die('Error creating the file ' . $filename); > foreach ($numbers as $number) < fputs($f, $number); >fclose($f); Code language: HTML, XML (xml)
  • First, define an array of five numbers from 1 to 5.
  • Second, use the fopen() to create the numbers.dat file.
  • Third, use the fputs() function to write each number in the $numbers array to the file.
  • Finally, close the file using the fclose() function.

Creating a file using the file_put_contents() function

The file_put_contents() function writes data into a file. Here’s the syntax of the file_put_contents() function:

file_put_contents ( string $filename , mixed $data , int $flags = 0 , resource $context = ? ) : intCode language: PHP (php)

If the file specified by the $filename doesn’t exist, the function creates the file.

The file_put_contents() function is identical to calling the fopen() , fputs() , and fclose() functions successively to write data to a file.

The following example downloads a webpage using the file_get_contents() function and write HTML to a file:

 $url = 'https://www.php.net'; $html = file_get_contents($url); file_put_contents('home.html', $html);Code language: HTML, XML (xml)
  • First, download a webpage https://www.php.net using the file_get_contents() function.
  • Second, write the HTML to the home.html file using the file_put_contents() function

Summary

  • Use the fopen() function with one of the mode w , w+ , a , a+ , x , x+ , c , c+ to create a new file.
  • Use the file_put_contents() function to create a file and write data to it.
  • The file_put_contents() function is identical to calling fopen() , fputs() , and fclose() functions successively to write data to a file.

Источник

Php get file name from string php

this one is probably not as efficient as the strpos and substr combo mentioned above, but its fun: As i said. there are lots of string manipulation methods in php and you could do it many other ways. Solution 1: You can use this way Solution 2: 1.If you don’t want to type all the link path inside the «basename()» function, you can use: this will return the whole path — (example below) 2.THEN make use of the ‘baseline()’ function like this: and will return the desired file name as a string.

Get a filename from a string in PHP

You can use basename() this way

$filename = basename("/uploads/attachments/18/105/WordPress_3_Cookbook.pdf"); 

1.If you don’t want to type all the link path inside the «basename()» function, you can use:

this will return the whole path — (example below)

"/uploads/attachments/18/105/WordPress_3_Cookbook.pdf" 

2.THEN make use of the ‘baseline()’ function like this:

 echo basename($_SERVER['REQUEST_URI']); 

and will return the desired file name as a string.

 // the output will be : WordPress_3_Cookbook.pdf 

How to get file name from a path in PHP ?, The basename() function is an inbuilt function that returns the base name of a file if the path of the file is provided as a parameter to the

Extract part of file name

$pieces = explode('.', $filename); $morePieces = explode('-', $pieces[0]); $cityname = $morePieces[1]; 

Combine strpos() and substr() .

$filename = "location-cityName.xml"; $dash = strpos($filename, '-') + 1; $dot = strpos($filename, '.'); echo substr($filename, $dash, ($dot - $dash)); 

There are a few ways. this one is probably not as efficient as the strpos and substr combo mentioned above, but its fun:

$string = "location-cityName.xml"; list($location, $remainder) = explode("-", $string); list($cityName, $extension) = explode(".", $remainder); 

As i said. there are lots of string manipulation methods in php and you could do it many other ways.

PHP — How to get a file name from url string, To extract the query string, you want PHP_URL_QUERY , not PHP_URL_PATH . $x = «http://i.imgur.com/test.png?stuff»; parse_url(

Get file name from the string using php

, , , , '; // Here I replace the src with "src" and id with "id" $string = str_replace(['src', 'id'], ['"src"', '"id"'], $string); // Then I wrap all the string in brackets to convert the string to valid JSON string. $json = '[' . $string . ']'; // Finally I decode the JSON string into a PHP array. $data = json_decode($json); // Here I am going to save the images names. $images = []; // Here I itterate the json body entries and I push into the $images array // the image name foreach($data as $entry) < array_push($images, $entry->src); > // And here I just print it out, to make sure the output is the following: print_r($images); // OUTPUT: // Array // ( // [0] => brand.png // [1] => centpourcent.png // [2] => corsa.png // [3] => cta.png // [4] => neons.png // ) 

You can preg_match_all() use to get all file names.

$str = ', , , , '; $r = preg_match_all('~(?:src:")([^"]+)(?:")~',$str,$match); var_dump($match[1]) 
array(5) < [0]=>string(9) "brand.png" [1]=> string(16) "centpourcent.png" [2]=> string(9) "corsa.png" [3]=> string(7) "cta.png" [4]=> string(9) "neons.png" > 

If a valid JSON string is to be generated from the specified string, this can also be done with a regular expression. The algorithm also works without changes with keys other than ‘src’ and ‘id’.

$jsonStr = '['.preg_replace('~\w+(?=:)~','"$0"', $str).']'; 

PHP, get file name without file extension, $exploded_filepath = explode(«.», $filepath_or_URL); $extension = end($exploded_filepath); echo basename($filepath_or_URL, «.».$extension ); //

Php add string variable to the begining of file name before upload it [duplicate]

before upload no, but when you save it yes:

 $path = "../videos/"; $path .= $username.basename($_FILES['uploaded_file']['name']); 

Get file name from the string using php, You can preg_match_all() use to get all file names. $str = ‘,

Источник

PHP String Exercises: Extract the file name from the specified string

Write a PHP script to extract the file name from the following string.

Sample String : ‘www.example.com/public_html/index.php’

Pictorial Presentation:

PHP String Exercises: Extract the file name from the specified string

Sample Solution:

Flowchart: Extract the file name from the specified string

PHP Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource’s quiz.

Follow us on Facebook and Twitter for latest update.

PHP: Tips of the Day

Have a look at $_SERVER[‘REQUEST_URI’], i.e.

$actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

(Note that the double quoted string syntax is perfectly correct)

If you want to support both HTTP and HTTPS, you can use

$actual_link = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

Editor’s note: using this code has security implications. The client can set HTTP_HOST and REQUEST_URI to any arbitrary value it wants.

  • Weekly Trends
  • Java Basic Programming Exercises
  • SQL Subqueries
  • Adventureworks Database Exercises
  • C# Sharp Basic Exercises
  • SQL COUNT() with distinct
  • JavaScript String Exercises
  • JavaScript HTML Form Validation
  • Java Collection Exercises
  • SQL COUNT() function
  • SQL Inner Join
  • JavaScript functions Exercises
  • Python Tutorial
  • Python Array Exercises
  • SQL Cross Join
  • C# Sharp Array Exercises

We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook

Источник

Работа с именами файлов в PHP

Набор PHP функций для работы с путями и именами файлов.

Получить имя файла

echo basename('path/file.png'); // file.png

Имя файла без расширения

$info = pathinfo('path/file.png'); echo $info['filename']; // file /* или */ echo pathinfo('path/donut.png', PATHINFO_FILENAME); // file

Получить расширение файла

echo mb_strtolower(mb_substr(mb_strrchr('path/file.png', '.'), 1)); // png /* или */ echo pathinfo('path/file.png', PATHINFO_EXTENSION); // png

Заменить расширение файла

Заменить расширение .jpeg на .jpg:

$file_name = 'file.jpeg'; $file_new = preg_replace('/\.jpeg$/', '.jpg', $file_name); echo $file_new; // file.jpg

Заменить несколько расширений на одно (.jpg, .jpeg, .png на .webp):

$file_name = 'file.jpeg'; $file_new = preg_replace('/\.(jpg|jpeg|png)$/', '.webp', $file_name); echo $file_new; // file.webp

Дописать текст в конец названия файла

$info = pathinfo('path/file.png'); $name = $info['dirname'] . '/' . $info['filename'] . '-' . time() . '.' . $info['extension']; echo $name; // path/file-1610877618.png

Безопасное сохранение файла

Чтобы не затереть существующий файл на сервере можно применить данную функцию.

В функцию передаётся путь и имя файла, если на сервере уже существует такой файл, функция к концу файла приписывает префикс. Также если директория не существует, пытается её создать.

function safe_file($filename) < $dir = dirname($filename); if (!is_dir($dir)) < mkdir($dir, 0777, true); >$info = pathinfo($filename); $name = $dir . '/' . $info['filename']; $prefix = ''; $ext = (empty($info['extension'])) ? '' : '.' . $info['extension']; if (is_file($name . $ext)) < $i = 1; $prefix = '_' . $i; while (is_file($name . $prefix . $ext)) < $prefix = '_' . ++$i; >> return $name . $prefix . $ext; > // Если в директории есть файл log.txt, файл будет сохранен с названием log_1.txt file_put_contents(safe_file(__DIR__ . '/log.txt'), $text);

Источник

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