This document discusses PHP include files, file input/output functions in PHP, and exceptions in PHP. It provides examples of including files using include() and require(), reading and writing files using functions like file_get_contents() and file_put_contents(), and throwing and catching exceptions. It also covers splitting strings using explode(), reading directories with scandir() and glob(), and managing user sessions and cookies in PHP.
Teaching Your Machine To Find FraudstersIan Barber
The slides from my talk at PHP Tek 11.
When dealing with money online, fraud is an ongoing problem for both
consumers and sellers. Researchers have been developing statistical
and machine learning techniques to detect shady sellers on auction
sites, spot fraudulent payments on e-commerce systems and catch click
fraud on adverts. While there is no silver bullet, you will learn to
flag suspicious activity and help protect your site from scammers
using PHP and a little help from some other technologies.
Conférence données à l'Open World Forum, 05 octobre 2013.
Comment créer une base de données noSQL par paires clés-valeurs en moins d'une heure, en se basant sur le bibliothèques Nanomsg et LightningDB.
As presented at Confoo 2013.
More than some arcane NoSQL tool, Redis is a simple but powerful swiss army knife you can begin using today.
This talk introduces the audience to Redis and focuses on using it to cleanly solve common problems. Along the way, we'll see how Redis can be used as an alternative to several common PHP tools.
Using Mikko Koppanen's PHP ZMQ extension we will look at how you can easily distribute work to background processes, provide flexible service brokering for your next service oriented architecture, and manage caches efficiently and easily with just PHP and the ZeroMQ libraries. Whether the problem is asynchronous communication, message distribution, process management or just about anything, ZeroMQ can help you build an architecture that is more resilient, more scalable and more flexible, without introducing unnecessary overhead or requiring a heavyweight queue manager node.
Type hints were introduced with PHP 5. PHP 7 will add the ability to type hint on scalars and even to explicitly state what type will be returned from the function. This talk briefly goes over these added features to PHP 7.
Conheça um pouco mais sobre Perl 6, uma linguagem de programação moderna, poderosa e robusta que permitirá que você escreva código de forma ágil e eficiente.
A talk I gave at the June 2010 meeting of the London Ruby User Group. It's about the first bit of ruby I ever wrote, way back in 2003. A little bit of personal history, a little bit of ruby history, a whole lot of terrible code for you to learn from.
Slide utilisé lors du Meetup du 16 juin 2017 organisé par l'AFUP Montpellier
Présentation des PHP Standards Recommendations (PSR). Leurs buts et l'avantage de les utiliser
El avance de las nuevas tecnologías y el manejo masivo de la información que éstas posibilitan, al igual que el surgimiento de nuevos espacios de interacción social-virtual, han facilitado la transformación de la experiencia del mundo social y la reformulación del concepto de “otro”.
El segundo sexo: alcances, logros y fracasos sobre la condición de la mujer e...Universidad del Quindío
En el presente trabajo trataremos de explicar por qué la mujer es considerada socialmente como un ser de segunda clase y subordinada al hombre, obligada a adoptar roles predeterminados, y por qué tal concepción hoy prevalece en Latinoamérica, justificando la dominación y la violencia contra las mujeres.
Teaching Your Machine To Find FraudstersIan Barber
The slides from my talk at PHP Tek 11.
When dealing with money online, fraud is an ongoing problem for both
consumers and sellers. Researchers have been developing statistical
and machine learning techniques to detect shady sellers on auction
sites, spot fraudulent payments on e-commerce systems and catch click
fraud on adverts. While there is no silver bullet, you will learn to
flag suspicious activity and help protect your site from scammers
using PHP and a little help from some other technologies.
Conférence données à l'Open World Forum, 05 octobre 2013.
Comment créer une base de données noSQL par paires clés-valeurs en moins d'une heure, en se basant sur le bibliothèques Nanomsg et LightningDB.
As presented at Confoo 2013.
More than some arcane NoSQL tool, Redis is a simple but powerful swiss army knife you can begin using today.
This talk introduces the audience to Redis and focuses on using it to cleanly solve common problems. Along the way, we'll see how Redis can be used as an alternative to several common PHP tools.
Using Mikko Koppanen's PHP ZMQ extension we will look at how you can easily distribute work to background processes, provide flexible service brokering for your next service oriented architecture, and manage caches efficiently and easily with just PHP and the ZeroMQ libraries. Whether the problem is asynchronous communication, message distribution, process management or just about anything, ZeroMQ can help you build an architecture that is more resilient, more scalable and more flexible, without introducing unnecessary overhead or requiring a heavyweight queue manager node.
Type hints were introduced with PHP 5. PHP 7 will add the ability to type hint on scalars and even to explicitly state what type will be returned from the function. This talk briefly goes over these added features to PHP 7.
Conheça um pouco mais sobre Perl 6, uma linguagem de programação moderna, poderosa e robusta que permitirá que você escreva código de forma ágil e eficiente.
A talk I gave at the June 2010 meeting of the London Ruby User Group. It's about the first bit of ruby I ever wrote, way back in 2003. A little bit of personal history, a little bit of ruby history, a whole lot of terrible code for you to learn from.
Slide utilisé lors du Meetup du 16 juin 2017 organisé par l'AFUP Montpellier
Présentation des PHP Standards Recommendations (PSR). Leurs buts et l'avantage de les utiliser
El avance de las nuevas tecnologías y el manejo masivo de la información que éstas posibilitan, al igual que el surgimiento de nuevos espacios de interacción social-virtual, han facilitado la transformación de la experiencia del mundo social y la reformulación del concepto de “otro”.
El segundo sexo: alcances, logros y fracasos sobre la condición de la mujer e...Universidad del Quindío
En el presente trabajo trataremos de explicar por qué la mujer es considerada socialmente como un ser de segunda clase y subordinada al hombre, obligada a adoptar roles predeterminados, y por qué tal concepción hoy prevalece en Latinoamérica, justificando la dominación y la violencia contra las mujeres.
La nausea, novela escrita por Jean Paul Sartre en 1931, nos narra la historia de Antoine Roquentin, un hombre que encuentra el sentimiento del tedio al encontrarse con las cosas y con otras personas, una sensación desagradable que se genera al darse cuenta que todo lo que nos rodea, incluso nosotros mismos, somos nada.
Generalmente podemos entender el sentido de la existencia de dos maneras, la primera, que es la más común, la explicará Frankl como la forma de afrontar cada situación concreta y que siempre se refiere a factores externos al sujeto (realizar ciertas actividades, hacer felices a otros o servir a Dios). La segunda, por el contrario, se refiere a que es uno mismo quien inventa el sentido de su propia existencia, pero, como dirá Sartre, se trata de una búsqueda constante, y no de un sentido completo o definitivo. Trataremos, entonces, de concluir cuál será el modo más conveniente de comprender el sentido de la existencia, si debemos vivir la vida simplemente sin preguntar por un sentido o debemos buscarlo, aunque dicha búsqueda nunca tenga un fin.
Para Améry, el suicida es despojado de su libertad ya que se tilda como enfermo para afirmar que no es posible que cualquier ser humano consciente pueda elegir su propia muerte, sino porque le falta algo en su mente o le sobra. Es preciso entonces, que se inicie un movimiento por fuera del campo de la salud mental y especialmente en el ámbito de la filosofía, que busque el reconocimiento del suicidio como un derecho humano en el que prime la libertad de elección del sujeto, de lo contrario, la sociedad seguirá excluyendo a los suicidas diciendo que ellos sólo buscan renunciar a la comunión con los otros, con la sociedad.
En el presente trabajo se pretende hacer un análisis del fenómeno de la violencia y de cómo éste se ha legitimado en nuestros pueblos como el único camino de acceder a los
derechos individuales, planteando que solamente a través de un egoísmo exacerbado podremos alcanzar lo que queremos. Primero, haremos un análisis de la película "la purga" (2013), en la cual una sociedad enmarcada en los intereses personales justifica por una noche la violencia extrema con el fin de "purgar" el instinto violento del hombre; luego, acudiremos a Mandeville para explicar por qué, desde su pensamiento, solamente en una sociedad en que los egoísmos personales interactúen, podrá haber un verdadero equilibrio,
un beneficio público y, posteriormente, desde Adam Smith nos daremos cuenta que ningún equilibrio fundado estrictamente en el egoísmo puede desprendernos de esa "simpatía" por
el otro, no podemos hacer invisible el sufrimiento ajeno.
Legitimación de la violencia como principio de equilibrio social. Ariel. Revista de Filosofía. Montevideo, Uruguay. Nº. 18, junio 2016. pp. 10-12. Registros del ISSN 1688-6658 (electrónico) e ISSN 2301-119X (impreso) en Biblioteca Nacional, MEC. Disponible en: http://issuu.com/revistadefilosofiaariel
Arielenlinea.wordpress.com
El presente libro ha sido llamado El suicidio como recuperación de la subjetividad, porque es recuperación de una subjetividad que nos ha sido negada, en tanto posibilidad de asumir la responsabilidad de nuestra propia existencia. El hombre individual no tiene derecho a decidir sobre su propia vida, pues nos han enseñado que corresponde a otros significarla y darle valor, claro está, desde su propio punto de vista. De esta manera, no soy dueño de mí mismo, de mi libertad, y si como dice Sartre: “el hombre es libre, el hombre es libertad” (Sartre.1984. p. 68); si no hay libertad, no hay sujeto, no hay subjetividad.
Introduction to source{d} Engine and source{d} Lookout source{d}
Join us for a presentation and demo of source{d} Engine and source{d} Lookout. Combining code retrieval, language agnostic parsing, and git management tools with familiar APIs parsing, source{d} Engine simplifies code analysis. source{d} Lookout, a service for assisted code review that enables running custom code analyzers on GitHub pull requests.
2. PHP Include File
Insert the content of one PHP file into another
PHP file before the server executes it
Use the
include() generates a warning, but the script
will continue execution
require() generates a fatal error, and the
script will stop
CS380
2
3. include() example
3
<a href="/default.php">Home</a>
<a href="/tutorials.php">Tutorials</a>
<a href="/references.php">References</a>
<a href="/examples.php">Examples</a>
<a href="/contact.php">Contact Us</a> PHP
<html>
<body>
<div class="leftmenu">
<?php include("menu.php"); ?>
</div>
<h1>Welcome to my home page.</h1>
<p>I have a great menu here.</p>
</body>
</html> PHP
6. Reading/writing files
contents of
foo.txt
file("foo.txt")
file_get_contents
("foo.txt")
Hello
how are
you?
I'm fine
array(
"Hellon", #0
"how aren", #1
"you?n", #2
"n", #3
"I'm finen" #4
)
"Hellon
how aren
you?n
n
I'm finen"
CS380
6
file returns lines of a file as an array
file_get_contents returns entire contents of a file
as a string
7. Reading/writing an entire file
file_get_contents returns entire contents of a file
as a string
file_put_contents writes a string into a file,
replacing any prior contents
CS380
7
# reverse a file
$text = file_get_contents("poem.txt");
$text = strrev($text);
file_put_contents("poem.txt", $text); PHP
8. Appending to a file
CS380
8
# add a line to a file
$new_text = "P.S. ILY, GTG TTYL!~";
file_put_contents("poem.txt", $new_text,
FILE_APPEND); PHP
old contents new contents
Roses are red,
Violets are blue.
All my base,
Are belong to you.
Roses are red,
Violets are blue.
All my base,
Are belong to you.
P.S. ILY, GTG TTYL!~
9. The file function
9
# display lines of file as a bulleted list
$lines = file("todolist.txt");
foreach ($lines as $line) {
?>
<li> <?= $line ?> </li>
<?php
}
?> PHP
file returns the lines of a file as an array of strings
each string ends with n
to strip the n off each line, use optional second parameter:
$lines = file("todolist.txt",FILE_IGNORE_NEW_LINES);
PHP
10. Unpacking an array: list
10
list($var1, ..., $varN) = array; PHP
$values = array(“mundruid", "18", “f", "96");
...
list($username, $age, $gender, $iq) = $values;
the list function accepts a comma-separated list of
variable names as parameters
use this to quickly "unpack" an array's contents into
several variables
PHP
CS380
11. Fixed-length files, file and
list
11
Xenia Mountrouidou
(919)685-2181
570-86-7326 contents of file personal.txt
list($name, $phone, $ssn) = file("personal.txt");
reads the file into an array of lines and unpacks the lines
into variables
Need to know a file's exact length/format
PHP
CS380
13. Example explode
13
Harry Potter, J.K. Rowling
The Lord of the Rings, J.R.R. Tolkien
Dune, Frank Herbert
contents of input file books.txt
<?php foreach (file(“books.txt") as $book) {
list($title, $author) = explode(“,", $book);
?>
<p> Book title: <?= $title ?>, Author: <?=
$author ?> </p>
<?php
}
?> PHP
CS380
14. Reading directories
function description
scandir
returns an array of all file
names in a given directory
(returns just the file names,
such as "myfile.txt")
glob
returns an array of all file
names that match a given
pattern
(returns a file path and
name, such as
"foo/bar/myfile.txt")
CS380
14
15. Example for glob
15
# reverse all poems in the poetry directory
$poems = glob("poetry/poem*.dat");
foreach ($poems as $poemfile) {
$text = file_get_contents($poemfile);
file_put_contents($poemfile, strrev($text));
print "I just reversed " .
basename($poemfile);
} PHP
glob can match a "wildcard" path with the * character
the basename function strips any leading directory from
a file path
CS380
16. Example for glob
16
# reverse all poems in the poetry directory
$poems = glob("poetry/poem*.dat");
foreach ($poems as $poemfile) {
$text = file_get_contents($poemfile);
file_put_contents($poemfile, strrev($text));
print "I just reversed " .
basename($poemfile);
} PHP
glob can match a "wildcard" path with the * character
the basename function strips any leading directory from
a file path
CS380
19. Exceptions
Used to change the normal flow of the code
execution if a specified error (exceptional)
condition occurs.
What normally happens when an exception is
triggered:
current code state is saved
code execution will switch to a predefined
(custom) exception handler function
the handler may then
resume the execution from the saved code state,
terminate the script execution or
continue the script from a different location in the code
19
20. Exception example
20
<?php
//create function with an exception
function checkStr($str)
{
if(strcmp($str, “correct”)!= 0)
{
throw new Exception(“String is not correct!");
}
return true;
}
//trigger exception
checkStr(“wrong”);
?> PHP
CS380
21. Exception example (cont.)
21
<?php
//create function with an exception
function checkStr($str)
{
…
}
//trigger exception in a "try" block
try
{
checkStr(“wrong”);
//If the exception is thrown, this text will not be shown
echo 'If you see this, the string is correct';
}
//catch exception
catch(Exception $e)
{
echo 'Message: ' .$e->getMessage();
}
?> PHP
22. PHP larger example
Display a random quote of the day:
I don't know half of you half as well as I should like; and I like less
than half of you half as well as you deserve.
J. R. R. Tolkien (1892 - 1973), The Fellowship of the Ring
I have not failed. I've just found 10,000 ways that won't work.
Thomas A. Edison (1847 - 1931), (attributed)
I am among those who think that science has great beauty. A
scientist in his laboratory is not only a technician: he is also a child
placed before natural phenomena which impress him like a fairy
tale.
Marie Curie (1867 - 1934)
I love deadlines. I like the whooshing sound they make as they fly
by. Douglas Adams
Statistics: The only science that enables different experts using the
same figures to draw different conclusions.
22
24. Cookies
Problem: HTTP is stateless
What is a cookie?
tiny bits of information that a web site could store
on the client's machine
they are sent back to the web site each time a
new page is requested by this client.
CS380
24
25. Bad Cookies?
Urban myth: tracking, violate privacy
Reality:
cookies are relatively harmless
can only store a small amount of information
CS380
25
26. Sessions
What is a session?
a combination of a server-side cookie and a
client-side cookie,
the client-side cookie contains only a reference to
the correct data on the server.
when the user visits the site:
their browser sends the reference code to the
server
the server loads the corresponding data.
CS380
26
27. Cookies vs Sessions
Cookies can be set to a long lifespan
Cookies work smoothly when you have a
cluster of web servers
Sessions are stored on the server, i.e. clients
do not have access to the information you
store about
Session data does not need to be transmitted
with each page; clients just need to send an ID
and the data is loaded from the local file.
Sessions can be any size you want because
they are held on your server,
27
29. Retrieve a Cookie Value
29
<?php
// Print a cookie
echo $_COOKIE["user"];
// A way to view all cookies
print_r($_COOKIE);
?>
CS380
PHP
30. Delete a Cookie
30
<?php
// set the expiration date to one hour ago
setcookie("user", "", time()+3600);
?>
CS380
PHP
31. Start/end a session
31
bool session_start ( void )
bool session_destroy ( void ) PHP
All your session data is stored in the session
superglobal array, $_SESSION
$_SESSION['var'] = $val;
$_SESSION['FirstName'] = "Jim"; PHP
CS380
Editor's Notes
Server side includes saves a lot of work. This means that you can create a standard header, footer, or menu file for all your web pages. When the header needs to be updated, you can only update the include file, or when you add a new page to your site, you can simply change the menu file (instead of updating the links on all your web pages).
file_put_contents can be called with an optional third parameter
appends (adds to the end) rather than replacing previous contents
a convenience, so you can refer to $username instead of $values[0], etc.
a convenience, so you can refer to $username instead of $values[0], etc.
for more complex string splitting, you can use regular expressions
glob can filter by accepting wildcard paths with the * character
glob("foo/bar/*.doc") returns all .doc files in the foo/bar subdirectory
glob("food*") returns all files whose names begin with "food"
glob("lecture*/slides*.ppt") examines all directories whose names begin with lecture and grabs all files whose names begin with "slides" and end with ".ppt“
basename("foo/bar/baz.txt") returns "baz.txt"
annoyingly, the current directory (".") and parent directory ("..") are included in the
array
don't need basename with scandir because it returns the file's names only
, whereas sessions are stored on the server, meaning in one of your web servers handles the first request, the other web servers in your cluster will not have the stored information.
whereas many web browsers have a limit on how big cookies can be to stop rogue web sites chewing up gigabytes of data with meaningless cookie information.
More long term: cookies
More flexibility, security: sessions
The setcookie() function must appear BEFORE the <html> tag.
The PHP $_COOKIE variable is used to retrieve a cookie value.
When deleting a cookie you should assure that the expiration date is in the past.