PHP Upload Image

PHP upload image

The code overlooks calling the function move_uploaded_file() which would check whether the indicated file is valid for uploading.

You may wish to review a simple example at:

http://www.w3schools.com/php/php_file_upload.asp

Multiple Image Upload PHP form with one input

$error=array();
$extension=array("jpeg","jpg","png","gif");
foreach($_FILES["files"]["tmp_name"] as $key=>$tmp_name) {
$file_name=$_FILES["files"]["name"][$key];
$file_tmp=$_FILES["files"]["tmp_name"][$key];
$ext=pathinfo($file_name,PATHINFO_EXTENSION);

if(in_array($ext,$extension)) {
if(!file_exists("photo_gallery/".$txtGalleryName."/".$file_name)) {
move_uploaded_file($file_tmp=$_FILES["files"]["tmp_name"][$key],"photo_gallery/".$txtGalleryName."/".$file_name);
}
else {
$filename=basename($file_name,$ext);
$newFileName=$filename.time().".".$ext;
move_uploaded_file($file_tmp=$_FILES["files"]["tmp_name"][$key],"photo_gallery/".$txtGalleryName."/".$newFileName);
}
}
else {
array_push($error,"$file_name, ");
}
}

and you must check your HTML code

<form action="create_photo_gallery.php" method="post" enctype="multipart/form-data">
<table width="100%">
<tr>
<td>Select Photo (one or multiple):</td>
<td><input type="file" name="files[]" multiple/></td>
</tr>
<tr>
<td colspan="2" align="center">Note: Supported image format: .jpeg, .jpg, .png, .gif</td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Create Gallery" id="selectedButton"/></td>
</tr>
</table>
</form>

Nice link on:

PHP Single File Uploading with vary basic explanation.

PHP file uploading with the Validation

PHP Multiple Files Upload With Validation Click here to download source code

PHP/jQuery Multiple Files Upload With The ProgressBar And Validation (Click here to download source code)

How To Upload Files In PHP And Store In MySql Database (Click here to download source code)

PHP Upload image then show

I think you would benefit from an uploading class or function that returns information for your uploaded image. This will help you store the results or display as you are looking to do. Here is one loosely based on what you provided with notation:

Form:

<form action="" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>

Script:

<?php
function UploadImage($settings = false)
{
// Input allows you to change where your file is coming from so you can port this code easily
$inputname = (isset($settings['input']) && !empty($settings['input']))? $settings['input'] : "fileToUpload";
// Sets your document root for easy uploading reference
$root_dir = (isset($settings['root']) && !empty($settings['root']))? $settings['root'] : $_SERVER['DOCUMENT_ROOT'];
// Allows you to set a folder where your file will be dropped, good for porting elsewhere
$target_dir = (isset($settings['dir']) && !empty($settings['dir']))? $settings['dir'] : "/uploads/";
// Check the file is not empty (if you want to change the name of the file are uploading)
if(isset($settings['filename']) && !empty($settings['filename']))
$filename = $settings['filename'];
// Use the default upload name
else
$filename = preg_replace('/[^a-zA-Z0-9\.\_\-]/',"",$_FILES[$inputname]["name"]);
// If empty name, just return false and end the process
if(empty($filename))
return false;
// Check if the upload spot is a real folder
if(!is_dir($root_dir.$target_dir))
// If not, create the folder recursively
mkdir($root_dir.$target_dir,0755,true);
// Create a root-based upload path
$target_file = $root_dir.$target_dir.$filename;
// If the file is uploaded successfully...
if(move_uploaded_file($_FILES[$inputname]["tmp_name"],$target_file)) {
// Save out all the stats of the upload
$stats['filename'] = $filename;
$stats['fullpath'] = $target_file;
$stats['localpath'] = $target_dir.$filename;
$stats['filesize'] = filesize($target_file);
// Return the stats
return $stats;
}
// Return false
return false;
}
?>

To use:

<?php
// Make sure the above function is included...
// Check file is uploaded
if(isset($_FILES["fileToUpload"]["name"]) && !empty($_FILES["fileToUpload"]["name"])) {
// Process and return results
$file = UploadImage();
// If success, show image
if($file != false) { ?>
<img src="<?php echo $file['localpath']; ?>" />
<?php
}
}
?>

RAW Feedback:

// This is what the array would look like on return of successful upload:
Array
(
[filename] => animal.png
[fullpath] => /data/19/2/133/150/2948313/user/2524254/htdocs/mydomain/uploads/animal.png
[localpath] => /uploads/animal.png
[filesize] => 35702
)

PHP Uploading files - image only checking

Yes, quite easily. But first off, you need some extra bits:

// never assume the upload succeeded
if ($_FILES['file']['error'] !== UPLOAD_ERR_OK) {
die("Upload failed with error code " . $_FILES['file']['error']);
}

$info = getimagesize($_FILES['file']['tmp_name']);
if ($info === FALSE) {
die("Unable to determine image type of uploaded file");
}

if (($info[2] !== IMAGETYPE_GIF) && ($info[2] !== IMAGETYPE_JPEG) && ($info[2] !== IMAGETYPE_PNG)) {
die("Not a gif/jpeg/png");
}

Relevant docs: file upload errors, getimagesize and image constants.

Upload an image from input type file to a server

To upload file thru ajax, use FormData, and to store data of image into a db table (say in a LONGBLOB field), you may use fread and send_long_data to do the job.

Please find below the code (including one to let you view the uploaded photos):

HTML

<script
src="https://code.jquery.com/jquery-3.6.0.js"
integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk="
crossorigin="anonymous"></script>

<form>
<input class="form-control" type="file" accept="image/jpg" id="pic_in_in" required>
<button class="btn" onclick="create_band()">Upload</button>
</form>

<script>

function create_band() {
//console.log("ADDED");

var file_data = $('#pic_in_in').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);

$.ajax({
async:false,
url: 'addBand.php', // <-- point to server-side PHP script
dataType: 'text', // <-- what to expect back from the PHP script, if anything
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(php_script_response){
alert(php_script_response); // <-- display response from the PHP script, if any
}
});

}
</script>

PHP (addBand.php)

<?php

ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL);

$servername = "localhost";
$username = "xxxxxxx";
$password = "xxxxxxx";
$dbname = "xxxxxxx";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$tmpName = $_FILES['file']['tmp_name'];

// Read the file
$fp = fopen($tmpName, 'r');
$image = fread($fp, filesize($tmpName));
fclose($fp);

$sql = "INSERT INTO va_band_name (band_img) VALUES (?)";

$statement = $conn->prepare($sql);
$null = NULL;

$statement->bind_param('b', $null);
$statement->send_long_data(0, $image);
$statement->execute();

$check = mysqli_stmt_affected_rows($statement);

if($check == 1){
$res = 'Image was uploaded';
}else{
$res = 'Something went wrong!';
}
echo $res;
}
?>

PHP (view uploaded photos):

Uploaded photos (if any):
<br>

<?php

$servername = "localhost";
$username = "xxxxxxx";
$password = "xxxxxxx";
$dbname = "xxxxxxx";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

$sql = "SELECT * FROM va_band_name";
$statement = $conn->prepare($sql);
$statement->execute();
$result = $statement->get_result();

foreach($result as $row){

echo '<img src="data:image/jpg;base64,'.base64_encode($row['band_img']).'" width="200" height=auto/>';
echo "<hr>";
}

?>

Php upload image to directory

The problem of your script is that you are probably trying to upload a file higher that your limit is! You specified a really low max filesize! Print out your $_FILES var to get information about what's wrong ;)

However, in order to move the file to your folder you still need to use move_uploaded_file:

$allow = array("jpg", "jpeg", "gif", "png");

$todir = 'uploads/';

if ( !!$_FILES['file']['tmp_name'] ) // is the file uploaded yet?
{
$info = explode('.', strtolower( $_FILES['file']['name']) ); // whats the extension of the file

if ( in_array( end($info), $allow) ) // is this file allowed
{
if ( move_uploaded_file( $_FILES['file']['tmp_name'], $todir . basename($_FILES['file']['name'] ) ) )
{
// the file has been moved correctly
}
}
else
{
// error this file ext is not allowed
}
}


Related Topics



Leave a reply



Submit