PHP file upload not working - php

I am trying to upload a picture but it always showing me the error. I think i have done everything it needs to upload a picture. Any help would be appreciated.
html:
<form action="../Code Files/User.php" method="post" enctype="multipart/form-data">
<div id="photo_settings2" style="margin-left:74px;">
<img id="Picture" src="../../img/User No-Frame.png"/>
</div>
<br><br><br><br>
<div id='Upload_Panel' style="margin-left: 32px;">
<input name='file' type='file' id='file_browse' onchange="readURL(this,'Picture')" style="cursor: pointer;"/>
</div>
<div id="delete" style="margin-top: -40px; margin-left: 198px; cursor: pointer">
<img src="../../img/Delete_Panel.png">
</div>
<div style="margin-left:144px; margin-top:-15px"></div>
<br><br>
</div>
</div>
</form>
php code:
$UploadDirectory = '/www/';
if(move_uploaded_file($_FILES['file']['file'], $UploadDirectory))
{
die('Success! File Uploaded.');
}
else
{
die('error uploading File!');
}

This should work:
if(move_uploaded_file($_FILES['file']['tmp_name'], basename($_FILES['file']['name'])))
{
die('Success! File Uploaded.');
}
else
{
die('error uploading File!');
}
Edit: I've changed the destination argument - now uploaded file will appear next to your php file. Remember about target folder permissions.

Working Code:
$UploadDirectory = '/wamp/www/img/Users/Users/'.basename($_FILES['file']['name']);
if(move_uploaded_file($_FILES['file']['tmp_name'], $UploadDirectory))
{
die('Success! File Uploaded.');
}
else
{
die('error uploading File!');
}

Related

Ajax file Upload giving the undefined index file from the php side

I've tried everything i came across and i am sure there is something i dont have in the code .Please i need some help thks.
This is the html which is a form with one input which should receive the file
<div id="Posts">
<h1 style="text-align: center;color: red;">SERVICES</h1>
<p style="text-align: center;"><span style="color:red;">***</span> please ensure to look at the definitions of every field... <span style="color:red;">***</span></p>
<form id="promo_imgs" enctype="multipart/formdata">
<h5 style="text-align: center;"> About the Services You offer</h5><hr style="width: 30%; border:0.5px dashed red;">
<div id="imgpr" class="imgpromo" style="max-width: 40%; min-height: 60px;border:dashed 0.5px;">
<label for="promotion" class="btn btn-primary">
Select an Image
</label>
<img src="" alt="" width="100%" style="max-height: 250px;" id="img">
<input type="file" name="promo0" accept=".png, .jpeg, .jpg" id="promotion" style="display:none;">
</div>
<button class="btn btn-primary" type="submit" id="serv_upload" name="serv_upload">Upload</button>
</form><span id="ajax">
<!--upload an image -->
</span>
then this is the jquery part of it which should preview the image (which works) and then upload the image(which goes successfully to return an undefined index file error)
/* to preview before upload service images*/
$(document).on('change',"#promotion",function(){
var link =URL.createObjectURL(event.target.files[0]);
console.log(link);
var $this=$(this);
$("#img").slideDown("fast").attr('src',link);
$("#serv_upload").slideDown("slow");
});
/* to upload service images*/
$(document).on('click',"#serv_upload",function(e){
e.preventDefault();
$("#ajax").html("Uploading...");
var files = $('#promotion').val(e.target.files);
for (var i = 0; i < files.length; i++) {
var file = files[i];
var formdata= new FormData();
formdata.append('file',file);
$("#ajax").append(file.name);
$.ajax({
type:"POST",
url:"aboutinsert.php",
data:{formdata:formdata},
processData:false,
contentType:false,
cache:false,
success: function(data){
$("#ajax").html(data);
}
});
}
});
Finally the php part
$dir="img/portfolio" ;
$file = $_FILES['file']['name'];
$path = $dir.basename($file);
$ext= pathinfo($path,PATHINFO_EXTENSION);
$extensions = array("JPG","jpg","jpeg","png");
$exts=strtolower($ext);
if (!in_array($exts, $extensions)) {
# code...
echo "sorry you donot have the right file format";
}
elseif ($_FILES['file']['size']>2000000) {
# code...
echo "your file is larger than 2mb";
}
elseif (file_exists($path)) {
# code...
echo "sorry a file already exists with this name change the name and try again";
}
else{
if (move_uploaded_file($_FILES['file']['tmp_name'], $path)) {
# code...
echo basename($_FILES['file']['name']). "upload success";
}
else{
echo "file Upload failed";
}
}
There seem to be some random names being used in the $_FILES array in your PHP code. You use:
$file = $_FILES['file']['name'];
and then
elseif ($_FILES['promo0']['size']>2000000) {
and finally
if (move_uploaded_file($_FILES['image']['tmp_name'], $path)) {
Which is it? If you're not certain, you could var_dump($_FILES); and see what you have.

excel file upload using phpexcel and data insertion to the mysql database

kindly help me to sort this out
i just need to upload an excel file to upload folder same time export data to the mysql database.
currently uploading is successfully happen and if i give excel file location and file name manually data within it will export to the database.
kindly tell me what method should it used to do this same time.
code set used to upload excel file to the 'uploads' folder
<?php
require_once './config/MainConfig.php';
include './config/dbc.php';
$uploadedStatus = 0;
if (isset($_POST["submit"])) {
if (isset($_FILES["file"])) {
// $_SESSION['date_ss'] = $_POST['date_ss'];
//if there was an error uploading the file
if ($_FILES["file"]["error"] > 0) {
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
} else {
if (file_exists($_FILES["file"]["name"])) {
unlink($_FILES["file"]["name"]);
$uploadedStatus = 2;
}
$name = basename($_FILES['file']['name']);
$name1 = explode('.', $name);
if ($name1[count($name1) - 1] == 'csv' || $name1[count($name1) - 1] == 'xlsx') {
$target_path = "uploads/";
$target_location = $target_path . basename($_FILES['file']['name']);
$_SESSION['target_location'] = $target_location;
// $datess = $_POST['date_ss'];
move_uploaded_file($_FILES["file"]["tmp_name"], $target_location);
$uploadedStatus = 1;
}
}
} else {
echo "No file selected <br />";
}
}
?>
<html>
<head>
<style>
.file-upload {
max-width: 580px;
height: 200px;
padding: 25px 35px 45px;
margin: 0 auto;
background-color: #fff;
border: 1px solid rgba(0,0,0,0.1);
}
</style>
</head>
<?php
if (array_key_exists("action", $_POST)) {
if ($_POST['action'] == 'sendManualFileUpoadingData') {
$Manual_note_No=$_POST['Manual_note_No'];
$Phone_amount= $_POST[' Phone_amount'];
echo $Manual_note_No;
}
}
?>
<div class="container">
<div class="wrapper">
<div class="file-upload">
<div class="row">
<div class="col-md-4">Transfer Note Number :</div>
<div class="col-md-4"><?php echo'' ?></div>
</div>
<div class="row">
<div class="col-md-4">Phone quantity:</div>
<div class="col-md-4"><?php echo '' ?></div>
</div>
<div class="row">
<div class="col-md-4"></div>
<div class="col-md-4">
<form action="fileuploadexecution.php" method="post" enctype="multipart/form-data">
<input type="file" id="file" name="file" multiple="multiple" />
<p style="text-align: right; margin-top: 20px;">
<input type="submit" value="Upload Files" name="submit" class= "btn btn-success" />
</p>
</form>
</div>
<div class="col-md-4"></div>
</div>
<div class="row">
<?php
if ($uploadedStatus == 1) {
echo 'file uploaded successfully';
} elseif ($uploadedStatus == 2) {
echo 'file already available';
}
?>
</div>
</div>
</div>
</div>
<!-- you need to include the ShieldUI CSS and JS assets in order for the Upload widget to work -->
<link rel="stylesheet" type="text/css" href="css/bootstrap.css" />
<script type="text/javascript" src="js/jquery.min.js"></script>
</html>
code set used to export excel file data into mysql table
<?php
session_start();
//all save,update,delete
require_once './config/dbc.php';
//db connectin
require_once './class/database.php';
require_once './class/systemSetting.php';
$system = new setting();
//calling the class setting from systemsetting.php
$database = new database();
// MainConfig::connectDB();
// $datess = $_SESSION['date_ss'];
// $q = mysql_fetch_array(mysql_query("SELECT MAX(commission.num_of_session +1)AS commax FROM commission"));
// $sess = $q['commax'];
set_include_path(get_include_path() . PATH_SEPARATOR . 'ex_class/');
include './xl_upload/ex_class/PHPExcel/IOFactory.php';
// This is the file path to be uploaded.
//
//echo $_SESSION['target_location'];
//$inputFileName = $target_path . basename($_FILES['file']['name']);
$inputFileName = 'testFile.xlsx';
try {
$objPHPExcel = PHPExcel_IOFactory::load($inputFileName);
} catch (Exception $e) {
die('Error loading file "' . pathinfo($inputFileName, PATHINFO_BASENAME) . '": ' . $e->getMessage());
}
$allDataInSheet = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);
$arrayCount = count($allDataInSheet); // Here get total count of row in that Excel sheet
$count = 1;
for ($count; $count <= $arrayCount; $count++) {
$Doc_No = trim($allDataInSheet[$count]["A"]);
$ESN = trim($allDataInSheet[$count]["B"]);
$insertTable = mysql_query("INSERT INTO `test_table` (`Doc_No`, `ESN`) VALUES ('".$Doc_No."','".$ESN."');") or die(mysql_error());
}
$msg = 'Record has been added. <div style="Padding:20px 0 0 0;">Go Back</div>';
?>
excel file that going to upload
Try the this
Execute a database backup query from PHP file. Below is an example of using SELECT INTO OUTFILE query for creating table backup:
$tableName = 'yourtable';
$backupFile = 'backup/yourtable.sql';
$query = "SELECT * INTO OUTFILE '$backupFile' FROM $tableName";
$result = mysqli_query($con,$query);
To restore the backup you just need to run LOAD DATA INFILE query like this:
$tableName = 'yourtable';
$backupFile = 'yourtable.sql';
$query = "LOAD DATA INFILE 'backupFile' INTO TABLE $tableName";
$result = mysqli_query($con,$query);

Image not showing on image slider

Hello im creating a dynamic image slider but the image is not showing. I can upload image in the file directory. I don't know what is the problem if the database is the problem or what. I'm new to html and css also to php. Can someone give me ideas what is the caused of not showing the images?
here it is the image is not showing but i can upload file to my gallery file directory.
here is my database sql.
here is my php code.
<?php
//for connecting db
include('connect.php');
if (!isset($_FILES['image']['tmp_name'])) {
echo "";
}
else
{
$file=$_FILES['image']['tmp_name'];
$image= addslashes(file_get_contents($_FILES['image']['tmp_name']));
$image_name= addslashes($_FILES['image']['name']);
move_uploaded_file($_FILES["image"]["tmp_name"],"gallery/" . $_FILES["image"]["name"]);
$photo="gallery/" . $_FILES["image"]["name"];
$query = mysqli_query($mysqli, "INSERT INTO images(photo)VALUES('$photo')");
$result = $query;
echo '<script type="text/javascript">alert("image successfully uploaded ");window.location=\'index.php\';</script>';
}
?>
<!DOCTYPE html>
<html>
<head>
<link href="css/style.css" rel="stylesheet" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script src="js/slider.js"></script>
<script>
$(document).ready(function () {
$('.flexslider').flexslider({
animation: 'fade',
controlsContainer: '.flexslider'
});
});
</script>
</head>
<body>
<div class="container">
<form class="form" action="" method="POST" enctype="multipart/form-data">
<div class="image">
<p>Upload images and try your self </p>
<div class="col-sm-4">
<input class="form-control" id="image" name="image" type="file" onchange='AlertFilesize();'/>
<input type="submit" value="image"/>
</div>
</div>
</form>
<div class="flexslider">
<ul class="slides">
<?php
// Creating query to fetch images from database.
$query = mysqli_query($mysqli, "SELECT * from images order by id desc limit 5");
$result = $query;
while($r = mysqli_fetch_array($result)){
?>
<li>
<img src="<?php echo $r['photo'];?>" width="400px" height="300px"/>
</li>
<?php
}
?>
</ul>
</div>
</div>
</body>
</html>
here is my connect.php
<?php
// hostname or ip of server
$servername='localhost';
// username and password to log onto db server
$dbusername='root';
$dbpassword='';
// name of database
$dbname='pegasus';
////////////// Do not edit below/////////
$mysqli = new mysqli($servername,$dbusername,$dbpassword,$dbname);
if($mysqli->connect_errno){
printf("Connect failed: %s\n", $mysql->connect_error);
exit();
}
?>
Image shows your column name is image and you are fetching records by column name photo.
Just change
<img src="<?php echo $r['photo'];?>" width="400px" height="300px"/>
to
<img src="<?php echo $r['image'];?>" width="400px" height="300px"/>

File Size Calculated but File Not Found

I am trying to install the "Waiting time file download script using php and jquery" script found at http://www.w3webtools.com/simple-page-download-file-using-php-and-jquery/
I have downloaded the demo scripts and installed them in my server at /var/www/test/.
When I try to call the demo files it recognizes the file size but says the file is not found. http://4x4submods.tk/test/download.php?f=advance-security-login-system-using-php-mysql.zip
Any ideas?
mod_rewrite is enabled.
This works:
<?php
header('Content-Type: text/html;charset=UTF-8');
include 'include/config.php';
include 'include/function.php';
?>
<!-- Edited to point to the latest copy of jquery! -->
<script src="http://code.jquery.com/jquery-2.0.0.js"></script><?php
$fname='hello.txt';
$download=1;
if(!file_exists(UPLOAD_DIR.'/'.$fname))
{
$download=0;
}
$downloadLink='download/'.makeHash($fname).'/'.$fname;
function file_size($url){
$size = filesize($url);
if($size >= 1073741824){
$fileSize = round($size/1024/1024/1024,1) . 'GB';
}elseif($size >= 1048576){
$fileSize = round($size/1024/1024,1) . 'MB';
}elseif($size >= 1024){
$fileSize = round($size/1024,1) . 'KB';
}else{
$fileSize = $size . ' bytes';
}
return $fileSize;
}
?>
<div class="container">
<span class="filename" id="fileinfo-filename" title="<?=$fname?>"><?=$fname?></span>
<span class="fileinfo" id="fileinfo">File Size: <span id="fileinfo-filesize"><?php
if($download!=0){
echo file_size(UPLOAD_DIR.'/'.$fname);
}else{
echo 'N/A';
}
?></span> - Your IP: <span id="fileinfo-views"><?=$_SERVER['REMOTE_ADDR'];?></span></span>
<div id="btnX" class="btn btn-blue">
<span class="text1" id="countdown-info">PREPARERING DOWNLOAD...</span>
<span class="timedown" id="countdown-time"></span>
</div>
<div id="<?=$download?>" class="loading" style="display: none;"></div>
<input id="download" type="text" style="display: none;" value="<?php echo $download ?>">
<a class="btn btn-green" id="btn-download" style="display: none;" href="<?=$downloadLink?>">
<span class="text2">DOWNLOAD</span>
</a>
</div>
<script type="text/javascript">
http://w3webtools.com/wp-admin/post-new.php#
var countDown;
jQuery(document).ready(function(){
countDown=function(start){
if(start==0)
{
jQuery('#countdown-time').html('');
jQuery('#countdown-info').html('PREPARERING DOWNLOAD...');
bla = $('#download').val();
if(bla==0){
jQuery('#countdown-info').html('ERROR: Press F5 to try again. <br></br>404: File not found!');
}else{
jQuery('#btnX').css('display','none');
jQuery('#btn-download').css('display','inline-block');
}
return true;
}
jQuery('#countdown-time').html(start+'s');
start--;
setTimeout('countDown('+start+')',1000);
}
countDown(5);
});
</script>
Function.php file:
<?php
function makeHash($fileName)
{
return md5( $fileName . SECURITY_CODE );
}
function verifyHash($fileName,$hashCode)
{
return $hashCode==makeHash($fileName);
}
Ensure that you use the same hash that you used in the key when decoding!
The rest was not really required and made it more complicated than necessary!
Including the file date in the hash, may make it not work if the file date changes for some reason, for example, if you need to do a system restore. You can probably put the server name back in the hash if you think you really want it!

add progress bar to jquery ajax file upload

hey there i am using ajax to upload images. the codes are as follows.
index.php
<html>
<head>
</head>
<script src="js/jquery.min.js"></script>
<script src="js/jquery.wallform.js"></script>
<script>
$(document).ready(function() {
$('#photoimg').die('click').live('change', function() {
//$("#preview").html('');
$("#imageform").ajaxForm({target: '#preview',
beforeSubmit:function(){
console.log('ttest');
$("#imageloadstatus").show();
$("#imageloadbutton").hide();
},
success:function(){
console.log('test');
$("#imageloadstatus").hide();
$("#imageloadbutton").show();
},
error:function(){
console.log('xtest');
$("#imageloadstatus").hide();
$("#imageloadbutton").show();
} }).submit();
});
});
</script>
<style>
body
{
font-family:arial;
}
#preview
{
color:#cc0000;
font-size:12px
}
.imgList
{
max-height:150px;
margin-left:5px;
border:1px solid #dedede;
padding:4px;
float:left;
}
</style>
<body>
<div>
<div id='preview'>
</div>
<form id="imageform" method="post" enctype="multipart/form-data" action='ajaxImageUpload.php' style="clear:both">
<h1>Upload your images</h1>
<div id='imageloadstatus' style='display:none'><img src="loader.gif" alt="Uploading...."/></div>
<div id='imageloadbutton'>
<input type="file" name="photos[]" id="photoimg" multiple />
</div>
</form>
</div>
</body>
</html>
the ajaxImageUpload.php
<?php
error_reporting(0);
session_start();
$session_id='1'; //$session id
define ("MAX_SIZE","9000");
function getExtension($str)
{
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$uploaddir = "uploads/"; //a directory inside
foreach ($_FILES['photos']['name'] as $name => $value)
{
$filename = stripslashes($_FILES['photos']['name'][$name]);
$size=filesize($_FILES['photos']['tmp_name'][$name]);
//get the extension of the file in a lower case format
$ext = getExtension($filename);
$ext = strtolower($ext);
if(in_array($ext,$valid_formats))
{
if ($size < (MAX_SIZE*1024))
{
$image_name=time().$filename;
echo "<img src='".$uploaddir.$image_name."' class='imgList'>";
$newname=$uploaddir.$image_name;
move_uploaded_file($_FILES['photos']['tmp_name'][$name], $newname);
}
else
{
echo '<span class="imgList">You have exceeded the size limit!</span>';
}
}
else
{
echo '<span class="imgList">Unknown extension!</span>';
}
}
}
echo $uploaddir.$image_name;
?>
right now it displays an animated gif while it uploads the images. what i want to do is remove the gif and replace it with a progress bar but i have no clue how to do this and i am on a time schedule. could anyone please tell me how to do this. thanks!
The PHP code for processing the upload does not run until the entire file is uploaded, so it is not possible for you detect how much of the file has been uploaded in that script.
Generally you find upload progress bars built into a browser or some "client-side" program like a Flash application that can control that level of transfer.
For a strict PHP and Javascript implementation there are some workarounds that are fragile and a lot of work and are not very common (hence why you are asking here). There are some jQuery plugins that exist that can do this http://plugins.jquery.com/uploadfile/.

Categories