View the last image uploaded to the database using php - php

I am new in php and I am trying to view the last image uploaded to the database using php.
insertion code running perfectly but the selection one accrued an issue.
here is my code
<?php
if (isset($_POST['UploadImage'])) {
$image = $_FILES['image']['tmp_name'];
$image_type = $_FILES['image']['type'];
if ($image == '') {
echo "<script> alert('please choose picture') </script>";
} else if ($image_type != "image/jpeg" && $image_type != "image/png" && $image_type != "image/gif") {
echo "<script> alert('image format is not correct ') </script>";
} else {
$query = "INSERT INTO image (ImageLink) VALUES ('" . $image . "')";
if (mysqli_query($db1, $query)) {
echo '<script> alert("image uploaded successfully") </script>';
} else {
echo '<script> alert("please try again") </script>';
}
}
if (mysqli_affected_rows($db1) > 0) {
$query_image = "SELECT ImageLink FROM image ORDER BY Image_Id DESC LIMIT 1;";
$result = mysqli_query($db1, $query_image);
while ($row = mysqli_fetch_assoc($result)) {
echo "<img width='450' height='600' src='data:image/jpeg; base64,".base64_encode($row['ImageLink'])."' >";
echo "<br>";
}
}
}?>
while running... image doesn't appear in page.
please any help in doing that...
thank you

Solution is:
HTML code
<table
style="border-style: solid; border-color: gray; margin-top: 17px; width: 100%; height: 50%; width: 100%">
<tr>
<td>please upload a picture :</td>
<td><input type="file" name="image" id="image"></td>
</tr>
<tr></tr>
<tr>
<td> </td>
<td><input type="submit" value="Upload Image" name="UploadImage"
id="UploadImage"> </td>
</tr>
</table>
PHP Code
<?php
if(isset($_POST["UploadImage"])){
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["image"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if (isset($_POST["UploadImage"])) {
$check = getimagesize($_FILES["image"]["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["image"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if ($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif") {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$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["image"]["tmp_name"], $target_file)) {
echo "The file " . basename($_FILES["image"]["name"]) . " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
$query = "INSERT INTO image (ImageLink) VALUES ('" . $target_file . "')";
if (mysqli_query($db1, $query)) {
echo '<script> alert("Image Has been Uploaded Successfully") </script>';
} else {
echo '<script> alert("Please Try Again") </script>';
}
if (mysqli_affected_rows($db1) > 0) {
$query_image = "SELECT ImageLink FROM image ORDER BY Image_Id DESC LIMIT 1;";
$result = mysqli_query($db1, $query_image);
while ($row = mysqli_fetch_assoc($result)) {
// var_dump( $row );
echo "<img width='450' height='600' src='data:image/jpeg; base64,".base64_encode(file_get_contents($row['ImageLink']))."'>";
echo "<br>";
}
}
}
}

Related

This is simple php code which displays image chosen from directory, but when I run it, It shows torn image and doesn't display the actual image

This is simple php code which displays image chosen from directory, but when I run it, It shows torn image and doesn't display the actual image..
This is the output that I am getting
Does anyone know why is this happening?
I have tried to run this in all browsers, and it is still showing
This is the code:
<html>
<head>
<title>PHP File Upload example</title>
</head>
<body style="background-color:cyan;">
<style>
p
{
background-color: yellow;
border: 3px solid black;
text-align: center;
}
#grad
{
background-image: linear-gradient(indigo,violet,cyan);
text-align: center;
}
</style>
<div id = "grad">
<b>
<form action="p10a.php" enctype="multipart/form-data" method="post">
Select image from dir :
<input type="file" name="file"><br/><br>
<input type="submit" value="Upload" name="Submit1"> <br/>
</b>
</form><p>
<?php
if(isset($_POST['Submit1']))
{
$target_dir = "C:/xampp/htdocs/LAMP LAB";
$target_file1 = basename($_FILES["file"]["name"]);
$target_file = $target_dir . basename($_FILES["file"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
$check = getimagesize($_FILES["file"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";?><br><?php
$file = $target_file1;
$filesize = filesize($file); // bytes
$filesize = round($filesize / 1024, 2); // kilobytes with two digits
echo "The size of your file is $filesize KB.";?><br><?php
echo "Content last changed: ".date("F d Y H:i:s.", filemtime($file));?></p>
<br><br><br><br><b><?php
echo "<img src='C:/xampp/htdocs/LAMP LAB".$imageFileType."' width='200'> "; //display image
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
?>
</body>
</html>
[This is the output that I am getting]
https://i.stack.imgur.com/mQNdX.png
Use the following code.
<html>
<head>
<title>PHP File Upload example</title>
</head>
<body style="background-color:cyan;">
<style>
p
{
background-color: yellow;
border: 3px solid black;
text-align: center;
}
#grad
{
background-image: linear-gradient(indigo,violet,cyan);
text-align: center;
}
</style>
<div id = "grad">
<b>
<form action="" enctype="multipart/form-data" method="post">
Select image from dir :
<input type="file" name="file"><br/><br>
<input type="submit" value="Upload" name="Submit1"> <br/>
</b>
</form><p>
<?php
if(isset($_POST['Submit1']))
{
$target_dir = "LAMP LAB/";
$target_file = $target_dir . basename($_FILES["file"]["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["file"]["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;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
echo $target_file;
// 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["file"]["tmp_name"], $target_file)) {
echo "The file ". htmlspecialchars( basename( $_FILES["file"]["name"])). " has been uploaded.";
echo "Content last changed: ".date("F d Y H:i:s.", filemtime($target_file));?></p>
<br><br><br><br><b><?php
echo "<img src='".$target_file."' width='200'> "; //display image
} else {
echo "Sorry, there was an error uploading your file.";
}
}
}
?>
</body>
</html>

How to display an image that I uploaded to a folder in a server? I am using php and mysql, in the data base is saved just the name of the picture

$target = "logo/";
$target = $target.basename($_FILES['file']['name']);
$logo = $_FILES['file']['name'];
$sqlimg = "UPDATE usuarios SET rutaimg = '$logo' WHERE user_name ='$_SESSION[username]'";
mysqli_query($con,$sqlimg);
if (move_uploaded_file($_FILES['file']['tmp_name'], $target)) {
echo "The file".basename($_FILES['uploadedfile']['name'])."Was uploaded";
} else {
echo "The picture wasnt uploaded";
}
Hi As you said that you have already uploaded your image and now want to show same. In this case you should use tag with src being the path/to/imagefolder/name of image stored in db
like you have fetched your data for a perticular user
<table border="1">
$sql="SELECT * FROM tbl_name";
$result = mysql_query($sql);
while($row=mysql_fetch_array($result))
{
?>
<tr>
<td><?php echo $row['name'] ?></td>
<td><?php echo $row['password'] ?></td>
<td><?php echo $row['username'] ?></td>
<td><img src="logo/<?php echo $row['file_name']?>"></td>
</tr>
<?php
}
?>
</table>
try jquery
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#image_upload_preview').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#inputFile").change(function () {
readURL(this);
});
https://jsfiddle.net/dave17/m2oum2su/
i hope it will be helpful
include ("conexion.php");
$showimg = "SELECT rutaimg FROM usuarios WHERE user_name='$_SESSION[username]'";
$result3= mysqli_query($connection, $showimg);
$file_path = "localhost/phplogin/";
if (mysqli_num_rows($result3)>0) {
while ($row = mysqli_fetch_array($result3))
{
$src= $row['rutaimg'];
}
}
?>
<img src="<?php echo $src; ?>">

PHP upload form won't upload more than 16 files

The files are relatively small XMLs that are far below the max upload limit, and I've adjusted my max_file_upload value in php.ini to 30. All of the files can be uploaded in any combination up to 16 of them. What's more, the form will not actually "POST." It will action over to the next page, but I've put in some code to display text if the form has been submitted, which it won't if more than 16 files are selected. I'm at a loss for this one, not much help around the web either.
<form method="post" enctype="multipart/form-data" name="uploadForm" id="uploadForm" action="?pa=uxf">
<table border="0" cellspacing="5" cellpadding="5">
<tbody>
<tr>
<td valign="top"><label for="fileField"><strong>Upload XML Files to Repository:</strong></label><br /><?php
if(isset($_POST['upload'])) {
$fileCount = count($_FILES['fileToUpload']['tmp_name']);
echo '<br /><br />File Count: '.$fileCount.'<br />';
for ($i = 0; $i < $fileCount; $i++) {
echo '<br />';
$target_dir = 'uploads/';
$target_file = $target_dir.basename($_FILES['fileToUpload']['name'][$i]);
$uploadOk = 1;
$fileType = pathinfo($target_file,PATHINFO_EXTENSION);
$check = filesize($_FILES['fileToUpload']['tmp_name'][$i]);
if($check !== false) {
echo '<span style="color: #00AA00">File is an xml.</span><br />'.$check['mime'];
$uploadOk = 1;
} else {
echo '<span style="color: #FF0000">File is not an xml.</span><br />';
$uploadOk = 0;
}
if (file_exists($target_file)) {
echo '<span style="color: #FF0000">Sorry, <strong>'.$target_file.'</strong> already exists.</span><br />';
$uploadOk = 0;
}
if ($_FILES['fileToUpload']['size'][$i] > 50000000) {
echo '<span style="color: #FF0000">Sorry, your file is too large. Must be less than 50MG.</span><br />';
$uploadOk = 0;
}
if($fileType != 'xml') {
echo '<span style="color: #FF0000">Sorry, only XML files are allowed.</span><br />';
$uploadOk = 0;
}
if ($uploadOk == 0) {
echo '<span style="color: #FF0000">Sorry, your file was not uploaded.</span><br />';
} else {
if (move_uploaded_file($_FILES['fileToUpload']['tmp_name'][$i], $target_file)) {
echo '<span style="color: #00AA00">The file '.basename($_FILES['fileToUpload']['name'][$i]).' has been uploaded.</span><br />';
} else {
echo '<span style="color: #FF0000">Sorry, there was an error uploading your file.</span><br />';
}
}
}
} ?>
<table width="100%" border="0" cellspacing="5" cellpadding="5">
<tbody>
<tr valign="top">
<td><input type="file" name="fileToUpload[]" id="fileToUpload[]" multiple></td>
</tr>
<tr valign="top">
<td><input type="submit" name="upload" id="upload" value="Upload XML"></td>
</tr>
</tbody>
</table></td>
<td valign="top"><strong>Uploaded Files List:</strong><br><?php
$int = 1;
foreach (new DirectoryIterator($directory) as $fileInfo) {
if($fileInfo->isDot()) continue;
$file = $fileInfo->getFilename();
echo $int.'. '.$file.'<br />';
$int++;
} ?></td>
</tr>
</tbody>
</table>
</form>
In addition to max_file_upload, there are two other ini settings that concern file uploads that may be relevant.
upload_max_filesize (default 2 MB) limits the per-file upload size, and post_max_size (default 8 MB) limits the total size of POST content, including file uploads.
If you are running afoul of either limit, that can result in the behavior you are seeing.
As both of these are relevant before php code beings executing, you'll need to look at your php.ini (and/or .htaccess settings, as the case may be) and ensure that they are set to a level that will allow for all of your POST content to be accepted.

Only allow image & PDF types in image uploader PHP script

I have a script that allows only 1 image to be uploaded which works fine.
But right now it allows any and all types to uploaded.
How do I only allow jpg, jpeg, gif, png & PDF files to be the only ones allowed to upload?
Here is part of my code.
<?php
// make a note of the current working directory, relative to root.
$directory_self = str_replace(basename($_SERVER['PHP_SELF']), '', $_SERVER['PHP_SELF']);
// make a note of the directory that will recieve the uploaded files
$uploadsDirectory = $_SERVER['DOCUMENT_ROOT'] . $directory_self . 'uploaded_files/';
// make a note of the location of the upload form in case we need it
$uploadForm = 'http://' . $_SERVER['HTTP_HOST'] . $directory_self . 'multiple.upload.form.php';
// make a note of the location of the success page
$uploadSuccess = 'http://' . $_SERVER['HTTP_HOST'] . $directory_self . 'multiple.upload.success.php';
// name of the fieldname used for the file in the HTML form
$fieldname = 'file';
//echo'<pre>';print_r($_FILES);exit;
// Now let's deal with the uploaded files
// possible PHP upload errors
$errors = array(1 => 'php.ini max file size exceeded',
2 => 'html form max file size exceeded',
3 => 'file upload was only partial',
4 => 'no file was attached');
// check the upload form was actually submitted else print form
isset($_POST['submit'])
or error('the upload form is needed', $uploadForm);
// check if any files were uploaded and if
// so store the active $_FILES array keys
$active_keys = array();
foreach($_FILES[$fieldname]['name'] as $key => $filename)
{
if(!empty($filename))
{
$active_keys[] = $key;
}
}
// check at least one file was uploaded
if (count($active_keys) < 1)
{ echo "<table border=\"0\" cellspacing=\"4\" cellpadding=\"4\" style=\"border: 1px solid black; text-align: center; font-family: arial; font-size: 14px;\" width=\"600px\" align=\"center\">
<tr>
<td>
<font size=\"3\" color=\"red\"><strong><u>Upload Error</u></strong></font>
<br>
<br>
<b>You must upload one file.</b>
<br><br>
Back to upload form
<br>
</td>
</tr>
</table> <div style=\"display: none;\"> "; }
//count($active_keys)
//or error('No files were uploaded', $uploadForm);
// check for standard uploading errors
foreach($active_keys as $key)
{
($_FILES[$fieldname]['error'][$key] == 0)
or error($_FILES[$fieldname]['tmp_name'][$key].': '.$errors[$_FILES[$fieldname]['error'][$key]], $uploadForm);
}
// check that the file we are working on really was an HTTP upload
foreach($active_keys as $key)
{
#is_uploaded_file($_FILES[$fieldname]['tmp_name'][$key])
or error($_FILES[$fieldname]['tmp_name'][$key].' not an HTTP upload', $uploadForm);
}
// make a unique filename for the uploaded file and check it is
// not taken... if it is keep trying until we find a vacant one
foreach($active_keys as $key)
{
$now = time();
while(file_exists($uploadFilename[$key] = $uploadsDirectory.$now.'-'.$_FILES[$fieldname]['name'][$key]))
{
$now++;
}
}
// now let's move the file to its final and allocate it with the new filename
foreach($active_keys as $key)
{
#move_uploaded_file($_FILES[$fieldname]['tmp_name'][$key], $uploadFilename[$key])
or error('receiving directory insuffiecient permission', $uploadForm);
}
// If you got this far, everything has worked and the file has been successfully saved.
// We are now going to redirect the client to the success page.
if($_FILES['file']['error'] === UPLOAD_ERR_INI_SIZE) {
// Handle the error
echo 'Your file is too large.';
die();
}
// make an error handler which will be used if the upload fails
function error($error, $location, $seconds = 5)
{
echo "<table border=\"0\" cellspacing=\"4\" cellpadding=\"4\" style=\"border: 1px solid black; text-align: center; font-family: arial; font-size: 14px;\" width=\"600px\" align=\"center\">
<tr>
<td>
<font size=\"3\" color=\"red\"><strong><u>Upload Error</u></strong></font>
<br>
<br>
<!--<b>Your proof is not a supported filetype.<br>
Please upload an image (jpg, gif, png, bmp file) or PDF file.
<br>
<br>
or</b>
<br>
<br>-->
<b>Your File Size is bigger then the maximum allowed - 2 MB.<br>
Please upload a smaller file.</b>
<br><br>
Back to upload form
<br>
</td>
</tr>
</table> <div style=\"display: none;\">";
}
/*
{
header("Refresh: $seconds; URL=\"$location\"");
echo '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"'."\n".
'"http://www.w3.org/TR/html4/strict.dtd">'."\n\n".
'<html lang="en">'."\n".
'<head>'."\n".
'<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">'."\n\n".
'<link rel="stylesheet" type="text/css" href="stylesheet.css">'."\n\n".
'<title>Upload error</title>'."\n\n".
'</head>'."\n\n".
'<body>'."\n\n".
'<div id="Upload">'."\n\n".
'<h1>Upload failure</h1>'."\n\n".
'<p>An error has occured: '."\n\n".
'<span class="red">' . $error . '...</span>'."\n\n".
' The upload form is reloading</p>'."\n\n".
' </div>'."\n\n".
'</html>';
exit;
} // end error handler
*/
// < input id="file1" name="file[]" type="file" style="border: 1px solid white;">
//$fi= $_POST['file[]'];
//$fi = "(0)";
$fi = array($_FILES['file']['name']['0'],$_FILES['file']['name']['1'],$_FILES['file']['name']['2']);
====EDIT====
I was able to get it to ONLY allow images, but now how to I allow PDF's to be uploaded also?
I added this code to my script.
foreach($active_keys as $key)
{
#getimagesize($_FILES[$fieldname]['tmp_name'][$key])
or error($_FILES[$fieldname]['tmp_name'][$key].' not an image', $uploadForm);
}
Just attached the following line in your code. its will checks upload file is image or pdf before it move to directory.
$allowedExts = array("gif", "jpeg", "jpg", "png", "pdf");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png")
|| ($_FILES["file"]["type"] == "application/pdf")
&& in_array($extension, $allowedExts)) {
// put the upload code here
} else {
// put error message here
}
I was able to achieve this with the code below.
$thefilename = $_FILES["file"]["name"][0];
/* first, check for suffix
(jpg, gif, png, bmp file) or PDF file */
$thefilesuffix = substr($thefilename, -3);
// echo "<p>".$thefilesuffix."</p><hr />";
switch($thefilesuffix)
{
case "pdf": case "PDF":
/* don't need to do anything special,
but notice the capitalized versions */
break;
case "jpg": case "gif": case "png": case "bmp":
case "JPG": case "GIF": case "PNG": case "BMP":
//ALLOWS ONLY IMAGES TO BE UPLOADED
foreach($active_keys as $key)
{
#getimagesize($_FILES[$fieldname]['tmp_name'][$key])
or error($_FILES[$fieldname]['tmp_name'][$key].' not an image', $uploadForm);
}
//ALLOWS ONLY IMAGES TO BE UPLOADED
break;
default:
echo "<table border=\"0\" cellspacing=\"4\" cellpadding=\"4\" style=\"border: 1px solid black; text-align: center; font-family: arial; font-size: 14px;\" width=\"600px\" align=\"center\">
<tr>
<td>
<font size=\"3\" color=\"red\"><strong><u>Upload Error</u></strong></font>
<br>
<br>
<b>Your proof must be an an image (jpg, gif, png, bmp file) or PDF file.<br>
Please upload a different file.</b>
<br>
<br>
Back to upload form
<br>
</td>
</tr>
</table> <div style=\"display: none;\">"; exit;
break;
}

php image upload

How to make a basic PHP uploader? I want my images to save in my htdocs/myfolder/
Here is my code:
<form enctype="multipart/form-data" method="post" action="img_uploader.php">
<input type="file" name="fileToUpload" /><br />
<input type="submit" value="Upload File" />
</form>
the code below is a simple example touching all the aspects of image or file upload take a look at it and understand it
<?php
/* to do large file uploads open the php.ini file and set "post_max_size = 150M" or the
size you wish and also set "upload_max_filesize = 120M" post_max_size must be greater than upload_max_filesize in oder
to work, also set the "max_input_time" and "max_execution_time" to 300 (5 minutes specified in seconds)
or more if you wish finally set them in your php script as below, also set "memory_limit = 1024M" or what you wish
by default "memory_limit = 128M" Note in Wamp this should be done in C:\wamp64\bin\apache\apache2.4.23\bin\php.ini and
in C:\wamp64\bin\php\php5.6.25\php.ini or C:\wamp64\bin\php\php7.0.10\php.ini depending on the php version you are using
the values must all be the same in all scripts */
ini_set('upload_max_filesize', '10M');
ini_set('post_max_size', '50M');
ini_set('max_input_time', 300);
ini_set('max_execution_time', 300);
ini_set('memory_limit','500M');
//set errors array
function output_errors($errors){
$output = array();
foreach($errors as $error){
$output[] = '<li>' . $error . '</li>';
}
return '<ul class="errors">' . implode('', $output) . '</ul>';
}
//set validation array
function output_valids($no_errors){
$output = array();
foreach($no_errors as $no_error){
$output[] = '<li>' . $no_error . '</li>';
}
return '<ul class="valid">' . implode('', $output) . '</ul>';
}
$no_errors = array();
$errors = array();
if (isset($_FILES['image']) AND $_FILES['image']['error']== 0){
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["image"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
$only_extentios = array('jpg', 'jpeg', 'gif','png');
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["image"]["tmp_name"]);
if($check !== false) {
array_push($no_errors,"File is an image - " . $check["mime"] . ".");
$uploadOk = 1;
} else {
array_push($errors,"File is not an image.");
$uploadOk = 0;
}
}
// check for correct image extention and size
if (!in_array($imageFileType,$only_extentios)){
array_push($errors,"Sorry, only jpg, jpeg, png & gif files are allowed.");
$uploadOk = 0;
}elseif ($_FILES["image"]["size"] > 10000000){
array_push($errors,"Sorry, your file is too large.");
$uploadOk = 0;
}
// Check if file already exists, if uploadok is set to one ant try to upload image
if (file_exists($target_file)) {
array_push($errors,"Sorry, file already exists.");
$uploadOk = 0;
}
if($uploadOk == 1){
move_uploaded_file($_FILES["image"]["tmp_name"], $target_file);
}else{
array_push($errors,"Sorry, your file was not uploaded.") ;
}
if (file_exists($target_file)){
array_push($no_errors,"The file ". basename( $_FILES["image"]["name"]). " has/had been uploaded.");
} else {
array_push($errors,"Sorry, there was an error uploading your image.");
}
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="utf-8"/>
<title > image upload </title>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<meta name="author" content="image uploader"/>
<style type="text/css" >
*,{
margin: 0px;
padding: 0px;
font-family: 'Oswald', sans-serif;
}
header,section,footer,aside,nav,article,hgroup {
display: block;
}
body{
width:100%; color:black;
display:-webkit-box;
-webkit-box-pack: center;
-webkit-box-orient:vertical;
-webkit-box-flex: 1;
background: rgba(204,204,255,0.9);
background-repeat:repeat;
}
.errors{
width:97%;
height:auto;
float:left;
margin-left:3%;
padding:10px;
}
.errors li{
text-align:left;
color:red;
font-size:15px;
list-style:;
}
.valid{
width:97%;
height:auto;
float:left;
margin-left:3%;
padding:10px;
}
.valid li{
text-align:left;
color:green;
font-size:15px;
list-style:;
}
</style>
</head>
<body>
<p><form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post" enctype="multipart/form-data" >
<?php
echo output_valids($no_errors);
?>
Sélectionnez une photo:
<label class="custom-file-upload" style=" margin:0px auto;"> <input type="file" name="image" /> choix </label>
<input type="submit" value="Envoyer " name="submit"/>
<?php
echo output_errors($errors);
?>
</form></p>
</body>
</html>
Here is a quick tutorial I found for doing a file upload:
http://www.tizag.com/phpT/fileupload.php
I read through it pretty quick, but it gives you the basic idea with some safety stuff to boot
specify your directory path here
$target_path = "uploads/";
replace the name of file input with uploadedfile and rest code will work fine
`
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}`
As Your Code below is working example:
first create a folder with name "myfolder" in your htdocs folder
[img_uploader.php]
<?php
$target_path = "myfolder/";
$target_path = $target_path . basename( $_FILES['fileToUpload']['name']);
if(move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['fileToUpload']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
?>
In the working directory is fine work upload but, uploading in the database at the same time is note working any one solve this problem? kindly.
function doInsert(){
if(isset($_POST['save'])){
if ( $_POST['BRANCHNAME'] == "" || $_POST['BRANCHLOCATION'] == "" || $_POST['BRANCHCONTACTNO'] == "" ) {
$messageStats = false;
message("All field is required!","error");
redirect('index.php?view=add');
}else{
$branch = New Branch();
$branch->BRANCHNAME = $_POST['BRANCHNAME'];
$branch->BRANCHLOCATION = $_POST['BRANCHLOCATION'];
$branch->BRANCHCONTACTNO = $_POST['BRANCHCONTACTNO'];
$branch->BRANCHLEVEL = $_POST['BRANCHLEVEL'];
$branch->BRANCHSTATUS = $_POST['BRANCHSTATUS'];
$branch->BRANCHMANAGER = $_POST['BRANCHMANAGER'];
$branch->BRANCHDESCRIPTION = $_POST['BRANCHDESCRIPTION'];
//$branch->PICLOCATION = $_POST['PICLOCATION'];
$branch->_FILES = $_POST['PICLOCATION'];
$file =$_FILES['PICLOCATION'];
$filename = $file['name'];
$filepath = $file['tmp_name'];
$fileerror = $file['error'];
if ($fileerror == 0) {
$destfile = 'photos/'.$filename;
move_uploaded_file($filepath, $destfile);
$branch->LATITUDE = $_POST["LATITUDE"];
$branch->LONGITUDE = $_POST["LONGITUDE"];
$branch->create();
message("New Branch created successfully!", "success");
redirect("index.php");
}
}
}
}

Categories