Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
I have the following function to upload a file to a database table field.
protected function _upload_file() {
...
}
Once uploaded, uploading a new file overwrites the original uploaded file.
What I want is to establish a new upload without overwriting the file. The way I see it, I would have to create a new function like;
function if_upload_file() {
...
}
If that function is successful, then repeat function.
Any idea how I could accomplish that?
Let the function return true if the file was uploaded successfully and as long as it stays true, you loop again and again. Like that
$con = true;
while($con) {
if($con) {
$con = your_function()
}
}
//your function
function your_function() {
//do your stuff here
if($file_upload_successful) {
return true;
} else {
return false;
}
}
At least i think this might work ... not even sure. Well, no risk no fun.
An alternative to Y U NO WORK's answer is to use the function recursively.
E.g. if you had an array of files to upload..
function foo($array_of_files) {
if(is_array($array_of_files) && count($array_of_files) > 0) {
$file = array_shift($array_of_files);
// ... Handle upload code.
if(count($array_of_files) > 0) {
foo($array_of_files);
}
}
}
However, this does build stack layers, and could be quite troublesome for debugging.
Using a while loop would be a sensible strategy so long as you handle the loop conditions correctly.
Related
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 is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
Before you close this question, I know that this is a subjective matter. What one person thinks is the best way, will not be the opinion of another. However, I am open to try anything that I need necessary and as the writer of this question should be the judge of the answers.
I am developing a rather complicated website which relies on several queries to the database to pull certain information. I loop through datasets and begin constructing HTML Mark-up.
This is just a general question, so there is no need to include the specifics. In general the format of my PHP for the site (excuding most of the structural HTML) is as follows:
$query = $mysqli->query("SELECT SOMETHING");
while ($row = $query->fetch_assoc()) {
$class = "";
// do some more queries based on these rows
if ($error) {
$class = "error";
} else { // note, I realize
$class = "success";
}
echo "<div class='something'>"
if ($conditionTrue) {
echo "<div class='$class'>More information..</div>";
}
echo "</div>";
}
The following example looks fine, but this quickly becomes messy as more markup is added. I am not looking for a templating engine, and not necessarily a library, but just general practices that other PHP developers do to keep code like this more manageable. Please also note, that separating the data into Logic and Layout is an option but I am seeking for more.
Sure, writing HTML inside PHP will get other PHP and HTML dev's heated everytime. Personally, I don't think there is any problem with it. This is how I would do it:
$query = $mysqli->query("SELECT SOMETHING");
while ($row = $query->fetch_assoc()) {
$class = "";
// do some more queries based on these rows
if ($error) {
$class = "error";
} else { // note, I realize
$class = "success";
}
?>
<div class='something'>
<?php
if ($conditionTrue) { ?>
<div class='$class'>More information..</div>
<?php } ?>
</div>
<?php } ?>
This is the basic idea, indenting in SO is a pain. You can close the php tag, write HTML and open it again to close your statement.
EDIT! I should add that if you try to put headers in PHP AFTER you write some HTML, it will give you an error. Specifically, headers already sent. If you want to redirect the page using headers, it needs to be BEFORE ANY HTML!
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 7 years ago.
Improve this question
I need help on how to make an API for PHP. I was trying to make one web server communicate with another webserver through PHP.
I also want it to update MySQL code. I was using $_GET but it was less secure. Here is my code, can you please take a look at it?
<?php
/*
example: website-url-here.com/?command=insert-command-here&password=testing
*/
$command = $_GET["command"];
$password = $_GET["password"];
if ($password == "testing") {
//Was not a good idea, less secure.
//echo eval($command);
//More secure
if ($command == "create-user")
{
//create user command here
}
else if ($command == "delete-user")
{
//delete user command here
}
else
{
die("Command is incorrect");
}
}
echo "Success";
?>
This question is way too open ended to answer in a StackOverflow answer. Try reading up a little on REST, and a lot on PDO, especially in the context of sanitizing user input.
Think about what would happen if somebody called your api with [url]?command=rm -rf .&password=testing
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 8 years ago.
Improve this question
i have the method:
public function getAppLink($app_path)
{
if( ! $this->isAppExists($app_path)) { return false; }
$content = $this->getContent();
// make sure that the link is available
$validate_link = \Validator::make(
['app_link' => $content->apps->$app_path->link],
['app_link' => 'active_url']
);
if($validate_link->fails())
{
$this->setAppStatus($app_path, 'stopped');
$this->setAppLink($app_path, 'invalid_link');
return '';
}
else {
$this->setAppStatus($app_path, 'started');
return $content->apps->$app_path->link;
}
}
i need to validate that localhost:xxxx link is active and can be accessed via the browser, before returning it.
somehow the laravel way of testing link is not working, am i doing this wrong, or i need to use a different approach?
note: xxxx is the port number
The Laravel active_url Validator is just a wrapper around the PHP checkdnsrr function. The purpose of this function is solely to check for DNS records, not to actually check if the server is responding.
Because you are on localhost, there are no DNS records so this check would not work.
If you want to check that a link can be accessed by the browser, you have to do that in JavaScript on the browser. Otherwise, you could have a case where http://localhost:1234 is accessible from the server but is not accessible from the browser because of the firewall or because the webserver is only listening on 127.0.0.1 and not on all IP addresses. While this will obviously work properly as long as you are doing all of your development on your local computer, it may cause you problems in production (depending, of course, on exactly what it is that you need this information for).
If you actually want to check whether the site is up, just do a CURL GET (or HEAD) request to the URL.
An easy way to use CURL in Laravel is with this composer package. The full documentation is too long to put here, but you can find it here.
i solved this problem by using fsockopen:
// ==================================================== isLinkValid()
//
// $link : the link you want to validate, ex: localhost:1234
//
// return true | false
//
private function isLinkValid($link)
{
if(strpos($link, ":") === false)
{
return false;
}
$arr_link = explode(":", $link);
$host = $arr_link[0];
$port = $arr_link[1];
$sock_open = #fsockopen($host, $port);
if(is_resource($sock_open))
{
fclose($sock_open);
return true;
}
return false;
}
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
$inputarray=array("username", "password");
foreach($inputarray as $inputkey);
if(isset($_POST[$inputkey]) && !empty($_POST[$inputkey]))
{
$inputname=$inputkey;
$inputresult=$_POST[$inputkey];
$$inputname=$inputresult;
}
else
{
die("You have to fill both fields.");
}
$username isn't being defined, only $password. Anyone know what's wrong?
It's just a typo:
foreach($inputarray as $inputkey);
You included a semicolon at the end of that line, so the foreach statement runs, then ends, and then the if clause executes on the last value that the foreach statement left in $inputkey.
Try:
foreach($inputarray as $inputkey)
{
if(isset($_POST[$inputkey]) && !empty($_POST[$inputkey]))
{
$inputname=$inputkey;
$inputresult=$_POST[$inputkey];
$$inputname=$inputresult;
}
else
{
die("You have to fill both fields.");
}
}
Error is probably due to the ; at the end the foreach line. This will cause the foreach line to run leaving to completion, but not run any other statements as there is no enclosure that follows it. Once completed the value of $inputkey will be "password" which is why you are only getting data from "password"
Try:
$inputarray=array("username", "password");
foreach($inputarray as $inputkey) {
if(isset($_POST[$inputkey]) && !empty($_POST[$inputkey])) {
$inputname=$inputkey;
$inputresult=$_POST[$inputkey];
$$inputname=$inputresult;
} else {
die("You have to fill both fields.");
}
} //endforeach
Variable variables are a code smell that you're making things hard on yourself. Instead of doing that, at this stage, and for the specific purposes of a login page, I would make life as simple, readable, and uncomplicated as you can.
Just do this:
$username = #$_POST['username']; // Just about the only place where using # is ok.
$password = #$_POST['password'];
if(!trim($username) || !trim($password)){
die("You have to fill both fields.");
}
A login form is not a place to innovate or make your code complicated. For a little added abstraction, you could put that information into a simple login validation function so that you can modify the criteria down the line (e.g. username must be longer than 1 character, or whatever).
But from looking at your code, you're making a CLASSIC MISTAKE:
DO NOT ROLL YOUR OWN LOGIN SYSTEM THE FIRST TIME AROUND.
Reuse an expert's login code and learn from that. Write other things in custom php, but borrow someone else's time tested login code for database parameterization, error checking, and abstraction. Writing your own login system is playing with fire.
It looks like you're assigning the string name $inputkey to the value. Also you were creating dynamic variables that you might never have found in your code.
$inputarray=array("username", "password");
foreach($inputarray as $inputkey=>$inputvalue);
if(isset($_POST[$inputkey]) && !empty($_POST[$inputkey]))
{
$inputname=$inputkey;
$inputresult=$_POST[$inputkey];
$inputname=$inputresult;
}
else
{
die("You have to fill both fields.");
}