Php echo input type file

PHP File Upload

However, with ease comes danger, so always be careful when allowing file uploads!

Configure The «php.ini» File

First, ensure that PHP is configured to allow file uploads.

In your «php.ini» file, search for the file_uploads directive, and set it to On:

Create The HTML Form

Next, create an HTML form that allow users to choose the image file they want to upload:

Some rules to follow for the HTML form above:

  • Make sure that the form uses method=»post»
  • The form also needs the following attribute: enctype=»multipart/form-data». It specifies which content-type to use when submitting the form

Without the requirements above, the file upload will not work.

  • The type=»file» attribute of the tag shows the input field as a file-select control, with a «Browse» button next to the input control

The form above sends data to a file called «upload.php», which we will create next.

Create The Upload File PHP Script

The «upload.php» file contains the code for uploading a file:

$target_dir = «uploads/»;
$target_file = $target_dir . basename($_FILES[«fileToUpload»][«name»]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST[«submit»])) $check = getimagesize($_FILES[«fileToUpload»][«tmp_name»]);
if($check !== false) echo «File is an image — » . $check[«mime»] . «.»;
$uploadOk = 1;
> else echo «File is not an image.»;
$uploadOk = 0;
>
>
?>

  • $target_dir = «uploads/» — specifies the directory where the file is going to be placed
  • $target_file specifies the path of the file to be uploaded
  • $uploadOk=1 is not used yet (will be used later)
  • $imageFileType holds the file extension of the file (in lower case)
  • Next, check if the image file is an actual image or a fake image

Note: You will need to create a new directory called «uploads» in the directory where «upload.php» file resides. The uploaded files will be saved there.

Check if File Already Exists

Now we can add some restrictions.

First, we will check if the file already exists in the «uploads» folder. If it does, an error message is displayed, and $uploadOk is set to 0:

// Check if file already exists
if (file_exists($target_file)) echo «Sorry, file already exists.»;
$uploadOk = 0;
>

Читайте также:  Как определить регистр буквы python

Limit File Size

The file input field in our HTML form above is named «fileToUpload».

Now, we want to check the size of the file. If the file is larger than 500KB, an error message is displayed, and $uploadOk is set to 0:

// Check file size
if ($_FILES[«fileToUpload»][«size»] > 500000) echo «Sorry, your file is too large.»;
$uploadOk = 0;
>

Limit File Type

The code below only allows users to upload JPG, JPEG, PNG, and GIF files. All other file types gives an error message before setting $uploadOk to 0:

Complete Upload File PHP Script

The complete «upload.php» file now looks like this:

$target_dir = «uploads/»;
$target_file = $target_dir . basename($_FILES[«fileToUpload»][«name»]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

// Check if image file is a actual image or fake image
if(isset($_POST[«submit»])) $check = getimagesize($_FILES[«fileToUpload»][«tmp_name»]);
if($check !== false) echo «File is an image — » . $check[«mime»] . «.»;
$uploadOk = 1;
> else echo «File is not an image.»;
$uploadOk = 0;
>
>

// Check if file already exists
if (file_exists($target_file)) echo «Sorry, file already exists.»;
$uploadOk = 0;
>

// Check file size
if ($_FILES[«fileToUpload»][«size»] > 500000) echo «Sorry, your file is too large.»;
$uploadOk = 0;
>

// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) echo «Sorry, your file was not uploaded.»;
// if everything is ok, try to upload file
> else if (move_uploaded_file($_FILES[«fileToUpload»][«tmp_name»], $target_file)) echo «The file «. htmlspecialchars( basename( $_FILES[«fileToUpload»][«name»])). » has been uploaded.»;
> else echo «Sorry, there was an error uploading your file.»;
>
>
?>

Complete PHP Filesystem Reference

For a complete reference of filesystem functions, go to our complete PHP Filesystem Reference.

Источник

Php – Echo the value inside html input type=file

I have a html form to upload files. After uploading if user need to edit the details the form is shown again with the data values populated from the database. How could i possibly show previous values of the uploaded files in the input type=file.

To be more specific this is my form:

 

Like i have echoed the ‘equipmentname’ in its textfield How could i possibly show the previous upload file value in its respective inputfield. Any suggestions are welcome. Thanks.

Best Solution

You can’t pre-populate a file form field.

A possible solution is to have an extra field or bit of html to «show» the value.
For example, assuming your file upload is an image and you are storing the path in your database, add an image element to show the image.

 
imagePath) > 0) < ?>image preview ?>

If the upload was a doc file, then you could show a thumbnail image that represents a doc file, there are plenty about.

Читайте также:  Python list all open files
Html – What are valid values for the id attribute in HTML

For HTML 4, the answer is technically:

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits (5), hyphens («-«), underscores («_»), colons («:»), and periods («.»).

HTML 5 is even more permissive, saying only that an id must contain at least one character and may not contain any space characters.

The id attribute is case sensitive in XHTML.

As a purely practical matter, you may want to avoid certain characters. Periods, colons and ‘#’ have special meaning in CSS selectors, so you will have to escape those characters using a backslash in CSS or a double backslash in a selector string passed to jQuery. Think about how often you will have to escape a character in your stylesheets or code before you go crazy with periods and colons in ids.

For example, the HTML declaration is valid. You can select that element in CSS as #first\.name and in jQuery like so: $(‘#first\\.name’). But if you forget the backslash, $(‘#first.name’) , you will have a perfectly valid selector looking for an element with id first and also having class name . This is a bug that is easy to overlook. You might be happier in the long run choosing the id first-name (a hyphen rather than a period), instead.

You can simplify your development tasks by strictly sticking to a naming convention. For example, if you limit yourself entirely to lower-case characters and always separate words with either hyphens or underscores (but not both, pick one and never use the other), then you have an easy-to-remember pattern. You will never wonder «was it firstName or FirstName ?» because you will always know that you should type first_name . Prefer camel case? Then limit yourself to that, no hyphens or underscores, and always, consistently use either upper-case or lower-case for the first character, don’t mix them.

A now very obscure problem was that at least one browser, Netscape 6, incorrectly treated id attribute values as case-sensitive. That meant that if you had typed id=»firstName» in your HTML (lower-case ‘f’) and #FirstName < color: red >in your CSS (upper-case ‘F’), that buggy browser would have failed to set the element’s color to red. At the time of this edit, April 2015, I hope you aren’t being asked to support Netscape 6. Consider this a historical footnote.

Читайте также:  Системами программирования являются java
Javascript – Retrieve the position (X,Y) of an HTML element
var rect = element.getBoundingClientRect(); console.log(rect.top, rect.right, rect.bottom, rect.left); 

Internet Explorer has supported this since as long as you are likely to care about and it was finally standardized in CSSOM Views. All other browsers adopted it a long time ago.

Some browsers also return height and width properties, though this is non-standard. If you’re worried about older browser compatibility, check this answer’s revisions for an optimised degrading implementation.

The values returned by element.getBoundingClientRect() are relative to the viewport. If you need it relative to another element, simply subtract one rectangle from the other:

var bodyRect = document.body.getBoundingClientRect(), elemRect = element.getBoundingClientRect(), offset = elemRect.top - bodyRect.top; alert('Element is ' + offset + ' vertical pixels from '); 
Related Question

Источник

Работа с MIME-типами в PHP

«Internet Media Types» или «Медиа типы» — является стандартом RFC 6838, который описывает формат файла. Причем браузеры используют MIME-типы в качестве основного критерия, не воспринимая расширения файлов.

MIME-тип состоит из типа и подтипа — двух значений разделённых « / », без использования пробелов и в нижнем регистре, например HTML страница:

Полный список MIME типов можно посмотреть тут.

К медиа типу может быть добавлен параметр для указания дополнительных деталей (например кодировка):

Как узнать MIME-тип загруженного файла

При загрузке файла через форму, MIME-тип файла доступен в массиве $_FILES , например:

Для определения MIME уже загруженного файла существует PHP-функция mime_content_type().

echo mime_content_type(__DIR__ . '/image.png'); // image/png echo mime_content_type(__DIR__ . '/text.txt'); // text/plain

При работе с изображениями, MIME-тип можно получить с помощью функции getimagesize():

$filename = __DIR__ . '/image.png'; $info = getimagesize($filename); print_r($info);

Результат:

Array ( [0] => 221 [1] => 96 [2] => 3 [3] => width="221" height="96" [bits] => 8 [mime] => image/png )

Важно помнить что при проверке файлов нельзя полагаться только на проверку MIME, т.к. его значение может быть скомпрометировано. Поэтому нужно проводить более детальную проверку (например по размеру изображения или его пересохранить в предполагаемом формате).

Отправка файлов из PHP

В PHP-скриптах, перед отправкой файлов клиенту, необходимо отправлять заголовок Content-Type , например файл XML:

$content = '. '; header("Content-Type: text/xml; charset=utf-8"); echo $content; exit();
$file = ROOT_DIR . '/market.zip'; header('Content-type: application/zip'); header('Content-Transfer-Encoding: Binary'); header('Content-length: ' . filesize($file)); header('Content-disposition: attachment; filename="' . basename($file) . '"'); readfile($file); exit();

Вывод изображения в зависимости от расширения файла:

$filename = __DIR__ . '/image.png'; $ext = mb_strtolower(mb_substr(mb_strrchr($filename, '.'), 1)); switch ($ext) < case 'png': header('Content-type: image/png'); break; case 'jpg': case 'jpeg': header('Content-type: image/jpeg'); break; case 'gif': header('Content-type: image/gif'); break; case 'wepb': header('Content-type: image/webp'); break; >readfile($filename); exit();

Источник

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