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.
Related
The below program is not working.
add_product.php
<?php
$name=$_REQUEST["txtname"];
$price=$_REQUEST["txtprice"];
$category=$_REQUEST["ddlcategory"];
$weight=$_REQUEST["txtweight"];
$description=$_REQUEST["txtdescription"];
$img=$_REQUEST["btnimage"];
$connect=mysql_connect("localhost","root","","CakeShop") or die(mysql_error());
echo "Connected..";
mysql_select_db(CakeShop);
if(isset($_REQUEST['btnadd']))
{
//The if loop gets executed even if the image is selected....!
if(getimagesize($Files['btnimage']['tmp_name'])==FALSE)
{
$message="Please select an image";
echo "<script type='text/javascript'>alert('$message');</script>";
}
else
{
$insert="Insert into tblProduct(p_name,p_price,p_category,p_weight,p_description,p_image) values ('$name','$price','$category','$weight','$description','$img');";
mysql_query($insert) or die("Failed to insert data");
echo "<h3>Product Details Inserted........</h3>";
}
}
mysql_close();
?>
add_product.html
<html>
<head>
<title>Cake Central</title>
</head>
<body>
<h1>ADD NEW PRODUCT</h1>
<hr>
<form method="post" action="add_product.php">
<table>
<tr>
<td>Name:</td>
<td><input type="text" name="txtname"></td>
</tr>
<tr>
<td>Price:</td>
<td><input type="text" name="txtprice"></td>
</tr>
<tr>
<td>Category:</td>
<td>
<select name="ddlcategory">
<option>Veg</option>
<option>Non-Veg</option>
</select>
</td>
</tr>
<tr>
<td>Weight:</td>
<td><input type="text" name="txtweight"></td>
</tr>
<tr>
<td>Description:</td>
<td><textarea rows="2" cols="16" name="txtdescription"></textarea></td>
</tr>
<tr>
<td>Image:</td>
<td><input name="btnimage" type="file" /></td>
</tr>
<tr>
<td><input class="btn" type="submit" name="btnadd" value=" Add "></td>
</tr>
</table>
</form>
</body>
</html>
I have simplified your code to the best of my knowledge. You don't really need two different pages so I have removed the action = "" in the form tag. Please let me know how it goes.
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
else
{
$db_selected = mysql_select_db('CakeShop', $conn);
if (!$db_selected)
{
die ('Can\'t Select DB : ' . mysql_error());
}
}
if(isset($_POST['check']) && $_FILES['file']['size'] > 0)
{
$name=$_POST["txtname"];
$price=$_POST["txtprice"];
$category=$_POST["ddlcategory"];
$weight=$_POST["txtweight"];
$description=$_POST["txtdescription"];
$tmpName = $_FILES['file']['tmp_name'];
$fp = fopen($tmpName, 'r');
$img = fread($fp, filesize($tmpName));
$img = addslashes($img);
fclose($fp);
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
}
$query = "INSERT INTO tblProduct (p_name,p_price,p_category,p_weight,p_description,p_image)
VALUES ('$name','$price','$category','$weight','$description','$img')";
mysql_query($query) or die('Error, query failed');
$imgid = mysql_insert_id();
echo "<br>Details successfully added to database<br>";
}
else
die('You have not selected any image');
?>
<html>
<head>
<title>Cake Central</title>
</head>
<body>
<h1>ADD NEW PRODUCT</h1>
<hr>
<form method="post" action="" enctype="multipart/form-data">
<table>
<tr>
<td>Name:</td>
<td><input type="text" name="txtname"></td>
</tr>
<tr>
<td>Price:</td>
<td><input type="text" name="txtprice"></td>
</tr>
<tr>
<td>Category:</td>
<td>
<select name="ddlcategory">
<option>Veg</option>
<option>Non-Veg</option>
</select>
</td>
</tr>
<tr>
<td>Weight:</td>
<td><input type="text" name="txtweight"></td>
</tr>
<tr>
<td>Description:</td>
<td><textarea rows="2" cols="16" name="txtdescription"></textarea></td>
</tr>
<tr>
<td>Image:</td>
<td><input name="btnimage" type="file" /></td>
</tr>
<tr>
<td><input type="hidden" name="check"></td>
</tr>
<tr>
<td><input class="btn" type="submit" name="btnadd" value=" Add "></td>
</tr>
</table>
</form>
</body>
</html>
Note: Since you are really new and have no idea about mysqli/PDO, I
have suggested a link and you will find alot of other useful articles
on this site as well, One of the reason why I did not change it to
mysqli/PDO was because I did not want you to get confused. cheers
Try adding the enctype attribute to the form tag.
<form method="post" action="add_product.php" enctype="multipart/form-data" >
I have this form
If the first radio button is clicked, the textfield below it is enabled and if the 2nd radio button is clicked, the file upload is enabled and the former is disabled,vice versa. It works fine if the file upload option is chosen but if the 1st radio button is chosen and the file upload is disabled, it doesn't insert data in the database. :/ What should be done to successfully send the form details even if the file upload is disabled/empty?
CODE:
<form name="form" method="POST" enctype="multipart/form-data">
<table width="416" height="245" border="1" align="center">
<tr>
<td colspan="2">Transaction No: <input type="text" name="transaction_no" id="transaction_no" /> </td>
</tr>
<tr>
<td colspan="2" align="center">Please select the mode of payment</td>
</tr>
<tr>
<td width="183" align="center"><input name="rad" type="radio" onclick="enableField(this)" value="Smart Money" checked="checked">
Smart Money</td>
<td width="201" align="center"><input name="rad" type="radio" onclick="enableField(this)" value="BPI"> BPI Bank Deposit</td>
</tr>
<tr>
<td align="center"><input type="text" name="contactno" id="contactno"></td>
<td align="center"><input name="filename" type="file" id="filename" disabled="disabled"/></td>
</tr>
<tr>
<td>Total amount sent:</td>
<td> <input type="text" name="totalsent" id="totalsent" /></td>
</tr>
<tr>
<td>Date sent:</td>
<td> <input type="text" name="datesent" id="datesent" /></td>
</tr>
<tr>
<td colspan="2" align="center"><input name="submit" type="submit" id="submit" value="Submit" /></td>
</tr>
</table>
<input type="hidden" name="MM_insert" value="form" />
</form>
PHP
<?php
if(isset($_FILES['filename'])){
$errors = array();
$file_name = $_FILES['filename']['name'];
$file_size =$_FILES['filename']['size'];
$file_tmp =$_FILES['filename']['tmp_name'];
$file_type=$_FILES['filename']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['filename']['name'])));
$expensions= array("jpeg","jpg","png");
if(in_array($file_ext,$expensions)=== false){
$errors[]="extension not allowed, please choose a JPEG or PNG file.";
}
if($file_size > 2097152){
$errors[]='File size must be excately 2 MB';
}
// pag walang error...
if (empty($errors)==true) {
// upload the file...
move_uploaded_file($file_tmp,"uploads/".$file_name);
$servername = "localhost";
$username = "root";
$password = " ";
$dbname = "admin";
// create new record in the database
include ("dbinfo.php");
mysql_query("INSERT INTO payment_form (date, Tracking, mode, ContactNo, totalsent, datesent, filename) VALUES (NOW(), '$transactionNo', '$rad', '$contactNo', '$totalSent', '$dateSent', '$file_name')") ;
header('Location: paymentform_success.php');
}else{
print_r($errors);
}
}
?>
Javascript for enable/disable
<script type="text/javascript">
function enableField(obj){
var form=obj.form;
var txtNames=['contactno','filename'], f;
var rads=document.getElementsByName(obj.name), r, i=0;
while(r=rads[i++]){
f=form[txtNames[i-1]];
if(r.checked){
f.removeAttribute('disabled');
f.focus();
}
else{
f.value='';
f.setAttribute('disabled','disabled')
}
}
}
</script>
You should first check which radio is checked and then decide what to do. It's not working because the whole script is under the if(isset($_FILES['filename'])). If the file upload is disabled then $_FILES will not be set and nothing will be executed.
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"]
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);
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'";