I have server running on PHP with file uploading script which I have typed in index.php. I want to upload the image file from designated path to server automatically.
PHP code:
<?php
if(isset($_POST['submit'])){
if(isset($_FILES['file'])){
$err=array();
$f_name=$_FILES['file']['name'];
//echo $f_name;
$size=$_FILES['file']['size'];
$type=$_FILES['file']['type'];
$file_tmp =$_FILES['file']['tmp_name'];
echo $file_tmp;
$file_ext=strtolower(end(explode('.',$_FILES['file']['name'])));
$allowed_ext= array('jpg','jpeg','png');
if(in_array($file_ext,$allowed_ext)==FALSE){
$err[]="extension not allowed";
}
if($size > 1000000){
$err[]='size is greater than 1MB';
}
if(empty($err)==TRUE){
//chmod('upload_image',755);
echo $_FILES['file']['tmp_name'];
$newname = dirname(__FILE__).'/upload_image/'.$f_name;
move_uploaded_file($_FILES['file']['tmp_name'],$newname);
echo 'success';
}
else{
print_r($err);
}
}
}
?>
<hr>
<form action="upload.php" method="post" enctype="multipart/form-data">
Upload your file here:<br>
<input type="file" name="file" />
<input type="submit" name="submit" value="submit"/>
</form>
Now I am trying to automate the form submission using a python script, something like:
def upload_file(path):
url='http://localhost/phptestprogram/upload.php'
files = {file: open(path,'rb')}
r = requests.post(url, files=files)
print r.text
but I am not able achieve my result.
Your php script is checking for isset($_POST['submit']) before it processes the file, but your python does not appear to be setting the post variable submit. You probably need to do something similar to:
r = requests.post(url, data = {"submit": "submit"}, files = files)
Related
I'm trying to fill this form
<form enctype="multipart/form-data" action="upload.php" method="POST">
<p>Upload your file</p>
<input type="file" name="uploaded_file"></input><br />
<input type="text" name="id"></input><br />
<input type="submit" value="Upload" name="upload"></input>
</form>
with python 3.8 using requests.post() in this way
import requests
path = "my\\path\\file.example"
id = str(input("Your id: "))
url = "http://mysite.example/upload.php"
file = {'uploaded_file': open(path, "rb"), 'id': id}
requests.post(url, files=file)
but it doesn't work.
If i fill the form manually it works, i also show you the PHP code of upload.php:
<?php
if(!empty($_FILES['uploaded_file'])){
$id = $_POST['id'];
$path = "users/".$id."/files/";
$path = $path . basename( $_FILES['uploaded_file']['name']);
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $path)){
echo "The file '". basename( $_FILES['uploaded_file']['name']).
"' has been uploaded in path: ".$path."\n";
}else{
echo "There was an error uploading the file, please try again!";
}
}
?>
Where am I doing wrong?
In files= you should send only file, not id.
files={'upload_file': open(path, "rb")}
eventually with some information about this file
files={'upload_file': ('foobar.txt', open(text,'rb'), 'text/plain')}
id should be rather in data= (eventually in json= or params=)
data={'id': id}
BTW: In PHP you could add code which display values which you get from client and then you will see if there are differences between data from form and data from requests()
Well pretty simple question.. But can't get it right for some reason.
What would be the html code to send a file to this?
move_uploaded_file($FILES["upload"]["tmpname"], $_POST["name"]);
Here's mine but when I used it and echo/vardump everything, I only have 'name' and not the file
<form action="uploader.php" method="post" id="myForm" enctype="multipart/form-data">
Select file to upload:
<input type="file" name="upload" id="upload">
<input type="text" name="name" id="name">
<button name="submit" class="btn btn-primary" type="submit" value="submit">Upload File</button>
</form>
Thank you
i try to add a comment but i can't
first check if upload permission is on in php.ini
file_uploads = On
If it set to on check your upload directory which you added in uploader.php file and use if to check $_FILES['upload'] is empty
this is a simple code to uploader.php file
<?php
if(!empty($_FILES['upload']))
{
$path = "upload/"; /// directory to upload
$path = $path . basename( $_FILES['upload']['name']);
if(move_uploaded_file($_FILES['upload']['tmp_name'], $path)) {
echo "The file ". basename( $_FILES['upload']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
}else {
echo 'No file selected to upload ';
}
I have a problem conserning uploading multiple files to my ftp server and I am using jQuery's multifile extension.
This is the multifile javascript code on page with the upload form (file_upload.php):
<script type="text/javascript">
$(function(){ // wait for document to load
$('.remove').MultiFile({
STRING: {
remove: '<img src="images/upload-remove.png" height="16" width="16" alt="x"/>',
denied:'You can't choose file $ext .\nTry again...',
file:'$file',
selected:'Chosen file: $file',
duplicate:'This file is already chosen:\n$file'
}
});
});
</script>
And this is the HTML form (file_upload.php):
<form name="uploader" action="file_upload2.php" method="post" enctype="multipart/form-data">
<fieldset>
<label for="file">Upload file:</label>
<br />
<input type="file" class="multi, remove" name="file[]" value="Upload file" />
<input type="submit" value="submit"/>
</fieldset>
</form>
The PHP part is where I don't get it. I tried to do it with this code (file_upload2.php):
<?php
if(isset($_POST['submit']))
{
$ftp_config['server'] = 'ftpserver.org'; //ftp host
$ftp_config['username'] = 'ftp_username'; // ftp username
$ftp_config['password'] = 'ftp_password'; // ftp user password
$ftp_config['web_root'] = 'public_html'; //foldername from user home dir.
$fileElementName = 'file[]'; //file field name
$conn_id = ftp_connect($ftp_config['server']);
$ftp_login = ftp_login($conn_id,$ftp_config['username'],$ftp_config['password']);
if(!ftp_put($conn_id,$ftp_config['web_root'].'/'.$_FILES[$fileElementName]['name'],$_FILES[$fileElementName]['tmp_name'],FTP_BINARY)){
$result = " Error occurred. ";
}else{
$result = " File has been uploaded. ";
}
echo $result;
}
?>
You have to loop through $_FILES for each file that was uploaded.
Do a print_r($_FILES); to see what you have to work with.
Below is my code where the user can upload a file. What I want to know is that is there a way so that via server side is there a way to first of all restrict the file formats of the files to jpeg and png only and then when the user clicks on the submit button, if the file format is correct then display an alert on the same page stating "File is correct" else display an alert stating "File is incorrect".
Can somebody please provide coding if they know how to do this. Thank you and any help will be much appreciated :)
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" 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>
</body>
</html>
A code for a total check of file uploads, you'll have to change $allowedtypes though. (Copied instead of linking because it was from a non-English site)
<?php
if(isset($_POST["submit"])){
$allowedtypes=array("jpg"=>true,"png"=>true,"gif"=>true,"txt"=>true);
$filename = $_FILES['file1']['name'];
$source = $_FILES['file1']['tmp_name'];
$file_size=$_FILES['file1']['size'];
$saveloc = "uploads/" . $filename;
$maxfilesize=1024*1024*10;
$nameext=explode(".",$filename);
if(preg_match('/^[A-Za-z0-9\-\_]{1,}\.[a-zA-Z0-9]{0,4}$/',$filename)){
if(!empty($allowedtypes[strtolower($nameext[1])]) && $allowedtypes[strtolower($nameext[1])]===true){
if($file_size<=$maxfilesize){
if(!file_exists($saveloc)){
if(move_uploaded_file($source, $saveloc)) {
chmod($saveloc,644);
echo "Successful upload. <a href='".$saveloc."'>Fájl megtekintése</a>";
}
else echo "Cannot move";
}
else echo "Existing file";
}
else echo "Too big file";
}
else echo "Not allowed extension";
}
else echo "Only alphanumeric files allowed";
}
else echo "<form method='post' enctype='multipart/form-data' action='secureupload.php'> File: <input type='file' name='file1' /><br /><input
name='MAX_FILE_SIZE' type='hidden' value='10485760' /> <input type='submit' value='Upload' name='submit' /></form>";
?>
You are talking about server side handler and write 'alert'...khm...
If u want to do stuff via server-side, then use php handler
http://php.net/manual/en/features.file-upload.post-method.php
If u want to do stuff via client-side, use javascript events, e.g on change event
<script>
function check() {
var file = document.getElementById('file').value;
var temp = file.split(/\.+/).pop();
alert(temp);
}
</script>
<input type="file" name="file" id="file" onchange="check();" />
You have file extension in temp var.
There are PHP functions to do this. You want to look at mime_content_type and finfo_file. These are built-in PHP commands that allow you to interpret that actual file type of a file being uploaded. You can then filter the mime types to only .gif/.jpg/etc. You want to check the mime types over the file name because the file name can be changed to mask the actual file type. If you want code samples, there are plenty on those pages as well as some excellent user-provided alternatives.
Something like this at the top of your file should work:
<?php
foreach ($_FILES as $file)
{
$tmp = explode(".", $file["tmp_name"]);
if (!in_array($tmp[count($tmp)-1], array("jpeg", "png"), true))
die("<script>alert('File is incorrect');</script>");
}
echo "<script>alert('File is correct');</script>";
?>
I am building a php application.
I can easily upload an image or any other type of data, but not a .jar. Below my code:
Upload.php
<form action="getfile.php" method="post" name="uploadForm" id="uploadForm" enctype="multipart/form-data" ><br>
<?php echo gettext("Image "); ?>
<input name="imagen" value="" type="file" id="imagen" />
<?php echo gettext("Jar "); ?>
<input name="jarFile" value="" type="file" id="jarFile" />
</form>
getfile.php
$fileName = $_FILES['jar']['name'];
$fileType = $_FILES['jar']['type'];
//Check the extension
if (!strpos($fileType, "jar") ) {
echo gettext("The simulation must be jar extension. Try again.");
}else{
if (move_uploaded_file($_FILES['jar']['tmp_name'], $path)){
echo gettext("Simulation stored succesfully.");
}else{
echo gettext("Something happened. Try again. ");
}
}
For images I am following the same aproach, but when I try to upload a jar file, I am always getting the error
The simulation must be jar extension. Try again
and $fileType is empty. Is there some restriction at this point? Am I missing something??
Thanks in advance
The type property is unreliable (and populated by the browser). Your best bet is to retrieve the MIME file type:
$fhandle = finfo_open(FILEINFO_MIME);
$mime_type = finfo_file($fhandle, $_FILES['jar']['tmp_name']);
The $mime_type should be application/java-archive.
PHP >= 5.3.0