Upload Image

How to Upload Image in PHP and Store in Database and Folder -Easy Ste

Here in this tutorial, I will show you How to Upload Image in PHP and Store in MySQL Database and Server Folder?. There are soo many ways to store an image in a server but here in this tutorial, we use PHP to control the file systems and MySQL databases. We store images in the server directory and use the MySQL database to trace those images. At last, we use data from our database to display those images.

An image can also be stored in a database but this will increase server load as well as database size. So as possible, it is not a good idea to store images in a database. Where server is designed to server file so it will serve image faster than a database.

Complete Tutorial of How to Upload Image in PHP

To make it easier for you to flow the code, I have divided this coding into four parts.

  • Creating a database table
  • HTML form to upload an image.
  • Upload image to server using PHP and Store file name in the MySQL database.
  • Retrieve images from the database and display on the web page.

Create Database Table

To store the image file name we need to create a table in the database. Execute the following SQL and it will create an images table with some basic fields in the MySQL database.

CREATE TABLE images ( id int(11) NOT NULL AUTO_INCREMENT, file_name varchar(255) COLLATE utf8_unicode_ci NOT NULL, uploaded_on datetime NOT NULL, PRIMARY KEY (id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Files and folder we need here

config.php

By using config.php file we connect our web page to our database so that we can store our image details into the database table. And later on, retrieve that image to display it on our webpage.

Читайте также:  Python replace takes no keyword arguments

For a database connection, we need localhost name $dbHost , database user name $dbUsername , database password $dbPassword , and database name $dbName .

connect_error) < die("Connection failed: " . $db->connect_error); > ?>

index.php

In this file, we write a code to make form. From which our user can upload their image. And also display uploaded images into our web page.

      Select Image File to Upload:  
query("SELECT file_name FROM images ORDER BY uploaded_on DESC"); if($query->num_rows > 0)< while($row = $query->fetch_assoc()) < $imageURL = 'uploads/'.$row["file_name"]; ?> > ?>

upload image layout

The form coding from line 7 – 11 is used to send an image into upload.php file with a post method and we use enctype=»multipart/form-data» because we are sending an image.

The coding line from 14 – 26 is used to display an image in a webpage just below the form.

upload.php

This file is used to get an image receives an image detail which is sent from index.php file. Then store the image in uploads folder at last store image details in MySQL database table.

Go back'; // File upload path $targetDir = "uploads/"; $fileName = basename($_FILES["file"]["name"]); $targetFilePath = $targetDir . $fileName; $fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION); if(isset($_POST["submit"]) && !empty($_FILES["file"]["name"]))< // Allow certain file formats $allowTypes = array('jpg','png','jpeg','gif','pdf'); if (!file_exists($targetFilePath)) < if(in_array($fileType, $allowTypes))< // Upload file to server if(move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath))< // Insert image file name into database $insert = $db->query("INSERT into images (file_name, uploaded_on) VALUES ('".$fileName."', NOW())"); if($insert) < $statusMsg .$fileName. "has been uploaded successfully." . $backlink; >else < $statusMsg = "File upload failed, please try again." . $backlink; >>else < $statusMsg = "Sorry, there was an error uploading your file." . $backlink; >>else < $statusMsg = "Sorry, only JPG, JPEG, PNG, GIF, & PDF files are allowed to upload." . $backlink; >>else < $statusMsg .$fileName. "is already exist." . $backlink; > >else < $statusMsg = 'Please select a file to upload.' . $backlink; >// Display status message echo $statusMsg; ?>
  • $statusMsg is used to store status message either it is success or failure on upload. Then at the end, we display that message.
  • $backlink is used to go to the home page.
  • Line 13 if the statement means that the upload process will continue only if the user selects the image and then click the submit button.
  • In 15. We store the extension in an array which we allow our user to upload on the server.
  • 16. The upload process will continue only if the selected image did not already exist in an uploads folder.
  • 17. After that we check does a selected file of a user, contain any of this extension ( JPG, JPEG, PNG, GIF, & PDF ). If yes, we continue the upload process else we print an error message.
  • 19. If an image is successfully uploaded in uploads folder on the server then we store the image details by using code line 21 and 22.
  • This is how we upload image file into the server using PHP and MySQL Database.

You may also like this handpick tutorial for you.

Also, watch the video of this tutorial.

Источник

Php server image file

I think the way an array of attachments works is kind of cumbersome. Usually the PHP guys are right on the money, but this is just counter-intuitive. It should have been more like:

Array
(
[0] => Array
(
[name] => facepalm.jpg
[type] => image/jpeg
[tmp_name] => /tmp/phpn3FmFr
[error] => 0
[size] => 15476
)

Anyways, here is a fuller example than the sparce one in the documentation above:

foreach ( $_FILES [ «attachment» ][ «error» ] as $key => $error )
$tmp_name = $_FILES [ «attachment» ][ «tmp_name» ][ $key ];
if (! $tmp_name ) continue;

$name = basename ( $_FILES [ «attachment» ][ «name» ][ $key ]);

if ( $error == UPLOAD_ERR_OK )
if ( move_uploaded_file ( $tmp_name , «/tmp/» . $name ) )
$uploaded_array [] .= «Uploaded file ‘» . $name . «‘.
\n» ;
else
$errormsg .= «Could not move uploaded file ‘» . $tmp_name . «‘ to ‘» . $name . «‘
\n» ;
>
else $errormsg .= «Upload error. [» . $error . «] on file ‘» . $name . «‘
\n» ;
>
?>

Do not use Coreywelch or Daevid’s way, because their methods can handle only within two-dimensional structure. $_FILES can consist of any hierarchy, such as 3d or 4d structure.

The following example form breaks their codes:

As the solution, you should use PSR-7 based zendframework/zend-diactoros.

use Psr \ Http \ Message \ UploadedFileInterface ;
use Zend \ Diactoros \ ServerRequestFactory ;

$request = ServerRequestFactory :: fromGlobals ();

if ( $request -> getMethod () !== ‘POST’ ) http_response_code ( 405 );
exit( ‘Use POST method.’ );
>

$uploaded_files = $request -> getUploadedFiles ();

if (
!isset( $uploaded_files [ ‘files’ ][ ‘x’ ][ ‘y’ ][ ‘z’ ]) ||
! $uploaded_files [ ‘files’ ][ ‘x’ ][ ‘y’ ][ ‘z’ ] instanceof UploadedFileInterface
) http_response_code ( 400 );
exit( ‘Invalid request body.’ );
>

$file = $uploaded_files [ ‘files’ ][ ‘x’ ][ ‘y’ ][ ‘z’ ];

if ( $file -> getError () !== UPLOAD_ERR_OK ) http_response_code ( 400 );
exit( ‘File uploading failed.’ );
>

$file -> moveTo ( ‘/path/to/new/file’ );

The documentation doesn’t have any details about how the HTML array feature formats the $_FILES array.

Array
(
[document] => Array
(
[name] => sample-file.doc
[type] => application/msword
[tmp_name] => /tmp/path/phpVGCDAJ
[error] => 0
[size] => 0
)
)

Multi-files with HTML array feature —

Array
(
[documents] => Array
(
[name] => Array
(
[0] => sample-file.doc
[1] => sample-file.doc
)

[type] => Array
(
[0] => application/msword
[1] => application/msword
) [tmp_name] => Array
(
[0] => /tmp/path/phpVGCDAJ
[1] => /tmp/path/phpVGCDAJ
)

The problem occurs when you have a form that uses both single file and HTML array feature. The array isn’t normalized and tends to make coding for it really sloppy. I have included a nice method to normalize the $_FILES array.

function normalize_files_array ( $files = [])

foreach( $files as $index => $file )

if (! is_array ( $file [ ‘name’ ])) $normalized_array [ $index ][] = $file ;
continue;
>

foreach( $file [ ‘name’ ] as $idx => $name ) $normalized_array [ $index ][ $idx ] = [
‘name’ => $name ,
‘type’ => $file [ ‘type’ ][ $idx ],
‘tmp_name’ => $file [ ‘tmp_name’ ][ $idx ],
‘error’ => $file [ ‘error’ ][ $idx ],
‘size’ => $file [ ‘size’ ][ $idx ]
];
>

?>

The following is the output from the above method.

Array
(
[document] => Array
(
[0] => Array
(
[name] => sample-file.doc
[type] => application/msword
[tmp_name] => /tmp/path/phpVGCDAJ
[error] => 0
[size] => 0
)

[documents] => Array
(
[0] => Array
(
[name] => sample-file.doc
[type] => application/msword
[tmp_name] => /tmp/path/phpVGCDAJ
[error] => 0
[size] => 0
) [1] => Array
(
[name] => sample-file.doc
[type] => application/msword
[tmp_name] => /tmp/path/phpVGCDAJ
[error] => 0
[size] => 0
)

Источник

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