Send file to remote php from local python in $_FILES - php

Preface: I started learning Python one month ago, please don't yell at me :)
I have a full developed site written in PHP, with all the functions I need with pages to insert "stuff" in the database. I am developing a command line program to insert the same thing and send them to the PHP scripts in the $_POST array, but I have no idea on how to send the file so that it would come up in the $_FILES array.
Here is what I have so far:
I send the $_POST values using the urllib modules and it works just fine
import urllib.request
import urllib.parse
data=urllib.parse.urlencode({"hello":"Yo!", "some":"AlphaBetaParkingLot"})
data=data.encode('utf_8')
request=urllib.request.Request("http://www.site.it/read_from_py.php")
f=urllib.request.urlopen(request, data)
out=f.read().decode('utf-8')
if out[0]=="1":
print("Connection acquired!")
else:
print("No connection!")
print("Exit!")
#Then actually exit!
...I read the filename from the local computer by prompting a choose file dialogbox...
from tkinter import Tk
from tkinter.filedialog import askopenfilename
Tk().withdraw()
filename=askopenfilename()
...but then I have no idea on what to do with the filename. I have looked around and I have seen no way on how to send this to the $_FILES in PHP.
I have a "dirty" solution: creating a temporary html with a form just with the file and make it choose from there, but I was wondering if there was a cleaner solution.
Thanks!
P.S. If you are wondering if I have all the things I need in the PHP scripts, why would I need this Python program? Well, you would be correct, I wouldn't need it but it's not up to me...

Try Like This
import urllib,MultipartPostHandler,urllib2,cookielib
cookies = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookies),MultipartPostHandler.MultipartPostHandler)
urllib2.install_opener(opener)
login = urllib.urlencode(dict(admin_user='admin',admin_pass='****'))
o=opener.open('http://some_domain_name.com/admin/index.php',login)
print o.read()
raw_params={"adtitle":"sample title",
"area":"sample area",
"addesc":"<p>sample post</p>",
"pic[0]":open("indian_eye.jpg", "rb"), #File Goes Here
"pic[1]":open("nature.jpg", "rb"),
"subcatid":"1",
"do":"post",
}
url="http://YOUR.php?cityid=15&subcatid=1"
opener.open(url, raw_params)
Hope it works!

Related

Pass data from php to python and get result

I want to send data from php to python and make some computations. After that I want to send result of that. The problem is I cannot send data from php to python.
python.php
username is working but shell_exec or python have problem
<?php
if(isset($_POST["username"])){
$nick = $_POST["username"];
echo shell_exec("python new.py '$nick'");
$jsonData = $_POST["prediction" ];
echo $jsonData;
}
?>
new.py
When I run python it prints C:\wamp\www\MLWebsite\website\new.py but it should be parameter
import pymysql.cursors
import sys
import urllib2, urllib
import requests
x=sys.argv[0]
print x
I want to get some idea about sending result because end of new.py
mydata=[('prediction','BIO')]
mydata=urllib.urlencode(mydata)
path='http://localhost/MLWebsite/website/python.php' #the url you want to POST to
req=urllib2.Request(path, mydata)
req.add_header("Content-type", "application/x-www-form-urlencoded")
page=urllib2.urlopen(req).read()
print page
I use Firebug plugin in Firefox and this error is also shown in webpage.
( ! ) Notice: Undefined
index: prediction in C:\wamp\www\MLWebsite\website\python.php on line
6 Call Stack #TimeMemoryFunctionLocation 10.0006245144{main}( )..\python.php:0
I assume the reason that you want to do it this way (i.e., using PhP to interact with user but having Python actually do the processing) is that you want to take advantage of python language for some tasks, but avoid having to use a separate webframework just for those tasks.
One way to accomplish it (albeit perhaps not the way you want to solve it) is to have PhP write the data to a text file with delimiters separating different chunks of data. Then have PhP call the Python file, which knows to read the text file.
In my example below Python writes to a file and PhP can open it if it wants, but you can go the other way as well. PhP could write to a .txt file, Python can read and manipulate, and then save to the same or different .txt file, and PhP can open and render the results.
Basically, you are using a .txt file as 'memory'.
This is an example:
<?php
echo "<h1>This is PhP!</h1>";
$returnedValue = shell_exec('/home/sitename/public_html/pythonFile.py');
echo $returnedValue; //This line may not be needed if there is nothing to return.
echo "<h2> Completed </h2>";
//Once the 'Complete' Above Renders in the Browser You Know that Python Did Whatever it Was Going to Do to the .txt File
//Now, if you want to have PhP Open the .txt File and Display it You Can
?>
#THIS IS PYTHON
#!/usr/bin/env python
file_object = open("NameOfTextFile.txt", "w+")
file_object.write("Hello World!")
file_object.close()
I realize this question is old, but I recently had the same issue and this is how I tried to resolve it. Hopefully it helps someone.
I think your question needs refinement.
From what I can tell, your python program is doing what one would expect.
$ cat 0.py
#!/usr/bin/python
import sys
print sys.argv[0]
print sys.argv[1]
$ chmod 755 0.py
$ python 0.py foo
0.py
foo
$ ./0.py foo bar
./0.py
foo
So, if your python program is prining 'new.py' as you wrote the question, I think that's expected behavior. Why you're passing unsanitized user input to a system call is another question. Why you're using a system call at all (why not set up a webservice with your python program?) is yet a further question.
I hope this helps.

iOS Swift / HTML-Code and PHP-Code in 'Strings'

I tried the following coding for a 'UIWebView:
let kapitel3 = "<html><head><title>Chapter 1</title></head><body><h1>This is a title!</h1></body></html>"
This HTML code works fine and "UIWebView" shows this code. But if I try to insert a PHP code within the HTML code like this:
let kapitel3 = "<html><head><title>Chapter 1</title></head><body><h1>This is a title!</h1><?php print \"Hello world!\";?></body></html>"
Then the PHP code won't be showed. Why doesn't 'UIWebView' translate this PHP code <?php print \"Hello world!\";?>?
Is it not possible to integrate PHP code in a String like above?
Thanks for any hints!
UIWebView is only a simple web-browser...
You can't use php like that if you don't have a local webserver with a php interpreter installed!
You could load a php page from a remote url but your phone must have an active internet connection...
Possible local solution:
You can't use php locally, but in a UIWebView you can still use javascript!
I don't know what you are trying to do...but if you need your app to work offline (with local files) using php is the wrong approach.

Agile Toolkit: Any way to upload files and fetch directly from $_FILES['uploadedfile']['tmp_name']?

I wrote a simple script in plain PHP that uses $_FILES['uploadedfile']['tmp_name'] to fetch a freshly uploaded file and process its contents directly without permanently storing it. The idea is to allow the user to upload a file containing several rows of data that will be automatically parsed and added to a database by the PHP script. There is no need to store the file itself or a reference to it in the database as only the file contents are important. I know of Import CSV to MySQL, but I am trying to keep things clean and easy for the user (and for the time being I am developing with phpDesktop + sqlite so that my application will be portable).
I am now trying to recreate this process within Agile Toolkit but I cannot seem to figure out how. I know that the filestore model must access ['tmp_name'] before it moves/renames the file but I cannot figure out how to poach just this functionality. I tried looking in /lib/Form/Field/Upload.php to see if any of the methods there might be of use, but I am quite new to PHP so these docs are baffling to me. getFilePath() looked promising, but it seems that $_FILES remains empty when I do something like:
$form = $page->add('Form');
$upl = $form->addField('Upload', 'file');
$form->addSubmit();
if ($form->isSubmitted()){
$form->js()->univ()->alert($upl->isUploaded())->execute(); //sends js alert('false')
}
I realize that AJAX cannot be used to post files and I have a feeling this is part of the problem but I am not really sure where to go from here. Any help would sincerely be appreciated.
Thanks.
Agile Toolkit uploads file as soon as it is selected - moves it immediately into filestore and creates database record, so not really what you need.
Anything you write in a plain PHP can also work with Agile Toolkit. You can disable JavaScript in the form by doing this:
$this->add('Form',array('js_widget'=>false));
Such a form would send you a normal POST request.
Ok, I managed to achieve what I wanted by creating a custom extension of Form_Field_Upload and redefining the loadPOST() method within it.
function loadPOST(){
Form_Field::loadPOST();
if($_GET[$this->name.'_upload_action']){
// This is JavaScript upload. We do not want to trigger form submission event
$_POST=array();
}
if($_GET[$this->name.'_upload_action'] || $this->isUploaded()){
if($this->model){
try{
$model=$this->model;
/*Function is identical to parent above this line*/
//process file here and do $model->set('custom_field',$value);
//I am using $this->getFilePath() to analyze the uploaded file
/*Function is identical to parent below this line*/
$model->save();
}catch(Exception $e){
$this->api->logger->logCaughtException($e);
$this->uploadFailed($e->getMessage()); //more user friendly
}
$this->uploadComplete($model->get());
}
}
if($_POST[$this->name.'_token']){
$a=explode(',',$_POST[$this->name.'_token']);$b=array();
foreach($a as $val)if($val)$b[]=$val;
$this->set(join(',',filter_var_array($b,FILTER_VALIDATE_INT)));
}
else $this->set($this->default_value);
}
I sure this is not the most elegant solution but it worked for my purpose anyway.

Import XML Google Spreadsheet - Help me with PHP code

I came across a requirement to import my DB-Users to a google-spreadsheet.
I did a code with the help of the below instruction.
http://www.distilled.net/blog/distilled/guide-to-google-docs-importxml/#chapter4
Now i can get all my DB-Users using the below code.
=importxml("http://mydomain.com/v5/admin/export_google.php","//tr")
If i paste the above code in a google spreadsheet i can see all my DB-Users in my spreadsheet.
Now, as far as security is concerned
http://mydomain.com/v5/admin/export_google.php -> If i type this url in my browser, then i can see all the db-users.
I need this file to be password protected. Only my client having the code to import the db-users can view my db-users.
Is there a way to keep the file password protected(export_google.php). I know, i can set a username and password at top of my php file but doing that will it won't work if i paste the code in google spreadsheet.
Could someone help me out.
In other words - my client having the code i.e. =importxml("http://mydomain.com/v5/admin/export_google.php","//tr") can take the db-users in google-spreadsheet. Others should not get the information of my db-users using the php file.
You just need to add some GET var to your request and check it inside your script.
Like so:
=importxml("http://example.com/v5/admin/export_google.php?pass=mypass","//tr")
And inside PHP script:
if (isset($_REQUEST['pass']) && $_REQUEST['pass'] == 'mypass') {
// your code here
}

Scala Lift - Run PHP file from within scala runtime

I'm not entirely sure the wording for the title is correct, but what I'm attempting to do is run and execute PHP files from within the Lift framework.
I'm not after any url queries to a PHP file residing on a server, more interested in somehow getting the PHP runtime working through my Scala/Lift app.
Use case: I have my app packaged into a .war file, I host this via a cloud provider. I upload code snippets to said app which then runs the php file and does whatever necessary.
I've seen various posts regarding Bianca but am hoping to keep this setup light and require only the PHP binary itself and a little code to get it flying.
Thanks in advance, please let me know if you need me to elaborate :)
“Never say never, because limits, like fears, are often just an
illusion.”
― Michael Jordan
What you really need is an open source (GPL), embeddable, full PHP 5 implementation, written entirely in Java!
Caucho's Quercus PHP Java runtime is just that, and it will let you run PHP within a Java app without external libraries or native code.
Below is a Quercus-PHP-in-Java code sample I found in this answer
import javax.script.ScriptEngine;
import com.caucho.quercus.script.QuercusScriptEngineFactory;
QuercusScriptEngineFactory factory = new QuercusScriptEngineFactory();
ScriptEngine engine = factory.getScriptEngine();
String phpCode = "<?php $foo = strlen('abc'); print $foo; return 'yikes'; ?>"; //PHP Code as String
Object o = engine.eval(phpCode);
System.out.println(o);
It should be little effort to convert this code to idiomatic Scala. Obviously, the 'phpCode' variable could be constructed from external PHP file contents etc.
Let us know how you get on ;-)
That's a bit of an odd requirement, but if it's what you need to do, you can use a ProcessBuilder to execute and interact with your PHP script from the command line.

Categories