get specific parts of my file name as links - javascript

this is how i want my file name looks like : 55478_john_toyota_red.pdf
i have to file in a table of those informations
and this is how i get my file name for the moment :
echo ''.$file.'';
i want to know how can i get the number in an echo and name in another one ...as links to the same file.
my files will change all the time.
should i change the name of my file? can it be done like that?

it worked with this :
$data = "$file";
list($numero,$nom,$marque,$couleur) = explode("_", $data);
echo ''.$numero.'';//in the same way i can get anything i want from the title
echo ''.$nom.'';

I would use explode function .. and then implode function to rebuild the file name like this:
$tempArray = explode('_', $file);
array_shift($tempArray);
$newFileName = implode(' ', $tempArray);
echo ''.$newFileName.'';
Try this version .. it should work now

Related

generate document and then zip with php

I have an issue.
I have an index.php with several checkboxes.
Every checkbox represents a piece of code.
I am trying to create some generating tool.
For example: if I select four checkboxes, I want that four specific parts of code to generate in one php file, then zip it and download on my computer.
I know I can do it something like this:
$files = array('list.php', 'one-image.php', 'gallery.php', 'pdf.php');
$zipname = 'file.zip';
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);
foreach ($files as $file) {
$zip->addFile($file);
}
$zip->close();
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipname);
header('Content-Length: ' . filesize($zipname));
readfile($zipname);
but, at the moment i am pretty lost.
Thanks in advance.
Copied from comments:
Read the files yourself using file_get_contents, concatenate using +, write to zip with ZipArchive::addFromString.

How to edit or replace xml string using php?

I had to change my question to simple question
For example: my XML file name is: ABC.xml
inside of this xml file is:
<li class="thumb"><a class="Alibaba" href="google.com"></a></li>
So, here is my question:
How to use PHP to search string inside of ABC.xml and find Alibaba name and replace it to AlibabaColor name and save it to ABC.xml
Please guide me and give me an example for this. Thank you
You can do this using php str_replace among many other functions. Here is a couple examples ->
If the XML is in a string already you can do this
PHP:
<?php
$myXmlString = str_replace('Alibaba', 'AlibabaColor', $myXmlString);
?>
If you need to get the XML data from another file there are a few ways to to do it depending on if you need to save it, just replace it and display it, or really what you are doing. Some of this comes down to preference.
Just need to display it?
<?php
$xml = file_get_contents(/path/to/file); // or http://path.to/file.xml
$myXmlString = str_replace('Alibaba', 'AlibabaColor', $xml);
?>
Need to change the file itself?
<?php
$xml = file_get_contents(/path/to/file); // or http://path.to/file.xml
$myXmlString = str_replace('Alibaba', 'AlibabaColor', $xml);
file_put_contents(/path/to/file, $myXmlString);
?>
--
To answer the below comment, here is working code from my server ->
xml:
<li>hello</li>
php:
$file = '/home/username/public_html/xml.xml';
$xml = file_get_contents($file);
$text = str_replace('hello','world',$xml);
file_put_contents($file, $text);
xml.xml after:
<li>world</li>
Keep in mind to change 'username' to the right one, or use an FQDN if you are more comfortable doing so. Make sure that the file has permission to be written to by a script as well.

URL in database to Javascript with PHP

I've added a table in my mySQL database which has two variables: ID and a URL.
ID has the value 1
and
URL has http://www.examplesite.com
I want to get "www examplesite com" from the database into a PHP file.
The PHP file should then send this string to a javascript file which will then open that URL.
So far I've been using getJSON with little success.
I'm new to PHP and Java and would really appreciate some help!
I want something like this in my .js file
$.getJSON('getlink.php', {'link'}, function(e) {
alert('Result from PHP: ' + e.result);
});
window.open(linkVariable'_blank')
I would like linkVariable to be www examplesite com
The javascript is linked to another php file which has a clickable element for the window.open.
How can I get the getlink.php and the .js file to communicate with each other?
EDIT:
My getlink.php would look something like this without any echo. The connection to mySQL is already written.
function get_links($url_link) {
$sql = "SELECT `name` FROM `variables` WHERE ID=?";
$res = $this->db->query($sql, array($url_link))->row_array();
return $res['URL'];
it would be better if you posted what code is in getlink.php.
I'd suggest you proceed like this. In getlink.php query the database to return the correct row.
There is different ways to do that, depending on what framework or library (PDO,mysql_,) you are using.
Then return the result as json
In the same file, call the function you just defined.
It should look to something like this
<?php
function get_links($url_link) {
$sql = "SELECT `name` FROM `variables` WHERE ID=?";
$res = $this->db->query($sql, array($url_link))->row_array();
return $res;
}
$result = get_links(1); //whatever the id is
return json_encode($result);
?>
In your javascrit you can do something like this
$.get(
"getlink.php",
function(data) {
alert(data.URL);
}
);
//My Idea
Read URL from the database and give it to the variable $link code below
$result=mysqli_query($dbconnection, "SELECT * FROM url"); //You can specify conditions
while($row=mysqli_fetch_array($result)){
$link=$row["URL"]; //We have our url from database here
}
//Link between JAVASCRIPT AND PHP
Put this code in a php to take $link and give it to getlink() function as a parameter
<script>
getlink("<?php echo $link?>"); //A java script function from your JS file to get url
</script>

PHP capture form data and image upload, save to server

I know that this should not be a difficult thing to accomplish in PHP however it is giving me the hardest time!
I am trying to do this:
1) Capture form string data AND an image upload in a single form
2) Upload both types of data to the server with a single non-ajax/traditional POST to a simple PHP script (process.php in this case)
3) Take the image the user uploaded, save it in as a text file in a directory named dynamically by the first letter of the first name and the entire last name concagnated together so for me the directory structure would be as follows: /home/uploads/nabrams/image.jpg, /home/uploads/nabrams/userdata.txt,
*The text file will contain the text strings from the client side form, the image from the input[type="file"], once again contained in the same form, sent to the server with 1 submission.
I am using a text file in order to provide the simplest case possible.
Here is the code I am working with currently:
<?php
$uploaddir = '/home/nicholasabrams/public_html' + '/newprofiledata/' + $lname + '/' + $_FILES['userfile']['name'];
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
echo "<p>";
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Upload failed";
}
echo "</p>";
echo '<pre>';
echo 'Here is some more debugging info:';
print_r($_POST);
print_r($_FILES);
print "</pre>";
However when attempting to upload an image of several formats and sizes (multiple attempts), I am stuck at an error-less blank window. To no surprise, the script did not upload or rename the image as desired.
Also - when trying to add the post data directly into the file name like so:
$uploaddir = '/home/nicholasabrams/public_html/' + $_POST['lname'] + '/' + $_FILES['userfile']['name']; $uploadfile = $uploaddir . basename($_FILES['userfile']['name']); if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile))...
I get filenames with 0pictureNameHere.jpg instead of NAbrams.jpg or if using post data to set the directory, I will never get the image or data in this way.
Side note:
I am a Javascript and jQuery ( <- mainly) developer, would it be worth it for me to attempt doing this with express or some other node module? I am not experienced with node although I have been "using it" for the last few months.
Thanks for the help!

Is json_encode extremely picky?

It appears that json_encode is being VERY picky about what other stuff can be inside my PHP file. Which is fine, because I just do what I normally would do in file A (with json_encode) in it's own file.
I just thought I would ask because I am storing a variable in the $_SESSION instead of updating my database with the variable because json_encode doesn't seem to want to work when I have all of the code in its file.
For instance, this code doesn't work:
<?php
session_start();
include 'dbcon.php';
$sessionID = uniqid();
echo json_encode($sessionID);
if(isSet($_POST['clearSession']) == '1')
{
$query = "UPDATE currentID SET id=('0')";
$execute = $mysqli->query($query) or die($mysqli->error.__LINE__);
} else {
$query = "UPDATE currentID SET id=('$sessionID')";
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);
}
?>
When going to the file in my browser, I do in fact get the json_encode results, however when my Javascript calls it it doesn't seem to correctly import it.
So, for now I simply have two PHP files:
<?php
session_start();
$sessionID = uniqid();
$_SESSION["sessionID"] = $sessionID;
echo json_encode($sessionID);
?>
Which echo's the same thing as in the first file, but this time my JavaScript correctly imports it.
and
<?php
session_start();
include 'dbcon.php';
if(isSet($_POST['clearSession']) == '1')
{
$query = "UPDATE currentID SET id=('0')";
$execute = $mysqli->query($query) or die($mysqli->error.__LINE__);
} else {
$sessionID = $_SESSION["sessionID"];
$query = "UPDATE currentID SET id=('$sessionID')";
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);
}
?>
I guess my question is, why does this happen? It seems kind of silly that I have to store the uniqid in a SESSION so that my other PHP file can add it to the database. Whereas if I simply had it in one file, then I could just update the database when I generate a new uniqid and avoid having to use $_SESSION in the first place.
You have this:
$sessionID = uniqid();
echo json_encode($sessionID); // "53d4c17abfe87"
Since uniqid() produces a plain string, your output is not valid JSON as per the format specification. You'll need something like this instead:
$sessionID = uniqid();
echo json_encode(array($sessionID)); // ["53d4c17abfe87"]
Why does json_encode() generate invalid JSON in the first place? Because some times it's useful to generate partial JSON. For instance, it's a handy trick to inject values into generated JavaScript code:
var foo = <?=json_encode($sessionID)?>;
It's also documented:
PHP implements a superset of JSON - it will also encode and decode
scalar types and NULL. The JSON standard only supports these values
when they are nested inside an array or an object.
So to answer the question title:
Is json_encode extremely picky?
On the contrary, it's fairly relaxed!
You don't need to store it in a session necessarily, it's the fact that $_SESSION is an array.
So, what you would want would be something like this:
echo json_encode(array('sessionID' => $sessionID));
And then when you parse the JSON with JavaScript you can access it like this:
obj = JSON.parse(jsonObj);
alert(obj.sessionID);
Obviously, jsonObj is the JSON passed from the server.
Hope this helps!

Categories

Resources