i have a php file that is called from a javascript with the purpose of uploading files to my server.
Clarification that what im doing is calling this php file with ajax, so as i understand it it's not run in the traditional sence, which is why i am not using $_FILE and $_POST as the whole point of this project is to handle fileupload / collection of user data is done without a page reload.
obviously we want some sort of serverside file validation, which i have set up in an if statement.
however the code succeeds and proceeds with the upload no matter what file type i select.
can someone tell me what is wrong / or guide me in the right direction ?
<?php
session_start();
$name = $_SESSION['name'];
$email = $_SESSION['email'];
$phone = $_SESSION['phone'];
$date = date('Y-m-d');
$mypath = $name . '-' . $phone . '-' . $date;
$ext = $_SERVER['HTTP_X_FILE_TYPE'];
$allow = array('psd', 'ai', 'eps', 'svg', 'jpg', 'png', 'docx', 'doc', 'pptx', 'ppt');
if(!in_array($ext,$allow)){
if(!file_exists($mypath)) {
mkdir($mypath,0777,TRUE);
}
$str = file_get_contents('php://input');
$title = $_SERVER['HTTP_X_FILE_NAME'];
$path = "$mypath/".$title;
file_put_contents($path,$str);
}else{
return false;
}
?>
much apreciated - Mr B
The problem with the code is (Like #Cashbee mentioned in the comments), is with if(!in_array($ext,$allow)) portion of the code. This part allows the file to be uploaded if the file extension is not in $allow array. The correct code should be as below.
<?php
session_start();
$name = $_SESSION['name'];
$email = $_SESSION['email'];
$phone = $_SESSION['phone'];
$date = date('Y-m-d');
$mypath = $name . '-' . $phone . '-' . $date;
$ext = $_SERVER['HTTP_X_FILE_TYPE'];
$allow = array('psd', 'ai', 'eps', 'svg', 'jpg', 'png', 'docx', 'doc', 'pptx', 'ppt');
if(in_array($ext,$allow)){
if(!file_exists($mypath)) {
mkdir($mypath,0777,TRUE);
}
$str = file_get_contents('php://input');
$title = $_SERVER['HTTP_X_FILE_NAME'];
$path = "$mypath/".$title;
file_put_contents($path,$str);
}else{
exit;
}
?>
Important Note : Please keep in mind that, trusting an extension based on a header set by a javascript command from browser has a high risk and shouldn't be trusted. If this is required, you must store those files in a folder either inaccessible/restricted from the web and serve them raw with the correct mime header upon request or check more than file extension on upload.
Related
Im trying to hide the src url for a pdf file in an iframe / embed. Im not sure how.
I tried with all the previously exiting answers, but none of them are working.
<?php
$url = $_GET['url'];
?>
<embed id="renderedPrint" style="height:calc(100% - 4px);width:calc(100% - 4px);padding:0;margin:0;border:0;"></embed>
<script>
$(document).ready(function() {
var encryptedString = "assets/labels/" + "<?php echo $url; ?>" + ".pdf";
$("#renderedPrint").attr("src", encodeURIComponent(encryptedString));
});
</script>
But no matter which method i use (Obfuscator, php openssl_encrypt/decrypt), the output url is always visible.
I dont want users to find the iframe/embed url. I want to make it difficult to or even hide the url from the front-end.
The purpose is that i dont want users to have direct access to the generated pdf file. They may copy the iframe src url and send it to someone else. We cant stop them from downloading the pdf, but i dont want them to copy the source url from the server.
check this code
you should be add file address to DB
<?php
// get id to search on DB and get detail
$id = $_REQUEST['id'];
try {
$conn = new PDO("pgsql:host=$host;port=5432;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//echo "Connected successfully";
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
$stmt = $conn->prepare("SELECT url FROM mytable WHERE id=? LIMIT 1");
$stmt->execute([$id]);
$row = $stmt->fetch();
// the address of file in server
$path = $row['url'];
$filename = basename($path);
if (file_exists($path) && is_readable($path)) {
// get the file size and send the http headers
$size = filesize($path);
header('Content-Type: application/octet-stream');
header('Content-Length: '.$size);
header('Content-Disposition: attachment; filename='.$filename);
header('Content-Transfer-Encoding: binary');
// open the file in binary read-only mode
// display the error messages if the file canĀ“t be opened
$file = # fopen($path, 'rb');
if ($file) {
// stream the file and exit the script when complete
fpassthru($file);
exit;
} else {
echo $err;
}
} else {
echo 'check that file exists and is readable';;
}
?>
I found a really good article with a feature I want to add to a page, but have been stuck the entire day with one small error. For reference the tutorial is located here.
Everything is working, the only thing that is not happening is the fact that the index.php webpage is not refreshing on changes made to the hosted php array. Could anyone glance at my code and tell me if I have a typo or missed part of the article?
My array file - selectedSystemStateResults.php
<?php
$selectedSystemStateResults = ["cart", "dogsss", "cows", "zebra", "snake"];
My serverside PHP script file - selectedSystemState-script.php
<?php
header("Cache-Control: no-cache");
header("Content-Type: text/event-stream");
// Require the file which contains the $animals array
require_once "selectedSystemStateResults.php";
// Encode the php array in json format to include it in the response
$selectedSystemStateResults = json_encode($selectedSystemStateResults);
echo "data: $selectedSystemStateResults" . "\n\n";
flush();
echo "retry: 1000\n";
echo "event: selectedSystemStateResultsMessage\n";
My Client side web page - index.php
<?php require "selectedSystemStateResults.php"; ?>
<html>
<body>
<?php foreach ($selectedSystemStateResults as $selectedSystemStateResult) : ?>
<li><?php echo $selectedSystemStateResult; ?></li>
<?php endforeach ?>
</ul>
<script src="/selectedSystemState-script.js"></script>
</body>
</html>
My javascript file - selectedSystemState-script.js
let eventSource = new EventSource('selectedSystemState-script.php');
eventSource.addEventListener("selectedSystemStateResultsMessage", function(event) {
let data = JSON.parse(event.data);
let listElements = document.getElementsByTagName("li");
for (let i = 0; i < listElements.length; i++) {
let selectedSystemStateResults = listElements[i].textContent;
if (!data.includes(selectedSystemStateResults)) {
listElements[i].style.color = "red";
}
}
});
I have read this and re-read this for the past 8 hours and feel really stuck. Does anyone see any blaring php or javascript typos or could the tutorial be wrong?
Please pardon the typo I had in the file names on my unedited original post. The directory shows the files all named properly.
Using this tutorial Using server-sent events
I found out that the script.php file must NOT stop executing !!
or (selectedSystemState-script.php) in your case .
So I guess the the tutorial you linked is wrong in some point ?
try this
while (1) {
// Every second, send a "selectedSystemStateResultsMessage" event.
echo "event: selectedSystemStateResultsMessage\n";
require("selectedSystemStateResults.php");
$selectedSystemStateResults = json_encode($selectedSystemStateResults);
echo "data: $selectedSystemStateResults" . "\n\n";
ob_end_flush();
flush();
sleep(1);
}
this is new to me but i noticed a few things :
1- the php event script file must have header text/event-stream
2- that file must not stop executing !
3- event: is sent before data: .
Hope this help
EDIT
After a test on your script It worked when I changed
<script src="/selectedSystemState-script.js"></script>
to <script src="./selectedSystemState-script.js"></script>
it was calling selectedSystemState-script.js from root folder ! and generate 404 error
and in selectedSystemState-script.php
<?php
header("Cache-Control: no-cache");
header("Content-Type: text/event-stream");
// Require the file which contains the $animals array
require_once "selectedSystemStateResults.php";
// Encode the php array in json format to include it in the response
$selectedSystemStateResults = json_encode($selectedSystemStateResults);
// data after event
flush();
echo "retry: 1000\n";
echo "event: selectedSystemStateResultsMessage\n";
echo "data: $selectedSystemStateResults" . "\n\n";
?>
and I edited selectedSystemState-script.js a bit :
let eventSource = new EventSource('selectedSystemState-script.php');
eventSource.addEventListener("selectedSystemStateResultsMessage", function(event) {
let data = JSON.parse(event.data);
let listElements = document.getElementsByTagName("li");
for (let i = 0; i < listElements.length; i++) {
let selectedSystemStateResults = listElements[i].textContent;
if (!data.includes(selectedSystemStateResults)) {
listElements[i].style.color = "red";
} else {
listElements[i].style.color = "blue";
}
}
});
<script src="/selectedSystemState-script.js"></script>
does not match your javascript filename selectSystemState-script.js. Verify javascript errors next time by opening the developer tools console!
Another error is that you're sending the data before setting the event name. The end of selectedSystemState-script.php should be:
echo "retry: 1000\n";
echo "event: selectedSystemStateResultsMessage\n";
echo "data: $selectedSystemStateResults" . "\n\n";
flush();
Js code
var server = '';
var orig_chat = chatUpdateSucess;
chatUpdateSucess = function(o){
if (o.GlobalChats && o.GlobalChats.length > 0) {
//TODO: Add setting to enable/diosable this
console.log(JSON.stringify(o.GlobalChats));
var xhr = new XMLHttpRequest();
xhr.open("POST", server+"/api.php?request=log_gc");
xhr.send(JSON.stringify(o.GlobalChats));
}
orig_chat.apply(this, arguments);
};
Server code named api.php
<?php
header("Access-Control-Allow-Origin: *");
if(!empty($_POST['o.GlobalChats'])){
$data = $_POST['o.GlobalChats'];
$fname = time() . ".txt";//generates random name
$file = fopen("" .$fname, 'w');//creates new file
fwrite($file, $fclose($file);
}
?>
console.log output
[{"PlayerId":237186,"toPlayerId":0,"chatid":16606292,"added":"/Date(1451764948837)/","addedText":"20:02","PlayerLink":"p=Kodabear|237186|T?|78|1|0|0-144-0-240-186-0-0-0-0-0-0-0-0|#IKnowAFighter|Neurofibromatosis Awareness day/Month|5-404-282-59","text":"Exmaple of a real chat"}]
I created a js that sends a file to my server every time the chat in the game is updated. But I am having problems with the server side code any advice would be great help. (PHP code was founded here
Saving a text file on server using JavaScript
Try to var_dump($_POST['o.GlobalChats']) to see if your data is reaching the server.
It seems like you are not writing the file to the system properly. Please read the examples at the manual (http://php.net/manual/pt_BR/function.fwrite.php)
Also, using time() is not safe, because two files may be created at the same UNIX timestamps in extreme cases, and one will overwrite the other
Try something like this:
$data = $_POST['o.GlobalChats'];
$fname = time() . "-" . rand ( 1 , 10000 ) . ".txt";
$handle = fopen($fname, 'w');
fwrite($handle, $data);
fclose($handle);
I'm pulling contents from text files into a textarea to be used and noticed it appeared that slashes were appearing near quotes and apostrophes. I was able to resolve that by disabling magic quotes on the server, however I noticed that special characters still don't seem to display properly.
What I am trying to figure out is there a way when retrieving the file to decode/encode them properly or to encode them so they're UTF 8 compliant in the first place? Below is my coding for retrieving the files:
<?php
$directory = $directory = 'users/' . $_SESSION['username'];
$filesContents = Array();
$files = scandir( $directory ) ;
foreach( $files as $file ) {
if ( ! is_dir( $file ) ) {
$filesContents[$file] = file_get_contents($directory , $file);
echo '<option value="'. $file .'">' . $file . '</option>';
}
}
?>
</select>
and below is my save script:
if($_POST['Action'] == "SAVE") {
// If a session already exists, this doesn't have any effect.
session_start();
// Sets the current directory to the directory this script is running in
chdir(dirname(__FILE__));
// Breakpoint
if( empty($_SESSION['username']) || $_SESSION['username'] == '' ) {
echo 'There is no session username';
}
if( empty($_POST['CodeDescription']) || $_POST['CodeDescription'] == '' ) {
echo 'There is no POST desired filename';
}
// This is assuming we are working from the current directory that is running this PHP file.
$USER_DIRECTORY = 'users/'.$_SESSION['username'];
// Makes the directory if it doesn't exist
if(!is_dir($USER_DIRECTORY)):
mkdir($USER_DIRECTORY);
endif;
// Put together the full path of the file we want to create
$FILENAME = $USER_DIRECTORY.'/'.$_POST['CodeDescription'].'.txt';
if( !is_file( $FILENAME ) ):
// Open the text file, write the contents, and close it.
file_put_contents($FILENAME, $_POST['Code']);
endif;
header('Location: mysite.site/evo/codesaveindex.php?saved=1&file='.$FILENAME);
}
?>
I am trying to create a PHP file that the browser will see as a js file, and are using the content-type header. But there's something not working, even though. So my question is, should this be interpreted as a valid .js file?:
<?php
header('Content-Type: application/javascript');
$mysql_host = "localhost";
$mysql_database = "lalalala";
$mysql_user = "lalalalal";
$mysql_password = "lalalallaala";
if (!mysql_connect($mysql_host, $mysql_user, $mysql_password))
die("Can't connect to database");
if (!mysql_select_db($mysql_database))
die("Can't select database");
mysql_query("SET NAMES 'utf8'");
?>
jQuery(document).ready(function() {
var urlsFinal = [
<?php
$result = mysql_query("SELECT * FROM offer_data ORDER BY id_campo DESC");
while($nt = mysql_fetch_array($result)) {
?>
"<?php echo $nt['url']; ?>",
<?php
};
?>
"oiasdoiajsdoiasdoiasjdioajsiodjaosdjiaoi.com"
];
scriptLoaded();
});
In order for your Browser to see your PHP file like a .js file, echo or print the entire PHP page into a string, there will be no need to use any headers, just something like:
// First let's make a secure page called database.php - put in a restricted folder
<?php
function db(){
return new mysqli('host', 'username', 'password', 'database');
}
?>
// now let's go over a new technique you'll cherish in the future - page.php
<?php
include 'restricted/database.php'; $db = db();
if($db->connect_errort)die("Can't connect to database. Error:".$db->connect_errno);
$db->query("UPDATE tabelName SET names='utf8' WHERE column='value'");
$sel = $db->query('SELECT * FROM offer_data ORDER BY id_campo DESC');
if($sel->num_rows > 0){
while($nt = $db->fetch_object()){
$output[] = $nt->url;
}
}
else{
die('No records were returned.')
}
$sel->free(); $out = implode("', '", $output); $db->close();
echo "jQuery(document).ready(function(){
var urlsFinal = ['$out'];
// more jQuery here - you may want to escape some jQuery \$ symbols
}"
?>
Now just make sure your script tag looks like:
<script type='text/javascript' src='page.php'></script>