Passing an uploaded file to a python script - php

I am trying to pass an uploaded file as an argument to a python script.
form.php
<html>
<body>
<form method="post" enctype="multipart/form-data" action = "formdata.php">
<label for="file">Upload File:</label>
<input type="file" name="file" id="file" />
<label for="user_email">Email:</label>
<input type="text" name="user_email" id="user_email" />
<input type="submit" id="submit" value="Submit" />
</form>
</body>
</html>
fomrdata.php
<?php
$email = $_POST['user_email'];
$uploaded_file = //don't know what to do here
$output = shell_exec("/usr/bin/python /var/www/Create.py $uploaded_file $email);
echo "<pre>$output</pre>";
?>
Create.py
# def moveMetadataFile():
# import shutil
# shutil.copyfile('/var/www/**uploaded_file**', '/var/www/temp/**uploaded_file**')
# some more code
upload = sys.argv[1]
email = sys.argv[2]
This works fine and I get the email and everything from the user and the code works if I specify a file name myself but now I want the python script to use the file that the user uploads. And I have absolutely no idea where to start?
If it's easier to answer this ignoring the commented out part then that'll work too.

You can get the filename using
$uploaded_file = $_FILES['file']['tmp_name'];
From the PHP documentation for tmp_name:
The temporary filename of the file in which the uploaded file was stored on the server.
See the PHP documentation | POST method uploads for more information. You would probably also want to use some of the other fields to make sure an error did not occur prior to calling the Python script.
Does that help?

Related

HTML not posting file to PHP

Here is my code:
<html>
<body>
<div>
<form action="<?=$_SERVER['PHP_SELF'];?>" method="post">
<input type="file" id="myFile" name="filename">
<input type="submit" name="Submit">
</form>
</div>
<?php
if(isset($_POST['Submit']))
{
$file = $_POST["myFile"];
echo("hello");
}
?>
</body>
</html>
when I run it and input a file it says: Undefined array key "myFile"
what am I doing wrong?
Uploaded files don't get added to the $_POST array but they are loaded into the $_FILES array. Try check that out.
You can then use the move_uploaded_file() to save it wherever you want.
Important: as soon as the script execution is over, the temporary uploaded file is removed if it was not saved somewhere else with move_uploaded_file().
The request transfers the data using the names of the form fields and not the IDs, the file data can be found in the global variable $_FILES.
Use $file = $_FILES['filename']['name']; for the name of the uploaded file
or $file = $_FILES['filename']['tmp_name']; for the temporary file path of the uploaded file.
Add on form enctype="multipart/form-data"
This value is necessary if the user will upload a file through the form.
Your file type name is "filename".
<html>
<body>
<div>
<form action="<?=$_SERVER['PHP_SELF'];?>" method="post" enctype="multipart/form-data">
<input type="file" id="myFile" name="filename">
<input type="submit" name="Submit">
</form>
</div>
<?php
if(isset($_POST['Submit']))
{
$file = $_FILES['filename']['tmp_name'];
echo("hello");
}
?>
</body>
</html>

How to create directory and save image in it using php

I have a code where I am selecting an image and then entering the name of the directory I want to create to save that image. After this, once a button is clicked the directory should be created in the given path and file should be saved in it.
Below is the code I am using:
<form enctype="multipart/form-data" action="upload.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="512000" />
Send this file: <input name="userfile" type="file"/>
<input type="text" name="idtest" value=<?php echo $idtest; ?> >
<input type="submit" value="Send File" multiple/>
</form>
upload.php
<?php
$uploaddir = 'G:/dataset/' . $idtest;
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']) ;
echo $uploadfile;
?>
Here in the above code I have not include the create directory part which I still have to work on. Now ideally the variable idtest should be appended with uploaddir variable so whenever I am printing the value of uploadfile the last directory should be the one which I entered in the text box. But its not working. Can anyone please throw some light on why its not working. Thanks
Give this upload script a try. Based on your comments, it seems the first issue is the directory name entered in the form not being added to the full uploadfile path. You will need to grab idtest from the $_POST variable first. I would also recommend using move_uploaded_file to move the uploaded file.
upload.php
<?php
$uploaddir = 'G:/dataset/' . $_POST['idtest'];
// check if directory exists
if(!is_dir($uploaddir)){
mkdir($uploaddir);
}
$uploadfile = $uploaddir ."/". basename($_FILES['userfile']['name']) ;
echo $uploadfile;
move_uploaded_file($_FILES['userfile']['tmp_name'],$uploadfile);
?>
Please ensure proper form validation and file name checks for security reasons, but that is beyond the scope of this answer. As the other commenters have mentioned, ensure file system permissions are set to allow writing to G:/dataset/.

Saving image with PHP on localhost uploaded with a form

i'm trying to save an image uploaded with a HTML form on my localhost server (working with Xampp), but although there are no errors, the file isn't saved anywhere.
This is the form, really simple:
<form id="form1" action="result.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="imguploaded" id="imguploaded" accept=".png, .jpg, .jpeg"></br>
<input class="btn btn-outline-danger btn-lg" id="inputbtn" type="submit" value="Upload Image" name="submit">
</form>
and this is the PHP code (on result.php):
<?php
$result=false;
$error=false;
if (isset($_FILES['imguploaded'])){
$nomefile = strtolower($_FILES['imguploaded']['name']);
$path = "caricamenti/$nomefile";
move_uploaded_file($_FILES['imguploaded']['name'], $path);
echo($path);
}
?>
the path exists and it is in the same folder of the .PHP files.
In move_uploaded_file($_FILES['imguploaded']['name'], $path); the first parameter isn't correct. It should be the temporary path where php stored it intermediatly, which you find in $_FILE['imguploaded']['tmp_name'].
So change that line to
move_uploaded_file($_FILES['imguploaded']['tmp_name'], $path);
relevant docs
Be sure to:
sanitize filename & extention first
check for allowed mimetypes, size, ..
Right now I could easily upload a php script and execute that.
Try this:
$file_name= $_FILES['imguploaded']['name'];
$file_tmp_name= $_FILES['imguploaded']['tmp_name'];
$div= explode('.',$file_name );
$file_txt= strtolower(end($div));
$unique_image= substr(md5(time()),0,10).".".$file_txt;
$uploaded_image= "caricamenti/".$unique_image;
move_uploaded_file($file_tmp_name,$uploaded_image);

Problems saving file in PHP ("failed to open stream: No such file or directory")

I am simply trying to save a file containing the serialized values of a form.
The Simple Form
<h2>PHP Form Validation Example</h2>
<form form method="post">
First Name: <input type="text" name="fname" value="
<?PHP
echo ($_POST['fname'])
?>">
<br><br>
<input type="submit" name="Save" value="Save Current Form">
Save File Name As: <input type="text" name="saveFile">
<br><br>
<input type="submit" name="Load" value="Load Old Form">
Load File: <input type="text" name="loadFile">
</form>
When i save/load the file i use the PHP code:
<?php
if (isset($_POST['Save'])) {
$PostArray = $_POST;
$s = base64_encode(serialize($PostArray));
$file = sprintf('/SavedForms/%s',$_POST['saveFile']);
file_put_contents($file, $s);
}
if (isset($_POST['Load'])) {
$file = sprintf("/SavedForms/%s",$_POST['loadFile']);
$_POST = unserialize(base64_decode(file_get_contents($file)));
}
?>
But it simply tells me
(when i try the save the file name "aaa")
that: "Warning: file_put_contents(/SavedForms/aaa) [function.file-put-contents]: failed to open stream: No such file or directory in"
I already have created the directory /SavedForms/ in the file as seen in the image below...
Could someone please let me know what i am doing wrong here!?!?
Remove the leading forward slash from the directory:
$file = sprintf('SavedForms/%s',$_POST['saveFile']);
Assuming that SavedForms is in the same directory as the executing php script.
Paths are relative to the script. By putting a leading slash, you are declaring an absolute path from the very root directory of your machine. This means it is currently looking for SavedForms in the root directory, and of course, it fails to find it

html forms - sending file to php with method post results in blank page

I have the following form:
<form name="uploadForm" action="proxy.php" method="POST" enctype="multipart/form-data">
<input id="fileToUpload" name="fileInput" type="file"/>
<input type="submit" name="uploadButton" value="Upload"/>
</form>
The php works as a proxy and is OK (i do have to change the POST method to PUT in the proxy).
When upload is finished, the page turns blank and the path i see in the browser is the path to the php.
What am i doing wrong?
after uploading the files in proxy.php redirect to the form page
//add single line at last
header("Location:form.php");
Another way that i like is to post data in the same file:
<form name="uploadForm" action="?action=upload" method="POST" enctype="multipart/form-data">
<input id="fileToUpload" name="fileInput" type="file"/>
<input type="submit" name="uploadButton" value="Upload"/>
</form>
at the beginning of your file that contains upload form, add this:
<?php
$uploadComplete = false;
if(isset($_GET["action"]) && $_GET["action"]=="upload")
{
// put upload codes that you have in proxy.php
$uploadComplete = true; // you can even set this variable to check if upload is done or not
}
?>

Categories