Adding the row ID to the filename of the uploaded file - php

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);

Related

Multiple Upload File with Unusual Condition PHP

I have this add button to select the file inside a upload form field:
$("#add_attachment").on('click', function() {
var no_attachment = parseInt($('#noa').val()) + 1;
$('#noa').val(no_attachment);
$("#tbody_attachment").append("<tr><td bgcolor='#d9d9d9' class='td-data_1'><div class='col-xs-12'><input type='number' class='form-control' name='noa_save[]' id='noa_save' placeholder='No' value='" + no_attachment + "' /></div></td><td bgcolor='#d9d9d9' class='td-data_1'><div class='col-xs-12'><input type='file' class='form-control' name='attachment_save[]' id='attachment_save' placeholder='Attachment'/></div></td><td bgcolor='#d9d9d9' class='td-data_1'><div align='center'><input type='button' name='attachment' id='remove_attachment' value='Remove' style='font-size:16px; width: 98%;'/></div></td></tr>");
});
$("#tbody_attachment").on('click', '#remove_attachment', function() {
$(this).closest('tr').remove();
var no_attachment = $('#noa').val();
$('#noa').val(parseInt(no_attachment) - 1);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" action="save_sop.php" enctype="multipart/form-data">
<div align="center">
<table class="table" id="t_attachment">
<thead>
<tr>
<th width="10%" bgcolor="#8eb4e3" class="td-data_1">
<div align="center">
<font size="3dp"><strong>No</strong></font>
</div>
</th>
<th bgcolor="#8eb4e3" class="td-data_1">
<div align="center">
<font size="3dp"><strong>Attachment</strong></font>
</div>
</th>
<th width="10%" bgcolor="#8eb4e3" class="td-data_1">
<div align="center">
<font size="3dp"><strong>Button</strong></font>
</div>
</th>
</tr>
</thead>
<tbody id="tbody_attachment">
<tr>
<td bgcolor="#d9d9d9" class="td-data_1">
<div class="col-xs-12">
<input type="number" class="form-control" name="noa" id="noa" placeholder="No" value="0" />
</div>
</td>
<td bgcolor="#d9d9d9" class="td-data_1">
<div class="col-xs-12">
<div align="justify">
<font size="3dp"><strong>Choose file after clicking Add button</strong></font>
</div>
</div>
</td>
<td bgcolor="#d9d9d9" class="td-data_1">
<div align="center"><input type="button" name="add_attachment" id="add_attachment" value="Add" style="font-size:16px; width: 98%;" /></div>
</td>
</tr>
</tbody>
</table>
</div>
</form>
You can run the code above to give an idea how's the form works.
And in the save_sop.php file, I have to upload the files that submitted from the previous form and also get the file name to be stored to MySQL database as a JSON array value.
Here's the code so far in the save_sop.php file:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
include 'con.php';
$total_attachment = mysqli_real_escape_string($con, $_POST['noa']);
$attachment["no"] = $_POST['noa_save'];
foreach($_FILES['attachment_save']['name'] as $filename) {
$imgFile = $filename;
$tmp_dir = $_FILES['attachment_save']['tmp_name'];
$imgSize = $_FILES['attachment_save']['size'];
$folder = 'sop/attachment/'; // upload directory
$imgExt = strtolower(pathinfo($imgFile, PATHINFO_EXTENSION)); // get image extension
// valid image extensions
$valid_extensions = array('jpeg', 'jpg', 'png', 'gif'); // valid extensions
// rename uploading image
$img = rand(1000, 1000000) . "." . $imgExt; //generate the random file name
// allow valid image file formats
if (in_array($imgExt, $valid_extensions)) {
// Check file size '50MB'
if ($imgSize < 5000000) {
//move_uploaded_file($tmp_dir, $folder . $img);
} else {
$errMSG = "Sorry, your file is too large.";
}
} else {
$errMSG = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
}
echo "Generated File Name: " . $img . "<hr />";
$attachment['attachment'] = $img;
}
$attachment_save = json_encode($attachment, true);
echo $attachment_save;
}
?>
When the echo $attachment_save called, the result I get is below.
Generated File Name: 430609.jpg
<hr />
Generated File Name: 575033.jpg
<hr />
{"no":["1","2"],"attachment":"575033.jpg"}
Inside foreach loop, I called echo "Generated File Name:" . $img; I do get the result as expected, but in the attachment array, I only get one filename instead of two.
I need to get two file name value inside the attachment['attachment'] array. The result expected should be:
{"no":["1","2"],"attachment":["430609.jpg", "575033.jpg"]}
Can anybody help me with this? thanks in advance.
Regards.
the answer lies on
$attachment. Instead of $attachment['attachment'] = $img;
it should be
$attachment['attachment'][] = $img;
and it's working perfectly.

image not uploading/moving into folder

i am uploading an image , image title is getting added to database but the file(image is not uploading/moving to the folder), i am getting 404 error for that image , i have set that folder permissions to 0777 and also max upload is 1024MB
$article_image = $_FILES['image']['name'];
$image_tmp = $_FILES['image']['tmp_name'];
define ('SITE_ROOT', realpath(dirname('_FILE_')));
move_uploaded_file($image_tmp,SITE_ROOT.'/images/$article_image');
$add="insert into articles(article_title,article_date,article_author,category,article_image,article_keywords,article_content) values ('$article_title','$article_date','$article_author','$article_category','$article_image','$article_keywords','$article_content')" ;
if(mysqli_query($conn,$add)== 1 ){
echo "<script> alert('article added')</script>";
}
else{
echo "failed".mysqli_error($conn) ;
}
}
what mistake am i doing ?
EDIT here is my html code
<form method="post" action="addarticle.php" enctype="multipart/form-data">
<table align="center">
<tr>
<td align="center"><h1> ADD ARTICLE</h1></td>
</tr>
<tr>
<td>Article Title</td>
<td><input type="text" name="title"></td>
<tr>
<td>Article Keyword</td>
<td><input type="text" name="keywords"></td>
<tr>
<td>Article Image</td>
<td><input type="file" name="image"></td>
</tr>
<td>Article Content</td>
<td><textarea name="content" cols="90" rows="30"></textarea></td>
</tr>
<tr>
<td><input type="submit" name="submit" value="submit"></td>
</tr>
</table>
</form>
Check your line with:
realpath(dirname('__FILE__'));
__FILE__
is a magic constant, and should not be wrapped in single or double quotes.
If you were to echo out the result of that function call you would probably see a different path than what you're expecting.
You're also trying to use string interpolation with single quotes around the variable instead of double:
SITE_ROOT.'/images/$article_image';
Should be:
SITE_ROOT."/images/$article_image";
Example:
if (!empty($_FILES['image'])) {
$tmp_file_to_upload = $_FILES['image'];
if ($_FILES['image']['error'] == UPLOAD_ERR_OK) {
$uploaded_name = $tmp_file_to_upload['name'];
$tmp_name = $tmp_file_to_upload['tmp_name'];
$destination = realpath(dirname(__FILE__))."images/$uploaded_name";
if (!move_uploaded_file($tmp_name, $destination)) {
die('Error uploading file.');
}
} else {
die('Error uploading file.');
}
}
Try this, Variable concatenation issue '/images/'.$article_image
move_uploaded_file($image_tmp,SITE_ROOT.'/images/'.$article_image);
instead of
move_uploaded_file($image_tmp,SITE_ROOT.'/images/$article_image');

Display Multple Uploaded Images on page with PHP

Okay, this is what I got so far, I'm able to upload one image and display it in a div, but I just cant seem to figure out how to do the same for loading multiple images. As in upload multiple images and display all uploaded images on screen. Any help is appreciated, thanks in advance.
Also: I kinda think I have to set a variable for
$_FILES['image']['name'][0]
$_FILES['image']['name'][1]
etc
and do a forloop to print it out? Correct me if I am wrong?
<?php
// prevent timezone warnings
date_default_timezone_set('America/New_York');
// set the upload location
$UPLOADDIR = "tmp";
// if the form has been submitted then save and display the image(s)
if(isset($_POST['Submit'])){
// loop through the uploaded files
foreach ($_FILES as $key => $value){
$image_tmp = $value['tmp_name'];
$image = $value['name'];
$image_file = "{$UPLOADDIR}{$image}";
// move the file to the permanent location
if(move_uploaded_file($image_tmp,$image_file)){
echo <<<HEREDOC
<div style="float:left;margin-right:10px">
<img src="{$image_file}" alt="file not found" /></br>
</div>
HEREDOC;
}
else{
echo "<h1>image file upload failed, image too big after compression</h1>";
}
}
}
else{
?>
<form name='newad' method='post' enctype='multipart/form-data' action=''>
<table>
<tr>
<td><input type='file' name='image'></td>
</tr>
<tr>
<td><input name='Submit' type='submit' value='Upload image'></td>
</tr>
</table>
</form>
<?php
}
?>
I' am not sure which CMS/Framework this is but If you change this line
From
<input type='file' name='image'>
To
<input type='file' name='image[]' multiple>
Hope this helps you out.
How are multiple files, you must have two loops. Put a foreach inside a for.
I believe that is what you want. Make sure the tmp folder has write permission.
<?php
// prevent timezone warnings
date_default_timezone_set('America/New_York');
// set the upload location
$UPLOADDIR = "tmp";
// if the form has been submitted then save and display the image(s)
if(isset($_POST['Submit'])){
$num_files = count($_FILES['image']['tmp_name']);
for($x = 0; $x < $num_files; $x++){
$image = $_FILES['image']['name'][$x];
$image_file = $UPLOADDIR."/". $image;
if(!is_uploaded_file($_FILES['image']['tmp_name'][$x])){
$messages[] = '<h1>'.$image.' image file upload failed, image too big after compression</h1>."<br>"';
}
if (move_uploaded_file($_FILES["image"]["tmp_name"][$x],$image_file)){
echo '
<div style="float:left;margin-right:10px">
<img src="'.$image_file.'" alt="file" /></br>
</div>';
} else{
echo "<h1>image file upload failed, image too big after compression</h1>";
}
}
}else {
?>
<form name='newad' method='post' enctype='multipart/form-data' action=''>
<table>
<tr>
<td><input type='file' name='image[]'></td>
</tr>
<tr>
<td><input type='file' name='image[]'></td>
</tr>
<tr>
<td><input name='Submit' type='submit' value='Upload image'></td>
</tr>
</table>
</form>
<?php
}
?>

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.

php multiple file upload script

Does anyone know of a good php or ajax multiple file upload script to upload to a web server?
The difference here is that nothing can be required on the client machine ie no flash!
I would like it to work just with the browser.
digitarald’s fancy upload
<table width="500" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<form action="multiple_upload_ac.php" method="post" enctype="multipart/form-data" name="form1" id="form1">
<td>
<table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">
<tr>
<td><strong>multiple Files Upload </strong></td>
</tr>
<tr>
<td>Select file
<input name="ufile[]" type="file" id="ufile[]" size="50" /></td>
</tr>
<tr>
<td>Select file
<input name="ufile[]" type="file" id="ufile[]" size="50" /></td>
</tr>
<tr>
<td>Select file
<input name="ufile[]" type="file" id="ufile[]" size="50" /></td>
</tr>
<tr>
<td align="center"><input type="submit" name="Submit" value="Upload" /></td>
</tr>
</table>
</td>
</form>
</tr>
</table>
STEP2: Create file multiple_upload_ac.php
<?php
//set where you want to store files
//in this example we keep file in folder upload
//$HTTP_POST_FILES['ufile']['name']; = upload file name
//for example upload file name cartoon.gif . $path will be upload/cartoon.gif
$path1= "upload/".$HTTP_POST_FILES['ufile']['name'][0];
$path2= "upload/".$HTTP_POST_FILES['ufile']['name'][1];
$path3= "upload/".$HTTP_POST_FILES['ufile']['name'][2];
//copy file to where you want to store file
copy($HTTP_POST_FILES['ufile']['tmp_name'][0], $path1);
copy($HTTP_POST_FILES['ufile']['tmp_name'][1], $path2);
copy($HTTP_POST_FILES['ufile']['tmp_name'][2], $path3);
//$HTTP_POST_FILES['ufile']['name'] = file name
//$HTTP_POST_FILES['ufile']['size'] = file size
//$HTTP_POST_FILES['ufile']['type'] = type of file
echo "File Name :".$HTTP_POST_FILES['ufile']['name'][0]."<BR/>";
echo "File Size :".$HTTP_POST_FILES['ufile']['size'][0]."<BR/>";
echo "File Type :".$HTTP_POST_FILES['ufile']['type'][0]."<BR/>";
echo "<img src=\"$path1\" width=\"150\" height=\"150\">";
echo "<P>";
echo "File Name :".$HTTP_POST_FILES['ufile']['name'][1]."<BR/>";
echo "File Size :".$HTTP_POST_FILES['ufile']['size'][1]."<BR/>";
echo "File Type :".$HTTP_POST_FILES['ufile']['type'][1]."<BR/>";
echo "<img src=\"$path2\" width=\"150\" height=\"150\">";
echo "<P>";
echo "File Name :".$HTTP_POST_FILES['ufile']['name'][2]."<BR/>";
echo "File Size :".$HTTP_POST_FILES['ufile']['size'][2]."<BR/>";
echo "File Type :".$HTTP_POST_FILES['ufile']['type'][2]."<BR/>";
echo "<img src=\"$path3\" width=\"150\" height=\"150\">";
///////////////////////////////////////////////////////
// Use this code to display the error or success.
$filesize1=$HTTP_POST_FILES['ufile']['size'][0];
$filesize2=$HTTP_POST_FILES['ufile']['size'][1];
$filesize3=$HTTP_POST_FILES['ufile']['size'][2];
if($filesize1 && $filesize2 && $filesize3 != 0)
{
echo "We have recieved your files";
}
else {
echo "ERROR.....";
}
//////////////////////////////////////////////
// What files that have a problem? (if found)
if($filesize1==0) {
echo "There're something error in your first file";
echo "<BR />";
}
if($filesize2==0) {
echo "There're something error in your second file";
echo "<BR />";
}
if($filesize3==0) {
echo "There're something error in your third file";
echo "<BR />";
}
?>
I found this code in http://www.phpeasystep.com/phptu/2.html
for more details check Tutorial
FancyUpload
SWFUpload
I'm a fan of plupload which support a wide variety of client technologies (html5, flash, silverlight, browserplus, gears) in addition to basic single file html4 upload, unlike SWFUpload which only does flash + html4 fallback.
It also integrates nicely with jQuery.

Categories