PHP uploading an image by posting a form [closed] - php

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
i am trying to upload image through following code.
although my if condition is executing as shown below but image is not moving to the specified path given by me. my code is below.
here is my html code
<form enctype="multipart/form-data" action="catcher.php" method="POST">
Send this file: <input name="userfile" type="file" />
<input type="submit" value="Send File" />
</form>
and here is my php code
<?php
$uploaddir = '/xampp/project/';
echo '<pre>';
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploaddir)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Possible file upload attack!\n";
}
echo 'Here is some more debugging info:';
print_r($_FILES);
print "</pre>";
?>
can any body point out whats wrong with my code i mean why the image i am trying to upload is not moving to the specified path,,

move_uploaded_file() requires the second parameter to be destination file, not directory.
You could do:
$filename = $uploaddir . basename($_FILES['userfile']['tmp_name']);
if( move_uploaded_file($_FILES['userfile']['tmp_name'], $filename)){
// ...
But there is good chance that multiple users will try to upload files with the same name, so I strictly recommend to handle this possibility.

$folder = "../images/stories/";
$result = move_uploaded_file($_FILES['excel']['tmp_name'], $folder.$filename);
Give destination folder name. (In above code, $folder is destination path variable)
You can see detail on this function:
function upload($name,$tmp_name){
$fileextarr=explode('.',$name);
$fileextarr[0];
$fileext=$fileextarr[count($fileextarr)-1];
$fpath = "../images/stories/lab_excel/";
$filename = ereg_replace(" ","_",$fileextarr[0]).'.'.$fileext;
//You can use restriction on file extensions also. (not necessary)
if($fileext=="xls" || $fileext=="xlsx" || $fileext=="doc"|| $fileext=="docx" || $fileext=="jpeg" || $fileext=="png" || $fileext=="gif" || $fileext=="tiff" || $fileext=="bmp" || $fileext=="jpg")
{
$uploadedfile = $filename;
}
//Here is the use of destination path:
$folder = "../images/stories/lab_excel/";
$result = move_uploaded_file($_FILES['excel']['tmp_name'], $folder.$filename);
/*echo $folder.$_FILES['excel']['name'];
die();*/
if($result){
$msg="File Uploaded Successfully";
return $folder.$filename;
}
else
{
return false;
}
}

Related

Cannot remove images from directory [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I have written these scripts to delete files (image, in fact) in a directory but have the choice to decide which one to delete and view before hand. The view.php script seems to be working fine, however the delete.php doesn't seem to be functioning because the images are not removing.
here are the scripts:
view.php
<?php
$path = '../product-uploads/gloves/'; // path for each page
$files = glob("{$path}*.*"); // Get the files
$files = array_filter($files, 'is_file'); // Get rid of directories
$dates = array_map('filectime', $files); // Get the creation times.
$md5s = array();
array_multisort($dates, $files, SORT_NUMERIC); // in order of creation
foreach ($files AS $file)
{
$hash = md5_file($file);
if (!in_array($hash, $md5s))
{
$md5s[] = $hash;
echo "<img src=\"$file\" /> <br />
<form action=\"delete.php\" method=\"post\">
<input type=\"hidden\" name=\"Name\" value=\"$file\">
<input type=\"submit\" value=\"Delete\">
</form>";
}
}
?>
delete.php
<?php
$path = '../product-uploads/gloves/';// images are here
$Name = $_POST['Name'];
$PathFile = $path.$Name;
$PathFile = basename($PathFile);
header('Location: view.php');
?>
This is because you don't remove the images in your delete.php
Use unlink on pathfile.

Create ZIP via PHP in a specific directory [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I found this awesome code to create a ZIP file using PHP via this link compress/archive folder using php script
<?php
// Config Vars
$sourcefolder = "./" ; // Default: "./"
$zipfilename = "myarchive.zip"; // Default: "myarchive.zip"
$timeout = 5000 ; // Default: 5000
// instantate an iterator (before creating the zip archive, just
// in case the zip file is created inside the source folder)
// and traverse the directory to get the file list.
$dirlist = new RecursiveDirectoryIterator($sourcefolder);
$filelist = new RecursiveIteratorIterator($dirlist);
// set script timeout value
ini_set('max_execution_time', $timeout);
// instantate object
$zip = new ZipArchive();
// create and open the archive
if ($zip->open("$zipfilename", ZipArchive::CREATE) !== TRUE) {
die ("Could not open archive");
}
// add each file in the file list to the archive
foreach ($filelist as $key=>$value) {
$zip->addFile(realpath($key), $key) or die ("ERROR: Could not add file: $key");
}
// close the archive
$zip->close();
echo "Archive ". $zipfilename . " created successfully.";
// And provide download link ?>
<a href="http:<?php echo $zipfilename;?>" target="_blank">
Download <?php echo $zipfilename?></a>
I would like to create the zip in a particular directory.
$zipfilename = "/path/to/my/zip/folder/myarchive.zip";
Simply make sure the folder is writable.

PHP Upload Data [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I am currently making a website where you can upload and download files like a cloud server or something of that sort. I was just wondering what happens if i dont have space on a Hard drive how would i tell PHP to upload to upload to a different hard drive and just stuff like that?
i have this code and i will be adding security but right now im testing:
<?php
set_time_limit(30000);
session_start();
include('../Connect/Connect.php');
$User = $_SESSION['User'];
$Get = 'SELECT * FROM Users WHERE Username = "'.$User.'"';
$Files = $_FILES['File'];
if(isset($User))
{
if(!empty($Files))
{
if($Result = $Connect->query($Get))
{
while($Row = $Result->fetch_assoc())
{
$Limit = $Row['Limit'];
for($X = 0; $X < count($Files['name']); $X++)
{
$Name = $Files['name'][$X];
$TMP = $Files['tmp_name'][$X];
move_uploaded_file($TMP, '../Users/' . $User . '/' . $Name);
}
}
}
}
}
else
{
header("location:../");
}
header("location:index.php");
$Connect->close();
?>
You could always use disk_free_space() before you try to upload/move files. Also, move_uploaded_file will probably return false, but that can be also because of other issues such as permissions.

how to upload a csv file and update the mysql db? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I want to use a csv file to update the mysql scv table. how to code ? I have no experiece doing this job.
<p>please select a scv file to upload</p>
<form action="index.php" method="post">
<input type="file" name="scv" />
<input type="submit" value="submit" />
</form>
<?php
mysql_connect('localhost','root','admin');
mysql_select_db('linjuming');
// how to upload a scv file and insert or update the "csv" table?
?>
Your upload file:
<form action="upload_target.php" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file"><br>
<input type="submit" name="submit" value="Submit">
</form>
Your upload_target.php
$ext = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
if ($ext == "csv" && $_FILES["file"]["error"] == 0)
{
$target = "upload/" . $_FILES["file"]["name"];
move_uploaded_file($_FILES["file"]["tmp_name"], $target);
if (($handle = fopen($target, "r")) !== FALSE)
{
while (($data = fgetcsv($handle, 1000, ";")) !== FALSE)
{
print_r($data);
}
fclose($handle);
}
}
Very basic and with very few checks / validations. The print_r($data) contains one line of your csv that you can now insert in your database.
However, I would recommend using PDO or MySQLi for that task, since the mysql functions of PHP will be deprecated in the future.
There's several parts of this:
First, your form MUST have the enctype set, as follows:
<form enctype="multipart/form-data" action="index.php" method="post">
Otherwise, it will not accept file uploads.
Once you've done that, then you can access the file using the $_FILES variable. After the file has been uploaded, then you can access it like so:
if (isset($_FILES["scv"])) {
$file = $_FILES["scv"];
$file_name = $file["name"];
$ext = pathinfo($file_name, PATHINFO_EXTENSION);
if ($ext!="CSV" && $ext!="TXT") {
die('The file must be csv or txt format.');
}
$saveto_path_and_name = '/path/to/file.csv'; // Where you want to save the file
move_uploaded_file($file["tmp_name"], $saveto_path_and_name);
}
Once you've saved the file, you then can open it and import it. That's not trivial to do, but here's some primer code:
// Open the file for reading
$handle = #fopen($saveto_path_and_name, "r") or die(__("Unable to open uploaded file!", "inventory"));
// Grab the first row to do some checks
$row = fgets($inv_file, 4096);
// See if it's comma or tab delimited
if (stripos($inv_row, "\t")) {
$sep = "\t";
} else {
$sep = ",";
}
while ( ! feof($handle)) {
$rowcount = 0;
// Get the individual fields
$inv_fields = explode($sep, $inv_row);
$fields = array();
// Iterate through the fields to do any sanitization, etc.
foreach ($inv_fields as $field) {
// Highly recommended to sanitize the variable $field here....
$fields[] = $field;
$rowcount++;
}
// This is where you would write your query statement to insert the data
// This is just EXAMPLE code. Use the DB access of your choice (PDO, MySQLi)
$sql = vsprintf('INSERT INTO `table` (`column`, `column2`, ...) VALUES (%s, %d, ...)', $fields);
// Get the next row of data from the file
$row = fgets($inv_file, 4096);
}

How to Secure php picture upload system [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I want to make picture upload system with php and i want users will be able to upload just
png,jpg files and not viruses or other files. how can i do this?
($_FILES["file"]["type"] == "image/png")
for more information about this click here
step 1: Check the extension (extension file ends with)
step 2: Check the MIME type ($file_info = getimagesize($_FILES['image_file']; $file_mime = $file_info['mime'];)
only allow the those image extension which you want to upload , for that you can make the white list
try something like
$whitelist = array(".jpeg",".jpg",".png");
foreach ($whitelist as $item)
{
if(preg_match("/$item\$/i", $_FILES['uploadfile']['name']))
{
$uploaddir='uploads/uploads_image/';
$uploadfilename=mysql_prep(basename($_FILES['uploadfile']['name']));
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
$iv= mcrypt_create_iv($iv_size,MCRYPT_DEV_RANDOM);
$newname= mcrypt_encrypt(MCRYPT_RIJNDAEL_256, "this is the key",$uploadfilename.time(), MCRYPT_MODE_ECB, $iv);
$newfilename= (bin2hex($newname));
$uploadfile=$uploaddir.$newfilename.".png";
$access=true;
}
}
you can also block the ip of the user if user try to upload miscellaneous file by making the black list
foreach ($blacklist as $item)
{
if(preg_match("/$item\$/i", $_FILES['uploadfile']['name']))
{
$network = ip2long("10.12.0.0");
$mask = ip2long("255.255.0.0");
$ip = ip2long($_SERVER{'REMOTE_HOST'});
if (($network & $mask) == ($ip & $mask)) {
die("Unauthorized");
}
}
}
1st check:-
//check if contain php and kill it
$pos = strpos($filename,'php');
if(!($pos === false)) {
die('error');
}
2nd check:-
//get the file ext
$file_ext = strrchr($filename, '.');
$image_list = array(".jpg",".jpeg",".gif",".png");
if (!(in_array($file_ext, $image_list))) {
die('not allowed extension,please upload images only');
}
3rd check:-
$fileType = $_FILES["uploaded_file"]["type==image/jpeg || image/gif || image/png"];
4th check:-
preg_match("/.(gif|jpg|png)$/i", $fileName);
hope these checks solve your problem....

Categories