JSFIDDLE
I'm using filedrop.js to create a file repository structure within my app. The above noted JSFIDDLE has all of the Javascript / jQuery / HTML and CSS code for this small module. While everything on the client end seems to be functioning properly (files can be DnD'd, progress bar acts correctly, console shows proper event triggers), the result on the server-side is always an empty $_FILES variable. My PHP (ajax.receiveFile.php) is as follows:
var_dump($_FILES);
ob_start();
$callback = &$_REQUEST['fd-callback'];
$job_id = &$_REQUEST['job_id'];
$subdir = &$_REQUEST['subdir'];
$j = loadJob($job_id);
$save_path = "D:\\JobFiles\\" . $j->gOrderNumber() . "\\" . $subdir . "\\";
if ( ($_FILES['fd-file']['size'] > 0) && is_uploaded_file($_FILES['fd-file']['tmp_name']) ) {
$name = $_FILES['fd-file']['name'];
if (move_uploaded_file($_FILES['fd-file']['tmp_name'], $save_path.$name)) {
$j->addAttachment($subdir,$name);
echo 'true';
} else {
echo 'false';
}
}
ob_end_flush();
FileDrop.js seems to be doing what it is supposed to do, as shown here:
I read here on SO that using the same element name over multiple input types of "file" can cause errors but I'm not sure that is the case here. I have double- and triple-checked the permissions on both the TEMP and TARGET upload folders, I have confirmed that all PHP variables are set as needed via visual inspection and PHPINFO(). The server config is PHP 5.4 on IIS7.
If anyone has any ideas on what else to look for, please contribute. Thanks!
This works for me:
file_put_contents('uploads/person/7.jpeg', fopen('php://input', 'r'));
Related
I have a WordPress issue and want to simply write log messages to a text file. I am aware that error_log exists, but want to have a more segregated log file for different messages.
I am using wp_filesystem->put_contents, and it DOES write to the file and succeeds, but it ONLY outputs the last call's data.
I have the following method:
public static function log_message($msg) {
error_log($msg);
require_once(ABSPATH . 'wp-admin/includes/file.php');
global $wp_filesystem;
if ( ! is_a( $wp_filesystem, 'WP_Filesystem_Base') ){
$creds = request_filesystem_credentials( site_url() );
wp_filesystem($creds);
}
$bt = debug_backtrace();
$caller = array_shift($bt);
$logStr = date("Y-m-d hh:ii A",time())." - ".$caller['file'].":".$caller['line']." - ".$msg;
$filePathStr = SRC_DIR.DIRECTORY_SEPARATOR.$logFileName;
$success = $wp_filesystem->put_contents(
$filePathStr,
$logStr,
FS_CHMOD_FILE // predefined mode settings for WP files
);
if(!$success) {
error_log("Writing to file \"".$filePathStr."\" failed.");
} else {
error_log("Writing to file \"".$filePathStr."\" succeeded.");
}
}
I call it using:
log_message("\nTest 1");
log_message("\nTest 2");
log_message("\nTest 3");
The output is ALWAYS ONLY Test 3 with the other invocations being ignored yet, their output appears in the debug.log as well as all the success messages.
Why would this be?
Looking at the WPCodex for the source code of this, it uses fwrite behind the scenes. The file is closed in this code, and I cannot use any "flush" technique.
Is there a way to figure this out?
I found that the source of WP_Filesystem uses file_put_contents (as the name does suggest), and I assumed this is for APPENDING to the file's data.
This is incorrect.
This function is to take data, and then WRITE it to the file, erasing prior data.
Mainly useful for creating resources, downloading a file, etc.
If I want to APPEND to a file, I need to use 'fwrite'.
This post describes that.
This is the example to APPEND to a file:
$filepath = '\path\to\file\';
$filename = 'out.log';
$fullpath = $filepath.$filename;
if(file_exists($fullpath)) {
$file = fopen($filepath.$filename, "a");//a for append -- could use a+ to create the file if it doesn't exist
$data = "test message";
fwrite($file, "\n". $data);
fclose($file);
} else {
error_log("The file \'".$fullpath."\' does not exist.");
}
The fopen docs describe this method and it's modes.
I want to open a server stored html report file on a client machine.
I want to bring back a list of all the saved reports in that folder (scandir).
This way the user can click on any of the crated reports to open them.
So id you click on a report to open it, you will need the location where the report can be opend from
This is my dilemma. Im not sure how to get a decent ip, port and folder location that the client can understand
Here bellow is what Ive been experimenting with.
Using this wont work obviously:
$path = $_SERVER['DOCUMENT_ROOT']."/reports/saved_reports/";
So I though I might try this instead.
$host= gethostname();
$ip = gethostbyname($host);
$ip = $ip.':'.$_SERVER['SERVER_PORT'];
$path = $ip."/reports/saved_reports/";
$files = scandir($path);
after the above code I loop through each file and generate a array with the name, date created and path. This is sent back to generate a list of reports in a table that the user can interact with. ( open, delete, edit)
But this fails aswell.
So im officially clueless on how to approach this.
PS. Im adding react.js as a tag, because that is my front-end and might be useful to know.
Your question may be partially answered here: https://stackoverflow.com/a/11970479/2781096
Get the file names from the specified path and hit curl or get_text() function again to save the files.
function get_text($filename) {
$fp_load = fopen("$filename", "rb");
if ( $fp_load ) {
while ( !feof($fp_load) ) {
$content .= fgets($fp_load, 8192);
}
fclose($fp_load);
return $content;
}
}
$matches = array();
// This will give you names of all the files available on the specified path.
preg_match_all("/(a href\=\")([^\?\"]*)(\")/i", get_text($ip."/reports/saved_reports/"), $matches);
foreach($matches[2] as $match) {
echo $match . '<br>';
// Again hit a cURL to download each of the reports.
}
Get list of reports:
<?php
$path = $_SERVER['DOCUMENT_ROOT']."/reports/saved_reports/";
$files = scandir($path);
foreach($files as $file){
if($file !== '.' && $file != '..'){
echo "<a href='show-report.php?name=".$file. "'>$file</a><br/>";
}
}
?>
and write second php file for showing html reports, which receives file name as GET param and echoes content of given html report.
show-report.php
<?php
$path = $_SERVER['DOCUMENT_ROOT']."/reports/saved_reports/";
if(isset($_GET['name'])){
$name = $_GET['name'];
echo file_get_contents($path.$name);
}
I'm trying to fetch gamerscore data from gamercard.xbox.com with my little script:
test.php
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
$regex = '/<div id=\"Gamerscore\">(.+?)<\/div>/';
$gamertag = 'Stallion83';
try {
$URL = file_get_contents('http://gamercard.xbox.com/en-US/' . $gamertag . '.card');
if ($URL == false) {
echo 'Error!';
}
} catch (Exception $e) {
echo $e;
}
preg_match($regex, $URL, $gs);
// Extract integer value from string
$gamerscore = filter_var($gs[1], FILTER_SANITIZE_NUMBER_INT);
// Force gs_int to be integer so it can be used with number_format later
$gs_int = (int)$gamerscore;
$textFile = 'data/gamerscore_' . $gamertag . '.txt';
// Save gamerscore value into everyone's own txt file
file_put_contents($textFile, $gs_int);
?>
Now this works and it creates a .txt file in the data folder which has only the gamerscore number inside. But my problem is if I run the script again after the gamerscore value has increased the script doesn't give me any errors and it seems to execute just fine but the gamerscore value it saves into the .txt file is the old value.
I can go to the URL http://gamercard.xbox.com/en-US/Stallion83.card and see the number is different than my script shows.
I thought it might be a caching issue but I think file_get_contents doesn't use caching.
Is there anything else I could set for file_get_contents to force it to get the most recent content of the URL specified? I tried using timeout but it didn't make any difference.
This is most likelly caused by cache. In this case, the server seems to be returning a cached version of the page.
Often, adding a random value to the URL can be a workaround, such as ?foo.
So, in your case, something like:
[...] . $gamertag . 'card?' . mt_rand());
So, if i have a file that when its empty it requires a specific function, but if the file is NOT empty it will proceed to show (else) something else. This is currently the format I am using. I have tired several different manners and variations of doing so (from PHP Manual examples to StackOverFlow Q/A). What it is doing is showing me the else not the if, since the file is actually empty...
<?
$file = 'config/config2.php';
if(!empty($file))
{
some code here!
}
else
{
some other code here!
}
?>
<?
$file = 'config/config2.php';
if(filesize($file)!=0)// NB:an empty 'looking' file could have a file size above 0
{
some code here!
}
else
{
some other code here!
}
?>
The problem seems to be that you are not actually loading the file before you check if it is empty.
You are only setting the variable $file to the string 'config/config2.php' not actually loading the file.
Before running your if statement do this:
$file = file_get_contents('config/config2.php');
or look into this: http://php.net/manual/en/function.fopen.php
I've recently inherited a website written in PHP and given the responsibility to move it from the current host to our own internal web servers.
I succesfully copied the files and i can browse the site on our webserver (IIS7) however some, not all, of the PHP scripts do not appear to execute properly.
For example, the following code loads some text content from a database and displays fine on the existing server,
<?php
$sql = "select * from tblsubpages where PageID = 1 " ;
$page_Result=mysql_query($sql);
while ( $page_Row = mysql_fetch_array ( $page_Result))
{
?>
<?=str_replace('<blockquote>','',$page_Row['Details']); ?>
however on the new server all i get is the following output in the place where the text content should be.
','',$page_Row['Details']); ?>
The files are identical on both sites and i've verified they can both succesfull connect to the mySQL server.
Question - Any ideas where i can begin troubleshooting or what can be the cause ?
It might be a problem with php.ini's short_open_tag directive on your new host. Check if it is off and if so, try switching it on.
In the php.ini file set :
short_open_tag = On
or change
<?=
to
<?php
First things first.
Make sure you are using the same php
versions
Copy over your php.ini file.
It looks like your ini file has short tags disabled. Change <?= to <?php echo
If you don't want to turn on short_tags you could try to convert them:
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator(DIRECTORY)) as $file) {
if (!$file->isFile()) continue;
$tokens = token_get_all(file_get_contents($file));
$source = '';
foreach ($tokens as $token) {
if (is_string($token)) {
$source .= $token;
continue;
}
if ($token[0] == T_OPEN_TAG_WITH_ECHO) {
$token[1] = '<?php echo ';
}
$source .= $token[1];
}
file_put_contents($file, $source);
}
This iterates over the token of the source and replaces T_OPEN_TAG_WITH_ECHO by <?php echo.