I am trying to get the full path of an uploaded file. The php code is like this:
<?php
$destination_path = getcwd() . DIRECTORY_SEPARATOR;
$result = 0;
$target_path = $destination_path . basename($_FILES['thefile']['name']);
if(#move_uploaded_file($_FILES['thefile']['tmp_name'],*$target_path)) {
$result = 1;
}
?>
<script language="javascript" type="text/javascript">
//d = '<?php echo basename( $_FILES['thefile']['name']); ?>';
d = '<?php echo $target_path; ?>';
window.top.window.phpUpload(d);
</script>
I can open the json file with the rem'd out line but I need the path to return it at session end. Testing with an alert the full path is shown without slashes and the initial letter 'n' of the filename missing ...
Any help much appreciated.
(Click on Names then open nset.json at this test site to see what I'm trying to do)
You are assumingly using this on Windows, where DIRECTORY_SEPARATOR is a backslash. If the filename starts with a n then your Javascript code will end up like this:
d = '..\path\nameoffile.txt';
Javascript unlike PHP will interpret \n in single quoted strings.
The solution to your dilemma is either not using DIRECTORY_SEPARATOR, or outputting a correctly escaped Javascript string:
d = <?php echo json_encode($target_path); ?>;
Do you mean the full path to the file on the client's machine? JavaScript security will not reveal that. It will just send the actual file name to the server.
Related
I have used a function
/*
Random File Function
Written By: Qassim Hassan
Website: wp-time.com
Twitter: #QQQHZ
*/
function Qassim_Random_File($folder_path = null){
if( !empty($folder_path) ){ // if the folder path is not empty
$files_array = scandir($folder_path);
$count = count($files_array);
if( $count > 2 ){ // if has files in the folder
$minus = $count - 1;
$random = rand(2, $minus);
$random_file = $files_array[$random]; // random file, result will be for example: image.png
$file_link = $folder_path . "/" . $random_file; // file link, result will be for example: your-folder-path/image.png
return '<img src="'.$file_link.'" alt="'.$random_file.'">';
}
else{
return "The folder is empty!";
}
}
else{
return "Please enter folder path!";
}
}
?>
to pull a random image from a specific wordpress directory. I can successfully call up a random image file however it does not display, just displays the image filename and a broken image icon.
The code I am using from the tutorial to display the image is <?php echo Qassim_Random_File("my-folder-name"); // display random image! ?>
I am brand new to php as of this week, and a fairly novice coder in general (know some basics) so I really am stumped. I've fooled with other possible solutions from stack overflow already but this tutorial is the only thing I've been able to get close to working. Many thanks if anyone can spot the problem!
This is showing up in the HTML inspector:
<div class="elementor-widget-container">
<h5>call</h5>
<a href="wp-content/uploads/H-PH-MA-Greyscale/image_2.jpg" target="_blank" title="image_2.jpg">
<img src="wp-content/uploads/H-PH-MA-Greyscale/image_2.jpg" alt="image_2.jpg">
</a>
</div>
You just need to replace this line:
$file_link = $folder_path . "/" . $random_file;
...with this one:
$file_link = get_site_url(null, $folder_path . "/" . $random_file);
What was the problem?
scandir is returning the physical file path, not the url to the file - we can confirm this is we look at one of the values it returns for $random_file, e.g. wp-content/uploads/H-PH-MA-Greyscale
This is a relative URL, but we need an absolute URL so that it will work no matter where it is called. We also need to include the site URL so that the path to wp-content is correct. (Note: site URL and home URL can be different - the site URL is the one that always point to the location of the WP files).
Another problem is the trailing slash (or lack of one) on the site URL. get_site_url and get_home_url do not add the trailing slash to the URL, so you need to add it yourself if it isn't included in the file path.
So how do we solve this?
Using the get_site_url function added the correct path to the WP files, and it also lets us pass it the file path with our without a preceding slash as a parameter, and it will add the slash on the path only if it is needed.
The code looks simple, if the folder exist and it has more then 2 file (it considers the "." and ".." and files when you use scandir) then you should be able to see something. What's the generated HTML code for that function call?
Be aware that the code you are using builds the file url using the phisical path, that isn't going to work. You should fix this part:
if( $count > 2 ){ // if has files in the folder
$minus = $count - 1;
$random = rand(2, $minus);
$random_file = $files_array[$random]; // random file, result will be for example: image.png
$file_link = get_home_url().$folder_path . "/" . $random_file; // file link, result will be for example: your-folder-path/image.png
return '<img src="'.$file_link.'" alt="'.$random_file.'">';
}
Notice the get_home_url() to build the real URL which is needed for your <img tag src
with the code below I get an image through a form on a html page, make some cuts in it and add another image to it, it's working perfectly.
I'm having problems with special characters in the name of the image that I got from the html form ...
In short, before you upload, crop images, move them, etc., I must treat their name ... removing blank spaces, remove accents, etc. ..
I tried to use some functions but without success .. Can someone give a help?
Here my code:
<?php
require( "./lib/WideImage.php");
// Example of accessing data for a newly uploaded file
$fileName = $_FILES["uploaded_file"]["name"];
$fileTmpLoc = $_FILES["uploaded_file"]["tmp_name"];
// Path and file name
$pathAndName = "cartelas/cart".$fileName;
// Run the move_uploaded_file() function here
$moveResult = move_uploaded_file($fileTmpLoc, $pathAndName);
// Evaluate the value returned from the function if needed
$image = WideImage::load($pathAndName);
$unh = WideImage::load("unh11.png");
$crop1 = $image->crop("25", "50", 111, 132);
$out1 = $crop1->merge($unh,'middle','middle');
$pathAndName1 = "unha-1-".$fileName;
$crop1->saveToFile('./cartelas/estampa'.$pathAndName1);
$out1->saveToFile('./cartelas/'.$pathAndName1);
echo "Imagens geradas:<BR>";
echo "<img src=./cartelas/estampa$pathAndName1><img src=./cartelas/$pathAndName1>";
?>
Thank you!
if u want to do it on php side you can do whatever you want with a filename. If you don't have to have exact same name you can use rawurlencode() or base64_encode(); or even md5() hash from the name. This should solve problems with weird names or special chars.
If u need store all this files u can do $newfilename = md5($filename) . '_' . uniqid(); so they will be unique. You can add also user id or something like that.
imclickingmaniac it would lose its extension if you do that! so instead do...
<?php
$ext=pathinfo($_FILES["file1"]["name"], PATHINFO_EXTENSION);
$fileName=md5($fileName);
$fileName="$fileName.$ext";
?>
UPDATE
Hello again. I found myself with a new problem. The php code worked perfectly on my PC (wamp server) but i've now uploaded it on a free webhost server and while the php part runs perfectly (it produces the array) the javascript function itself doesn't work cause there are no photos in the website when it's loaded. I tried to test it by putting in the function's first line an alert to see if it runs but never showed up. I think that the server for some reason doesn't realise that it is a javascript function because i also had in the getphotos.php this:
window.onload = photos();
which appart from starting the photos function, shows a text. When i moved that line in js file and put the show text line first, it run showing the text but still no photos. What do you think????
END OF UPDATE
Hello to everyone. I am building a website that shows some photos. I want the site to automatically generate the html code that shows the photos by reading the file names in the photo folder, but i need also to use javascript. So I found through the web a solution with php generating javascript which than generates the html code I want and I think this is what I need. But... it doesn't work X_X. So I need someone's help!
Firstly, here is the php/javascript(in getPhotos.php):
<?
header("content-type: text/javascript");
//This function gets the file names of all images in the current directory
//and ouputs them as a JavaScript array
function returnImages() {
$pattern="(*.jpg)|(*.png)|(*.jpeg)|(*.gif)"; //valid image extensions
$files = array();
$curimage=0;
if($handle = opendir('/photos/')) {
while(false !== ($file = readdir($handle))){
if(eregi($pattern, $file)){ //if this file is a valid image
//Output it as a JavaScript array element
echo 'galleryArray['.$curimage.']="'.$file .'";';
$curimage++;
}
}
closedir($handle);
}
return($files);
}
//here starts the javascript function
echo 'window.onload = photos;
function photos(){
var i;
var text1 = "";
var text2 = "";
var text3 = "";
var galleryArray=new Array();'; //Define array in JavaScript
returnImages(); //Output the array elements containing the image file names
//short the images in three sets depending on their names and produce the code
echo 'for(i=0; i<galleryArray.length; i++){
if(galleryArray[i].indexOf("set1_")!=-1){
text1+= "<a rel=\"gallery\" title=\"\" href=\"photos/"+galleryArray[i]+"\">\n<img alt=\"\" src=\"photos/"+galleryArray[i]+"\" />\n</a>\n" ;
}else if(galleryArray[i].indexOf("set2_")!=-1){
text2+= "<a rel=\"gallery\" title=\"\" href=\"photos/"+galleryArray[i]+"\">\n<img alt=\"\" src=\"photos/"+galleryArray[i]+"\" />\n</a>\n" ;
}else if(galleryArray[i].indexOf("set3_")!=-1){
text3+= "<a rel=\"gallery\" title=\"\" href=\"photos/"+galleryArray[i]+"\">\n<img alt=\"\" src=\"photos/"+galleryArray[i]+"\" />\n</a>\n" ;
}
}';
//create text nodes and put them in the correct div
echo 'var code1 = document.createTextNode(text1);
var code2 = document.createTextNode(text2);
var code3 = document.createTextNode(text3);
document.getElementById("galleryBox1").appendChild(code1);
document.getElementById("galleryBox2").appendChild(code2);
document.getElementById("galleryBox3").appendChild(code3);
}';
?>
And this is the code in the mane page index.html:
<script type="text/javascript" src="getPhotos.php"></script><!--get photos from dir-->
This is it, and it doesn't work! I know I ask to much by just giving all the code and asking for help but i can't even think what's wrong, let alone how to fix it.... So please, if you have any idea it would be great.
; after returnImages() is missing.
This function (readdir) may return Boolean
FALSE, but may also return a
non-Boolean value which evaluates to
FALSE, such as 0 or "". Please read
the section on Booleans for more
information. Use the === operator for
testing the return value of this
function.
http://php.net/manual/en/function.readdir.php
So try to use while(false != ($file = readdir($handle))){
or while(FALSE !== ($file = readdir($handle))){
Your regular expression is wrong, for one. You need to look at a regex tutorial, like this one.
I can't figure out how to get the same result from my Javascript as I do from my PHP. In particular, Javascript always leaves out the backslashes. Please ignore the random forward and backslashes; I put them there so that I can cover my basis on a windows system or any other system. Output:
Input String: "/root\wp-cont ent\#*%'i#$#%$&^(###''mage6.jpg:"
/root\wp-content\image6.jpg (PHP Output)
/rootwp-contentimage6.jpg (Javascript Output)
I would appreciate any help!
PHP:
<?php
$path ="/root\wp-cont ent\#*%'i#$#%$&^(###''mage6.jpg:";
$path = preg_replace("/[^a-zA-Z0-9\\\\\/\.-]/", "", $path);
echo $path;
?>
Javascript:
<script type="text/javascript">
var path = "/root\wp-cont ent\#*%'i#$#%$&^(###''mage6.jpg:"; //exact same string as PHP
var regx = /[^a-zA-Z0-9\.\/-]/g;
path = path.replace(regx,"");
document.write("<br>"+path);
</script>
Your problem is that you're not escaping the backslashes in your JS string, which you should always do (even in PHP) if you mean a backslash.
Example:
var path = "/root\wp-cont ent\#*%'i#$#%$&^(###''mage6.jpg:";
alert(path);
path = "/root\\wp-cont ent\\#*%'i#$#%$&^(###''mage6.jpg:";
alert(path);
Yup, Qtax is correct, then you can use this:
var regx = /[^a-zA-Z0-9\.\/-\\]/g;
I'm trying to open a text file and output its contents with the code below. The text file includes line breaks but when I echo the file its unformatted. How do I fix this?
Thanks.
<html>
<head>
</head>
<body>
$fh = fopen("filename.txt", 'r');
$pageText = fread($fh, 25000);
echo $pageText;
</body>
</html>
To convert the plain text line breaks to html line breaks, try this:
$fh = fopen("filename.txt", 'r');
$pageText = fread($fh, 25000);
echo nl2br($pageText);
Note the nl2br function wrapping the text.
One line of code:
echo nl2br( file_get_contents('file.txt') );
If you just want to show the output of the file within the HTML code formatted the same way it is in the text file you can wrap your echo statement with a pair of pre tags:
echo "<pre>" . $pageText . "</pre>;
Some of the other answers look promising depending on what you are trying todo.
For simple reads like this, I'd do something like this:
$fileContent = file_get_contents("filename.txt");
echo str_replace("\n","<br>",$fileContent);
This will take care of carriage return and output the text. Unless I'm writing to a file, I don't use fopen and related functions.
Hope this helps.
Before the echo, be sure to include
header('Content-Type: text/plain');
Are you outputting to HTML or plain text? If HTML try adding a <br> at the end of each line. e.g.
while (!feof($handle)) {
$buffer = fgets($handle, 4096); // Read a line.
echo "$buffer<br/>";
}
Trying to get line breaks to work reading a .txt file on Apache2 and PHP 5.3.3 with MacOSX 10.6.6 and Camino, the echo nl2br( $text); didn't work right until I printed the file size first too.
BTW it doesn't seem to matter if the .txt file has Linux/MacOSX LF or Windows CRLF line breaks or the text encoding is UTF-8 or Windows Latin1, Camino gets it out OK.
<?php
$filename = "/Users/Shared/Copies/refrain.txt";
$file_ptr = fopen ( $filename, "r" );
$file_size = filesize ( $filename );
$text = fread ( $file_ptr, $file_size );
fclose ( $file_ptr );
echo ( "File size : $file_size bytes<br> <br>" );
echo nl2br ( $text );
?>
You need to wrap your PHP code into <?php <YOU CODE HERE >?>, and save it as .php or .php5 (depends on your apache set up).
Say you have an index.php file hosted by the web server. You want to insert some multi-line text file contents into it. That's how you do it:
<body>
<div>Some multi-line message below:</div>
<div><?= nl2br(file_get_contents('message.txt.asc')); ?></div>
</body>
This <?= ... ?> part is just a shorthand, which instructs the web server, that it needs to be treated as a PHP echo argument.