Hi I have this PHP code (Custom Script) to query for FileAttachment URL from RightNow Incidents,
<?php
define("CUSTOM_SCRIPT", true);
define(DEBUG, false);
define(COMMIT, true);
ini_set('display_errors',1);
error_reporting(E_ALL ^ E_NOTICE);
$ip_dbreq = true;
require_once( get_cfg_var("doc_root")."/ConnectPHP/Connect_init.php" );
use RightNow\Connect\v1_2 as RNCPHP;
try{
initConnectAPI('user','Pass');
}
catch(Exception $error) {
echo $error->getMessage();
}
$img_url = "";
$inc_id = 296;
$entity = RNCPHP\Incident::fetch($inc_id);
foreach($entity->FileAttachments as $fileattach) {
$img_url = $fileattach->getAdminURL();
}
$img_id = 23;
$image_location = HTMLROOT . "/euf/assets/images/integration_images/images/".$inc_id."-".$img_id.".png";
file_put_contents($img_url, fopen( $image_location , 'r'));
header('Location: $image_location');
?>
This will return the file downloading url which if opened in browser will automatically download the image to my computer
URL : https://host.com/cgi-bin/some.cfg/php/admin/console_util/fa_get.php?p_parms=eUofFOziR6q7tVDrMAkPfz_F0iz5Nf17TjtEH18Z72PdbM9JJq6g4VNUF4oXfPY~UpgHsJhH0Nr7KKYBg78sV69A2pcj3h1cn5_mRTSyJtQHtkwQz8bqcldb8gjEUwtfQkgPVNx3u1jHjCESYm7aXKv7v4zqVV1_f_MTJp1ooey9tMHBsFlsKw0jQjurEl15gIeFNt011UglH3ccOhCvgimvVmsMvs2HbrVymNwZ1HmMtKewDQfdCy35Oi5kgotrQHoJ3QQn10fuGTjlrjgW1MEXncdTUHx2645YZxlmraur7_mpIJzWw9Rg!!
I want to use this url to download the image directly to Customer Portal folder
"/euf/assets/images/" with incident ID and Image ID as name, then build a new url for that image and redirect my above script to that image url so that we can see the image on browser directly.
Send the content type header before the location header so that the browser knows the endpoint is an image.
This approach is dangerous, though, because you are basically exposing protected incident data on the public internet as assets is not a secured folder.
Related
I would like to be able to save a JSON file that is in a database to the user's PC. In summary, I'm storing setup files from a sim racing game, that use a JSON format, in a database, and I'd like the user to be able to upload/download these JSON files (to share with others, etc).
I've got the upload working, using PDO, so there is a column called setup that is a text data type. I'm using a form, with a $FILES() to fetch the uploaded json file, with some checks to ensure it's a valid setup json.
$setup = file_get_contents($_FILES['setupjson']['tmp_name']); //get json from file uploaded
$setupJSON = json_decode($setup); //decode into object
$car = $setupJSON->carName; //carName from object
if ($obj->searchCarName($car) > 0) // if search matches (car exists)
{
if($obj->insertSingleSetup($_POST["name"], $_POST["description"], $_POST["type"], $car, $_POST["track"], $setup) !== false)
{
header('Location: add.php?success');
exit();
}
else
{
header('Location: add.php?error=Error+adding+the+setup');
exit();
}
}
else
{
header('Location: add.php?error=Please+submit+a+valid+setup');
exit();
}
}
The issue i'm having is downloading the file again. I've been able to view the JSON directly
<?php
include('../db.php');
$setup_id = $_POST['setup'];
try {
$connectionString = sprintf("mysql:host=%s;dbname=%s;charset=utf8mb4",
DB::DB_HOST,
DB::DB_NAME);
$pdo = new PDO($connectionString, DB::DB_USER, DB::DB_PASSWORD);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$sql = 'SELECT * FROM setups WHERE setup_id= :setupID';
$query = $pdo->prepare($sql);
$query->bindValue(':setupID', $setup_id);
$result = $query->execute();
$setup = $query->fetch(PDO::FETCH_ASSOC);
processSetup($setup);
} catch (PDOException $e) {
die("Could not connect to the database $dbname :" . $e->getMessage());
}
function processSetup($setupRow)
{
$setup = $setupRow['setup'];
$setupJSON = json_decode($setup);
echo '<pre>';
echo $setup;
echo '</pre>';
}
?>
but I can't work out how to download it. I've researched that it's related to headers, but everytime I try something, it never works. I just want the save file dialog to appear with the json, and preferably, the option to set the filename outputted to a chosen variable.
Just figured it out, on the processSetup function, I changed the code to this
function processSetup($setupRow)
{
$setup = $setupRow['setup'];
header('Content-type: application/json');
header('Content-disposition: attachment; filename=setup.json');
echo $setup;
}
If I add some code to give the JSON it's proper filename, it'll be perfect :D
I made the post function from the application in c#, then I want to insert the post data into the mysql database via the php file.
how can I prevent the entry of empty data into the database? because if I open the URL http://example.com/api/index.php directly in the browser, then there will be empty data that goes into the database, except the ip address.
I do not want if someone opens the url http://example.com/api/index.php directly, then there will be empty data entering the database because it can cause spam.
c# code :
public void uploadFile(string url, string filepath)
{
WebClient webClient = new WebClient();
try
{
webClient.UploadFile(url, "POST", filepath);
}
catch
{
}
finally
{
webClient.Dispose();
}
}
string lickey = desktoppath + randnumber + ".lic";
uploadFile(string.Format(url + api,
new object[]
{
licKeyID,
name,
GetAddress(),
}),
lickey);
private string url = "http://example.com/api";
private string api = "/index.php?lickey_id={0}&username={1}&password={2}&address={3}";
php code :
<?php
include('config.php');
$uploaddir = 'newdir/';
$uploadfile = $uploaddir . basename($_FILES['file']['name']);
$id = mysql_real_escape_string($_GET['license_id']) . '.lic';
$blacklist = array(".php", ".phtml", ".php3", ".php4", ".html", ".htm");
foreach ($blacklist as $item)
if(preg_match("/$item\$/i", $_FILES['file']['name'])) exit;
$f1 = file_get_contents($_FILES['file']['tmp_name']);
$fd = fopen($uploaddir.$id, 'w') or die("failed to create file");
fwrite($fd, $f1);
fclose($fd);
$check = mysql_query("SELECT * FROM `License` WHERE
`license_id`='".mysql_real_escape_string($_GET['license_id'])."' AND `checked`='false'");
if(mysql_num_rows($check) > 0)
{
exit(0);
}
mysql_query("INSERT INTO `License` SET
`ip`='".$_SERVER['REMOTE_ADDR']."',
`file`='$uploaddir".$id."',
`license_id`='".mysql_real_escape_string($_GET['license_id'])."',
`username`='".mysql_real_escape_string($_GET['username'])."',
`address`='".mysql_real_escape_string($_GET['address'])."',
`checked`='false'");
echo mysql_error();
mysql_close($dbcon);
?>
Validate input.
This can be done in many ways. One of them could be checking if $_FILES global variable contains file key, and if $_GET contains license_id, username and address.
if (isset($_FILES['file'])) {
die('Request invalid');
}
PS. Generally, using global variables is burdened with a security risk. What you could do, without refactoring this completely, think about adding a custom header (like X-Client: My Fancy CSharp Application), and validating it inside PHP code.
i would like to customize my function, currently, when i click download it automatically download mp3 file, but i want it just to redirect to the download page and let the user click download themselves, so i don't want it be auto download, how should i correct my code please help this is my code thank
In short, i want to close force download, this is my website you could try it, www.vox79.com
and here is my download helper code this link(http://www.vox79.com/page/35-code)
function download_mp3()
{
$query = decode(urlencode($this->input->get("q",TRUE)));
$data = json_decode(searchYoutube($query));
$artist = urldecode($this->input->get("a",TRUE));
$track = urldecode($this->input->get("t",TRUE));
setDownload($artist,$track,'','mp3');
$videoID = get_video_id($data);
$video = "https://www.youtube.com/watch?v=".$videoID;
$download_service = $this->config->item("download_service");
$download_service = str_ireplace("%youtube_url%", $video, $download_service);
$download_service = str_ireplace("%youtube_video%", $videoID, $download_service);
if($videoID == '')
{
redirect("http://www.youtube.com/results?search_query=$query",'location');
}
else
{
redirect($download_service,'location');
}
}
if($videoID == '')
{
header('Location: http://www.youtube.com/results?search_query=$query');
}
I have a file in which a user can view its stored files. I want that only the logged in user and it can only be viewed by that member who has stored that file. It works fine when I view other files like .html, .txt etc. But when I view any image, it doesn't work.
This is my script :
require ('config.php');
$id = intval($_GET['id']);
$dn2 = mysql_query('select authorid from files where uploadid="'.$id.'"');
while($dnn2 = mysql_fetch_array($dn2))
{
if(isset($_SESSION['username']) and ($_SESSION['userid']==$dnn2['authorid'] or $_SESSION['username']==$admin)){
$query = "SELECT data, filetype FROM files where uploadid=$id"; //Find the file, pull the filecontents and the filetype
$result = MYSQL_QUERY($query); // run the query
if($row=mysql_fetch_row($result)) // pull the first row of the result into an array(there will only be one)
{
$data = $row[0]; // First bit is the data
$type = $row[1]; // second is the filename
Header( "Content-type: $type"); // Send the header of the approptiate file type, if it's' a image you want it to show as one :)
print $data; // Send the data.
}
else // the id was invalid
{
echo "invalid id";
}
}
}
How can I view the image?
I have an that displays an interactive pdf form. How do I create a button to get data from the pdf document. Need help please, been on this the whole day.
Here's the php file that supposed to get the pdf data
if(isset($_POST) && is_array($_POST) && count($_POST)){
$data=array();
$data['topmostSubform[0].Page1[0].Applicant_Surname[0]']=$_POST['topmostSubform_0__Page1_0__Applicant_Surname_0_'];
$data['topmostSubform[0].Page1[0].Applicant_FirstName[0]']=$_POST['topmostSubform_0__Page1_0__Applicant_FirstName_0_'];
// need the function definition
require_once'createFDF.php';
// some variables to use
// file name will be <the current timestamp>.fdf
$kui = time();
/*$kui = time();*/
$fdf_file=$kui.'.fdf';
// the directory to write the result in
$fdf_dir=dirname(__FILE__).'/results';
// need to know what file the data will go into
$pdf_doc='http://localhost/uniApp/results/fillsheet.pdf';
// generate the file content
$fdf_data=createFDF($pdf_doc,$data);
// this is where you'd do any custom handling of the data
// if you wanted to put it in a database, email the
// FDF data, push ti back to the user with a header() call, etc.
// write the file out
if($fp=fopen($fdf_dir.'/'.$fdf_file,'w')){
fwrite($fp,$fdf_data,strlen($fdf_data));
/* echo $fdf_file,' written successfully.';*/
system("pdftk fillsheet.pdf fill_form results/". $fdf_file. " output results/$kui.pdf flatten");
$_SESSION['message'] = 'Your application has been updated';
$message = 'written successfully.';
echo $kui,' written successfully.';
}else{
die('Unable to create file:'.$fdf_dir.'/'.$fdf_file);
}
fclose($fp);
}
It works well when it using pure php code, but doesn't work when i try it from the <iframe>