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());
Related
I have a task to do in which i have to list the directories with it's files which i did, but i don't understand how to delete file or edit specific file in the directories any help will be appreciated Thanks.
<?php
error_reporting(0);
if(isset($_GET['dir']))
{
// /$path = 'E:\xampp\\'.$_GET['dir'];
$path = $_GET['dir'];
}
else
{
$path = 'E:\xampp\\';
}
if(is_dir($path))
{
$arrDir = scandir($path);
echo "<ul>";
foreach ($arrDir as $key => $value)
{
echo "<a href='http://localhost/vishrut/FileUpload/filelist.php?
dir=".$path.'/'.$value."'>".$value.'</a><br>';
}
echo "</ul>";
}
else
{
echo "<textarea>";
echo file_get_contents($path);
echo "</textarea>"."<br>";
}
?>
There are lots of PHP's functions to handle files: https://www.php.net/manual/en/ref.filesystem.php
For your needs see these:
file_get_contents to read the entire file contents
file_put_contents to write the content in a file
unlink to delete a file
So, the steps to modify a file may be:
get the complete contents with file_get_contents:
$contents = file_get_contents($filePath);
apply your edits to the $contents content:
$newContents = ...
overwrite the file content:
file_put_contents($filePath, $newContents);
To delete a file is simple:
unlink($filePath);
It's important to note that your code is subjected to injection because you don't check the user data passed with $_GET.
If your script will be used only by you it's ok, instead you must check all user input: the first rule of Web programming is NEVER TRUST YOUR USERS! Also trusted users may write wrong characters in the url and that may have unexpected results (e.g. delete the wrong file!)
Read https://www.php.net/manual/en/mongodb.security.script_injection.php
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);
}
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'));
Can someone explain me why when i POST RAW Data for example "test.txt" in the below script
<?php
echo file_get_contents("php://input");
?>
it only prints the text "test.txt" instead of the file contents of that file?
Thank you
Your code reads the contents of the raw POST data and echoes it back.
Whereas what you want is this:
// retrieve the requested filename
$fileName = file_get_contents("php://input");
// echo the contents of the requested file
echo file_get_contents($fileName);
Depending on what you're trying to, you may wish to sanitize the $fileName input (not shown: too broad) and restrict access to a specific local directory:
$path = $myLocalDirectory . DIRECTORY_SEPARATOR . $fileName;
if (file_exists($path) {
echo file_get_conents($path);
}
Try like this ..
$input = "abc.txt";
echo file_get_contents($input);
It gives the content of the text file abc.txt