how to handling non English chars with php - php

I have code in php that create file with name that user input like below
html
<form method="post">
<input type="text" name="file">
<input type="submit">
</form>
php
$file = $_POST['file'].'.php';
$f = fopen($file, 'w');
fclose($f);
the problem appear when user use non-english chars
example user input = اللغة العربيه
resault = ظ…ط±ط§ظ‡ظ‚ظˆ-ط§ظ„طھط§ظٹطھظ†ط.php
but it should be = اللغة العربيه.php

Trying to create files with non-english filenames can be quite hard.
Easiest solution is to not use such filenames at all, but encode all filenames e.g. with urlencode:
$filename = $_POST['file'].'.php';
$encoded_filename = urlencode($filename);
$f = fopen($encoded_filename, 'w');
fclose($f);
This will not affect English characters and will allow creating filenames using any language.
Note that each filesystem will have some limits on how long filesnames can be, so if $encoded_filename becomes too long this will not work.

Related

Save an image with $_POST['name_surname'] in PHP (from input)

I have a Signature Pad source code, this system save the signatures in one folder (with .png extension), but work only via md5.
<?php
$result = array();
$imagedata = base64_decode($_POST['img_data']);
$filename = md5(date("dmYhisA"));
//Location to where you want to created sign image
$file_name = './doc_signs/'.$filename.'.png';
file_put_contents($file_name,$imagedata);
$result['status'] = 1;
$result['file_name'] = $file_name;
echo json_encode($result);
?>
In the homepage I have the signature pad, and one "input" in html with name "nome_cognome_cliente"
<input name="nome_cognome_cliente" type="text" required="true" placeholder="Nome e Cognome"><br><br>
I would like save the signatures files with the name that user write in it.
I tested to write this in $filename variable. But doesn't work... where am i wrong? Thanks for helping.
$filename = $_POST['nome_cognome_cliente'];
Also, I would like save this signatures (images) in one Database with the date of entry (DD/MM/YYYY).

php file write arrays variables html not working

I am trying to make a website where you input a value to order food. In php i am trying to make it create a txt file that i can view. I have gotten it to make the file, but instead of a number, it simply displays 'Fries: Array' and the 'Array' should be a number. My php and HTML code is as follows...
HTML:
<input type="number" name="Fries" min="0" max="69"><br>
PHP:
<?php
$path = "Fries.txt";
$fh = fopen("Fries.txt", "w") or die("Unable to open file!");
$fries = array(['Fries']);
$string = 'Fries: '. strval($fries[0]);
fwrite($fh, $string);
fclose($fh);
?>`
If anyone can tell me how to get php to read HTML form data, that wiuld be great
Assuming that you're aware of all of the potential pitfalls of taking user input and writing it to a file without any type of validation: square brackets in PHP are a shortcut for defining a new array. So what you've written is equivalent to:
$fries = array(array('Fries'));
Also, you're assigning your new array the string value "fries," when you say you're trying to get this from your user input. Try the following:
...
$fries = 'Fries: ' . $_REQUEST['Fries'];
fwrite($fh, $string);
...
No need to use strval() - value is already a string.
And as far as validation, you may want to add the following before you assign your $fries variable:
if (is_numeric($_REQUEST['Fries'] && $_REQUEST['Fries'] >= 0 && $_REQUEST['Fries'] <= 69)
HTML:
<form method="post">
<input type="number" name="fries" min="0" max="69"><br>
<input type="submit" name="submit">
</form>
PHP:
<?php
$path = "Fries.txt";
$fh = fopen($path, "w") or die("Unable to open file!");
$string = 'Fries: '. filter_input(INPUT_POST,'fries');
fwrite($fh, $string);
fclose($fh);
?>

Google Cloud Storage uploaded unreadable filesnames (php)

After some problems i could finally upload files with google app engine to my bucket, but now the name of the uploaded file is unreadable, like a temp name, encrypted or something, like this:
L2FwcGhvc3RpbmdfcHJvZC9ibG9icy9BRW5CMlVvQWFjdkRYbWhtY1dPRGc2ZjlkVzRUU0lOV0FFMThWZnAxbUl1MzFVUndLSWdYVTBvdHhyYXl4UWdNOElXWklvX2hkQjdfaHYxbWNvc0dlSEtSQ184enJCU3M4QS5PTW5KWVBiTWdWZTJGdmQ4
How can i give the name that i want to an uploaded file???
I'm using the same code as the one given in the google developers documentation, like this:
require_once 'google/appengine/api/cloud_storage/CloudStorageTools.php';
use google\appengine\api\cloud_storage\CloudStorageTools;
$options = [ 'gs_bucket_name' => 'my_bucket' ];
$upload_url = CloudStorageTools::createUploadUrl('/upload_handler.php', $options);
<form action="<?php echo $upload_url?>" enctype="multipart/form-data" method="post">
Files to upload: <br>
<input type="file" name="uploaded_files" size="40">
<input type="submit" value="Send">
</form>
Does anybody know if Amazon's S3 is easier and more standard friendly? Also if it's posible to comunicate with GAP, I think i read that it is posible, but now i'm not sure about anything, too late and my brain is burnt :(
Thanks in advance!!
I made it work, it was easy, i just missunderstood something...
It must be done in upload_handler.php, is obvious but...xD. And as Mars says with move_uploaded_file, or with rename. Something like this (maybe is usefull for someone):
$gs_tmpName = $_FILES["myfile"]['tmp_name'];
$ext = strrchr($gs_name, ".");
$desired_name = "<desired_name>$ext";
$desired_name = mb_convert_encoding($desired_name, "UTF-8", "AUTO");
$desired_name = urlencode($desired_name);
$options = array('gs'=>array('acl'=>'public-read','Content-Type' => $_FILES['myfile']['type']));
$ctx = stream_context_create($options);
rename($gs_tmpName, "gs://<bucket_name>/".$desired_name, $ctx);
$publicUrl = CloudStorageTools::getPublicUrl('gs://<bucket_name>/'.$desired_name , true);

php random image file name

Okay im using a snippet I found on google to take a users uploaded image and put it in my directory under Content
But Im worried about duplicates so I was going have it upload the image as a Random number
well here is my code you can probably understand what im going for through it anyways
<label for="file">Profile Pic:</label> <input type="file" name="ProfilePic" id="ProfilePic" /><br />
<input type="submit" name="submit" value="Submit" />
$ProfilePicName = $_FILES["ProfilePic"]["name"];
$ProfilePicType = $_FILES["ProfilePic"]["type"];
$ProfilePicSize = $_FILES["ProfilePic"]["size"];
$ProfilePicTemp = $_FILES["ProfilePic"]["tmp_name"];
$ProfilePicError = $_FILES["ProfilePic"]["error"];
$RandomAccountNumber = mt_rand(1, 99999);
echo $RandomAccountNumber;
move_uploaded_file($ProfilePicTemp, "Content/".$RandomAccountNumber.$ProfilePicType);
And then basicly after all this Im going try to get it to put that random number in my database
Someone gave me a new snippet that looks like it will do what I want but now the file isnt making it all the way to my directory
$RandomAccountNumber = uniqid();
echo $RandomAccountNumber;
move_uploaded_file($ProfilePicName,"Content/".$RandomAccountNumber);
try using the php uniqid method to generate the unique id you need
http://php.net/manual/en/function.uniqid.php
$RandomAccountNumber = uniqid();
move_uploaded_file($ProfilePicTemp, "Content/" . $RandomAccountNumber);
When I upload images, I usually save it as the sha1() of the image's contents (sha1_file()). That way, you get two birds with one stone: You'll never (if you do, go fill out the closest lottery) get duplicate file names, AND, you'll prevent duplicate images (because duplicate images would have the same checksum).
Then, you have a database to sort out which image is which, and correctly display them to the user.
This is what I use when uploading pictures: a combination of session_id(), time() and a random string:
$rand = genRandomString();
$final_filename = $rand."_".session_id()."_".time();
function genRandomString()
{
$length = 5;
$characters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWZYZ";
$real_string_length = strlen($characters) ;
$string="id";
for ($p = 0; $p < $length; $p++)
{
$string .= $characters[mt_rand(0, $real_string_length-1)];
}
return strtolower($string);
}
I hope this help.
random != unique
No matter what method you use to generate a 'random' file name you're probably going to want to do this to avoid collisions.
$path = '/path/to/directory/';
do {
$filename = some_function();
} while( file_exists($path.$filename) );
It's not super-necessary, but if you're just looking for peace of mind in case of a one-in-a-million filename collision then those couple extra lines will do the trick.
One of my favorite Coding Horror articles addresses why this approach is dumber than it looks, and you should use something like uniqid instead of mt_rand(1, 99999);...

PHP best way to output certain data to text?

Ok, so I have a form that takes a username and a code. This is then passed to php for processing. I am not super php saavy, so I want to be able to take a specific portion of the out put and write it to a text file, this form would be used over and over, and I want the text to be appended to the file. As you can see from the output I'm looking to capture, it's basically writing to some code that will be used for usernames in a css. So here is what I have...
The HTML Form
<html><body>
<h4>Codes Form</h4>
<form action="codes.php" method="post">
Username: <input name="Username" type="text" />
Usercode: <input name="Usercode" type="text" />
<input type="submit" value="Post It!" />
</form>
</body></html>
The PHP
--><html><body>
<?php
$Usercode = $_POST['Usercode'];
$Username = $_POST['Username'];
echo "You have recorded the following in our system ". $Username . " " . $Usercode . ".<br />";
echo "Thanks for contributing!";
echo .author[href$="/$Username"]:after {
echo content: "($Usercode)"
echo }
?>
</body></html>
All that I would like to be written to the text file would be this portion..
--> .author[href$="/$Username"]:after {
content: "($Usercode)"
}
Basically, the text file would have line after line of that exact same code, but with different usernames and usercodes. Hopefully, the variable $Usercode and $Username can also be captured and written into the output in the manner that I have it written. I'm just baffled by output buffering in php and clean and flush etc, and fwrite doesn't seem to be able to write without wiping a file clean each time it writes to it. I may be wrong of course. Anyone care to help?
Try this:
<?php
$output = "--> .author[href=$Username]:after { \n"
."content: ($Usercode)\n"
."}";
$fp = fopen($file, 'a');
fwrite($fp, $output);
fwrite($fp, "\n");
fclose($fp);
?>
The flag a will open already a text file and place the pointer to the end of file, so this will not overwrite your already file, more information in fopen.
You can use the function file_put_contents($file, $data, FILE_APPEND); where $file is the path of the file you are writing to, data is the whatever value you are writing to the file. This assumes you are using php5. If not, you will have to create a handle with fopen, write to the file with fwrite and end with fclose to close the file pointed to in your fopen handle.

Categories