Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I have a problem I use an internal server when I pass a value through the URL and type a valid value showing me a message that he did not scroll see my code:
// pass value from this URL:
http://localhost/test/get.php?name=aa
<?php
// include Marei DB Class
include 'DB.php';
// get content input and create json object to parse it
$data = file_get_contents("php://input");
$obj = json_decode($data);
// create db instance to use marei db queris
$db = DB::getInstance();
// set type of header response to application/json for respone
header('Content-Type: application/json');
if(!empty($_GET["name"])){
print "{\"status\":0,\"message\":\"Username is Non !\"}" ;
}else{
print "{\"status\":0,\"message\":\"Username is Don !\"}" ;
}
?>
// print these lines :
{"status":0,"message":"Username is Non !"}
Change if(!empty($_GET["name"])){
to if(empty($_GET["name"])){
You did the mistake to use ! operator.
PHP is understanding it as a not
And you're asking if the $_GET variable is NOT empty the result is true of course.
Please check http://php.net/manual/en/language.operators.php for more informations.
Could you clarify the method in which a file is being uploaded to your server? Form input?
Assuming that a file is being uploaded...I can see 2 maybe 3 issues, all of which are not mutually exclusive, so it could be be all three issues working together to foil your coding plans...
ONE Use $_FILES , not input
$name = $_FILES['file']['name']; <--- name of the file from its source
$path - $_FILES['file']['tmp_name']; <--- path to the uploaded file
you have to move the uploaded file from your uploads folder... to its new home.
TWO Request method should be POST not GET... Especially the request is created by a form.
THREE - check your php.ini file to make sure file uploads are enabled.
empty is enough. Also you can use
if (!$_GET["name"]) {
print json_encode(['status' => 0, 'message' => 'Username is Non !']);
}
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
"Send a message as a POST request to a web service. The address must
start with “http://”, and may optionally include the port number
(default is 80) and the path to a specific web service. The
notification message fills the body of the content part of the POSTed
message, with no key=value form-style formatting – you just read the
input stream directly."
The above is extracted from the Alien UHF RFID F800 manual. The mentioned request is used to send the RFID tags that are scanned by the reader to a web service. The domain name is myrfidtest.com and the path is /insertdb.php. Now the insertdb.php is set up to accept two parameters, for example, id and RFID tag number. So the complete URL is http://myrfidtest.com/insertdb.php?id=21&rfid=2eda1. This data then gets successfully inserted into my database.
Hence I understand how to insert data into the cloud-hosted database using the above URL. However, I do not understand the extract, and what is meant by "you just read the input stream directly"?
In addition, how do I change the insert.php script to accept the tags from the reader?
My insert.php scritp:
<?php
class data_new
{
public $conn='';
function __construct($id,$rfid)
{
$this->storeInDB($id,$rfid);
}
function storeInDB($id,$rfid)
{
$conn = new mysqli('localhost','user','password','db');
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$sql = "insert into cloud set id='".$id."', rfid='".$rfid."'";
if ($conn->query($sql) === TRUE)
{
echo "New record created successfully";
}
else
{
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
}
if($_GET['id'] != '' and $_GET['rfid'] != '')
{
$data_new = new data_new($_GET['id'],$_GET['rfid']);
}
?>
Normally when you post form data in a HTTP request, you (or your browser) puts the posted data into the body of the HTTP request, and formats it rather like a querystring e.g. field1=value1&field2=value2, so that the server receiving the request can tell the fields apart and know which value belongs to which field. I think the article is saying that in this particular request, the entire body of the request is simply a single field containing the notification data, without any name=value style formatting - because there's only one parameter in the body.
In PHP, posted data normally appears in the $_POST array, with one entry in the array per parameter in the data (so you'd end up with $_POST["field1"], $_POST["field2"], etc. But you can also read the raw input data using:
$postdata = file_get_contents("php://input");
instead. This would be useful in the case mentioned above where the data is just one big stream of text inside the request body, rather than being formatted.
P.S. I can't answer the second part of your question " how do I change the insert.php" because I don't know what script you're referring to, what it does or looks like, or what tags you're talking about. I suggest asking a second, separate question about that as it sounds like a different issue, and giving a clear example of what you mean, within the question text.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
Hello everyone again here,
I want to create a PHP script for my software which generates and returns the specific code using one $_GET request with a string and using another verificates this code, then forbid running same string.
Something what should work like this:
1st user's software runs "http://example.com/codes.php?create=" and string like "abc".
and script returns code based on "abc", e.g. "4aO45k", "12sdF4" etc.
2nd user's software runs "http://example.com/codes.php?verify=" and this code.
If this code exists, return true and remove it FOREVER, meaning this code will never be generated again. If this code doesn't exist, return false.
If 1st user's software will run "http://example.com/codes.php?create=abc" another code will be generated.
In simple words:
if $_GET is create, then
generate random alphanumeric string, save it and return
if $_GET is verify, then
check if this string exists, if so, then
return true, remove from saved
otherwise
return false
Possible without databases, SQL, mySQL, FireBird...?
How do I make it using .ini files as storage?
Thanks.
It's possible with files. You can do something like the simple solution below:
A couple of notes:
I don't know what you intend by based on exactly, so this just uses the input as a prefix
This stores every code in a file indefinitely; if used a lot this file will grow very large and checking for the existence of codes, and ensuring new codes are unique can grow very slow
The same code can be verified multiple times, but will never be recreated. Marking them as used after verification is of course possible as well
As a general rule don't go creating global functions and shoving everything in one file like this. It's really just proof of concept of what was asked
<?php
$file = fopen('codes', 'a');
if (!empty($_GET['create'])) {
$seed = $_GET['create'];
do {
$code = uniqid($seed);
} while (codeExists($code));
fwrite($file, $code . "\n");
echo $code;
}
else if (!empty($_GET['verify'])) {
echo codeExists($_GET['verify']) ? 'found' : 'not found';
}
function codeExists($verification) {
$file = fopen('codes', 'r');
$found = false;
while ($code = trim(fgets($file))) {
if ($code == $verification) {
$found = true;
break;
}
}
return $found;
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I'm trying to get a variable which I declared in one php file to another without including the whole first php
while($row = mysql_fetch_assoc($sql)) {
// Urlaubstage ausgeben
if($row['frtutage'] < 1) {
$verbraucht = "0";
} else {
$verbraucht = $row['frtutage'];
}
$resturlaub = $row['miturlaubstage'] + $row['mitutagevorjahr'] - $verbraucht;
$urlaubgesamt = $row['miturlaubstage'] + $row['mitutagevorjahr'];
I need the variable $resturlaub in the second PHP without calculating the variable again.
How do I do this? Or is it even possible?
Thanks.
edit: the first php file is about calculating vacation days and how much I have remaind after taking a few vacation days, in the second file I need the calculation of the remaining days then, so I just want to use the variable again and not calculate it again
You can try somehting like
$var = 'random_query';
$page= 'yourpage.com/?my_var='.serialize($var);
header("Location: $page");
exit;
and in your page you can get the value by
if (isset($_GET['my_var']))
{
$my_var = unserialize($_GET['my_var']);
}
But it would depend on the size of that variable that you need to pass, and what is the purpose of the scripts.
If you don't want to include the whole first php file but only a variable then you should create a third file (called: variables.php or config.php for example).
Then include variables.php in both file so the variable will be shared among your scripts
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am doing
index.php?letter=1&show=cat.jpg
File I do not include, but use it only as <img src="$_GET['show']">
Is it safe?
Simple code to validate the input.
// Check File Param provided
$filename = (isset($_GET['show']) ? $_GET['show'] : '');
if (strlen($filename) == 0) {
die('File Not Provided');
}
// remove leading '/' or double slashes (will also hack out http:// injections)
$filename = trim($filename);
$filename = str_replace('//', '/', $filename);
while (strlen($filename) > 0 && strcmp(substr($filename,0,1), '/') == 0) {
$filename = substr($filename, 1);
}
// Check filename exists
if (file_exists('./' . $filename)) { // Note the "./", also will to prevent cross site injections; if using a sub-directory, add in here
die ('file does not exist');
}
// Check file actually is an image
if (!#getImageSize('./' . $filename)) {
die ('file is not an image');
}
// Should be safe at this point.
You could also preg_match for a pattern if you know the pattern of filename e.g. always expecting a .png).
You probably also want to handle errors differently, but this should give you an idea.
Yes, Its safe to use. But you want to take care of XSS attacks.
Actually now you are showing the content attached to your parameter show inside your html page. Think a scenario if a user edited the 'cat.jpg' and inserted some script content into it.
See this simple example by Arjun Sreedharan.
XSS attack to your url would be as shown below
index.php?letter=1&show=Path/To/some/other/Image"></img><h1>XSS Attack</h1><div> Showing False data in your website</div><img src="Some/Other/Image.jpg
The Html rendered in your page would be
<img src="Path/To/some/other/Image"></img>
<h1>XSS Attack</h1>
<div> Showing False data in your website</div>
<img src="Some/Other/Image.jpg">
The solution is to encode html. HtmlEntities in PHP.
Yes, it is safe but the mechanism to deliver/show that file should be proper to handle only authorized requests.
If you want then you can do it by POST, but some time its possessive when you refresh the page and browser asking to confirm that previously posted data sends back to server again.
Above are my personal view.
I'd say get something like image_id from URL and then retrieve the relevant data from database and output your own data (e.g. file name) in the markup.
Even if you consider different ways of validating or filtering the users' input, you might still be open to some attacks or maybe bugs. To avoid that, again, I'd recommend to get a key from user and then based on that key output the data. Validating that key is much easier and also you are not gonna to output it again -- you're using that only in the back-end so it won't be a security hole for XSS attacks for example.
<img src="/images/<?php echo basename(preg_replace('/[^a-z0-9\.-]/i','',$_GET['show'])); ?>">
This will this will only return name of a file even if path or url is passed.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
While($enreg=mysql_fetch_array($res))
{
$link_d.="<font color=\"red\">clic here to download</font></td>"
}
i want to use the href so it leads to download link, also to send the id to a php file so i can get how many times the files have been downloaded !
How can we use href to multiple links !
You can't. A link can only point to one resource.
Instead, what you should do is have your PHP script redirect to the file. The link points at your PHP script with the counter, and then set a Location: header (which automatically sets a 302 status code for redirection) with the value being the URL you want to redirect to.
Also, you should really use htmlspecialchars() around any variable data you use in an HTML context, to ensure you are generating valid HTML.
Ideally you would have some checks to see if it's a human downloading (Web crawlers may trigger it - we will put no-follow in the link which will help though). You could also use a database but that gets more complicated. My preferred way would be to use Google Analytics Events. But here is a simple PHP script that might fulfill your needs without the complexity of the other solutions.
First modify your links to have a tracker script and to urlencode
$link_d.= '<a style="color:red" href="tracker.php?url='.urlencode($enreg[link]).'" target="_blank">click here to download</a>';
}
Then create a script that will record downloads (tracker.php)
<?php
// keep stats in a file - you can change the path to have it be below server root
// or just use a secret name - must be writeable by server
$statsfile = 'stats.txt';
// only do something if there is a url
if(isset($_GET['url'])) {
//decode it
$url = urldecode($_GET['url']);
// Do whatever check you want here to see if it's a valud link - you can add a regex for a URL for example
if(strpos($url, 'http') != -1) {
// load current data into an array
$lines = file($statsfile);
// parse array into something useable by php
$stats = array();
foreach($lines as $line) {
$bits = explode('|', $line);
$stats[(string)$bits[0]] = (int)$bits[1];
}
// see if there is an entry already
if(!isset($stats[$url])) {
// no so let's add it with a count of 1
$stats[$url] = 1;
} else {
// yes let's increment
$stats[$url]++;
}
// get a blank string to write to file
$data = null;
// get our array into some human readabke format
foreach($stats as $url => $count) {
$data .= $url.'|'.$count."\n";
}
// and write to file
file_put_contents($statsfile, $data);
}
// now redirect to file
header('Location: ' . $url);
}
You can't.
Anchor are meant to lead to one ressource.
What you want to do is tipically addressed by using an intermediate script that count the hit and redirect to the ressource.
eg.
Click here to download
redirect.php
// Increment for example, a database :
// UPDATE downloads SET hits = (hits + 1) WHERE id=42
// Get the URI
// SELECT uri FROM downloads WHERE id=42
// Redirect to the URI
// (You may also need to set Content-type header for file downloads)
header( "Location: $uri" );
You may optimize this by passing the uri as a second parameter so that you won't need to fetch it at redirect time.
Click here to download
Another way of collecting this kind of statistics is to use some javascript tools provided by your statistics provider, like Google Analytics or Piwik, adding a listener to the click event.
It is less invasive for your base code but won't let you easily reuse collected data in your site (for example if you want to show a "top download" list).
Create a file with download script for example download.php and route all your downloads through it. Update your counter in this page and use appropriate headers for download.
eg:
url may be download.php?id=1&file=yourfile
in download.php
//get id and file
//database operation to update your count
//headers for download