Text and image upload php

Php – Upload Text and Image with one form, storing path and text in database with PHP

I’ve been working on this code for the last week and its racking my brain. I’ve searched on forums high and low and can only find very little on this specific subject.

I want to use a form to upload Text and images. Images get uploaded to directory (upload/), while image path and text is INSERTed INTO database table (upgrade.Testimonials). The index, uploader php, and upload folder all exist at www.mywebsite.com/testimonials

UPON EXECUTING THE FORM I RECEIVE A «Connected to $ftp_server, for user $USERNAME SAVED
Stored in: upload/» BUT NO PHOTO IS UPLOADED AND THE PATH STORED IN DB HAS NO TITLE. BUT ALL OTHER INFORMATION IS SUBMITTED TO DATABASE FINE.

I’ve opened it the file_upload.php in TextWrangler and it doesn’t give me any errors. Hosting with Godaddy.

Other than NY major vulnerability to SQL Injection,
why am i not able to upload the images!?

Here is what I have so far, please help!

  mysql_select_db("$db_name")or die("cannot select DB"); $ftp_server = ""; $ftp_conn = ftp_connect($ftp_server) or die("Could not connect to $ftp_server"); // login with username and password $login_result = ftp_login($ftp_conn, $ftp_user, $ftp_pass); // check connection if ((!$ftp_conn) || (!$login_result)) < echo "FTP connection has failed!"; echo "Attempted to connect to $ftp_server for user $ftp_user"; exit; >else < echo "Connected to $ftp_server, for user $ftp_user"; >$Fname = $_POST['fname']; $Email = $_POST['email']; $Content = $_POST['content']; $filePath="http://www.mywebsite.com/testimonials/upload/" . $_FILES["file"]["name"]; $Type = $_POST['type']; if ($_FILES["file"]["error"] > 0) < echo "Error: NO CHOSEN FILE 
"; echo"INSERT TO DATABASE FAILED"; > else < move_uploaded_file($_FILES["file"]["tmp_name"], __DIR__ . "/upload/" . $_FILES["file"]["name"]); echo"SAVED
"; $query_image = "INSERT INTO $tbl_name (fname, email, content, image,type, submission_date) VALUES ('$Fname','$Email','$Content','$filePath','$Type',curdate())"; if(mysql_query($query_image)) < echo "Stored in: " . "upload/" . $_FILES["file"]["name"]; >else < echo 'File name not stored in database'; >> > ?>
 
Name
Email: (will not be publicized)
Client Type Comments Image

Best Solution

Solved: Below is working code to; Upload File/image to ftp directory, store the path in database table, store current date, and text from form ALL FROM ONE FORM.

I searched for weeks online looking for a concise way to submit all this information on one row in the db, simultaneously. Could only piece it together, here it is for you guys.

For beginners: 1)Create 2 files in your html daw. Index.php and file_upload.php. Index will be where you put your html, the file_upload.php file is where you add the php code. Php files usually start with

The ID row must be set to primary key and INT. The rest should be set to Varchar with a specific amount of characters (your choosing).

4)Create upload folder at same location as index.php and file_upload.php. Be sure and add file permissions to upload folder to prohibit or allow public edits.

5) switch out ‘http://www.yourwebsite.com/directory’ in my code with your website and page directory.

In the following case, upgrade is the database name, and Testimonials is the table name.

 mysql_select_db("$db_name")or die("cannot select DB"); $ftp_conn = ftp_connect($ftp_server) or die("Could not connect to $ftp_server"); // login with username and password $login_result = ftp_login($ftp_conn, $ftp_user, $ftp_pass); // check connection if ((!$ftp_conn) || (!$login_result)) < echo "FTP connection has failed!"; echo "Attempted to connect to $ftp_server for user $ftp_user"; exit; >else < echo "Connected to $ftp_server, for user $ftp_user"; >$Fname = $_POST['fname']; $Email = $_POST['email']; $Content = $_POST['content']; $Type = $_POST['type']; $uploadDir = 'http://www.yourwebsite.com/directory/'.'upload/'; $fileName = $_FILES['image']['name']; $filePath = $uploadDir . $fileName; if(move_uploaded_file($_FILES["image"]["tmp_name"],"upload/".$_FILES["image"]["name"])) < // If file has uploaded successfully, store its name in data base $query_image = "INSERT INTO $tbl_name(fname,email,content,image,type,submission_date) VALUES ('$Fname','$Email','$Content','$filePath','$Type',curdate())"; if(mysql_query($query_image)) < echo "Stored in: " . "upload/" . $_FILES["image"]["name"]; >else < echo 'File name not stored in database'; >> else > ?> 
 
Name
Email: (will not be publicized)
Client Type Comments Image

Источник

Text and image upload php

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
)

Источник

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;
>

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.

Источник

File Upload in PHP with Examples [2 Steps]

In this article we are going to cover File Upload in PHP with Examples.

What is file upload in PHP?

PHP allows you to upload single and multiple files through few lines of code only. And it is easy to upload files to the server. PHP file upload features allows you to upload binary and text files both.

PHP $_FILES:

In PHP, global $_FILES contains all the information of file. The help of $_FILES global, we can get file name, file type, file size, temp file name.

$_FILES[‘filename’][‘name’]
$_FILES[‘filename’][‘type’]

Returns MIME type of the file.

$_FILES[‘filename’][‘size’]

Returns size of the file in bytes.

$_FILES[‘filename’][‘tmp_name’]

Returns temporary file name of the file which was stored on the server.

$_FILES[‘filename’][‘error]

Returns error code associated with this file.

Create The HTML Form

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

File Upload in PHP with Examples [2 Steps] 1

Upload.php

 else < echo "File is not an image."; $uploadOk = 0; >> if (file_exists($target_file)) < echo "Sorry, file already exists."; $uploadOk = 0; >if ($_FILES["fileToUpload"]["size"] > 500000) < echo "Sorry, your file is too large."; $uploadOk = 0; >if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) < echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed."; $uploadOk = 0; >if ($uploadOk == 0) < echo "Sorry, your file was not uploaded."; >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."; >> ?> 

File Upload in PHP with Examples [2 Steps] 2

In this article we have covered File Upload in PHP with Examples.

Related Articles:

Источник

Читайте также:  List python удаление элементов
Оцените статью