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);
}
?>
Related
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.
I need my page bargraph.html to get parameters like .../bargraph.html?di=xxxx&mn=yyyy and save the values of di and mn using a php script in a text file named cred.txt. The code I'm using for bargraph.html is
<body>
<?php
$mobile_num = $_GET["mn"];
$device_id = $_GET["di"];
$file_name = "cred.txt";
$location = "cred/".$file_name;
$text = $mobile_num."\n".$mobile_num;
$my_file = fopen($location, "w") or die("Unable to open file!");
fwrite($my_file, $text);
echo "response submitted successfully!";
fclose($my_file);
?>
</body>
The file named cred.txt is not created inside the cred/ directory and neither I get any errors. What am I doing wrong?
If the same thing can be done using JavaScript I'll use that instead of php for this purpose.
The question references bargraph.html - presumably the php code that you have is NOT on that page but a separate script? If that is the case then if you were to use exception handling to try to track down the issue it might help. Also, I have always found better success when using full paths as opposed to relative ones
<?php
if( isset( $_GET['mn'], $_GET['di'] ) ){
try{
$filename='cred.txt';
$mobile_num=filter_input( INPUT_GET, 'mn', FILTER_SANITIZE_STRING );
$device_id=filter_input( INPUT_GET, 'di', FILTER_SANITIZE_STRING );
/*
I have always found it is best to use a full path rather than relative
Change `path/to/` to the appropriate path
*/
$path=$_SERVER['DOCUMENT_ROOT'] . '/path/to/cred';
/* If the path does not exist, warn user */
if( !realpath( $path ) ){
throw new Exception( sprintf( 'Unable to find path: %s', $path ) );
}
/* Can the chosen directory be read? */
if( is_readable( $path ) && is_writable( $path ) ){
$file=$path . '/' . $filename;
#$text=$mobile_num . PHP_EOL . $mobile_num . PHP_EOL;
/* I think this is probably what you intended? */
$text=$device_id . PHP_EOL . $mobile_num . PHP_EOL;
$status=file_put_contents( $file, $text, FILE_APPEND | FILE_TEXT );
throw new Exception( $status ? sprintf('All good! Saved %s',$file) : sprintf('Error - unable to save %s',$file) );
} else {
/*
should set permissions if reading/writing of target folder failed
chmod($path,0777); etc
*/
throw new Exception( sprintf( 'The path %s is either not readable or writable',$path ));
}
}catch( Exception $e ){
exit( $e->getMessage() );
}
}
?>
Using a plain HTML page you could send an ajax request to the above PHP script ( in code below called bargraph.php )
<html>
<head>
<title>ajax-store credentials</title>
</head>
<body>
<form id='bg'>
<input type='text' name='mn' id='mn' placeholder='Mobile number: eg 0141 353 3874' />
<input type='text' name='di' id='di' placeholder='Device ID: eg yellow banana' />
<input type='button' id='bttn' value='Go' />
</form>
<script>
document.getElementById('bttn').onclick=function(e){
var mn=document.getElementById('mn').value;
var di=document.getElementById('di').value;
if( mn != '' && di != '' ){
var xhr=new XMLHttpRequest();
xhr.onload=function(r){
document.getElementById('status').innerHTML=this.response;
};
xhr.onerror=function(r){
document.getElementById('status').innerHTML=err.message;
};
xhr.open('GET','?mn='+mn+'&di='+di,true);
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.send();
}
}
</script>
<div id='status'></div>
</body>
</html>
You can do like this.
$mobile_num = $_GET["mn"];
$device_id = $_GET["di"];
$file_name = "cred.txt";
$path = getcwd();
$location = $path.'/cred/'.$file_name;
$text = $device_id."\n".$mobile_num;
$my_file = fopen($location, "w") or die("Unable to open file!");
fwrite($my_file, $text);
echo "response submitted successfully!";
fclose($my_file);
You need to give write permission on cred folder.
I am trying to install Magento community edition 1.9.2.1 into cPanel through Godaddy. I have so far extracted the tar file into the file manager, moved all the items in the Magento folder into root, and given folders proper permissions to run.
When I go into my website to open up the installation wizard I see this
I cannot click the continue button it doesn't work. When I inspect the page I get these errors.
I think its a jQuery problem. Looks like the website doesn't load any JavaScript. I tried adding a jQuery CDN link to the head but no avail. I have saved a jQuery CDN into my file system and called it through head still nothing.
I don't know what's the problem. JavaScript is enabled in my browser, so it should work.
i think this should be permission issue.i have attached a code,copy that in a new file(eg. magento-cleanup.php ) and upload to your magento root and run it using url(http://youdomain/magento-cleanup.php). it helps you to fix permission issue.
<?php
## Function to set file permissions to 0644 and folder permissions to 0755
function AllDirChmod( $dir = "./", $dirModes = 0755, $fileModes = 0644 ){
$d = new RecursiveDirectoryIterator( $dir );
foreach( new RecursiveIteratorIterator( $d, 1 ) as $path ){
if( $path->isDir() ) chmod( $path, $dirModes );
else if( is_file( $path ) ) chmod( $path, $fileModes );
}
}
## Function to clean out the contents of specified directory
function cleandir($dir) {
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
if ($file != '.' && $file != '..' && is_file($dir.'/'.$file)) {
if (unlink($dir.'/'.$file)) { }
else { echo $dir . '/' . $file . ' (file) NOT deleted!<br />'; }
}
else if ($file != '.' && $file != '..' && is_dir($dir.'/'.$file)) {
cleandir($dir.'/'.$file);
if (rmdir($dir.'/'.$file)) { }
else { echo $dir . '/' . $file . ' (directory) NOT deleted!<br />'; }
}
}
closedir($handle);
}
}
function isDirEmpty($dir){
return (($files = #scandir($dir)) && count($files) <= 2);
}
echo "----------------------- CLEANUP START -------------------------<br/>";
$start = (float) array_sum(explode(' ',microtime()));
echo "<br/>*************** SETTING PERMISSIONS ***************<br/>";
echo "Setting all folder permissions to 755<br/>";
echo "Setting all file permissions to 644<br/>";
AllDirChmod( "." );
echo "Setting pear permissions to 550<br/>";
chmod("pear", 550);
echo "<br/>****************** CLEARING CACHE ******************<br/>";
if (file_exists("var/cache")) {
echo "Clearing var/cache<br/>";
cleandir("var/cache");
}
if (file_exists("var/session")) {
echo "Clearing var/session<br/>";
cleandir("var/session");
}
if (file_exists("var/minifycache")) {
echo "Clearing var/minifycache<br/>";
cleandir("var/minifycache");
}
if (file_exists("downloader/pearlib/cache")) {
echo "Clearing downloader/pearlib/cache<br/>";
cleandir("downloader/pearlib/cache");
}
if (file_exists("downloader/pearlib/download")) {
echo "Clearing downloader/pearlib/download<br/>";
cleandir("downloader/pearlib/download");
}
if (file_exists("downloader/pearlib/pear.ini")) {
echo "Removing downloader/pearlib/pear.ini<br/>";
unlink ("downloader/pearlib/pear.ini");
}
echo "<br/>************** CHECKING FOR EXTENSIONS ***********<br/>";
If (!isDirEmpty("app/code/local/")) {
echo "-= WARNING =- Overrides or extensions exist in the app/code/local folder<br/>";
}
If (!isDirEmpty("app/code/community/")) {
echo "-= WARNING =- Overrides or extensions exist in the app/code/community folder<br/>";
}
$end = (float) array_sum(explode(' ',microtime()));
echo "<br/>------------------- CLEANUP COMPLETED in:". sprintf("%.4f", ($end-$start))." seconds ------------------<br/>";
?>
EDIT: Missed the echo statement!
EDIT2: Added missing paranthesis!
EDIT3: Found the solution. See below!
What I am trying to achieve is this:
Dynamically create a Javascript-file with PHP
Serve Javascript-file as .js as embeddable Javascript on different URLs
Dynamically add Page Name and Page URL information inside the JS to be used in Javascript
Currently I do the following:
code.php
<?php header("Content-type: application/x-javascript"); ?>
/*
<?php echo $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'] ;?>
*/
/*
<?php
$func = new Functions;
echo $func->getPageURL();
echo $func->getPageName();
?>
*/
var fred;
...
class.functions.php
<?php
class Functions {
function getPageURL() {
$isHTTPS = (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on");
$port = (isset($_SERVER["SERVER_PORT"]) && ((!$isHTTPS && $_SERVER["SERVER_PORT"] != "80") || ($isHTTPS && $_SERVER["SERVER_PORT"] != "443")));
$port = ($port) ? ':'.$_SERVER["SERVER_PORT"] : '';
$data = ($isHTTPS ? 'https://' : 'http://').$_SERVER["SERVER_NAME"].$port.$_SERVER["REQUEST_URI"];
return $data;
}
function getPageName() {
$data = substr($_SERVER["SCRIPT_NAME"],strrpos($_SERVER["SCRIPT_NAME"],"/")+1);
return $data;
}
}
Whenever someone triggers my script-embed code I route them to my code.php. Example:
<script src="//servingdomain/dynamic/123.js"></script>
Now, my code.php does a great job, but returns me this:
/*
servingdomain/dynamic/123.js
*/
/*
https://servingdomain/dynamic/123.js
index.php
*/
var fred;
...
Unfortunately my getPageURL und getPageName are not executed properly, but I am failing to understand why.
I am aiming to get this as output:
/*
servingdomain/dynamic/123.js
*/
/*
https://otherdomain/blog/awesome-article (page-url)
Awesome Article to read (page-name)
*/
var fred;
...
How should I takle this problem and get this working correctly either by clean code or dirty workaround ... I am aware of window.location.pathname and window.location.href in Javascript, but I need those to be passed in PHP, since I need to reuse this information to generate dynamic code in code.php.
Solution
Using $_SERVER['HTTP_REFERER'] gives correct referrer and running that through
<?php
echo $_SERVER['HTTP_REFERER'];
$func = new Functions;
echo $func->getPageTitle($_SERVER['HTTP_REFERER']);
?>
class.functions.php
function getPageTitle($url){
$str = file_get_contents($url);
if(strlen($str)>0){
preg_match("/\<title\>(.*)\<\/title\>/",$str,$title);
return $title[1];
}
}
Output
https://otherdomain/blog/awesome-article (page-url)
Awesome Article to read (page-name)
<?php
$func = new Functions;
$purl = $func->getPageURL()."\n";//use ()
$pname = $func->getPageName();
echo $purl;
echo $pname;
?>
The PHP code is executed just fine, but it just doesn't have any result. You need to write out the values to the file:
<?php header("Content-type: application/x-javascript"); ?>
/*
<?php echo $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'] ;?>
*/
/*
<?php
$func = new Functions;
$purl = $func->getPageURL;
$pname = $func->getPageName;
printf("%s\n", $purl);
printf("%s\n", $pname);
?>
*/
var fred;
...
This will write the values of those variables to the javascript file.
Note that if you want to use these values in the javascript code, you need to assign them to a javascript variable like this, outside of javascript comments:
printf("var pageName='%s'\n", $pname);
That way, you can use pageName in your javascript.
Solution
Using $_SERVER['HTTP_REFERER'] gives correct referrer
<?php
echo $_SERVER['HTTP_REFERER'];
$func = new Functions;
echo $func->getPageTitle($_SERVER['HTTP_REFERER']);
?>
Running that through this function
class.functions.php
function getPageTitle($url){
$str = file_get_contents($url);
if(strlen($str)>0){
preg_match("/\<title\>(.*)\<\/title\>/",$str,$title);
return $title[1];
}
}
Output
https://otherdomain/blog/awesome-article (page-url)
Awesome Article to read (page-name)
I am attempting to use JSONP to return an array from PHP to JavaScript. Hopefully, my code will demonstrate exactly what I'm trying to do because I am not even so sure how to word it...
My PHP file, port 80, hence the need to use JSONP and not JSON (I tried already)
I am not sure if I am forming the $_GET variables correctly either, I'm pretty certain it's wrong though and my lack of knowledge is the reason for this...
<?php
$directory = './thumbnails/';
// create a handler to the directory
$dirhandler = opendir($directory);
// read all the files from directory
$nofiles=0;
while (false !== ($file = readdir($dirhandler))) {
// if $file isn't this directory or its parent
//add to the $files array
if ($file != '.' && $file != '..')
{
$thumbs[$nofiles]= 'http://localhost:80/mapScripts/thumbnails/' . $file;
$nofiles++;
}
}
//$i = rand(0, 3);
//$output = "{";
for($i=0; $i < 3; $i++){
$json[i] = json_encode($thumbs[$i]);
$output = $output . $_GET['thumbnails' . $i]. "(".$json[i].")";
//$output = $output . "'thumb" . $i . "':'" . $thumbs[$i] . "',";
}
//$output = $output . "}";
//echo $_GET['thumbnails'] ."(".$json.")";
echo $output;
?>
Then in JavaScript on port 8080 (cross-domain and yes it worked fine until I tried to use this array as opposed to just passing one image url) I want to get each image url from the PHP array so that I can make icons using the image..
function makeThumbs(data, layer){
var icon = new OpenLayers.Icon(data);
layer.addMarker(new OpenLayers.Marker(new OpenLayers.LonLat(93.9, 29.53).transform(new OpenLayers.Projection("EPSG:4326"), new OpenLayers.Projection("EPSG:900913")),icon));
for(var m = 0; m < layer.markers.length; m++){
layer.markers[m].events.register("click", layer.markers[m], function clickIcon(e){alert("How are you?");});
$("[id$=innerImage]").css({"border-style":"solid","border-width":"3px","border-color": "white"});
}
}
$.getJSON('http://localhost:80/mapScripts/getThumbs.php?thumbnails2=?', function(data) {makeThumbs(data, markers);});
again the url I am passing to the $.getJSON method is also probably wrong. I need to know how to select the exact photo url from the array being passed, not all the JSONP data.
I appreciate your time and feedback for helping me with this.
elshae
I actually found one way of doing it..Here goes..
<?php
$directory = './thumbnails/';
// create a handler to the directory
$dirhandler = opendir($directory);
// read all the files from directory
$nofiles=0;
while (false !== ($file = readdir($dirhandler))) {
// if $file isn't this directory or its parent
//add to the $files array
if ($file != '.' && $file != '..')
{
$thumbs[$nofiles]= 'http://localhost:80/mapScripts/thumbnails/' . $file;
$nofiles++;
}
}
//$i = rand(0, 3);
$output = $_GET['thumbnails'] . "({";
for($i=0; $i < 3; $i++){
//$json[i] = json_encode($thumbs[$i]);
//$output = $output . $_GET['thumbnails' . $i]. "(".$json[i].")";
$output = $output . "'thumb" . $i . "':'" . $thumbs[$i] . "',";
}
$output = $output . "})";
//echo $_GET['thumbnails'] ."(".$json.")";
echo $output;
?>
That outputs:
({'thumb0':'http://localhost:80/mapScripts/thumbnails/Tibet2.jpeg','thumb1':'http://localhost:80/mapScripts/thumbnails/lhasa.jpeg','thumb2':'http://localhost:80/mapScripts/thumbnails/Tibet.jpg',})
Then in JavaScript I just:
function makeThumbs(data, layer){
alert("already Here "+ data);
var icon = new OpenLayers.Icon(data);
alert(icon.url);
layer.addMarker(new OpenLayers.Marker(new OpenLayers.LonLat(93.9, 29.53).transform(new OpenLayers.Projection("EPSG:4326"), new OpenLayers.Projection("EPSG:900913")),icon));
for(var m = 0; m < layer.markers.length; m++){
layer.markers[m].events.register("click", layer.markers[m], function clickIcon(e){alert("How are you?");});
$("[id$=innerImage]").css({"border-style":"solid","border-width":"3px","border-color": "white"});
}
}
$.getJSON('http://localhost:80/mapScripts/getThumbs.php?thumbnails=?', function(data) {makeThumbs(data.thumb2, markers);});
So it seems after the $_GET variable you can put typical JSON data and fetch it as you normally would (notice the data.thumb2 in the JavaScript).