CSV file upload not working - php

I am trying to import csv file to database table using php. The problem is uploaded file is not recognized as csv file in the receiving page. Here is my code:
My form:
<form enctype='multipart/form-data' method='post' action="new_campaign.php" class="add_campaign_form">
<table class="add_campaign_table">
<tr>
<td><label>Campaign Name<label></td>
</tr>
<tr>
<td><input type="text" id="name" class="name" name="camp_name" value='' required/></td>
</tr>
<tr>
<td><label>Notes<label></td>
</tr>
<tr>
<td><textarea id="notes" name="camp_note" rows="4" cols="50" maxlength="250" placeholder="Campaign details" value='' required>
</textarea></td>
</tr>
<tr>
<td><label>Upload CSV File<label></td>
</tr>
<tr>
<td><input type="file" name="csv_file" id="csv" /></td>
</tr>
</table>
<input type="submit" class="submit" alt="Submit" width="120" height="30"/>
<br><br>
</form>
new_campaign.php
if(isset($_FILES) && $_FILES["file"]['error']==0){
if (($_FILES["file"]["type"] == "application/vnd.ms-excel")) {
if ($_FILES["file"]["error"] > 0) {
echo "error uploading the file";
}
else {
echo "hooray!";
}
}
else {
echo "this is not a csv file";
}
}
else{
echo "no files";
}
It keeps throwing me : "this is not a csv file"
I am getting the other field values in the receiving page. Any help?

Thanks Sean. Here is the working code:
if(isset($_FILES) && $_FILES["csv_file"]['error']==0){
//echo "file type: ".$_FILES["csv_file"]["type"];
if (($_FILES["csv_file"]["type"] == "text/csv")) {
if ($_FILES["text/csv"]["error"] > 0) {
echo "error uploading the file";
}
else {
echo "hooray!";
}
}
else {
echo "this is not a csv file";
}
}
else{
echo "no files";
}

Your input is name="csv_file"
<input type="file" name="csv_file" id="csv" />
So it should be
if(isset($_FILES) && $_FILES["csv_file"]['error']==0){
if (($_FILES["csv_file"]["type"] == "application/vnd.ms-excel")) {
if ($_FILES["csv_file"]["error"] > 0) {
...
not $_FILES["file"]['error']/$_FILES["file"]["type"]

Related

i am trying to update my data with an image updation too but the image isset would not work in php

Hey guys i have created a register form with an image upload too but when i try to update this form i try to get the id but the isset of my image is not working so it just wont run my update query do check it out
this is the updation form where all the values will be displayed for edit now can i run the update function in the isset condition of my submit button and then update the data
<title>Register Update</title>
<?php
//error_reporting(0);
$id=$_GET['id'];
function __autoload($classname)
{
include "$classname.php";
}
$obj = new connect();
$st=$obj->con();
if (isset($_POST['sub']))
{
$upd= new update();
$upd->updatedata($_POST);
}
$qry = "select * from register ";
$run = mysqli_query($st,$qry);
$row = mysqli_fetch_assoc($run);
{
$g = $row['gen'];
$l = $row['lang'];
}
$query=mysqli_query($st,"select * from register where id='$id'");
//echo "<ul>";
while($query2=mysqli_fetch_assoc($query))
{
//print_r($query2);
echo "<form method='POST' action='RegisterRetrieve.php'>";
echo "<table>";
?>
<p><input type="hidden" name="sid" value="<?php echo $query2['id']; ?>"></p>
<tr>
<td>
First Name:
</td>
<td><input type="text" name="uname" value="<?php echo $query2['uname']; ?>"></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="pwd" value="<?php echo $query2['pwd']; ?>"></td>
</tr>
<tr>
<td>Email Id:</td>
<td><input type="text" name="emailid" value="<?php echo $query2['emailid']; ?>"
</td>
</tr>
<tr>
<td>Radio Button: Are you male or female?</td>
<?php
if ($g == "male"){
echo "<td><input type='radio' name='gen' value='Male' id='gen' checked> Male <input type='radio' name='gen' value='Female' id='gen'> Female </td>";
}
else
{
echo "<td><input type='radio' name='gen' value='Male' id='gen'> Male <input type='radio' name='gen' value='Female' id='gen' checked> Female </td>";
}
?>
</tr>
<tr>
<td>Check Box: Check the languages you know?</td>
<td><?php
$lang=explode(',',$l);
//print_r($lang);
if(in_array('Cricket', $lang))
echo '<input type="checkbox" name="lang[0]" value="Cricket" checked>Cricket';
else
echo '<input type="checkbox" name="lang[0]" value="Cricket">Cricket';
if(in_array('Basketball', $lang))
echo '<input type="checkbox" name="lang[1]" value="Basketball" checked>Basketball';
else
echo '<input type="checkbox" name="lang[1]" value="Basketball">Basketball';
if(in_array('Hockey', $lang))
echo '<input type="checkbox" name="lang[2]" value="Hockey" checked>Hockey';
else
echo '<input type="checkbox" name="lang[2]" value="Hockey">Hockey'."<br>";
?>
</td>
</tr>
<tr>
<td>Mobile No:</td>
<td><input type="text" name="mobile" value="<?php echo $query2['mobile']; ?>"
</td>
</tr>
<tr>
<td>10th Marks:</td>
<td><input type="text" name="marks_10" value="<?php echo $query2['10marks'];?>"
</td>
</tr>
<tr>
<td>
12th Marks:</td>
<td><input type="text" name="marks_12" value="<?php echo $query2['12marks'];?>"</td>
</tr>
<tr>
<td>
Browse Image:</td>
<td><input type="file" name="file1"></td>
<td><img src='img/<?php echo $query2['name'];?>' width='150px' height='150px'></td>
</tr>
<tr>
<td>
<select name="priority">
<option value="admin">
admin
</option>
<option value="<?php echo $query2['priority']; ?>"><?php echo $query2['priority']; ?>
</option>
<option value="superadmin">
superadmin
</option>
</select>
</td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" value="submit" name="sub"><br>
</td>
</tr>
<?php
echo "<table>";
echo "</form>";
}
//echo "</ul>";
?>
now my update query which i m using but when i try to isset my image it just wont go in that condition
<?php
class update extends connect
{
function updatedata($rel)
{
$obj= new connect();
$obj->con();
extract($_POST);
$id=$_GET['id'];
$line = implode("," ,$lang);
print_r($_POST);
if(isset($_FILES["file1"]))
{
extract($_POST);
echo "hello";
$name = $_FILES['file1']['name'];
$type = $_FILES['file1']['type'];
$size = $_FILES['file1']['size'];
$tmp_name = $_FILES['file1']['tmp_name'];
$loc = 'img/';
$ext = substr($name,strpos($name,'.')+1);
if($_FILES['file1']['size']>= '10000' || $_FILES['file1']['size']<="23000000")
{
//echo $size;
}
else{
// echo "size is not supported";
}
$val = $_FILES['file1']['size'];
if($ext == 'jpg' || $ext == 'png')
{
//echo $lang;
//print_r($_POST);
//exit;
$val =("update register set uname='$uname',pwd='$pwd',emailid='$emailid',gen='$gen',lang='$line',mobile='$mobile',10marks='$marks_10',12marks='$marks_12' file1='$name' where id=$sid");
//print_r($qry);
$res=mysqli_query($this->con(),$val);
//print_r($run);
if($res)
{
move_uploaded_file($tmp_name,$loc.$name);
//echo "data saved";
//echo "Data inserted";
}
else
{
//echo "Data Not Inserted";
}
}
}
}
//print_r($val);
// return $res;
}
?>
Your html is broken:
</tr>
<?php
echo "<table>"; <--shouldn't this be </table>?
echo "</form>";
}

Adding the row ID to the filename of the uploaded file

I want to add the ID number of the row to the uploaded file file name.
e.g. if the file name is stack.pdf before uploading, after uploading it should change to stack-ID#.pdf.
This is the PHP Codes that is use to upload
$sp=mysqli_connect("localhost","root","","ara");
if($sp->connect_errno){
echo "Error <br/>".$sp->error;
}
$path="pdf/";
if(isset($_POST['upload']))
{
$path=$path.$_FILES['file_upload']['name'];
if(move_uploaded_file($_FILES['file_upload']['tmp_name'],$path))
{
echo " ".basename($_FILES['file_upload']['name'])." has been uploaded<br/>";
echo '<img src="gallery/'.$_FILES['file_upload']['name'].'" width="48" height="48"/>';
$img=$_FILES['file_upload']['name'];
$query="insert into library (path,CreatedTime) values('$img',now())";
if($sp->query($query)){
echo "<br/>Inserted to DB also";
}else{
echo "Error <br/>".$sp->error;
}
}
else
{
echo "There is an error,please retry or ckeck path";
}
}
And this is the form
<form action="accept-file.php" method="post" enctype="multipart/form-data">
<table width="384" border="1" align="center">
<tr>
<td width="108">Select File</td>
<td width="260"><label>
<input type="file" name="file_upload">
</label></td>
</tr>
<tr>
<td><label>
<input type="submit" name="upload" value="Upload File">
</label></td>
<td> </td>
</tr>
</table>
</form>
I will really appreciate your help. Thanks.
Try this:
$uploadFileName = $_FILES['file_upload']['name'];
//get extention of upload file
$attachment_ext = explode('.', $uploadFileName);
$ext_pt = $attachment_ext[1];
//Give a new name for the file
$newName = '123'.$uploadFileName.".".$ext_pt;
$path = "YOURPATHHERE/";
$save_attchment = $path.$newName ; //setting the path
move_uploaded_file($_FILES['file_upload']['tmp_name'], $save_attchment);

Html multiple select field issue with php

I've a html form with multiple select field. I'm trying to validate it with php. but i can't validate this multiple select field with php. It's show me success message without any validation.
Please kindly tell me what's the problem in my code. Thank you.
Php Code:
<?php
if(isset($_POST['Submit']) && $_POST['Submit'] == "Send SMS")
{
if(isset($_POST['number']))
$number = $_POST['number'];
$msg = inputvalid($_POST['txt']);
$err = array();
if(isset($msg) && isset($number))
{
if(empty($msg) && empty($number))
$err[] = "All field require";
else
{
if(empty($msg))
$err[] = "Your message require";
if(empty($number))
$err[] = "Select your mobile number";
}
}
if(!empty($err))
{
echo "<div class='error'>";
foreach($err as $er)
{
echo "<font color=red>$er.</font><br/>";
}
echo "</div>";
echo "<br/>";
}
else
{
echo "good";
}
}
?>
Html Code:
<form name="frm" method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']) ?>">
<table width="800" border="0" cellspacing="10" cellpadding="0">
<tr>
<td valign="top">Number</td>
<td>
<select multiple="multiple" size="10" name="number[]">
<option value="">--Select Member--</option>
<?php
$class = mysql_query("SELECT * FROM e_members");
while($res = mysql_fetch_array($class))
{
$phone = $res['phone'];
?>
<option value="<?php echo $phone; ?>"> <?php echo $phone; ?></option>
<?php
}
?>
</select>
</td>
</tr>
<tr>
<td valign="top">Write message</td>
<td>
<textarea class="textarea" placeholder="Your message" name="txt" onkeyup="counter(this);">
<?php if(isset($_POST['txt'])) echo $_POST['txt']; ?>
</textarea>
<br/>
<input type="" name="lbl" style="border:none;">
<br/>
</td>
</tr>
<tr>
<td> </td>
<td>
<input type="submit" name="Submit2" value="Save SMS" class="view"/>
<input type="submit" name="Submit" value="Send SMS" class="submit"/>
</td>
</tr>
</table>
</form>
Update:
After select multiple/single value var_dump showing:
array(1) { [0]=> string(13) "8801814758545" }
Without select it's showing:
NULL
You are trying to validate array $number using empty($number). It won't work as you expected
You can validate this as if (is_array($number) && count($number) > 0)
The problem is that your check for empty values is inside for check for if(isset($msg) && isset($number)) and as soon as you post the form these variables are set. As you are already check that the post is set then remove this outer if statement and just check for empty values and it should work.

How to update form data in database with and without updating image using php, mysql

Below code is to update form details in database. It would update database only if image is changed/upload amother image. What should be done if we don't want to upload new image but need to update other form details? Thanks for solution, in advance!!!
<html>
<head>
<title>Update the Contact Record</title>
<link rel="stylesheet" type="text/css" href="cms_style.css">
<script>
window.onunload = function(){ window.opener.location.reload(); };
</script>
</head>
<body>
<h2 align="center">Update the Record</h2>
<?php
// error_reporting(~E_NOTICE);
//echo "Test 1 <br>";
$cid = $_GET['id'];
$uid = $_GET['uid'];
/* echo "<br> value of Con ID is : "; echo $cid;
echo "<br> value of UID is : "; echo $uid; */
if($uid==1) {
//echo "<br> Test 2 ";
updateRecord($cid);
} else if (isset($_GET['id']) ) {
//echo "<br>Test 3 ";
$ResumeID = $_GET['id'];
$sql="SELECT * from data WHERE ResumeID=$ResumeID";
$result = mysql_query($sql);
$Row=mysql_fetch_row($result);
?>
<form align="center" action="updateRecord.php?id=<? echo "$Row[0]"?>&uid=1" method="post" enctype="multipart/form-data">
<table align="center">
<input type="hidden" name="resumeid" value="<? echo "$Row[0]"?>">
<!-- <? echo "<tr> <td> Resume ID </td> <td>$Row[0]</td> </tr>" ?> -->
<div align="center">
<tr>
<td> Name of the Candidate</td>
<td><input type="text" name="NameoftheCandidate" size="25" value="<? echo "$Row[1]" ?>"></td>
</tr>
<tr>
<td>TelephoneNo</td>
<td><input type="text" name="TelephoneNo" size="25" value="<? echo "$Row[2]"?>"></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" name="Email" size="25" value="<? echo "$Row[3]"?>"></td>
</tr>
<tr>
<td>WEYears</td>
<td><input type="text" name="WEYears" size="25" value="<? echo "$Row[4]"?>"></td>
</tr>
<tr>
<td>CurrentLocation</td>
<td><input type="text" name="CurrentLocation" size="25" value="<? echo "$Row[5]"?>"></td>
</tr>
<tr>
<td>PreferredLocation</td>
<td><input type="text" name="PreferredLocation" size="25" value="<? echo "$Row[6]"?>"></td>
</tr>
<tr>
<td>CurrentEmployer</td>
<td><input type="text" name="CurrentEmployer" size="25" value="<? echo "$Row[7]"?>"></td>
</tr>
<tr>
<td>CurrentDesignation</td>
<td><input type="text" name="CurrentDesignation" size="25" value="<? echo "$Row[8]"?>"></td>
</tr>
<tr>
<td>AnnualSalary</td>
<td><input type="text" name="AnnualSalary" size="25" value="<? echo "$Row[9]"?>"></td>
</tr>
<tr>
<td>UGCourse</td>
<td><input type="text" name="UGCourse" size="25" value="<? echo "$Row[10]"?>"></td>
</tr>
<tr>
<td> Image:
<? echo $Row[12]; ?> </td>
</tr>
<tr>
<? echo '<td><img src="http://localhost/cmsapp_latest/processimage.php?id=' . $Row[0] . '"></td>'; ?>
</tr>
<tr>
<td><input type="hidden" name="MAX_FILE_SIZE" value="10000000" />Change Image:</td>
<td><input name="userfile" type="file" /></td>
</tr>
<tr>
<td align="center"><input type="submit" name="submitvalue" value="UPDATE" ></td>
<td align="center"><input type="button" name="cancelvalue" value="CANCEL" onClick="self.close(); return false;"></td>
</tr>
</div>
</table>
</form>
<?php
} // end of else if
function updateRecord($cid) {
$msg = "Intial Value";
$maxsize = 10000000; //set to approx 10 MB
if($_FILES['userfile']['error']== UPLOAD_ERR_OK) {
echo "Print uplod error - ";
echo UPLOAD_ERR_OK;
//check whether file is uploaded with HTTP POST
if(is_uploaded_file($_FILES['userfile']['tmp_name'])) {
echo "tEST 02 - ";
//checks size of uploaded image on server side
if( $_FILES['userfile']['size'] < $maxsize) {
$finfo = finfo_open(FILEINFO_MIME);
if(strpos(finfo_file($finfo, $_FILES['userfile']['tmp_name']),"image")===0) {
echo "tEST 03 - ";
// prepare the image for insertion
$imgData =addslashes(file_get_contents($_FILES['userfile']['tmp_name']));
$sql= "UPDATE data SET NameoftheCandidate=\"$_POST[NameoftheCandidate]\", TelephoneNo='$_POST[TelephoneNo]', Email='$_POST[Email]', WEYears='$_POST[WEYears]',CurrentLocation='$_POST[CurrentLocation]', PreferredLocation='$_POST[PreferredLocation]', CurrentEmployer=\"$_POST[CurrentEmployer]\", CurrentDesignation='$_POST[CurrentDesignation]', AnnualSalary='$_POST[AnnualSalary]', UGCourse=\"$_POST[UGCourse]\", image=\"{$imgData}\", name=\"{$_FILES['userfile']['name']}\" WHERE ResumeID=$_GET[id]";
//echo $sql;
//$result = mysql_query($sql);
if(mysql_query($sql))
echo "Record updated";
else
echo "Record update failed";
}
else
$msg="<p>Uploaded file is not an image.</p>";
}
else {
// if the file is not less than the maximum allowed, print an error
$msg='<div>File exceeds the Maximum File limit</div>
<div>Maximum File limit is '.$maxsize.' bytes</div>
<div>File '.$_FILES['userfile']['name'].' is '.$_FILES['userfile']['size'].
' bytes</div><hr />';
}
}
else
$msg="File not uploaded successfully.";
}
else {
$msg= file_upload_error_message($_FILES['userfile']['error']);
}
return $msg;
} // end of update function
function file_upload_error_message($error_code) {
switch ($error_code) {
case UPLOAD_ERR_INI_SIZE:
return 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
case UPLOAD_ERR_FORM_SIZE:
return 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
case UPLOAD_ERR_PARTIAL:
return 'The uploaded file was only partially uploaded';
case UPLOAD_ERR_NO_FILE:
return 'No file was uploaded';
case UPLOAD_ERR_NO_TMP_DIR:
return 'Missing a temporary folder';
case UPLOAD_ERR_CANT_WRITE:
return 'Failed to write file to disk';
case UPLOAD_ERR_EXTENSION:
return 'File upload stopped by extension';
default:
return 'Unknown upload error';
}
}
?>
</body>
</html>
Hi I have done solution for this.Just add below code before
if($_FILES['userfile']['error']== UPLOAD_ERR_OK)
if($_FILES['userfile']['error']== UPLOAD_ERR_NO_FILE)
{
//echo UPLOAD_ERR_NO_FILE;
SQL update query
//echo $sql;
if(mysql_query($sql))
echo "Record updated";
else
echo "Record update failed";
}
Include below code in your php script
if ($_FILES["userfile"]["error"] == 0)
{
//update database code goes here
}
Create a hidden field for old image and populate with the value from database in your form.
$image=$_FILES["NEW-IMAGE-FIELD"]["name"];
if($image!="") {
SCRIPT TO UPLOAD NEW IMAGE
SCRIPT TO REMOVE OLD IMAGE
}
else
{
$image = $_REQUEST["HIDDEN-OLD-IMAGE-FIELD"];
}
$query = UPDATE DATABASE DETAIL WITH image='$image'";

SFTP local file upload using PHP

I have the following script below where I try to mimic a file upload via FTP but have changed it for SFTP using phpseclib.
The script echoes out fine until the line:
$upload = $conn_id->put($paths.'/'.$name, $filep,
NET_SFTP_LOCAL_FILE);
echo "upload == ".$upload."\n";
where nothing happens or prints out.
here is the full script:
<?
include('Net/SSH2.php');
if(!isset($_POST["submit"])){?>
<form action="upload.php" method="POST" enctype="multipart/form-data">
<table align="center">
<tr>
<td align="right">
Server:
</td>
<td>
<input size="50" type="text" name="server" value="">
</td>
</tr>
<tr>
<td align="right">
Username:
</td>
<td>
<input size="50" type="text" name="user" value="">
</td>
</tr>
<tr>
<td align="right">
Password:
</td>
<td>
<input size="50" type="text" name="password" value="" >
</td>
</tr>
<tr>
<td align="right">
Path on the server:
</td>
<td>
<input size="50" type="text" name="pathserver" >
</td>
</tr>
<tr>
<td align="right">
Select your file to upload:
</td>
<td>
<input name="userfile" type="file" size="50">
</td>
</tr>
</table>
<table align="center">
<tr>
<td align="center">
<input type="submit" name="submit" value="Upload image" />
</td>
</tr>
</table>
</form>
<?}
else
{
set_time_limit(300);//for setting
$paths=$_POST['pathserver'];
echo "paths == ".$paths."\n";
$filep=$_FILES['userfile']['tmp_name'];
echo "filep == ".$filep."\n";
$sftp_server=$_POST['server'];
echo "sftp_server == ".$sftp_server."\n";
$sftp_user_name=$_POST['user'];
echo "sftp_user_name == ".$sftp_user_name."\n";
$sftp_user_pass=$_POST['password'];
echo "sftp_user_pass == ".$sftp_user_pass."\n";
$name=$_FILES['userfile']['name'];
echo "name == ".$name."\n";
// set up a connection to ftp server
$conn_id = new Net_SSH2($sftp_server);
// login with username and password
$login_result = $conn_id->login($sftp_user_name, $sftp_user_pass);
// check connection and login result
if ((!$conn_id) || (!$login_result)) {
echo "SFTP connection has encountered an error!";
echo "Attempted to connect to $sftp_server for user $sftp_user_name....";
exit;
} else {
echo "Connected to $sftp_server, for user $sftp_user_name".".....";
}
echo "HERE "."\n";
// upload the file to the path specified
$upload = $conn_id->put($paths.'/'.$name, $filep, NET_SFTP_LOCAL_FILE);
echo "upload == ".$upload."\n";
// check the upload status
if (!$upload) {
echo "SFTP upload has encountered an error!";
} else {
echo "Uploaded file with name $name to $sftp_server ";
}
// close the FTP connection
ftp_close($conn_id);
}
?>
Which library is NET/ssh2.php? Looks like http://phpseclib.sourceforge.net?
You're mixing their SSH2 and SFTP libraries. Taken directly from their manual, the code you want is:
<?php
include('Net/SFTP.php');
$sftp = new Net_SFTP('www.domain.tld');
if (!$sftp->login('username', 'password')) {
exit('Login Failed');
}
echo $sftp->pwd() . "\r\n";
$sftp->put('filename.ext', 'hello, world!');
print_r($sftp->nlist());
?>
So just change the $data in the "put" function to be the filename, and adding the mode as you've done in your code.
An alternative would be the PECL functions provided by PHP. These have sftp functions "built in". Example code is http://www.php.net/manual/en/function.ssh2-sftp.php and if it still doesn't work, we'll be better placed to help debug as we can all access it.

Categories