CouchDB view is accessible, but won't run query - php

I used couchdb's PHP lib to add a view:
public function addView() {
$design_doc = new stdClass();
$design_doc->_id = '_design/need';
$design_doc->language = 'javascript';
$design_doc->views = array( 'all' => array('map' => "function(doc) { if (doc.type == 'need') emit(doc.type, doc) }" ) );
$result = $this->client->storeDoc($design_doc);
return $result;
}
In my shell, I viewed its doc to confirm it was created:
curl -X GET mysite.com/bids/_design/need
{
"_id":"_design/need",
"_rev":"1-0ed4b41b839ade9ca36fb950cac1c39b",
"language":"javascript",
"views":
{
"all":
{
"map":"function(doc) { if (doc.type == 'need') emit(doc.type, doc) }"
}
}
}
Then when trying to actually execute the view, it throws eacces error:
curl -X GET mysite.com/bids/_design/need/_view/all
{
"error":"error","reason":"eacces"
}
Permissions: the instance is running as root.
Am I using the wrong syntax to execute the view query?
Could it be that there is an issue with the encoding of the string that was passed via PHP?

"eacces" suggests that it's a problem with the permissions or ownership on the directory your databases are stored in.
For each database, the database server will create a subdirectory called .<db_name>_design containing a file for each design document in that database. It's likely that the user your CouchDB instance is running as doesn't have permission to create that directory, or perhaps the file within it.
Check that the directory your databases are in, and everything thereunder, is owned by the user your CouchDB is running as, and that the directories and files have sensible permissions. It's /usr/local/var/lib/couchdb if you installed from source, but will probably be different if you used a package.

There was some issue with character encoding by php. Running the exact same query in curl was successful and the view was then able to run properly

Related

laravel rest api upload file to server

Am creating a REST api with laravel that allows a user to select an image file from their android device, then upload it to the server. The mage is converted to base64 before it's sent to the server alongside other parameters. I want to convert this base64 to a file and store it on the server then generate a link that can be used to access it. here is what i have tried so far and it doesnt work: I have already created a symlink to storage
public function create(Request $request)
{
$location = new Location();
$location->name = $request->location_name;
$location->latitude = $request->latitude;
$location->longitude = $request->longitude;
$location->saveOrFail();
$provider = new Provider();
$provider->name = $request->provider_name;
$provider->location_id = $location->id;
$provider->category_id = $request->category_id;
$provider->description = $request->description;
$provider->image = request()->file(base64_decode($request->encoded_image))->store('public/uploads');
$provider->saveOrFail();
return json_encode(array('status'=>'success', 'message'=>'Provider created successfully'));
}
As already commented by Amando, you can use the Intervention/Image package, having used it for many years I can say it will do what you want and very well.
What I would also add though, is you may also want to consider, whether you indeed need to store it as a file at all.
Depending on what it will be used for, and the size etc, you could consider storing it in the DB itself, along with any other information. This removes the dependency on a file server, and will make your application much more flexible with regards to infrastructure requirements.
At the end of the day, files are just data, if you will always get the file when you get the other data, reduce the steps and keep related data together.
Either way, hope you get it sorted :)

execute external php via cron

I have a script on my shared hosting. When i execute the script it checks if there are new members on the site. If so, the script headers to my windows server with two get parameters and a script there will execute and make a useracount for the new user. this works manualy and for 1 user just fine, however, i want to add cron to this so it runs every 15 minutes. this is'nt the problem when there is one user, but is the script has more then one user, it wont reach there becouse of the header. How can i fix this?
my code:
$array = $arr->invoices->invoice;
foreach($array as $key => $value) {
if(!order_is_active($value->id)) {
$username_win = strtolower($value->firstname) . rand(9,9999);
$password_win = ucfirst(maakpass(10, TRUE, TRUE));
if (add_user_to_db($value->id, $value->userid, $value->status, $username_win, $password_win)) {
header('location: http://ip/adduper/?username=' . htmlspecialchars($username_win) . '&password=' . htmlspecialchars($password_win));
} else {
echo 'order bestaat al';
}
}
}
You can store all of the users in an array and then send the json encoded string to your other server which will then json_decode it to get back an array. It can then loop over the array and add each user.
Rather than doing a header, I'd move toward doing CURL
This will allow you to more cleanly return from the Windows machine a status of success or failure. As with all remote connections, you have to account for when one machine can't connect to the other.....and it isn't a matter of if that case will happen, but when. Such is the nature of the Internet.
With a PHP header, a failed connection would create all sorts of chaos.

Route URI to a specific folder in CakePHP

Introduction :
I have this path in my CakePHP : app/webroot/storage/5/C/_demo/omar.txt , this one will be redirected to http://localhost/storage/5/C/_demo/omar.txt
My problem :
I want this path http://localhost/storage/5/C/_demo/omar.txt to be something like this http://localhost/storage/uehKDj44/C/_demo/omar.txt , where uehKDj44 is number 5 , the reason why I'm doing like that is I don't want anyone to change number 5 to any number so they can't access otherwise they login first , let's say if 5 belongs to a user will be open , but if not won't be open , is there any better way to secure it better than that ?
Thanks
Storing restricted data as plain files inside of the htdocs folder (or webroot for CakePHP), where they can be requested without further authorization is always a risky business and should be avoided.
I cannot determine what kind of data you store in the .txt file, but I assume it is not fetched from the database and then saved. My understanding is that the link to the file is displayed to a logged in (authorized) user.
Proposal of a more secure solution:
Move the files outside of the webroot folder and create a constant with the absolute path to that folder (USERDATA_PATH). Remember to set read permission for web server user (www-data for Apache)
Create a model, e.g. UserData with an underlying database table storing a relation between a user and a magic hash (e.g. 1 => 'uehKDj44', 2 => 'ds83skf' etc.). You can also store file names to make it a bit less complicated.
Create a controller UserDataController with an action serveFile which will take the secret key as a parameter, match it with the file and output the file to the user.
public function serveFile($hash= null) {
try
{
$data = $this->UserData->findByHash($hash);
if (!$data) {
throw new Exception('No match found');
}
// Load the data from file
$this->set('output', file_get_contents(USERDATA_PATH.DS.$data['UserData']['filename']));
}
catch (Exception $ex)
{
// No match found - display error message / log
}
}
Then in view:
header('Content-type: text/plain');
echo $output;
This should do the trick.

php and cron job questions, can I change one variable in php file from another php file?

I have 3 questions that will greatly help me with my project that I am stuck on, after much narrowing down these are the resulted questions arised from solutions:
Can I use one php file to change a variable value in another php file, can these values be read also from one php file to another?
How can I use crob job to change variable values within my php code?
Lastly, can cron read variable values in my php files??? for Example, if statements that will decide what to trigger and how to trigger when cron time comes?
I am a little new at cron and going deeper into php and need all the exeprtise help. I cant use any CURL or frameworks.
Please prevent the hijacking of my topic, the data I want is simple change $variable=1 in filenameA.php to $variable=2 using filenameB.php
This is not a very good practice, but it's the simplest thing you can do:
You need three files: my_script.php, my_cron_job.php, and my_data.txt.
In the script that control's $data (this is called my_cron_job.php):
<?php
$values = array(
"some_key" => "some_value",
"anything" => "you want"
);
file_put_contents("my_data.txt",serialize($values));
Running it will also create my_data.txt.
Then, in my_script.php:
<?php
$data = unserialize(file_get_contents("my_data.txt"));
print_r($data); //if you want to look at what you've got.
I'm not sure what type of data you are exchanging between PHP files. I'm fairly new as well, but will see what the community thinks of my answer. (Criticism welcomed)
I would have my PHP files write my common data to a txt file. When the cron job executes the PHP files, the PHP files can access/write to the txt file with the common data.
You seem to be describing a configuration file of some type.
I would recommend either an XML file or a database table.
For an XML file you could have something like:
<settings>
<backup>
<active>1</active>
<frequency>daily</frequency>
<script_file>backup.php</script_file>
</backup>
<reporting>
<active>1</active>
<frequency>weekly</frequency>
<script_file>generate_report.php</script_file>
</reporting>
<time_chime>
<active>1</active>
<frequency>hourly</frequency>
<script_file>ring_bell.php</script_file>
</time_chime>
</settings>
then have some controller script that cron calls hourly that reads the XML file and calls the scripts accordingly. Your crontab would look like:
0 * * * * php /path/to/script/cron_controller.php
and cron_controller.php would contain something like:
$run_time = time();
$cron_config = simplexml_load_file($conf_file_location);
if($cron_config === false) die('failed to load config file');
foreach($cron_config as $cron) {
if($cron->active != 1) continue; //cron must be active
$run_script = false;
switch((string) $cron->frequency) {
case 'hourly':
$run_script = true;
break;
case 'daily':
if(date('H', $run_time) == '00') //is it midnight?
$run_script = true;
break;
case 'weekly':
if(date('w:H', $run_time) == '0:00') //is it sunday at midnight?
$run_script = true;
break;
}
if($run_script) {
$script_file = (string) $cron->script_file;
if(file_exists($script_file)) {
echo "running $script_file\n";
require($script_file);
}
else {
echo "could not find $script_file\n";
}
}
}
and if you need to edit your configuration with php scripts you can use SimpleXML to do it, then just save it back to the original location with $cron_config->saveXML($conf_file_location);

Silverlight Localhost on Xampp

I am trying to retrive data to my SL application from PHP, MySQL service which is hosted locally on Xampp.
I can see my php file running OK and deliver results via JSON (http://localhost/silverlight/data.php) but SL cannot receive it. I belive it has something to do with correct URl path but I cant figure it out. Also I've putted clientaccesspolicy.xml file to allow cross-domain access but with no avail:(
public partial class MainPage : UserControl
{
WebClient wc = new WebClient();
ObservableCollection<ToDoItem> myToDoList = new ObservableCollection<ToDoItem>();
string baseURI = "http://localhost/silverlight/";
public MainPage()
{
InitializeComponent();
wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);
wc.DownloadStringAsync(new Uri(baseURI + "data.php",UriKind.Absolute));
}
void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error == null && e.Result!= "")
{ JsonValue completeResult = JsonPrimitive.Parse(e.Result);
string resultType = completeResult["returnType"].ToString().Replace("'", "").Trim();}
The clientaccesspolicy.xml file you use only allows cross-domain access for web service requests (as specified by http-request-headers="SOAPAction")
For WebClient to work the way you use it, you need to enable content requests as well.
Try specifying http-request-headers="*" or http-request-headers="SOAPAction,Content-Type".
Also, do check that the clientaccesspolicy.xml file is located at the root of the host, i.e. http://localhost/clientaccesspolicy.xml. Eventually when you decide to deploy your application, you'll have to make sure the file is placed in the root of the deployment host as well, e.g. http://example.org/clientaccesspolicy.xml

Categories